Merge pull request #977 from jasonleenaylor/bug-18558
[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  *   Marek Safar (marek.safar@gmail.com)
9  *
10  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12  * Copyright 2011-2014 Xamarin Inc (http://www.xamarin.com).
13  */
14
15 #include <config.h>
16 #include <glib.h>
17 #include <stdarg.h>
18 #include <string.h>
19 #include <ctype.h>
20 #ifdef HAVE_ALLOCA_H
21 #include <alloca.h>
22 #endif
23 #ifdef HAVE_SYS_TIME_H
24 #include <sys/time.h>
25 #endif
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #if defined (HOST_WIN32)
30 #include <stdlib.h>
31 #endif
32 #if defined (HAVE_WCHAR_H)
33 #include <wchar.h>
34 #endif
35
36 #include "mono/utils/mono-membar.h"
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/threads.h>
39 #include <mono/metadata/threads-types.h>
40 #include <mono/metadata/threadpool.h>
41 #include <mono/metadata/monitor.h>
42 #include <mono/metadata/reflection.h>
43 #include <mono/metadata/assembly.h>
44 #include <mono/metadata/tabledefs.h>
45 #include <mono/metadata/exception.h>
46 #include <mono/metadata/file-io.h>
47 #include <mono/metadata/console-io.h>
48 #include <mono/metadata/mono-route.h>
49 #include <mono/metadata/socket-io.h>
50 #include <mono/metadata/mono-endian.h>
51 #include <mono/metadata/tokentype.h>
52 #include <mono/metadata/domain-internals.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/class-internals.h>
55 #include <mono/metadata/marshal.h>
56 #include <mono/metadata/gc-internal.h>
57 #include <mono/metadata/mono-gc.h>
58 #include <mono/metadata/rand.h>
59 #include <mono/metadata/sysmath.h>
60 #include <mono/metadata/string-icalls.h>
61 #include <mono/metadata/debug-helpers.h>
62 #include <mono/metadata/process.h>
63 #include <mono/metadata/environment.h>
64 #include <mono/metadata/profiler-private.h>
65 #include <mono/metadata/locales.h>
66 #include <mono/metadata/filewatcher.h>
67 #include <mono/metadata/char-conversions.h>
68 #include <mono/metadata/security.h>
69 #include <mono/metadata/mono-config.h>
70 #include <mono/metadata/cil-coff.h>
71 #include <mono/metadata/number-formatter.h>
72 #include <mono/metadata/security-manager.h>
73 #include <mono/metadata/security-core-clr.h>
74 #include <mono/metadata/mono-perfcounters.h>
75 #include <mono/metadata/mono-debug.h>
76 #include <mono/metadata/mono-ptr-array.h>
77 #include <mono/metadata/verify-internals.h>
78 #include <mono/metadata/runtime.h>
79 #include <mono/metadata/file-mmap.h>
80 #include <mono/metadata/seq-points-data.h>
81 #include <mono/io-layer/io-layer.h>
82 #include <mono/utils/strtod.h>
83 #include <mono/utils/monobitset.h>
84 #include <mono/utils/mono-time.h>
85 #include <mono/utils/mono-proclib.h>
86 #include <mono/utils/mono-string.h>
87 #include <mono/utils/mono-error-internals.h>
88 #include <mono/utils/mono-mmap.h>
89 #include <mono/utils/mono-io-portability.h>
90 #include <mono/utils/mono-digest.h>
91 #include <mono/utils/bsearch.h>
92 #include <mono/utils/mono-mutex.h>
93 #include <mono/utils/mono-threads.h>
94
95 #if defined (HOST_WIN32)
96 #include <windows.h>
97 #include <shlobj.h>
98 #endif
99 #include "decimal-ms.h"
100
101 extern MonoString* ves_icall_System_Environment_GetOSVersionString (void);
102
103 ICALL_EXPORT MonoReflectionAssembly* ves_icall_System_Reflection_Assembly_GetCallingAssembly (void);
104
105 static MonoArray*
106 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional);
107
108 static inline MonoBoolean
109 is_generic_parameter (MonoType *type)
110 {
111         return !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR);
112 }
113
114 static void
115 mono_class_init_or_throw (MonoClass *klass)
116 {
117         if (!mono_class_init (klass))
118                 mono_raise_exception (mono_class_get_exception_for_failure (klass));
119 }
120
121 /*
122  * We expect a pointer to a char, not a string
123  */
124 ICALL_EXPORT gboolean
125 mono_double_ParseImpl (char *ptr, double *result)
126 {
127         gchar *endptr = NULL;
128         *result = 0.0;
129
130         if (*ptr){
131                 /* mono_strtod () is not thread-safe */
132                 mono_mutex_lock (&mono_strtod_mutex);
133                 *result = mono_strtod (ptr, &endptr);
134                 mono_mutex_unlock (&mono_strtod_mutex);
135         }
136
137         if (!*ptr || (endptr && *endptr))
138                 return FALSE;
139         
140         return TRUE;
141 }
142
143 ICALL_EXPORT MonoObject *
144 ves_icall_System_Array_GetValueImpl (MonoObject *this, guint32 pos)
145 {
146         MonoClass *ac;
147         MonoArray *ao;
148         gint32 esize;
149         gpointer *ea;
150
151         ao = (MonoArray *)this;
152         ac = (MonoClass *)ao->obj.vtable->klass;
153
154         esize = mono_array_element_size (ac);
155         ea = (gpointer*)((char*)ao->vector + (pos * esize));
156
157         if (ac->element_class->valuetype)
158                 return mono_value_box (this->vtable->domain, ac->element_class, ea);
159         else
160                 return *ea;
161 }
162
163 ICALL_EXPORT MonoObject *
164 ves_icall_System_Array_GetValue (MonoObject *this, MonoObject *idxs)
165 {
166         MonoClass *ac, *ic;
167         MonoArray *ao, *io;
168         gint32 i, pos, *ind;
169
170         MONO_CHECK_ARG_NULL (idxs, NULL);
171
172         io = (MonoArray *)idxs;
173         ic = (MonoClass *)io->obj.vtable->klass;
174         
175         ao = (MonoArray *)this;
176         ac = (MonoClass *)ao->obj.vtable->klass;
177
178         g_assert (ic->rank == 1);
179         if (io->bounds != NULL || io->max_length !=  ac->rank) {
180                 mono_set_pending_exception (mono_get_exception_argument (NULL, NULL));
181                 return NULL;
182         }
183
184         ind = (gint32 *)io->vector;
185
186         if (ao->bounds == NULL) {
187                 if (*ind < 0 || *ind >= ao->max_length) {
188                         mono_set_pending_exception (mono_get_exception_index_out_of_range ());
189                         return NULL;
190                 }
191
192                 return ves_icall_System_Array_GetValueImpl (this, *ind);
193         }
194         
195         for (i = 0; i < ac->rank; i++) {
196                 if ((ind [i] < ao->bounds [i].lower_bound) ||
197                     (ind [i] >=  (mono_array_lower_bound_t)ao->bounds [i].length + ao->bounds [i].lower_bound)) {
198                         mono_set_pending_exception (mono_get_exception_index_out_of_range ());
199                         return NULL;
200                 }
201         }
202
203         pos = ind [0] - ao->bounds [0].lower_bound;
204         for (i = 1; i < ac->rank; i++)
205                 pos = pos*ao->bounds [i].length + ind [i] - 
206                         ao->bounds [i].lower_bound;
207
208         return ves_icall_System_Array_GetValueImpl (this, pos);
209 }
210
211 ICALL_EXPORT void
212 ves_icall_System_Array_SetValueImpl (MonoArray *this, MonoObject *value, guint32 pos)
213 {
214         MonoClass *ac, *vc, *ec;
215         gint32 esize, vsize;
216         gpointer *ea, *va;
217         int et, vt;
218
219         guint64 u64 = 0;
220         gint64 i64 = 0;
221         gdouble r64 = 0;
222
223         if (value)
224                 vc = value->vtable->klass;
225         else
226                 vc = NULL;
227
228         ac = this->obj.vtable->klass;
229         ec = ac->element_class;
230
231         esize = mono_array_element_size (ac);
232         ea = (gpointer*)((char*)this->vector + (pos * esize));
233         va = (gpointer*)((char*)value + sizeof (MonoObject));
234
235         if (mono_class_is_nullable (ec)) {
236                 mono_nullable_init ((guint8*)ea, value, ec);
237                 return;
238         }
239
240         if (!value) {
241                 mono_gc_bzero_atomic (ea, esize);
242                 return;
243         }
244
245 #define NO_WIDENING_CONVERSION G_STMT_START{\
246         mono_set_pending_exception (mono_get_exception_argument ( \
247                 "value", "not a widening conversion")); \
248         return; \
249 }G_STMT_END
250
251 #define CHECK_WIDENING_CONVERSION(extra) G_STMT_START{\
252                 if (esize < vsize + (extra)) {                                                    \
253                         mono_set_pending_exception (mono_get_exception_argument (       \
254                         "value", "not a widening conversion")); \
255                         return;                                                                 \
256                 } \
257 }G_STMT_END
258
259 #define INVALID_CAST G_STMT_START{ \
260                 mono_get_runtime_callbacks ()->set_cast_details (vc, ec); \
261         mono_set_pending_exception (mono_get_exception_invalid_cast ()); \
262         return; \
263 }G_STMT_END
264
265         /* Check element (destination) type. */
266         switch (ec->byval_arg.type) {
267         case MONO_TYPE_STRING:
268                 switch (vc->byval_arg.type) {
269                 case MONO_TYPE_STRING:
270                         break;
271                 default:
272                         INVALID_CAST;
273                 }
274                 break;
275         case MONO_TYPE_BOOLEAN:
276                 switch (vc->byval_arg.type) {
277                 case MONO_TYPE_BOOLEAN:
278                         break;
279                 case MONO_TYPE_CHAR:
280                 case MONO_TYPE_U1:
281                 case MONO_TYPE_U2:
282                 case MONO_TYPE_U4:
283                 case MONO_TYPE_U8:
284                 case MONO_TYPE_I1:
285                 case MONO_TYPE_I2:
286                 case MONO_TYPE_I4:
287                 case MONO_TYPE_I8:
288                 case MONO_TYPE_R4:
289                 case MONO_TYPE_R8:
290                         NO_WIDENING_CONVERSION;
291                 default:
292                         INVALID_CAST;
293                 }
294                 break;
295         }
296
297         if (!ec->valuetype) {
298                 if (!mono_object_isinst (value, ec))
299                         INVALID_CAST;
300                 mono_gc_wbarrier_set_arrayref (this, ea, (MonoObject*)value);
301                 return;
302         }
303
304         if (mono_object_isinst (value, ec)) {
305                 if (ec->has_references)
306                         mono_value_copy (ea, (char*)value + sizeof (MonoObject), ec);
307                 else
308                         mono_gc_memmove_atomic (ea, (char *)value + sizeof (MonoObject), esize);
309                 return;
310         }
311
312         if (!vc->valuetype)
313                 INVALID_CAST;
314
315         vsize = mono_class_instance_size (vc) - sizeof (MonoObject);
316
317         et = ec->byval_arg.type;
318         if (et == MONO_TYPE_VALUETYPE && ec->byval_arg.data.klass->enumtype)
319                 et = mono_class_enum_basetype (ec->byval_arg.data.klass)->type;
320
321         vt = vc->byval_arg.type;
322         if (vt == MONO_TYPE_VALUETYPE && vc->byval_arg.data.klass->enumtype)
323                 vt = mono_class_enum_basetype (vc->byval_arg.data.klass)->type;
324
325 #define ASSIGN_UNSIGNED(etype) G_STMT_START{\
326         switch (vt) { \
327         case MONO_TYPE_U1: \
328         case MONO_TYPE_U2: \
329         case MONO_TYPE_U4: \
330         case MONO_TYPE_U8: \
331         case MONO_TYPE_CHAR: \
332                 CHECK_WIDENING_CONVERSION(0); \
333                 *(etype *) ea = (etype) u64; \
334                 return; \
335         /* You can't assign a signed value to an unsigned array. */ \
336         case MONO_TYPE_I1: \
337         case MONO_TYPE_I2: \
338         case MONO_TYPE_I4: \
339         case MONO_TYPE_I8: \
340         /* You can't assign a floating point number to an integer array. */ \
341         case MONO_TYPE_R4: \
342         case MONO_TYPE_R8: \
343                 NO_WIDENING_CONVERSION; \
344         } \
345 }G_STMT_END
346
347 #define ASSIGN_SIGNED(etype) G_STMT_START{\
348         switch (vt) { \
349         case MONO_TYPE_I1: \
350         case MONO_TYPE_I2: \
351         case MONO_TYPE_I4: \
352         case MONO_TYPE_I8: \
353                 CHECK_WIDENING_CONVERSION(0); \
354                 *(etype *) ea = (etype) i64; \
355                 return; \
356         /* You can assign an unsigned value to a signed array if the array's */ \
357         /* element size is larger than the value size. */ \
358         case MONO_TYPE_U1: \
359         case MONO_TYPE_U2: \
360         case MONO_TYPE_U4: \
361         case MONO_TYPE_U8: \
362         case MONO_TYPE_CHAR: \
363                 CHECK_WIDENING_CONVERSION(1); \
364                 *(etype *) ea = (etype) u64; \
365                 return; \
366         /* You can't assign a floating point number to an integer array. */ \
367         case MONO_TYPE_R4: \
368         case MONO_TYPE_R8: \
369                 NO_WIDENING_CONVERSION; \
370         } \
371 }G_STMT_END
372
373 #define ASSIGN_REAL(etype) G_STMT_START{\
374         switch (vt) { \
375         case MONO_TYPE_R4: \
376         case MONO_TYPE_R8: \
377                 CHECK_WIDENING_CONVERSION(0); \
378                 *(etype *) ea = (etype) r64; \
379                 return; \
380         /* All integer values fit into a floating point array, so we don't */ \
381         /* need to CHECK_WIDENING_CONVERSION here. */ \
382         case MONO_TYPE_I1: \
383         case MONO_TYPE_I2: \
384         case MONO_TYPE_I4: \
385         case MONO_TYPE_I8: \
386                 *(etype *) ea = (etype) i64; \
387                 return; \
388         case MONO_TYPE_U1: \
389         case MONO_TYPE_U2: \
390         case MONO_TYPE_U4: \
391         case MONO_TYPE_U8: \
392         case MONO_TYPE_CHAR: \
393                 *(etype *) ea = (etype) u64; \
394                 return; \
395         } \
396 }G_STMT_END
397
398         switch (vt) {
399         case MONO_TYPE_U1:
400                 u64 = *(guint8 *) va;
401                 break;
402         case MONO_TYPE_U2:
403                 u64 = *(guint16 *) va;
404                 break;
405         case MONO_TYPE_U4:
406                 u64 = *(guint32 *) va;
407                 break;
408         case MONO_TYPE_U8:
409                 u64 = *(guint64 *) va;
410                 break;
411         case MONO_TYPE_I1:
412                 i64 = *(gint8 *) va;
413                 break;
414         case MONO_TYPE_I2:
415                 i64 = *(gint16 *) va;
416                 break;
417         case MONO_TYPE_I4:
418                 i64 = *(gint32 *) va;
419                 break;
420         case MONO_TYPE_I8:
421                 i64 = *(gint64 *) va;
422                 break;
423         case MONO_TYPE_R4:
424                 r64 = *(gfloat *) va;
425                 break;
426         case MONO_TYPE_R8:
427                 r64 = *(gdouble *) va;
428                 break;
429         case MONO_TYPE_CHAR:
430                 u64 = *(guint16 *) va;
431                 break;
432         case MONO_TYPE_BOOLEAN:
433                 /* Boolean is only compatible with itself. */
434                 switch (et) {
435                 case MONO_TYPE_CHAR:
436                 case MONO_TYPE_U1:
437                 case MONO_TYPE_U2:
438                 case MONO_TYPE_U4:
439                 case MONO_TYPE_U8:
440                 case MONO_TYPE_I1:
441                 case MONO_TYPE_I2:
442                 case MONO_TYPE_I4:
443                 case MONO_TYPE_I8:
444                 case MONO_TYPE_R4:
445                 case MONO_TYPE_R8:
446                         NO_WIDENING_CONVERSION;
447                 default:
448                         INVALID_CAST;
449                 }
450                 break;
451         }
452
453         /* If we can't do a direct copy, let's try a widening conversion. */
454         switch (et) {
455         case MONO_TYPE_CHAR:
456                 ASSIGN_UNSIGNED (guint16);
457         case MONO_TYPE_U1:
458                 ASSIGN_UNSIGNED (guint8);
459         case MONO_TYPE_U2:
460                 ASSIGN_UNSIGNED (guint16);
461         case MONO_TYPE_U4:
462                 ASSIGN_UNSIGNED (guint32);
463         case MONO_TYPE_U8:
464                 ASSIGN_UNSIGNED (guint64);
465         case MONO_TYPE_I1:
466                 ASSIGN_SIGNED (gint8);
467         case MONO_TYPE_I2:
468                 ASSIGN_SIGNED (gint16);
469         case MONO_TYPE_I4:
470                 ASSIGN_SIGNED (gint32);
471         case MONO_TYPE_I8:
472                 ASSIGN_SIGNED (gint64);
473         case MONO_TYPE_R4:
474                 ASSIGN_REAL (gfloat);
475         case MONO_TYPE_R8:
476                 ASSIGN_REAL (gdouble);
477         }
478
479         INVALID_CAST;
480         /* Not reached, INVALID_CAST does not return. Just to avoid a compiler warning ... */
481         return;
482
483 #undef INVALID_CAST
484 #undef NO_WIDENING_CONVERSION
485 #undef CHECK_WIDENING_CONVERSION
486 #undef ASSIGN_UNSIGNED
487 #undef ASSIGN_SIGNED
488 #undef ASSIGN_REAL
489 }
490
491 ICALL_EXPORT void 
492 ves_icall_System_Array_SetValue (MonoArray *this, MonoObject *value,
493                                  MonoArray *idxs)
494 {
495         MonoClass *ac, *ic;
496         gint32 i, pos, *ind;
497
498         MONO_CHECK_ARG_NULL (idxs,);
499
500         ic = idxs->obj.vtable->klass;
501         ac = this->obj.vtable->klass;
502
503         g_assert (ic->rank == 1);
504         if (idxs->bounds != NULL || idxs->max_length != ac->rank) {
505                 mono_set_pending_exception (mono_get_exception_argument (NULL, NULL));
506                 return;
507         }
508
509         ind = (gint32 *)idxs->vector;
510
511         if (this->bounds == NULL) {
512                 if (*ind < 0 || *ind >= this->max_length) {
513                         mono_set_pending_exception (mono_get_exception_index_out_of_range ());
514                         return;
515                 }
516
517                 ves_icall_System_Array_SetValueImpl (this, value, *ind);
518                 return;
519         }
520         
521         for (i = 0; i < ac->rank; i++)
522                 if ((ind [i] < this->bounds [i].lower_bound) ||
523                     (ind [i] >= (mono_array_lower_bound_t)this->bounds [i].length + this->bounds [i].lower_bound)) {
524                         mono_set_pending_exception (mono_get_exception_index_out_of_range ());
525                         return;
526                 }
527
528         pos = ind [0] - this->bounds [0].lower_bound;
529         for (i = 1; i < ac->rank; i++)
530                 pos = pos * this->bounds [i].length + ind [i] - 
531                         this->bounds [i].lower_bound;
532
533         ves_icall_System_Array_SetValueImpl (this, value, pos);
534 }
535
536 ICALL_EXPORT MonoArray *
537 ves_icall_System_Array_CreateInstanceImpl (MonoReflectionType *type, MonoArray *lengths, MonoArray *bounds)
538 {
539         MonoClass *aklass, *klass;
540         MonoArray *array;
541         uintptr_t *sizes, i;
542         gboolean bounded = FALSE;
543
544         MONO_CHECK_ARG_NULL (type, NULL);
545         MONO_CHECK_ARG_NULL (lengths, NULL);
546
547         MONO_CHECK_ARG (lengths, mono_array_length (lengths) > 0, NULL);
548         if (bounds)
549                 MONO_CHECK_ARG (bounds, mono_array_length (lengths) == mono_array_length (bounds), NULL);
550
551         for (i = 0; i < mono_array_length (lengths); i++) {
552                 if (mono_array_get (lengths, gint32, i) < 0) {
553                         mono_set_pending_exception (mono_get_exception_argument_out_of_range (NULL));
554                         return NULL;
555                 }
556         }
557
558         klass = mono_class_from_mono_type (type->type);
559         mono_class_init_or_throw (klass);
560
561         if (bounds && (mono_array_length (bounds) == 1) && (mono_array_get (bounds, gint32, 0) != 0))
562                 /* vectors are not the same as one dimensional arrays with no-zero bounds */
563                 bounded = TRUE;
564         else
565                 bounded = FALSE;
566
567         aklass = mono_bounded_array_class_get (klass, mono_array_length (lengths), bounded);
568
569         sizes = alloca (aklass->rank * sizeof(intptr_t) * 2);
570         for (i = 0; i < aklass->rank; ++i) {
571                 sizes [i] = mono_array_get (lengths, guint32, i);
572                 if (bounds)
573                         sizes [i + aklass->rank] = mono_array_get (bounds, gint32, i);
574                 else
575                         sizes [i + aklass->rank] = 0;
576         }
577
578         array = mono_array_new_full (mono_object_domain (type), aklass, sizes, (intptr_t*)sizes + aklass->rank);
579
580         return array;
581 }
582
583 ICALL_EXPORT MonoArray *
584 ves_icall_System_Array_CreateInstanceImpl64 (MonoReflectionType *type, MonoArray *lengths, MonoArray *bounds)
585 {
586         MonoClass *aklass, *klass;
587         MonoArray *array;
588         uintptr_t *sizes, i;
589         gboolean bounded = FALSE;
590
591         MONO_CHECK_ARG_NULL (type, NULL);
592         MONO_CHECK_ARG_NULL (lengths, NULL);
593
594         MONO_CHECK_ARG (lengths, mono_array_length (lengths) > 0, NULL);
595         if (bounds)
596                 MONO_CHECK_ARG (bounds, mono_array_length (lengths) == mono_array_length (bounds), NULL);
597
598         for (i = 0; i < mono_array_length (lengths); i++) {
599                 if ((mono_array_get (lengths, gint64, i) < 0) ||
600                     (mono_array_get (lengths, gint64, i) > MONO_ARRAY_MAX_INDEX)) {
601                         mono_set_pending_exception (mono_get_exception_argument_out_of_range (NULL));
602                         return NULL;
603                 }
604         }
605
606         klass = mono_class_from_mono_type (type->type);
607         mono_class_init_or_throw (klass);
608
609         if (bounds && (mono_array_length (bounds) == 1) && (mono_array_get (bounds, gint64, 0) != 0))
610                 /* vectors are not the same as one dimensional arrays with no-zero bounds */
611                 bounded = TRUE;
612         else
613                 bounded = FALSE;
614
615         aklass = mono_bounded_array_class_get (klass, mono_array_length (lengths), bounded);
616
617         sizes = alloca (aklass->rank * sizeof(intptr_t) * 2);
618         for (i = 0; i < aklass->rank; ++i) {
619                 sizes [i] = mono_array_get (lengths, guint64, i);
620                 if (bounds)
621                         sizes [i + aklass->rank] = (mono_array_size_t) mono_array_get (bounds, guint64, i);
622                 else
623                         sizes [i + aklass->rank] = 0;
624         }
625
626         array = mono_array_new_full (mono_object_domain (type), aklass, sizes, (intptr_t*)sizes + aklass->rank);
627
628         return array;
629 }
630
631 ICALL_EXPORT gint32 
632 ves_icall_System_Array_GetRank (MonoObject *this)
633 {
634         return this->vtable->klass->rank;
635 }
636
637 ICALL_EXPORT gint32
638 ves_icall_System_Array_GetLength (MonoArray *this, gint32 dimension)
639 {
640         gint32 rank = ((MonoObject *)this)->vtable->klass->rank;
641         uintptr_t length;
642
643         if ((dimension < 0) || (dimension >= rank)) {
644                 mono_set_pending_exception (mono_get_exception_index_out_of_range ());
645                 return 0;
646         }
647         
648         if (this->bounds == NULL)
649                 length = this->max_length;
650         else
651                 length = this->bounds [dimension].length;
652
653 #ifdef MONO_BIG_ARRAYS
654         if (length > G_MAXINT32) {
655                 mono_set_pending_exception (mono_get_exception_overflow ());
656                 return 0;
657         }
658 #endif
659         return length;
660 }
661
662 ICALL_EXPORT gint64
663 ves_icall_System_Array_GetLongLength (MonoArray *this, gint32 dimension)
664 {
665         gint32 rank = ((MonoObject *)this)->vtable->klass->rank;
666
667         if ((dimension < 0) || (dimension >= rank)) {
668                 mono_set_pending_exception (mono_get_exception_index_out_of_range ());
669                 return 0;
670         }
671         
672         if (this->bounds == NULL)
673                 return this->max_length;
674         
675         return this->bounds [dimension].length;
676 }
677
678 ICALL_EXPORT gint32
679 ves_icall_System_Array_GetLowerBound (MonoArray *this, gint32 dimension)
680 {
681         gint32 rank = ((MonoObject *)this)->vtable->klass->rank;
682
683         if ((dimension < 0) || (dimension >= rank)) {
684                 mono_set_pending_exception (mono_get_exception_index_out_of_range ());
685                 return 0;
686         }
687         
688         if (this->bounds == NULL)
689                 return 0;
690         
691         return this->bounds [dimension].lower_bound;
692 }
693
694 ICALL_EXPORT void
695 ves_icall_System_Array_ClearInternal (MonoArray *arr, int idx, int length)
696 {
697         int sz = mono_array_element_size (mono_object_class (arr));
698         mono_gc_bzero_atomic (mono_array_addr_with_size_fast (arr, sz, idx), length * sz);
699 }
700
701 ICALL_EXPORT gboolean
702 ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* dest, int dest_idx, int length)
703 {
704         int element_size;
705         void * dest_addr;
706         void * source_addr;
707         MonoVTable *src_vtable;
708         MonoVTable *dest_vtable;
709         MonoClass *src_class;
710         MonoClass *dest_class;
711
712         src_vtable = source->obj.vtable;
713         dest_vtable = dest->obj.vtable;
714
715         if (src_vtable->rank != dest_vtable->rank)
716                 return FALSE;
717
718         if (source->bounds || dest->bounds)
719                 return FALSE;
720
721         /* there's no integer overflow since mono_array_length returns an unsigned integer */
722         if ((dest_idx + length > mono_array_length_fast (dest)) ||
723                 (source_idx + length > mono_array_length_fast (source)))
724                 return FALSE;
725
726         src_class = src_vtable->klass->element_class;
727         dest_class = dest_vtable->klass->element_class;
728
729         /*
730          * Handle common cases.
731          */
732
733         /* Case1: object[] -> valuetype[] (ArrayList::ToArray) 
734         We fallback to managed here since we need to typecheck each boxed valuetype before storing them in the dest array.
735         */
736         if (src_class == mono_defaults.object_class && dest_class->valuetype)
737                 return FALSE;
738
739         /* Check if we're copying a char[] <==> (u)short[] */
740         if (src_class != dest_class) {
741                 if (dest_class->valuetype || dest_class->enumtype || src_class->valuetype || src_class->enumtype)
742                         return FALSE;
743
744                 /* It's only safe to copy between arrays if we can ensure the source will always have a subtype of the destination. We bail otherwise. */
745                 if (!mono_class_is_subclass_of (src_class, dest_class, FALSE))
746                         return FALSE;
747         }
748
749         if (dest_class->valuetype) {
750                 element_size = mono_array_element_size (source->obj.vtable->klass);
751                 source_addr = mono_array_addr_with_size_fast (source, element_size, source_idx);
752                 if (dest_class->has_references) {
753                         mono_value_copy_array (dest, dest_idx, source_addr, length);
754                 } else {
755                         dest_addr = mono_array_addr_with_size_fast (dest, element_size, dest_idx);
756                         mono_gc_memmove_atomic (dest_addr, source_addr, element_size * length);
757                 }
758         } else {
759                 mono_array_memcpy_refs_fast (dest, dest_idx, source, source_idx, length);
760         }
761
762         return TRUE;
763 }
764
765 ICALL_EXPORT void
766 ves_icall_System_Array_GetGenericValueImpl (MonoObject *this, guint32 pos, gpointer value)
767 {
768         MonoClass *ac;
769         MonoArray *ao;
770         gint32 esize;
771         gpointer *ea;
772
773         ao = (MonoArray *)this;
774         ac = (MonoClass *)ao->obj.vtable->klass;
775
776         esize = mono_array_element_size (ac);
777         ea = (gpointer*)((char*)ao->vector + (pos * esize));
778
779         mono_gc_memmove_atomic (value, ea, esize);
780 }
781
782 ICALL_EXPORT void
783 ves_icall_System_Array_SetGenericValueImpl (MonoObject *this, guint32 pos, gpointer value)
784 {
785         MonoClass *ac, *ec;
786         MonoArray *ao;
787         gint32 esize;
788         gpointer *ea;
789
790         ao = (MonoArray *)this;
791         ac = (MonoClass *)ao->obj.vtable->klass;
792         ec = ac->element_class;
793
794         esize = mono_array_element_size (ac);
795         ea = (gpointer*)((char*)ao->vector + (pos * esize));
796
797         if (MONO_TYPE_IS_REFERENCE (&ec->byval_arg)) {
798                 g_assert (esize == sizeof (gpointer));
799                 mono_gc_wbarrier_generic_store (ea, *(gpointer*)value);
800         } else {
801                 g_assert (ec->inited);
802                 g_assert (esize == mono_class_value_size (ec, NULL));
803                 if (ec->has_references)
804                         mono_gc_wbarrier_value_copy (ea, value, 1, ec);
805                 else
806                         mono_gc_memmove_atomic (ea, value, esize);
807         }
808 }
809
810 ICALL_EXPORT void
811 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray (MonoArray *array, MonoClassField *field_handle)
812 {
813         MonoClass *klass = array->obj.vtable->klass;
814         guint32 size = mono_array_element_size (klass);
815         MonoType *type = mono_type_get_underlying_type (&klass->element_class->byval_arg);
816         int align;
817         const char *field_data;
818
819         if (MONO_TYPE_IS_REFERENCE (type) || type->type == MONO_TYPE_VALUETYPE) {
820                 MonoException *exc = mono_get_exception_argument("array",
821                         "Cannot initialize array of non-primitive type.");
822                 mono_set_pending_exception (exc);
823                 return;
824         }
825
826         if (!(field_handle->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA)) {
827                 MonoException *exc = mono_get_exception_argument("field_handle",
828                         "Field doesn't have an RVA");
829                 mono_set_pending_exception (exc);
830                 return;
831         }
832
833         size *= array->max_length;
834         field_data = mono_field_get_data (field_handle);
835
836         if (size > mono_type_size (field_handle->type, &align)) {
837                 MonoException *exc = mono_get_exception_argument("field_handle",
838                         "Field not large enough to fill array");
839                 mono_set_pending_exception (exc);
840                 return;
841         }
842
843 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
844 #define SWAP(n) {\
845         guint ## n *data = (guint ## n *) mono_array_addr (array, char, 0); \
846         guint ## n *src = (guint ## n *) field_data; \
847         guint ## n *end = (guint ## n *)((char*)src + size); \
848 \
849         for (; src < end; data++, src++) { \
850                 *data = read ## n (src); \
851         } \
852 }
853
854         /* printf ("Initialize array with elements of %s type\n", klass->element_class->name); */
855
856         switch (type->type) {
857         case MONO_TYPE_CHAR:
858         case MONO_TYPE_I2:
859         case MONO_TYPE_U2:
860                 SWAP (16);
861                 break;
862         case MONO_TYPE_I4:
863         case MONO_TYPE_U4:
864         case MONO_TYPE_R4:
865                 SWAP (32);
866                 break;
867         case MONO_TYPE_I8:
868         case MONO_TYPE_U8:
869         case MONO_TYPE_R8:
870                 SWAP (64);
871                 break;
872         default:
873                 memcpy (mono_array_addr (array, char, 0), field_data, size);
874                 break;
875         }
876 #else
877         memcpy (mono_array_addr (array, char, 0), field_data, size);
878 #endif
879 }
880
881 ICALL_EXPORT gint
882 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetOffsetToStringData (void)
883 {
884         return offsetof (MonoString, chars);
885 }
886
887 ICALL_EXPORT MonoObject *
888 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_GetObjectValue (MonoObject *obj)
889 {
890         if ((obj == NULL) || (! (obj->vtable->klass->valuetype)))
891                 return obj;
892         else
893                 return mono_object_clone (obj);
894 }
895
896 ICALL_EXPORT void
897 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunClassConstructor (MonoType *handle)
898 {
899         MonoClass *klass;
900         MonoVTable *vtable;
901
902         MONO_CHECK_ARG_NULL (handle,);
903
904         klass = mono_class_from_mono_type (handle);
905         MONO_CHECK_ARG (handle, klass,);
906
907         vtable = mono_class_vtable_full (mono_domain_get (), klass, TRUE);
908
909         /* This will call the type constructor */
910         mono_runtime_class_init (vtable);
911 }
912
913 ICALL_EXPORT void
914 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_RunModuleConstructor (MonoImage *image)
915 {
916         MonoError error;
917
918         mono_image_check_for_module_cctor (image);
919         if (image->has_module_cctor) {
920                 MonoClass *module_klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | 1, &error);
921                 mono_error_raise_exception (&error);
922                 /*It's fine to raise the exception here*/
923                 mono_runtime_class_init (mono_class_vtable_full (mono_domain_get (), module_klass, TRUE));
924         }
925 }
926
927 ICALL_EXPORT MonoBoolean
928 ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStack (void)
929 {
930         guint8 *stack_addr;
931         guint8 *current;
932         size_t stack_size;
933         /* later make this configurable and per-arch */
934         int min_size = 4096 * 4 * sizeof (void*);
935         mono_thread_info_get_stack_bounds (&stack_addr, &stack_size);
936         /* if we have no info we are optimistic and assume there is enough room */
937         if (!stack_addr)
938                 return TRUE;
939 #ifdef HOST_WIN32
940         // FIXME: Windows dynamically extends the stack, so stack_addr might be close
941         // to the current sp
942         return TRUE;
943 #endif
944         current = (guint8 *)&stack_addr;
945         if (current > stack_addr) {
946                 if ((current - stack_addr) < min_size)
947                         return FALSE;
948         } else {
949                 if (current - (stack_addr - stack_size) < min_size)
950                         return FALSE;
951         }
952         return TRUE;
953 }
954
955 ICALL_EXPORT MonoObject *
956 ves_icall_System_Object_MemberwiseClone (MonoObject *this)
957 {
958         return mono_object_clone (this);
959 }
960
961 ICALL_EXPORT gint32
962 ves_icall_System_ValueType_InternalGetHashCode (MonoObject *this, MonoArray **fields)
963 {
964         MonoClass *klass;
965         MonoObject **values = NULL;
966         MonoObject *o;
967         int count = 0;
968         gint32 result = (int)(gsize)mono_defaults.int32_class;
969         MonoClassField* field;
970         gpointer iter;
971
972         klass = mono_object_class (this);
973
974         if (mono_class_num_fields (klass) == 0)
975                 return result;
976
977         /*
978          * Compute the starting value of the hashcode for fields of primitive
979          * types, and return the remaining fields in an array to the managed side.
980          * This way, we can avoid costly reflection operations in managed code.
981          */
982         iter = NULL;
983         while ((field = mono_class_get_fields (klass, &iter))) {
984                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
985                         continue;
986                 if (mono_field_is_deleted (field))
987                         continue;
988                 /* FIXME: Add more types */
989                 switch (field->type->type) {
990                 case MONO_TYPE_I4:
991                         result ^= *(gint32*)((guint8*)this + field->offset);
992                         break;
993                 case MONO_TYPE_STRING: {
994                         MonoString *s;
995                         s = *(MonoString**)((guint8*)this + field->offset);
996                         if (s != NULL)
997                                 result ^= mono_string_hash (s);
998                         break;
999                 }
1000                 default:
1001                         if (!values)
1002                                 values = g_newa (MonoObject*, mono_class_num_fields (klass));
1003                         o = mono_field_get_value_object (mono_object_domain (this), field, this);
1004                         values [count++] = o;
1005                 }
1006         }
1007
1008         if (values) {
1009                 int i;
1010                 mono_gc_wbarrier_generic_store (fields, (MonoObject*) mono_array_new (mono_domain_get (), mono_defaults.object_class, count));
1011                 for (i = 0; i < count; ++i)
1012                         mono_array_setref (*fields, i, values [i]);
1013         } else {
1014                 *fields = NULL;
1015         }
1016         return result;
1017 }
1018
1019 ICALL_EXPORT MonoBoolean
1020 ves_icall_System_ValueType_Equals (MonoObject *this, MonoObject *that, MonoArray **fields)
1021 {
1022         MonoClass *klass;
1023         MonoObject **values = NULL;
1024         MonoObject *o;
1025         MonoClassField* field;
1026         gpointer iter;
1027         int count = 0;
1028
1029         MONO_CHECK_ARG_NULL (that, FALSE);
1030
1031         if (this->vtable != that->vtable)
1032                 return FALSE;
1033
1034         klass = mono_object_class (this);
1035
1036         if (klass->enumtype && mono_class_enum_basetype (klass) && mono_class_enum_basetype (klass)->type == MONO_TYPE_I4)
1037                 return (*(gint32*)((guint8*)this + sizeof (MonoObject)) == *(gint32*)((guint8*)that + sizeof (MonoObject)));
1038
1039         /*
1040          * Do the comparison for fields of primitive type and return a result if
1041          * possible. Otherwise, return the remaining fields in an array to the 
1042          * managed side. This way, we can avoid costly reflection operations in 
1043          * managed code.
1044          */
1045         *fields = NULL;
1046         iter = NULL;
1047         while ((field = mono_class_get_fields (klass, &iter))) {
1048                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
1049                         continue;
1050                 if (mono_field_is_deleted (field))
1051                         continue;
1052                 /* FIXME: Add more types */
1053                 switch (field->type->type) {
1054                 case MONO_TYPE_U1:
1055                 case MONO_TYPE_I1:
1056                 case MONO_TYPE_BOOLEAN:
1057                         if (*((guint8*)this + field->offset) != *((guint8*)that + field->offset))
1058                                 return FALSE;
1059                         break;
1060                 case MONO_TYPE_U2:
1061                 case MONO_TYPE_I2:
1062                 case MONO_TYPE_CHAR:
1063                         if (*(gint16*)((guint8*)this + field->offset) != *(gint16*)((guint8*)that + field->offset))
1064                                 return FALSE;
1065                         break;
1066                 case MONO_TYPE_U4:
1067                 case MONO_TYPE_I4:
1068                         if (*(gint32*)((guint8*)this + field->offset) != *(gint32*)((guint8*)that + field->offset))
1069                                 return FALSE;
1070                         break;
1071                 case MONO_TYPE_U8:
1072                 case MONO_TYPE_I8:
1073                         if (*(gint64*)((guint8*)this + field->offset) != *(gint64*)((guint8*)that + field->offset))
1074                                 return FALSE;
1075                         break;
1076                 case MONO_TYPE_R4:
1077                         if (*(float*)((guint8*)this + field->offset) != *(float*)((guint8*)that + field->offset))
1078                                 return FALSE;
1079                         break;
1080                 case MONO_TYPE_R8:
1081                         if (*(double*)((guint8*)this + field->offset) != *(double*)((guint8*)that + field->offset))
1082                                 return FALSE;
1083                         break;
1084
1085
1086                 case MONO_TYPE_STRING: {
1087                         MonoString *s1, *s2;
1088                         guint32 s1len, s2len;
1089                         s1 = *(MonoString**)((guint8*)this + field->offset);
1090                         s2 = *(MonoString**)((guint8*)that + field->offset);
1091                         if (s1 == s2)
1092                                 break;
1093                         if ((s1 == NULL) || (s2 == NULL))
1094                                 return FALSE;
1095                         s1len = mono_string_length (s1);
1096                         s2len = mono_string_length (s2);
1097                         if (s1len != s2len)
1098                                 return FALSE;
1099
1100                         if (memcmp (mono_string_chars (s1), mono_string_chars (s2), s1len * sizeof (gunichar2)) != 0)
1101                                 return FALSE;
1102                         break;
1103                 }
1104                 default:
1105                         if (!values)
1106                                 values = g_newa (MonoObject*, mono_class_num_fields (klass) * 2);
1107                         o = mono_field_get_value_object (mono_object_domain (this), field, this);
1108                         values [count++] = o;
1109                         o = mono_field_get_value_object (mono_object_domain (this), field, that);
1110                         values [count++] = o;
1111                 }
1112
1113                 if (klass->enumtype)
1114                         /* enums only have one non-static field */
1115                         break;
1116         }
1117
1118         if (values) {
1119                 int i;
1120                 mono_gc_wbarrier_generic_store (fields, (MonoObject*) mono_array_new (mono_domain_get (), mono_defaults.object_class, count));
1121                 for (i = 0; i < count; ++i)
1122                         mono_array_setref_fast (*fields, i, values [i]);
1123                 return FALSE;
1124         } else {
1125                 return TRUE;
1126         }
1127 }
1128
1129 ICALL_EXPORT MonoReflectionType *
1130 ves_icall_System_Object_GetType (MonoObject *obj)
1131 {
1132 #ifndef DISABLE_REMOTING
1133         if (obj->vtable->klass == mono_defaults.transparent_proxy_class)
1134                 return mono_type_get_object (mono_object_domain (obj), &((MonoTransparentProxy*)obj)->remote_class->proxy_class->byval_arg);
1135         else
1136 #endif
1137                 return mono_type_get_object (mono_object_domain (obj), &obj->vtable->klass->byval_arg);
1138 }
1139
1140 ICALL_EXPORT void
1141 mono_type_type_from_obj (MonoReflectionType *mtype, MonoObject *obj)
1142 {
1143         mtype->type = &obj->vtable->klass->byval_arg;
1144         g_assert (mtype->type->type);
1145 }
1146
1147 ICALL_EXPORT gint32
1148 ves_icall_ModuleBuilder_getToken (MonoReflectionModuleBuilder *mb, MonoObject *obj, gboolean create_open_instance)
1149 {
1150         MONO_CHECK_ARG_NULL (obj, 0);
1151         
1152         return mono_image_create_token (mb->dynamic_image, obj, create_open_instance, TRUE);
1153 }
1154
1155 ICALL_EXPORT gint32
1156 ves_icall_ModuleBuilder_getMethodToken (MonoReflectionModuleBuilder *mb,
1157                                         MonoReflectionMethod *method,
1158                                         MonoArray *opt_param_types)
1159 {
1160         MONO_CHECK_ARG_NULL (method, 0);
1161         
1162         return mono_image_create_method_token (
1163                 mb->dynamic_image, (MonoObject *) method, opt_param_types);
1164 }
1165
1166 ICALL_EXPORT void
1167 ves_icall_ModuleBuilder_WriteToFile (MonoReflectionModuleBuilder *mb, HANDLE file)
1168 {
1169         mono_image_create_pefile (mb, file);
1170 }
1171
1172 ICALL_EXPORT void
1173 ves_icall_ModuleBuilder_build_metadata (MonoReflectionModuleBuilder *mb)
1174 {
1175         mono_image_build_metadata (mb);
1176 }
1177
1178 ICALL_EXPORT void
1179 ves_icall_ModuleBuilder_RegisterToken (MonoReflectionModuleBuilder *mb, MonoObject *obj, guint32 token)
1180 {
1181         mono_image_register_token (mb->dynamic_image, token, obj);
1182 }
1183
1184 static gboolean
1185 get_caller (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1186 {
1187         MonoMethod **dest = data;
1188
1189         /* skip unmanaged frames */
1190         if (!managed)
1191                 return FALSE;
1192
1193         if (m == *dest) {
1194                 *dest = NULL;
1195                 return FALSE;
1196         }
1197         if (!(*dest)) {
1198                 *dest = m;
1199                 return TRUE;
1200         }
1201         return FALSE;
1202 }
1203
1204 static gboolean
1205 get_executing (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1206 {
1207         MonoMethod **dest = data;
1208
1209         /* skip unmanaged frames */
1210         if (!managed)
1211                 return FALSE;
1212
1213         if (!(*dest)) {
1214                 if (!strcmp (m->klass->name_space, "System.Reflection"))
1215                         return FALSE;
1216                 *dest = m;
1217                 return TRUE;
1218         }
1219         return FALSE;
1220 }
1221
1222 static gboolean
1223 get_caller_no_reflection (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
1224 {
1225         MonoMethod **dest = data;
1226
1227         /* skip unmanaged frames */
1228         if (!managed)
1229                 return FALSE;
1230
1231         if (m->wrapper_type != MONO_WRAPPER_NONE)
1232                 return FALSE;
1233
1234         if (m->klass->image == mono_defaults.corlib && !strcmp (m->klass->name_space, "System.Reflection"))
1235                 return FALSE;
1236
1237         if (m == *dest) {
1238                 *dest = NULL;
1239                 return FALSE;
1240         }
1241         if (!(*dest)) {
1242                 *dest = m;
1243                 return TRUE;
1244         }
1245         return FALSE;
1246 }
1247
1248 static MonoReflectionType *
1249 type_from_name (const char *str, MonoBoolean ignoreCase)
1250 {
1251         MonoMethod *m, *dest;
1252
1253         MonoType *type = NULL;
1254         MonoAssembly *assembly = NULL;
1255         MonoTypeNameParse info;
1256         char *temp_str = g_strdup (str);
1257         gboolean type_resolve = FALSE;
1258
1259         /* mono_reflection_parse_type() mangles the string */
1260         if (!mono_reflection_parse_type (temp_str, &info)) {
1261                 mono_reflection_free_type_info (&info);
1262                 g_free (temp_str);
1263                 return NULL;
1264         }
1265
1266
1267         /*
1268          * We must compute the calling assembly as type loading must happen under a metadata context.
1269          * For example. The main assembly is a.exe and Type.GetType is called from dir/b.dll. Without
1270          * the metadata context (basedir currently) set to dir/b.dll we won't be able to load a dir/c.dll.
1271          */
1272         m = mono_method_get_last_managed ();
1273         dest = m;
1274
1275         mono_stack_walk_no_il (get_caller_no_reflection, &dest);
1276         if (!dest)
1277                 dest = m;
1278
1279         /*
1280          * FIXME: mono_method_get_last_managed() sometimes returns NULL, thus
1281          *        causing ves_icall_System_Reflection_Assembly_GetCallingAssembly()
1282          *        to crash.  This only seems to happen in some strange remoting
1283          *        scenarios and I was unable to figure out what's happening there.
1284          *        Dec 10, 2005 - Martin.
1285          */
1286
1287         if (dest) {
1288                 assembly = dest->klass->image->assembly;
1289                 type_resolve = TRUE;
1290         } else {
1291                 g_warning (G_STRLOC);
1292         }
1293
1294         if (info.assembly.name)
1295                 assembly = mono_assembly_load (&info.assembly, assembly ? assembly->basedir : NULL, NULL);
1296
1297
1298         if (assembly) {
1299                 /* When loading from the current assembly, AppDomain.TypeResolve will not be called yet */
1300                 type = mono_reflection_get_type (assembly->image, &info, ignoreCase, &type_resolve);
1301         }
1302
1303         if (!info.assembly.name && !type) /* try mscorlib */
1304                 type = mono_reflection_get_type (NULL, &info, ignoreCase, &type_resolve);
1305
1306         if (assembly && !type && type_resolve) {
1307                 type_resolve = FALSE; /* This will invoke TypeResolve if not done in the first 'if' */
1308                 type = mono_reflection_get_type (assembly->image, &info, ignoreCase, &type_resolve);
1309         }
1310
1311         mono_reflection_free_type_info (&info);
1312         g_free (temp_str);
1313
1314         if (!type) 
1315                 return NULL;
1316
1317         return mono_type_get_object (mono_domain_get (), type);
1318 }
1319
1320 #ifdef UNUSED
1321 MonoReflectionType *
1322 mono_type_get (const char *str)
1323 {
1324         char *copy = g_strdup (str);
1325         MonoReflectionType *type = type_from_name (copy, FALSE);
1326
1327         g_free (copy);
1328         return type;
1329 }
1330 #endif
1331
1332 ICALL_EXPORT MonoReflectionType*
1333 ves_icall_type_from_name (MonoString *name,
1334                           MonoBoolean throwOnError,
1335                           MonoBoolean ignoreCase)
1336 {
1337         char *str = mono_string_to_utf8 (name);
1338         MonoReflectionType *type;
1339
1340         type = type_from_name (str, ignoreCase);
1341         g_free (str);
1342         if (type == NULL){
1343                 MonoException *e = NULL;
1344                 
1345                 if (throwOnError)
1346                         e = mono_get_exception_type_load (name, NULL);
1347
1348                 mono_loader_clear_error ();
1349                 if (e) {
1350                         mono_set_pending_exception (e);
1351                         return NULL;
1352                 }
1353         }
1354         
1355         return type;
1356 }
1357
1358
1359 ICALL_EXPORT MonoReflectionType*
1360 ves_icall_type_from_handle (MonoType *handle)
1361 {
1362         MonoDomain *domain = mono_domain_get (); 
1363
1364         return mono_type_get_object (domain, handle);
1365 }
1366
1367 ICALL_EXPORT MonoBoolean
1368 ves_icall_System_Type_EqualsInternal (MonoReflectionType *type, MonoReflectionType *c)
1369 {
1370         if (c && type->type && c->type)
1371                 return mono_metadata_type_equal (type->type, c->type);
1372         else
1373                 return (type == c) ? TRUE : FALSE;
1374 }
1375
1376 /* System.TypeCode */
1377 typedef enum {
1378         TYPECODE_EMPTY,
1379         TYPECODE_OBJECT,
1380         TYPECODE_DBNULL,
1381         TYPECODE_BOOLEAN,
1382         TYPECODE_CHAR,
1383         TYPECODE_SBYTE,
1384         TYPECODE_BYTE,
1385         TYPECODE_INT16,
1386         TYPECODE_UINT16,
1387         TYPECODE_INT32,
1388         TYPECODE_UINT32,
1389         TYPECODE_INT64,
1390         TYPECODE_UINT64,
1391         TYPECODE_SINGLE,
1392         TYPECODE_DOUBLE,
1393         TYPECODE_DECIMAL,
1394         TYPECODE_DATETIME,
1395         TYPECODE_STRING = 18
1396 } TypeCode;
1397
1398 ICALL_EXPORT guint32
1399 ves_icall_type_GetTypeCodeInternal (MonoReflectionType *type)
1400 {
1401         int t = type->type->type;
1402
1403         if (type->type->byref)
1404                 return TYPECODE_OBJECT;
1405
1406 handle_enum:
1407         switch (t) {
1408         case MONO_TYPE_VOID:
1409                 return TYPECODE_OBJECT;
1410         case MONO_TYPE_BOOLEAN:
1411                 return TYPECODE_BOOLEAN;
1412         case MONO_TYPE_U1:
1413                 return TYPECODE_BYTE;
1414         case MONO_TYPE_I1:
1415                 return TYPECODE_SBYTE;
1416         case MONO_TYPE_U2:
1417                 return TYPECODE_UINT16;
1418         case MONO_TYPE_I2:
1419                 return TYPECODE_INT16;
1420         case MONO_TYPE_CHAR:
1421                 return TYPECODE_CHAR;
1422         case MONO_TYPE_PTR:
1423         case MONO_TYPE_U:
1424         case MONO_TYPE_I:
1425                 return TYPECODE_OBJECT;
1426         case MONO_TYPE_U4:
1427                 return TYPECODE_UINT32;
1428         case MONO_TYPE_I4:
1429                 return TYPECODE_INT32;
1430         case MONO_TYPE_U8:
1431                 return TYPECODE_UINT64;
1432         case MONO_TYPE_I8:
1433                 return TYPECODE_INT64;
1434         case MONO_TYPE_R4:
1435                 return TYPECODE_SINGLE;
1436         case MONO_TYPE_R8:
1437                 return TYPECODE_DOUBLE;
1438         case MONO_TYPE_VALUETYPE: {
1439                 MonoClass *klass = type->type->data.klass;
1440                 
1441                 if (klass->enumtype) {
1442                         t = mono_class_enum_basetype (klass)->type;
1443                         goto handle_enum;
1444                 } else if (mono_is_corlib_image (klass->image)) {
1445                         if (strcmp (klass->name_space, "System") == 0) {
1446                                 if (strcmp (klass->name, "Decimal") == 0)
1447                                         return TYPECODE_DECIMAL;
1448                                 else if (strcmp (klass->name, "DateTime") == 0)
1449                                         return TYPECODE_DATETIME;
1450                         }
1451                 }
1452                 return TYPECODE_OBJECT;
1453         }
1454         case MONO_TYPE_STRING:
1455                 return TYPECODE_STRING;
1456         case MONO_TYPE_SZARRAY:
1457         case MONO_TYPE_ARRAY:
1458         case MONO_TYPE_OBJECT:
1459         case MONO_TYPE_VAR:
1460         case MONO_TYPE_MVAR:
1461         case MONO_TYPE_TYPEDBYREF:
1462                 return TYPECODE_OBJECT;
1463         case MONO_TYPE_CLASS:
1464                 {
1465                         MonoClass *klass =  type->type->data.klass;
1466                         if (klass->image == mono_defaults.corlib && strcmp (klass->name_space, "System") == 0) {
1467                                 if (strcmp (klass->name, "DBNull") == 0)
1468                                         return TYPECODE_DBNULL;
1469                         }
1470                 }
1471                 return TYPECODE_OBJECT;
1472         case MONO_TYPE_GENERICINST:
1473                 return TYPECODE_OBJECT;
1474         default:
1475                 g_error ("type 0x%02x not handled in GetTypeCode()", t);
1476         }
1477         return 0;
1478 }
1479
1480 ICALL_EXPORT guint32
1481 ves_icall_type_is_subtype_of (MonoReflectionType *type, MonoReflectionType *c, MonoBoolean check_interfaces)
1482 {
1483         MonoDomain *domain; 
1484         MonoClass *klass;
1485         MonoClass *klassc;
1486
1487         g_assert (type != NULL);
1488         
1489         domain = ((MonoObject *)type)->vtable->domain;
1490
1491         if (!c) /* FIXME: dont know what do do here */
1492                 return 0;
1493
1494         klass = mono_class_from_mono_type (type->type);
1495         klassc = mono_class_from_mono_type (c->type);
1496
1497         /* Interface check requires a more complex setup so we
1498          * only do for them. Otherwise we simply avoid mono_class_init.
1499          */
1500         if (check_interfaces) {
1501                 mono_class_init_or_throw (klass);
1502                 mono_class_init_or_throw (klassc);
1503         } else if (!klass->supertypes || !klassc->supertypes) {
1504                 mono_class_setup_supertypes (klass);
1505                 mono_class_setup_supertypes (klassc);
1506         }
1507
1508         if (type->type->byref)
1509                 return klassc == mono_defaults.object_class;
1510
1511         return mono_class_is_subclass_of (klass, klassc, check_interfaces);
1512 }
1513
1514 static gboolean
1515 mono_type_is_primitive (MonoType *type)
1516 {
1517         return (type->type >= MONO_TYPE_BOOLEAN && type->type <= MONO_TYPE_R8) ||
1518                         type-> type == MONO_TYPE_I || type->type == MONO_TYPE_U;
1519 }
1520
1521 static MonoType*
1522 mono_type_get_underlying_type_ignore_byref (MonoType *type)
1523 {
1524         if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
1525                 return mono_class_enum_basetype (type->data.klass);
1526         if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
1527                 return mono_class_enum_basetype (type->data.generic_class->container_class);
1528         return type;
1529 }
1530
1531 ICALL_EXPORT guint32
1532 ves_icall_type_is_assignable_from (MonoReflectionType *type, MonoReflectionType *c)
1533 {
1534         MonoDomain *domain; 
1535         MonoClass *klass;
1536         MonoClass *klassc;
1537
1538         g_assert (type != NULL);
1539         
1540         domain = ((MonoObject *)type)->vtable->domain;
1541
1542         klass = mono_class_from_mono_type (type->type);
1543         klassc = mono_class_from_mono_type (c->type);
1544
1545         if (type->type->byref ^ c->type->byref)
1546                 return FALSE;
1547
1548         if (type->type->byref) {
1549                 MonoType *t = mono_type_get_underlying_type_ignore_byref (type->type);
1550                 MonoType *ot = mono_type_get_underlying_type_ignore_byref (c->type);
1551
1552                 klass = mono_class_from_mono_type (t);
1553                 klassc = mono_class_from_mono_type (ot);
1554
1555                 if (mono_type_is_primitive (t)) {
1556                         return mono_type_is_primitive (ot) && klass->instance_size == klassc->instance_size;
1557                 } else if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) {
1558                         return t->type == ot->type && t->data.generic_param->num == ot->data.generic_param->num;
1559                 } else if (t->type == MONO_TYPE_PTR || t->type == MONO_TYPE_FNPTR) {
1560                         return t->type == ot->type;
1561                 } else {
1562                          if (ot->type == MONO_TYPE_VAR || ot->type == MONO_TYPE_MVAR)
1563                                  return FALSE;
1564
1565                          if (klass->valuetype)
1566                                 return klass == klassc;
1567                         return klass->valuetype == klassc->valuetype;
1568                 }
1569         }
1570         return mono_class_is_assignable_from (klass, klassc);
1571 }
1572
1573 ICALL_EXPORT guint32
1574 ves_icall_type_IsInstanceOfType (MonoReflectionType *type, MonoObject *obj)
1575 {
1576         MonoClass *klass = mono_class_from_mono_type (type->type);
1577         mono_class_init_or_throw (klass);
1578         return mono_object_isinst (obj, klass) != NULL;
1579 }
1580
1581 ICALL_EXPORT guint32
1582 ves_icall_get_attributes (MonoReflectionType *type)
1583 {
1584         MonoClass *klass = mono_class_from_mono_type (type->type);
1585         return klass->flags;
1586 }
1587
1588 ICALL_EXPORT MonoReflectionMarshalAsAttribute*
1589 ves_icall_System_Reflection_FieldInfo_get_marshal_info (MonoReflectionField *field)
1590 {
1591         MonoClass *klass = field->field->parent;
1592         MonoMarshalType *info;
1593         MonoType *ftype;
1594         int i;
1595
1596         if (klass->generic_container ||
1597             (klass->generic_class && klass->generic_class->context.class_inst->is_open))
1598                 return NULL;
1599
1600         ftype = mono_field_get_type (field->field);
1601         if (ftype && !(ftype->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL))
1602                 return NULL;
1603
1604         info = mono_marshal_load_type_info (klass);
1605
1606         for (i = 0; i < info->num_fields; ++i) {
1607                 if (info->fields [i].field == field->field) {
1608                         if (!info->fields [i].mspec)
1609                                 return NULL;
1610                         else
1611                                 return mono_reflection_marshal_as_attribute_from_marshal_spec (field->object.vtable->domain, klass, info->fields [i].mspec);
1612                 }
1613         }
1614
1615         return NULL;
1616 }
1617
1618 ICALL_EXPORT MonoReflectionField*
1619 ves_icall_System_Reflection_FieldInfo_internal_from_handle_type (MonoClassField *handle, MonoType *type)
1620 {
1621         gboolean found = FALSE;
1622         MonoClass *klass;
1623         MonoClass *k;
1624
1625         g_assert (handle);
1626
1627         if (!type) {
1628                 klass = handle->parent;
1629         } else {
1630                 klass = mono_class_from_mono_type (type);
1631
1632                 /* Check that the field belongs to the class */
1633                 for (k = klass; k; k = k->parent) {
1634                         if (k == handle->parent) {
1635                                 found = TRUE;
1636                                 break;
1637                         }
1638                 }
1639
1640                 if (!found)
1641                         /* The managed code will throw the exception */
1642                         return NULL;
1643         }
1644
1645         return mono_field_get_object (mono_domain_get (), klass, handle);
1646 }
1647
1648 ICALL_EXPORT MonoArray*
1649 ves_icall_System_Reflection_FieldInfo_GetTypeModifiers (MonoReflectionField *field, MonoBoolean optional)
1650 {
1651         MonoError error;
1652         MonoType *type = mono_field_get_type_checked (field->field, &error);
1653         mono_error_raise_exception (&error);
1654
1655         return type_array_from_modifiers (field->field->parent->image, type, optional);
1656 }
1657
1658 ICALL_EXPORT int
1659 vell_icall_get_method_attributes (MonoMethod *method)
1660 {
1661         return method->flags;
1662 }
1663
1664 ICALL_EXPORT void
1665 ves_icall_get_method_info (MonoMethod *method, MonoMethodInfo *info)
1666 {
1667         MonoError error;
1668         MonoDomain *domain = mono_domain_get ();
1669         MonoMethodSignature* sig;
1670
1671         sig = mono_method_signature_checked (method, &error);
1672         if (!mono_error_ok (&error))
1673                 mono_error_raise_exception (&error);
1674
1675
1676         MONO_STRUCT_SETREF (info, parent, mono_type_get_object (domain, &method->klass->byval_arg));
1677         MONO_STRUCT_SETREF (info, ret, mono_type_get_object (domain, sig->ret));
1678         info->attrs = method->flags;
1679         info->implattrs = method->iflags;
1680         if (sig->call_convention == MONO_CALL_DEFAULT)
1681                 info->callconv = sig->sentinelpos >= 0 ? 2 : 1;
1682         else {
1683                 if (sig->call_convention == MONO_CALL_VARARG || sig->sentinelpos >= 0)
1684                         info->callconv = 2;
1685                 else
1686                         info->callconv = 1;
1687         }
1688         info->callconv |= (sig->hasthis << 5) | (sig->explicit_this << 6); 
1689 }
1690
1691 ICALL_EXPORT MonoArray*
1692 ves_icall_get_parameter_info (MonoMethod *method, MonoReflectionMethod *member)
1693 {
1694         MonoDomain *domain = mono_domain_get (); 
1695
1696         return mono_param_get_objects_internal (domain, method, member->reftype ? mono_class_from_mono_type (member->reftype->type) : NULL);
1697 }
1698
1699 ICALL_EXPORT MonoReflectionMarshalAsAttribute*
1700 ves_icall_System_MonoMethodInfo_get_retval_marshal (MonoMethod *method)
1701 {
1702         MonoDomain *domain = mono_domain_get (); 
1703         MonoReflectionMarshalAsAttribute* res = NULL;
1704         MonoMarshalSpec **mspecs;
1705         int i;
1706
1707         mspecs = g_new (MonoMarshalSpec*, mono_method_signature (method)->param_count + 1);
1708         mono_method_get_marshal_info (method, mspecs);
1709
1710         if (mspecs [0])
1711                 res = mono_reflection_marshal_as_attribute_from_marshal_spec (domain, method->klass, mspecs [0]);
1712                 
1713         for (i = mono_method_signature (method)->param_count; i >= 0; i--)
1714                 if (mspecs [i])
1715                         mono_metadata_free_marshal_spec (mspecs [i]);
1716         g_free (mspecs);
1717
1718         return res;
1719 }
1720
1721 ICALL_EXPORT gint32
1722 ves_icall_MonoField_GetFieldOffset (MonoReflectionField *field)
1723 {
1724         MonoClass *parent = field->field->parent;
1725         if (!parent->size_inited)
1726                 mono_class_init (parent);
1727         mono_class_setup_fields_locking (parent);
1728
1729         return field->field->offset - sizeof (MonoObject);
1730 }
1731
1732 ICALL_EXPORT MonoReflectionType*
1733 ves_icall_MonoField_GetParentType (MonoReflectionField *field, MonoBoolean declaring)
1734 {
1735         MonoClass *parent;
1736
1737         parent = declaring? field->field->parent: field->klass;
1738
1739         return mono_type_get_object (mono_object_domain (field), &parent->byval_arg);
1740 }
1741
1742 ICALL_EXPORT MonoObject *
1743 ves_icall_MonoField_GetValueInternal (MonoReflectionField *field, MonoObject *obj)
1744 {       
1745         MonoClass *fklass = field->klass;
1746         MonoClassField *cf = field->field;
1747         MonoDomain *domain = mono_object_domain (field);
1748
1749         if (fklass->image->assembly->ref_only) {
1750                 mono_set_pending_exception (mono_get_exception_invalid_operation (
1751                                         "It is illegal to get the value on a field on a type loaded using the ReflectionOnly methods."));
1752                 return NULL;
1753         }
1754
1755         if (mono_security_core_clr_enabled ())
1756                 mono_security_core_clr_ensure_reflection_access_field (cf);
1757
1758         return mono_field_get_value_object (domain, cf, obj);
1759 }
1760
1761 ICALL_EXPORT void
1762 ves_icall_MonoField_SetValueInternal (MonoReflectionField *field, MonoObject *obj, MonoObject *value)
1763 {
1764         MonoError error;
1765         MonoClassField *cf = field->field;
1766         MonoType *type;
1767         gchar *v;
1768
1769         if (field->klass->image->assembly->ref_only) {
1770                 mono_set_pending_exception (mono_get_exception_invalid_operation (
1771                                         "It is illegal to set the value on a field on a type loaded using the ReflectionOnly methods."));
1772                 return;
1773         }
1774
1775         if (mono_security_core_clr_enabled ())
1776                 mono_security_core_clr_ensure_reflection_access_field (cf);
1777
1778         type = mono_field_get_type_checked (cf, &error);
1779         if (!mono_error_ok (&error))
1780                 mono_error_raise_exception (&error);
1781
1782         v = (gchar *) value;
1783         if (!type->byref) {
1784                 switch (type->type) {
1785                 case MONO_TYPE_U1:
1786                 case MONO_TYPE_I1:
1787                 case MONO_TYPE_BOOLEAN:
1788                 case MONO_TYPE_U2:
1789                 case MONO_TYPE_I2:
1790                 case MONO_TYPE_CHAR:
1791                 case MONO_TYPE_U:
1792                 case MONO_TYPE_I:
1793                 case MONO_TYPE_U4:
1794                 case MONO_TYPE_I4:
1795                 case MONO_TYPE_R4:
1796                 case MONO_TYPE_U8:
1797                 case MONO_TYPE_I8:
1798                 case MONO_TYPE_R8:
1799                 case MONO_TYPE_VALUETYPE:
1800                 case MONO_TYPE_PTR:
1801                         if (v != NULL)
1802                                 v += sizeof (MonoObject);
1803                         break;
1804                 case MONO_TYPE_STRING:
1805                 case MONO_TYPE_OBJECT:
1806                 case MONO_TYPE_CLASS:
1807                 case MONO_TYPE_ARRAY:
1808                 case MONO_TYPE_SZARRAY:
1809                         /* Do nothing */
1810                         break;
1811                 case MONO_TYPE_GENERICINST: {
1812                         MonoGenericClass *gclass = type->data.generic_class;
1813                         g_assert (!gclass->context.class_inst->is_open);
1814
1815                         if (mono_class_is_nullable (mono_class_from_mono_type (type))) {
1816                                 MonoClass *nklass = mono_class_from_mono_type (type);
1817                                 MonoObject *nullable;
1818
1819                                 /* 
1820                                  * Convert the boxed vtype into a Nullable structure.
1821                                  * This is complicated by the fact that Nullables have
1822                                  * a variable structure.
1823                                  */
1824                                 nullable = mono_object_new (mono_domain_get (), nklass);
1825
1826                                 mono_nullable_init (mono_object_unbox (nullable), value, nklass);
1827
1828                                 v = mono_object_unbox (nullable);
1829                         }
1830                         else 
1831                                 if (gclass->container_class->valuetype && (v != NULL))
1832                                         v += sizeof (MonoObject);
1833                         break;
1834                 }
1835                 default:
1836                         g_error ("type 0x%x not handled in "
1837                                  "ves_icall_FieldInfo_SetValueInternal", type->type);
1838                         return;
1839                 }
1840         }
1841
1842         if (type->attrs & FIELD_ATTRIBUTE_STATIC) {
1843                 MonoVTable *vtable = mono_class_vtable_full (mono_object_domain (field), cf->parent, TRUE);
1844                 if (!vtable->initialized)
1845                         mono_runtime_class_init (vtable);
1846                 mono_field_static_set_value (vtable, cf, v);
1847         } else {
1848                 mono_field_set_value (obj, cf, v);
1849         }
1850 }
1851
1852 ICALL_EXPORT MonoObject *
1853 ves_icall_MonoField_GetRawConstantValue (MonoReflectionField *this)
1854 {       
1855         MonoObject *o = NULL;
1856         MonoClassField *field = this->field;
1857         MonoClass *klass;
1858         MonoDomain *domain = mono_object_domain (this); 
1859         gchar *v;
1860         MonoTypeEnum def_type;
1861         const char *def_value;
1862         MonoType *t;
1863         MonoError error;
1864
1865         mono_class_init (field->parent);
1866
1867         t = mono_field_get_type_checked (field, &error);
1868         if (!mono_error_ok (&error))
1869                 mono_error_raise_exception (&error);
1870
1871         if (!(t->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT)) {
1872                 mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
1873                 return NULL;
1874         }
1875
1876         if (image_is_dynamic (field->parent->image)) {
1877                 MonoClass *klass = field->parent;
1878                 int fidx = field - klass->fields;
1879
1880                 g_assert (fidx >= 0 && fidx < klass->field.count);
1881                 g_assert (klass->ext);
1882                 g_assert (klass->ext->field_def_values);
1883                 def_type = klass->ext->field_def_values [fidx].def_type;
1884                 def_value = klass->ext->field_def_values [fidx].data;
1885                 if (def_type == MONO_TYPE_END) {
1886                         mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
1887                         return NULL;
1888                 }
1889         } else {
1890                 def_value = mono_class_get_field_default_value (field, &def_type);
1891                 /* FIXME, maybe we should try to raise TLE if field->parent is broken */
1892                 if (!def_value) {
1893                         mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
1894                         return NULL;
1895                 }
1896         }
1897
1898         /*FIXME unify this with reflection.c:mono_get_object_from_blob*/
1899         switch (def_type) {
1900         case MONO_TYPE_U1:
1901         case MONO_TYPE_I1:
1902         case MONO_TYPE_BOOLEAN:
1903         case MONO_TYPE_U2:
1904         case MONO_TYPE_I2:
1905         case MONO_TYPE_CHAR:
1906         case MONO_TYPE_U:
1907         case MONO_TYPE_I:
1908         case MONO_TYPE_U4:
1909         case MONO_TYPE_I4:
1910         case MONO_TYPE_R4:
1911         case MONO_TYPE_U8:
1912         case MONO_TYPE_I8:
1913         case MONO_TYPE_R8: {
1914                 MonoType *t;
1915
1916                 /* boxed value type */
1917                 t = g_new0 (MonoType, 1);
1918                 t->type = def_type;
1919                 klass = mono_class_from_mono_type (t);
1920                 g_free (t);
1921                 o = mono_object_new (domain, klass);
1922                 v = ((gchar *) o) + sizeof (MonoObject);
1923                 mono_get_constant_value_from_blob (domain, def_type, def_value, v);
1924                 break;
1925         }
1926         case MONO_TYPE_STRING:
1927         case MONO_TYPE_CLASS:
1928                 mono_get_constant_value_from_blob (domain, def_type, def_value, &o);
1929                 break;
1930         default:
1931                 g_assert_not_reached ();
1932         }
1933
1934         return o;
1935 }
1936
1937 ICALL_EXPORT MonoReflectionType*
1938 ves_icall_MonoField_ResolveType (MonoReflectionField *ref_field)
1939 {
1940         MonoError error;
1941         MonoClassField *field = ref_field->field;
1942         MonoType *type = mono_field_get_type_checked (field, &error);
1943         if (!mono_error_ok (&error))
1944                 mono_error_raise_exception (&error);
1945         return mono_type_get_object (mono_object_domain (ref_field), type);
1946 }
1947
1948 ICALL_EXPORT MonoReflectionType*
1949 ves_icall_MonoGenericMethod_get_ReflectedType (MonoReflectionGenericMethod *rmethod)
1950 {
1951         MonoMethod *method = rmethod->method.method;
1952
1953         return mono_type_get_object (mono_object_domain (rmethod), &method->klass->byval_arg);
1954 }
1955
1956 /* From MonoProperty.cs */
1957 typedef enum {
1958         PInfo_Attributes = 1,
1959         PInfo_GetMethod  = 1 << 1,
1960         PInfo_SetMethod  = 1 << 2,
1961         PInfo_ReflectedType = 1 << 3,
1962         PInfo_DeclaringType = 1 << 4,
1963         PInfo_Name = 1 << 5
1964 } PInfo;
1965
1966 ICALL_EXPORT void
1967 ves_icall_get_property_info (MonoReflectionProperty *property, MonoPropertyInfo *info, PInfo req_info)
1968 {
1969         MonoDomain *domain = mono_object_domain (property); 
1970
1971         if ((req_info & PInfo_ReflectedType) != 0)
1972                 MONO_STRUCT_SETREF (info, parent, mono_type_get_object (domain, &property->klass->byval_arg));
1973         if ((req_info & PInfo_DeclaringType) != 0)
1974                 MONO_STRUCT_SETREF (info, declaring_type, mono_type_get_object (domain, &property->property->parent->byval_arg));
1975
1976         if ((req_info & PInfo_Name) != 0)
1977                 MONO_STRUCT_SETREF (info, name, mono_string_new (domain, property->property->name));
1978
1979         if ((req_info & PInfo_Attributes) != 0)
1980                 info->attrs = property->property->attrs;
1981
1982         if ((req_info & PInfo_GetMethod) != 0)
1983                 MONO_STRUCT_SETREF (info, get, property->property->get ?
1984                                                         mono_method_get_object (domain, property->property->get, property->klass): NULL);
1985         
1986         if ((req_info & PInfo_SetMethod) != 0)
1987                 MONO_STRUCT_SETREF (info, set, property->property->set ?
1988                                                         mono_method_get_object (domain, property->property->set, property->klass): NULL);
1989         /* 
1990          * There may be other methods defined for properties, though, it seems they are not exposed 
1991          * in the reflection API 
1992          */
1993 }
1994
1995 ICALL_EXPORT void
1996 ves_icall_get_event_info (MonoReflectionMonoEvent *event, MonoEventInfo *info)
1997 {
1998         MonoDomain *domain = mono_object_domain (event); 
1999
2000         MONO_STRUCT_SETREF (info, reflected_type, mono_type_get_object (domain, &event->klass->byval_arg));
2001         MONO_STRUCT_SETREF (info, declaring_type, mono_type_get_object (domain, &event->event->parent->byval_arg));
2002
2003         MONO_STRUCT_SETREF (info, name, mono_string_new (domain, event->event->name));
2004         info->attrs = event->event->attrs;
2005         MONO_STRUCT_SETREF (info, add_method, event->event->add ? mono_method_get_object (domain, event->event->add, NULL): NULL);
2006         MONO_STRUCT_SETREF (info, remove_method, event->event->remove ? mono_method_get_object (domain, event->event->remove, NULL): NULL);
2007         MONO_STRUCT_SETREF (info, raise_method, event->event->raise ? mono_method_get_object (domain, event->event->raise, NULL): NULL);
2008
2009 #ifndef MONO_SMALL_CONFIG
2010         if (event->event->other) {
2011                 int i, n = 0;
2012                 while (event->event->other [n])
2013                         n++;
2014                 MONO_STRUCT_SETREF (info, other_methods, mono_array_new (domain, mono_defaults.method_info_class, n));
2015
2016                 for (i = 0; i < n; i++)
2017                         mono_array_setref (info->other_methods, i, mono_method_get_object (domain, event->event->other [i], NULL));
2018         }               
2019 #endif
2020 }
2021
2022 static void
2023 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
2024 {
2025         int i;
2026         MonoClass *ic;
2027
2028         mono_class_setup_interfaces (klass, error);
2029         if (!mono_error_ok (error))
2030                 return;
2031
2032         for (i = 0; i < klass->interface_count; i++) {
2033                 ic = klass->interfaces [i];
2034                 g_hash_table_insert (ifaces, ic, ic);
2035
2036                 collect_interfaces (ic, ifaces, error);
2037                 if (!mono_error_ok (error))
2038                         return;
2039         }
2040 }
2041
2042 typedef struct {
2043         MonoArray *iface_array;
2044         MonoGenericContext *context;
2045         MonoError *error;
2046         MonoDomain *domain;
2047         int next_idx;
2048 } FillIfaceArrayData;
2049
2050 static void
2051 fill_iface_array (gpointer key, gpointer value, gpointer user_data)
2052 {
2053         FillIfaceArrayData *data = user_data;
2054         MonoClass *ic = key;
2055         MonoType *ret = &ic->byval_arg, *inflated = NULL;
2056
2057         if (!mono_error_ok (data->error))
2058                 return;
2059
2060         if (data->context && ic->generic_class && ic->generic_class->context.class_inst->is_open) {
2061                 inflated = ret = mono_class_inflate_generic_type_checked (ret, data->context, data->error);
2062                 if (!mono_error_ok (data->error))
2063                         return;
2064         }
2065
2066         mono_array_setref (data->iface_array, data->next_idx++, mono_type_get_object (data->domain, ret));
2067
2068         if (inflated)
2069                 mono_metadata_free_type (inflated);
2070 }
2071
2072 ICALL_EXPORT MonoArray*
2073 ves_icall_Type_GetInterfaces (MonoReflectionType* type)
2074 {
2075         MonoError error;
2076         MonoClass *class = mono_class_from_mono_type (type->type);
2077         MonoClass *parent;
2078         FillIfaceArrayData data = { 0 };
2079         int len;
2080
2081         GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
2082
2083         if (class->generic_class && class->generic_class->context.class_inst->is_open) {
2084                 data.context = mono_class_get_context (class);
2085                 class = class->generic_class->container_class;
2086         }
2087
2088         for (parent = class; parent; parent = parent->parent) {
2089                 mono_class_setup_interfaces (parent, &error);
2090                 if (!mono_error_ok (&error))
2091                         goto fail;
2092                 collect_interfaces (parent, iface_hash, &error);
2093                 if (!mono_error_ok (&error))
2094                         goto fail;
2095         }
2096
2097         data.error = &error;
2098         data.domain = mono_object_domain (type);
2099
2100         len = g_hash_table_size (iface_hash);
2101         if (len == 0) {
2102                 g_hash_table_destroy (iface_hash);
2103                 if (!data.domain->empty_types)
2104                         data.domain->empty_types = mono_array_new_cached (data.domain, mono_defaults.monotype_class, 0);
2105                 return data.domain->empty_types;
2106         }
2107
2108         data.iface_array = mono_array_new_cached (data.domain, mono_defaults.monotype_class, len);
2109         g_hash_table_foreach (iface_hash, fill_iface_array, &data);
2110         if (!mono_error_ok (&error))
2111                 goto fail;
2112
2113         g_hash_table_destroy (iface_hash);
2114         return data.iface_array;
2115
2116 fail:
2117         g_hash_table_destroy (iface_hash);
2118         mono_error_raise_exception (&error);
2119         return NULL;
2120 }
2121
2122 ICALL_EXPORT void
2123 ves_icall_Type_GetInterfaceMapData (MonoReflectionType *type, MonoReflectionType *iface, MonoArray **targets, MonoArray **methods)
2124 {
2125         gboolean variance_used;
2126         MonoClass *class = mono_class_from_mono_type (type->type);
2127         MonoClass *iclass = mono_class_from_mono_type (iface->type);
2128         MonoReflectionMethod *member;
2129         MonoMethod* method;
2130         gpointer iter;
2131         int i = 0, len, ioffset;
2132         MonoDomain *domain;
2133
2134         mono_class_init_or_throw (class);
2135         mono_class_init_or_throw (iclass);
2136
2137         mono_class_setup_vtable (class);
2138
2139         ioffset = mono_class_interface_offset_with_variance (class, iclass, &variance_used);
2140         if (ioffset == -1)
2141                 return;
2142
2143         len = mono_class_num_methods (iclass);
2144         domain = mono_object_domain (type);
2145         mono_gc_wbarrier_generic_store (targets, (MonoObject*) mono_array_new (domain, mono_defaults.method_info_class, len));
2146         mono_gc_wbarrier_generic_store (methods, (MonoObject*) mono_array_new (domain, mono_defaults.method_info_class, len));
2147         iter = NULL;
2148         while ((method = mono_class_get_methods (iclass, &iter))) {
2149                 member = mono_method_get_object (domain, method, iclass);
2150                 mono_array_setref (*methods, i, member);
2151                 member = mono_method_get_object (domain, class->vtable [i + ioffset], class);
2152                 mono_array_setref (*targets, i, member);
2153                 
2154                 i ++;
2155         }
2156 }
2157
2158 ICALL_EXPORT void
2159 ves_icall_Type_GetPacking (MonoReflectionType *type, guint32 *packing, guint32 *size)
2160 {
2161         MonoClass *klass = mono_class_from_mono_type (type->type);
2162         mono_class_init_or_throw (klass);
2163
2164         if (image_is_dynamic (klass->image)) {
2165                 MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)type;
2166                 *packing = tb->packing_size;
2167                 *size = tb->class_size;
2168         } else {
2169                 mono_metadata_packing_from_typedef (klass->image, klass->type_token, packing, size);
2170         }
2171 }
2172
2173 ICALL_EXPORT MonoReflectionType*
2174 ves_icall_MonoType_GetElementType (MonoReflectionType *type)
2175 {
2176         MonoClass *class;
2177
2178         if (!type->type->byref && type->type->type == MONO_TYPE_SZARRAY)
2179                 return mono_type_get_object (mono_object_domain (type), &type->type->data.klass->byval_arg);
2180
2181         class = mono_class_from_mono_type (type->type);
2182         mono_class_init_or_throw (class);
2183
2184         // GetElementType should only return a type for:
2185         // Array Pointer PassedByRef
2186         if (type->type->byref)
2187                 return mono_type_get_object (mono_object_domain (type), &class->byval_arg);
2188         else if (class->element_class && MONO_CLASS_IS_ARRAY (class))
2189                 return mono_type_get_object (mono_object_domain (type), &class->element_class->byval_arg);
2190         else if (class->element_class && type->type->type == MONO_TYPE_PTR)
2191                 return mono_type_get_object (mono_object_domain (type), &class->element_class->byval_arg);
2192         else
2193                 return NULL;
2194 }
2195
2196 ICALL_EXPORT MonoReflectionType*
2197 ves_icall_get_type_parent (MonoReflectionType *type)
2198 {
2199         if (type->type->byref)
2200                 return NULL;
2201
2202         MonoClass *class = mono_class_from_mono_type (type->type);
2203         return class->parent ? mono_type_get_object (mono_object_domain (type), &class->parent->byval_arg): NULL;
2204 }
2205
2206 ICALL_EXPORT MonoBoolean
2207 ves_icall_type_ispointer (MonoReflectionType *type)
2208 {
2209         return type->type->type == MONO_TYPE_PTR;
2210 }
2211
2212 ICALL_EXPORT MonoBoolean
2213 ves_icall_type_isprimitive (MonoReflectionType *type)
2214 {
2215         return (!type->type->byref && (((type->type->type >= MONO_TYPE_BOOLEAN) && (type->type->type <= MONO_TYPE_R8)) || (type->type->type == MONO_TYPE_I) || (type->type->type == MONO_TYPE_U)));
2216 }
2217
2218 ICALL_EXPORT MonoBoolean
2219 ves_icall_type_isbyref (MonoReflectionType *type)
2220 {
2221         return type->type->byref;
2222 }
2223
2224 ICALL_EXPORT MonoBoolean
2225 ves_icall_type_iscomobject (MonoReflectionType *type)
2226 {
2227         MonoClass *klass = mono_class_from_mono_type (type->type);
2228         mono_class_init_or_throw (klass);
2229
2230         return mono_class_is_com_object (klass);
2231 }
2232
2233 ICALL_EXPORT MonoReflectionModule*
2234 ves_icall_MonoType_get_Module (MonoReflectionType *type)
2235 {
2236         MonoClass *class = mono_class_from_mono_type (type->type);
2237         return mono_module_get_object (mono_object_domain (type), class->image);
2238 }
2239
2240 ICALL_EXPORT MonoReflectionAssembly*
2241 ves_icall_MonoType_get_Assembly (MonoReflectionType *type)
2242 {
2243         MonoDomain *domain = mono_domain_get (); 
2244         MonoClass *class = mono_class_from_mono_type (type->type);
2245         return mono_assembly_get_object (domain, class->image->assembly);
2246 }
2247
2248 ICALL_EXPORT MonoReflectionType*
2249 ves_icall_MonoType_get_DeclaringType (MonoReflectionType *type)
2250 {
2251         MonoDomain *domain = mono_domain_get ();
2252         MonoClass *class;
2253
2254         if (type->type->byref)
2255                 return NULL;
2256         if (type->type->type == MONO_TYPE_VAR) {
2257                 MonoGenericContainer *param = mono_type_get_generic_param_owner (type->type);
2258                 class = param ? param->owner.klass : NULL;
2259         } else if (type->type->type == MONO_TYPE_MVAR) {
2260                 MonoGenericContainer *param = mono_type_get_generic_param_owner (type->type);
2261                 class = param ? param->owner.method->klass : NULL;
2262         } else {
2263                 class = mono_class_from_mono_type (type->type)->nested_in;
2264         }
2265
2266         return class ? mono_type_get_object (domain, &class->byval_arg) : NULL;
2267 }
2268
2269 ICALL_EXPORT MonoString*
2270 ves_icall_MonoType_get_Name (MonoReflectionType *type)
2271 {
2272         MonoDomain *domain = mono_domain_get (); 
2273         MonoClass *class = mono_class_from_mono_type (type->type);
2274
2275         if (type->type->byref) {
2276                 char *n = g_strdup_printf ("%s&", class->name);
2277                 MonoString *res = mono_string_new (domain, n);
2278
2279                 g_free (n);
2280
2281                 return res;
2282         } else {
2283                 return mono_string_new (domain, class->name);
2284         }
2285 }
2286
2287 ICALL_EXPORT MonoString*
2288 ves_icall_MonoType_get_Namespace (MonoReflectionType *type)
2289 {
2290         MonoDomain *domain = mono_domain_get (); 
2291         MonoClass *class = mono_class_from_mono_type (type->type);
2292
2293         while (class->nested_in)
2294                 class = class->nested_in;
2295
2296         if (class->name_space [0] == '\0')
2297                 return NULL;
2298         else
2299                 return mono_string_new (domain, class->name_space);
2300 }
2301
2302 ICALL_EXPORT gint32
2303 ves_icall_MonoType_GetArrayRank (MonoReflectionType *type)
2304 {
2305         MonoClass *class;
2306
2307         if (type->type->type != MONO_TYPE_ARRAY && type->type->type != MONO_TYPE_SZARRAY) {
2308                 mono_set_pending_exception (mono_get_exception_argument ("type", "Type must be an array type"));
2309                 return 0;
2310         }
2311
2312         class = mono_class_from_mono_type (type->type);
2313
2314         return class->rank;
2315 }
2316
2317 ICALL_EXPORT MonoArray*
2318 ves_icall_MonoType_GetGenericArguments (MonoReflectionType *type)
2319 {
2320         MonoArray *res;
2321         MonoClass *klass, *pklass;
2322         MonoDomain *domain = mono_object_domain (type);
2323         MonoVTable *array_vtable = mono_class_vtable_full (domain, mono_array_class_get_cached (mono_defaults.systemtype_class, 1), TRUE);
2324         int i;
2325
2326         klass = mono_class_from_mono_type (type->type);
2327
2328         if (klass->generic_container) {
2329                 MonoGenericContainer *container = klass->generic_container;
2330                 res = mono_array_new_specific (array_vtable, container->type_argc);
2331                 for (i = 0; i < container->type_argc; ++i) {
2332                         pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
2333                         mono_array_setref (res, i, mono_type_get_object (domain, &pklass->byval_arg));
2334                 }
2335         } else if (klass->generic_class) {
2336                 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2337                 res = mono_array_new_specific (array_vtable, inst->type_argc);
2338                 for (i = 0; i < inst->type_argc; ++i)
2339                         mono_array_setref (res, i, mono_type_get_object (domain, inst->type_argv [i]));
2340         } else {
2341                 res = mono_array_new_specific (array_vtable, 0);
2342         }
2343         return res;
2344 }
2345
2346 ICALL_EXPORT gboolean
2347 ves_icall_Type_get_IsGenericTypeDefinition (MonoReflectionType *type)
2348 {
2349         MonoClass *klass;
2350
2351         if (!IS_MONOTYPE (type))
2352                 return FALSE;
2353
2354         if (type->type->byref)
2355                 return FALSE;
2356
2357         klass = mono_class_from_mono_type (type->type);
2358         return klass->generic_container != NULL;
2359 }
2360
2361 ICALL_EXPORT MonoReflectionType*
2362 ves_icall_Type_GetGenericTypeDefinition_impl (MonoReflectionType *type)
2363 {
2364         MonoClass *klass;
2365
2366         if (type->type->byref)
2367                 return NULL;
2368
2369         klass = mono_class_from_mono_type (type->type);
2370
2371         if (klass->generic_container) {
2372                 return type; /* check this one */
2373         }
2374         if (klass->generic_class) {
2375                 MonoClass *generic_class = klass->generic_class->container_class;
2376                 gpointer tb;
2377
2378                 tb = mono_class_get_ref_info (generic_class);
2379
2380                 if (generic_class->wastypebuilder && tb)
2381                         return tb;
2382                 else
2383                         return mono_type_get_object (mono_object_domain (type), &generic_class->byval_arg);
2384         }
2385         return NULL;
2386 }
2387
2388 ICALL_EXPORT MonoReflectionType*
2389 ves_icall_Type_MakeGenericType (MonoReflectionType *type, MonoArray *type_array)
2390 {
2391         MonoClass *class;
2392         MonoType *geninst, **types;
2393         int i, count;
2394
2395         g_assert (IS_MONOTYPE (type));
2396         mono_class_init_or_throw (mono_class_from_mono_type (type->type));
2397
2398         count = mono_array_length (type_array);
2399         types = g_new0 (MonoType *, count);
2400
2401         for (i = 0; i < count; i++) {
2402                 MonoReflectionType *t = mono_array_get (type_array, gpointer, i);
2403                 types [i] = t->type;
2404         }
2405
2406         geninst = mono_reflection_bind_generic_parameters (type, count, types);
2407         g_free (types);
2408         if (!geninst)
2409                 return NULL;
2410
2411         class = mono_class_from_mono_type (geninst);
2412
2413         /*we might inflate to the GTD*/
2414         if (class->generic_class && !mono_verifier_class_is_valid_generic_instantiation (class)) {
2415                 mono_set_pending_exception (mono_get_exception_argument ("typeArguments", "Invalid generic arguments"));
2416                 return NULL;
2417         }
2418
2419         return mono_type_get_object (mono_object_domain (type), geninst);
2420 }
2421
2422 ICALL_EXPORT gboolean
2423 ves_icall_Type_get_IsGenericInstance (MonoReflectionType *type)
2424 {
2425         MonoClass *klass;
2426
2427         if (type->type->byref)
2428                 return FALSE;
2429
2430         klass = mono_class_from_mono_type (type->type);
2431
2432         return klass->generic_class != NULL;
2433 }
2434
2435 ICALL_EXPORT gboolean
2436 ves_icall_Type_get_IsGenericType (MonoReflectionType *type)
2437 {
2438         MonoClass *klass;
2439
2440         if (!IS_MONOTYPE (type))
2441                 return FALSE;
2442
2443         if (type->type->byref)
2444                 return FALSE;
2445
2446         klass = mono_class_from_mono_type (type->type);
2447         return klass->generic_class != NULL || klass->generic_container != NULL;
2448 }
2449
2450 ICALL_EXPORT gint32
2451 ves_icall_Type_GetGenericParameterPosition (MonoReflectionType *type)
2452 {
2453         if (!IS_MONOTYPE (type))
2454                 return -1;
2455
2456         if (is_generic_parameter (type->type))
2457                 return mono_type_get_generic_param_num (type->type);
2458         return -1;
2459 }
2460
2461 ICALL_EXPORT GenericParameterAttributes
2462 ves_icall_Type_GetGenericParameterAttributes (MonoReflectionType *type)
2463 {
2464         g_assert (IS_MONOTYPE (type));
2465         g_assert (is_generic_parameter (type->type));
2466         return mono_generic_param_info (type->type->data.generic_param)->flags;
2467 }
2468
2469 ICALL_EXPORT MonoArray *
2470 ves_icall_Type_GetGenericParameterConstraints (MonoReflectionType *type)
2471 {
2472         MonoGenericParamInfo *param_info;
2473         MonoDomain *domain;
2474         MonoClass **ptr;
2475         MonoArray *res;
2476         int i, count;
2477
2478         g_assert (IS_MONOTYPE (type));
2479
2480         domain = mono_object_domain (type);
2481         param_info = mono_generic_param_info (type->type->data.generic_param);
2482         for (count = 0, ptr = param_info->constraints; ptr && *ptr; ptr++, count++)
2483                 ;
2484
2485         res = mono_array_new (domain, mono_defaults.monotype_class, count);
2486         for (i = 0; i < count; i++)
2487                 mono_array_setref (res, i, mono_type_get_object (domain, &param_info->constraints [i]->byval_arg));
2488
2489
2490         return res;
2491 }
2492
2493 ICALL_EXPORT MonoBoolean
2494 ves_icall_MonoType_get_IsGenericParameter (MonoReflectionType *type)
2495 {
2496         return is_generic_parameter (type->type);
2497 }
2498
2499 ICALL_EXPORT MonoBoolean
2500 ves_icall_TypeBuilder_get_IsGenericParameter (MonoReflectionTypeBuilder *tb)
2501 {
2502         return is_generic_parameter (tb->type.type);
2503 }
2504
2505 ICALL_EXPORT void
2506 ves_icall_EnumBuilder_setup_enum_type (MonoReflectionType *enumtype,
2507                                                                            MonoReflectionType *t)
2508 {
2509         enumtype->type = t->type;
2510 }
2511
2512 ICALL_EXPORT MonoReflectionMethod*
2513 ves_icall_MonoType_GetCorrespondingInflatedMethod (MonoReflectionType *type, 
2514                                                    MonoReflectionMethod* generic)
2515 {
2516         MonoDomain *domain; 
2517         MonoClass *klass;
2518         MonoMethod *method;
2519         gpointer iter;
2520                 
2521         domain = ((MonoObject *)type)->vtable->domain;
2522
2523         klass = mono_class_from_mono_type (type->type);
2524         mono_class_init_or_throw (klass);
2525
2526         iter = NULL;
2527         while ((method = mono_class_get_methods (klass, &iter))) {
2528                 if (method->token == generic->method->token)
2529                         return mono_method_get_object (domain, method, klass);
2530         }
2531
2532         return NULL;
2533 }
2534
2535
2536
2537 ICALL_EXPORT MonoReflectionMethod *
2538 ves_icall_MonoType_get_DeclaringMethod (MonoReflectionType *ref_type)
2539 {
2540         MonoMethod *method;
2541         MonoType *type = ref_type->type;
2542
2543         if (type->byref || (type->type != MONO_TYPE_MVAR && type->type != MONO_TYPE_VAR)) {
2544                 mono_set_pending_exception (mono_get_exception_invalid_operation ("DeclaringMethod can only be used on generic arguments"));
2545                 return NULL;
2546         }
2547         if (type->type == MONO_TYPE_VAR)
2548                 return NULL;
2549
2550         method = mono_type_get_generic_param_owner (type)->owner.method;
2551         g_assert (method);
2552         return mono_method_get_object (mono_object_domain (ref_type), method, method->klass);
2553 }
2554
2555 ICALL_EXPORT MonoReflectionDllImportAttribute*
2556 ves_icall_MonoMethod_GetDllImportAttribute (MonoMethod *method)
2557 {
2558         static MonoClass *DllImportAttributeClass = NULL;
2559         MonoDomain *domain = mono_domain_get ();
2560         MonoReflectionDllImportAttribute *attr;
2561         MonoImage *image = method->klass->image;
2562         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
2563         MonoTableInfo *tables = image->tables;
2564         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
2565         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
2566         guint32 im_cols [MONO_IMPLMAP_SIZE];
2567         guint32 scope_token;
2568         const char *import = NULL;
2569         const char *scope = NULL;
2570         guint32 flags;
2571
2572         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
2573                 return NULL;
2574
2575         if (!DllImportAttributeClass) {
2576                 DllImportAttributeClass = 
2577                         mono_class_from_name (mono_defaults.corlib,
2578                                                                   "System.Runtime.InteropServices", "DllImportAttribute");
2579                 g_assert (DllImportAttributeClass);
2580         }
2581                                                                                                                 
2582         if (image_is_dynamic (method->klass->image)) {
2583                 MonoReflectionMethodAux *method_aux = 
2584                         g_hash_table_lookup (
2585                                                                           ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2586                 if (method_aux) {
2587                         import = method_aux->dllentry;
2588                         scope = method_aux->dll;
2589                 }
2590
2591                 if (!import || !scope) {
2592                         mono_set_pending_exception (mono_get_exception_argument ("method", "System.Reflection.Emit method with invalid pinvoke information"));
2593                         return NULL;
2594                 }
2595         }
2596         else {
2597                 if (piinfo->implmap_idx) {
2598                         mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
2599                         
2600                         piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
2601                         import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
2602                         scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
2603                         scope = mono_metadata_string_heap (image, scope_token);
2604                 }
2605         }
2606         flags = piinfo->piflags;
2607         
2608         attr = (MonoReflectionDllImportAttribute*)mono_object_new (domain, DllImportAttributeClass);
2609
2610         MONO_OBJECT_SETREF (attr, dll, mono_string_new (domain, scope));
2611         MONO_OBJECT_SETREF (attr, entry_point, mono_string_new (domain, import));
2612         attr->call_conv = (flags & 0x700) >> 8;
2613         attr->charset = ((flags & 0x6) >> 1) + 1;
2614         if (attr->charset == 1)
2615                 attr->charset = 2;
2616         attr->exact_spelling = (flags & 0x1) != 0;
2617         attr->set_last_error = (flags & 0x40) != 0;
2618         attr->best_fit_mapping = (flags & 0x30) == 0x10;
2619         attr->throw_on_unmappable = (flags & 0x3000) == 0x1000;
2620         attr->preserve_sig = FALSE;
2621
2622         return attr;
2623 }
2624
2625 ICALL_EXPORT MonoReflectionMethod *
2626 ves_icall_MonoMethod_GetGenericMethodDefinition (MonoReflectionMethod *method)
2627 {
2628         MonoMethodInflated *imethod;
2629         MonoMethod *result;
2630
2631         if (method->method->is_generic)
2632                 return method;
2633
2634         if (!method->method->is_inflated)
2635                 return NULL;
2636
2637         imethod = (MonoMethodInflated *) method->method;
2638
2639         result = imethod->declaring;
2640         /* Not a generic method.  */
2641         if (!result->is_generic)
2642                 return NULL;
2643
2644         if (image_is_dynamic (method->method->klass->image)) {
2645                 MonoDynamicImage *image = (MonoDynamicImage*)method->method->klass->image;
2646                 MonoReflectionMethod *res;
2647
2648                 /*
2649                  * FIXME: Why is this stuff needed at all ? Why can't the code below work for
2650                  * the dynamic case as well ?
2651                  */
2652                 mono_image_lock ((MonoImage*)image);
2653                 res = mono_g_hash_table_lookup (image->generic_def_objects, imethod);
2654                 mono_image_unlock ((MonoImage*)image);
2655
2656                 if (res)
2657                         return res;
2658         }
2659
2660         if (imethod->context.class_inst) {
2661                 MonoClass *klass = ((MonoMethod *) imethod)->klass;
2662                 /*Generic methods gets the context of the GTD.*/
2663                 if (mono_class_get_context (klass)) {
2664                         MonoError error;
2665                         result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
2666                         mono_error_raise_exception (&error);
2667                 }
2668         }
2669
2670         return mono_method_get_object (mono_object_domain (method), result, NULL);
2671 }
2672
2673 ICALL_EXPORT gboolean
2674 ves_icall_MonoMethod_get_IsGenericMethod (MonoReflectionMethod *method)
2675 {
2676         return mono_method_signature (method->method)->generic_param_count != 0;
2677 }
2678
2679 ICALL_EXPORT gboolean
2680 ves_icall_MonoMethod_get_IsGenericMethodDefinition (MonoReflectionMethod *method)
2681 {
2682         return method->method->is_generic;
2683 }
2684
2685 ICALL_EXPORT MonoArray*
2686 ves_icall_MonoMethod_GetGenericArguments (MonoReflectionMethod *method)
2687 {
2688         MonoArray *res;
2689         MonoDomain *domain;
2690         int count, i;
2691
2692         domain = mono_object_domain (method);
2693
2694         if (method->method->is_inflated) {
2695                 MonoGenericInst *inst = mono_method_get_context (method->method)->method_inst;
2696
2697                 if (inst) {
2698                         count = inst->type_argc;
2699                         res = mono_array_new (domain, mono_defaults.systemtype_class, count);
2700
2701                         for (i = 0; i < count; i++)
2702                                 mono_array_setref (res, i, mono_type_get_object (domain, inst->type_argv [i]));
2703
2704                         return res;
2705                 }
2706         }
2707
2708         count = mono_method_signature (method->method)->generic_param_count;
2709         res = mono_array_new (domain, mono_defaults.systemtype_class, count);
2710
2711         for (i = 0; i < count; i++) {
2712                 MonoGenericContainer *container = mono_method_get_generic_container (method->method);
2713                 MonoGenericParam *param = mono_generic_container_get_param (container, i);
2714                 MonoClass *pklass = mono_class_from_generic_parameter (
2715                         param, method->method->klass->image, TRUE);
2716                 mono_array_setref (res, i,
2717                                 mono_type_get_object (domain, &pklass->byval_arg));
2718         }
2719
2720         return res;
2721 }
2722
2723 ICALL_EXPORT MonoObject *
2724 ves_icall_InternalInvoke (MonoReflectionMethod *method, MonoObject *this, MonoArray *params, MonoException **exc) 
2725 {
2726         /* 
2727          * Invoke from reflection is supposed to always be a virtual call (the API
2728          * is stupid), mono_runtime_invoke_*() calls the provided method, allowing
2729          * greater flexibility.
2730          */
2731         MonoMethod *m = method->method;
2732         MonoMethodSignature *sig = mono_method_signature (m);
2733         MonoImage *image;
2734         int pcount;
2735         void *obj = this;
2736
2737         *exc = NULL;
2738
2739         if (mono_security_core_clr_enabled ())
2740                 mono_security_core_clr_ensure_reflection_access_method (m);
2741
2742         if (!(m->flags & METHOD_ATTRIBUTE_STATIC)) {
2743                 if (!mono_class_vtable_full (mono_object_domain (method), m->klass, FALSE)) {
2744                         mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_class_get_exception_for_failure (m->klass));
2745                         return NULL;
2746                 }
2747
2748                 if (this) {
2749                         if (!mono_object_isinst (this, m->klass)) {
2750                                 char *this_name = mono_type_get_full_name (mono_object_get_class (this));
2751                                 char *target_name = mono_type_get_full_name (m->klass);
2752                                 char *msg = g_strdup_printf ("Object of type '%s' doesn't match target type '%s'", this_name, target_name);
2753                                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", msg));
2754                                 g_free (msg);
2755                                 g_free (target_name);
2756                                 g_free (this_name);
2757                                 return NULL;
2758                         }
2759                         m = mono_object_get_virtual_method (this, m);
2760                         /* must pass the pointer to the value for valuetype methods */
2761                         if (m->klass->valuetype)
2762                                 obj = mono_object_unbox (this);
2763                 } else if (strcmp (m->name, ".ctor") && !m->wrapper_type) {
2764                         mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Non-static method requires a target."));
2765                         return NULL;
2766                 }
2767         }
2768
2769         if (sig->ret->byref) {
2770                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "Cannot invoke method returning ByRef type via reflection"));
2771                 return NULL;
2772         }
2773
2774         pcount = params? mono_array_length (params): 0;
2775         if (pcount != sig->param_count) {
2776                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name (mono_defaults.corlib, "System.Reflection", "TargetParameterCountException"));
2777                 return NULL;
2778         }
2779
2780         if ((m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT) && !strcmp (m->name, ".ctor") && !this) {
2781                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Cannot invoke constructor of an abstract class."));
2782                 return NULL;
2783         }
2784
2785         image = m->klass->image;
2786         if (image->assembly->ref_only) {
2787                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_get_exception_invalid_operation ("It is illegal to invoke a method on a type loaded using the ReflectionOnly api."));
2788                 return NULL;
2789         }
2790
2791         if (image_is_dynamic (image) && !((MonoDynamicImage*)image)->run) {
2792                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_get_exception_not_supported ("Cannot invoke a method in a dynamic assembly without run access."));
2793                 return NULL;
2794         }
2795         
2796         if (m->klass->rank && !strcmp (m->name, ".ctor")) {
2797                 int i;
2798                 uintptr_t *lengths;
2799                 intptr_t *lower_bounds;
2800                 pcount = mono_array_length (params);
2801                 lengths = alloca (sizeof (uintptr_t) * pcount);
2802                 /* Note: the synthetized array .ctors have int32 as argument type */
2803                 for (i = 0; i < pcount; ++i)
2804                         lengths [i] = *(int32_t*) ((char*)mono_array_get (params, gpointer, i) + sizeof (MonoObject));
2805
2806                 if (m->klass->rank == 1 && sig->param_count == 2 && m->klass->element_class->rank) {
2807                         /* This is a ctor for jagged arrays. MS creates an array of arrays. */
2808                         MonoArray *arr = mono_array_new_full (mono_object_domain (params), m->klass, lengths, NULL);
2809
2810                         for (i = 0; i < mono_array_length (arr); ++i) {
2811                                 MonoArray *subarray = mono_array_new_full (mono_object_domain (params), m->klass->element_class, &lengths [1], NULL);
2812
2813                                 mono_array_setref_fast (arr, i, subarray);
2814                         }
2815                         return (MonoObject*)arr;
2816                 }
2817
2818                 if (m->klass->rank == pcount) {
2819                         /* Only lengths provided. */
2820                         lower_bounds = NULL;
2821                 } else {
2822                         g_assert (pcount == (m->klass->rank * 2));
2823                         /* lower bounds are first. */
2824                         lower_bounds = (intptr_t*)lengths;
2825                         lengths += m->klass->rank;
2826                 }
2827
2828                 return (MonoObject*)mono_array_new_full (mono_object_domain (params), m->klass, lengths, lower_bounds);
2829         }
2830         return mono_runtime_invoke_array (m, obj, params, NULL);
2831 }
2832
2833 #ifndef DISABLE_REMOTING
2834 ICALL_EXPORT MonoObject *
2835 ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this, MonoArray *params, MonoArray **outArgs) 
2836 {
2837         MonoDomain *domain = mono_object_domain (method); 
2838         MonoMethod *m = method->method;
2839         MonoMethodSignature *sig = mono_method_signature (m);
2840         MonoArray *out_args;
2841         MonoObject *result;
2842         int i, j, outarg_count = 0;
2843
2844         if (m->klass == mono_defaults.object_class) {
2845                 if (!strcmp (m->name, "FieldGetter")) {
2846                         MonoClass *k = this->vtable->klass;
2847                         MonoString *name;
2848                         char *str;
2849                         
2850                         /* If this is a proxy, then it must be a CBO */
2851                         if (k == mono_defaults.transparent_proxy_class) {
2852                                 MonoTransparentProxy *tp = (MonoTransparentProxy*) this;
2853                                 this = tp->rp->unwrapped_server;
2854                                 g_assert (this);
2855                                 k = this->vtable->klass;
2856                         }
2857                         
2858                         name = mono_array_get (params, MonoString *, 1);
2859                         str = mono_string_to_utf8 (name);
2860                 
2861                         do {
2862                                 MonoClassField* field = mono_class_get_field_from_name (k, str);
2863                                 if (field) {
2864                                         MonoClass *field_klass =  mono_class_from_mono_type (field->type);
2865                                         if (field_klass->valuetype)
2866                                                 result = mono_value_box (domain, field_klass, (char *)this + field->offset);
2867                                         else 
2868                                                 result = *((gpointer *)((char *)this + field->offset));
2869                                 
2870                                         out_args = mono_array_new (domain, mono_defaults.object_class, 1);
2871                                         mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
2872                                         mono_array_setref (out_args, 0, result);
2873                                         g_free (str);
2874                                         return NULL;
2875                                 }
2876                                 k = k->parent;
2877                         } while (k);
2878
2879                         g_free (str);
2880                         g_assert_not_reached ();
2881
2882                 } else if (!strcmp (m->name, "FieldSetter")) {
2883                         MonoClass *k = this->vtable->klass;
2884                         MonoString *name;
2885                         guint32 size;
2886                         gint32 align;
2887                         char *str;
2888                         
2889                         /* If this is a proxy, then it must be a CBO */
2890                         if (k == mono_defaults.transparent_proxy_class) {
2891                                 MonoTransparentProxy *tp = (MonoTransparentProxy*) this;
2892                                 this = tp->rp->unwrapped_server;
2893                                 g_assert (this);
2894                                 k = this->vtable->klass;
2895                         }
2896                         
2897                         name = mono_array_get (params, MonoString *, 1);
2898                         str = mono_string_to_utf8 (name);
2899                 
2900                         do {
2901                                 MonoClassField* field = mono_class_get_field_from_name (k, str);
2902                                 if (field) {
2903                                         MonoClass *field_klass =  mono_class_from_mono_type (field->type);
2904                                         MonoObject *val = mono_array_get (params, gpointer, 2);
2905
2906                                         if (field_klass->valuetype) {
2907                                                 size = mono_type_size (field->type, &align);
2908                                                 g_assert (size == mono_class_value_size (field_klass, NULL));
2909                                                 mono_gc_wbarrier_value_copy ((char *)this + field->offset, (char*)val + sizeof (MonoObject), 1, field_klass);
2910                                         } else {
2911                                                 mono_gc_wbarrier_set_field (this, (char*)this + field->offset, val);
2912                                         }
2913                                 
2914                                         out_args = mono_array_new (domain, mono_defaults.object_class, 0);
2915                                         mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
2916
2917                                         g_free (str);
2918                                         return NULL;
2919                                 }
2920                                 
2921                                 k = k->parent;
2922                         } while (k);
2923
2924                         g_free (str);
2925                         g_assert_not_reached ();
2926
2927                 }
2928         }
2929
2930         for (i = 0; i < mono_array_length (params); i++) {
2931                 if (sig->params [i]->byref) 
2932                         outarg_count++;
2933         }
2934
2935         out_args = mono_array_new (domain, mono_defaults.object_class, outarg_count);
2936         
2937         /* handle constructors only for objects already allocated */
2938         if (!strcmp (method->method->name, ".ctor"))
2939                 g_assert (this);
2940
2941         /* This can be called only on MBR objects, so no need to unbox for valuetypes. */
2942         g_assert (!method->method->klass->valuetype);
2943         result = mono_runtime_invoke_array (method->method, this, params, NULL);
2944
2945         for (i = 0, j = 0; i < mono_array_length (params); i++) {
2946                 if (sig->params [i]->byref) {
2947                         gpointer arg;
2948                         arg = mono_array_get (params, gpointer, i);
2949                         mono_array_setref (out_args, j, arg);
2950                         j++;
2951                 }
2952         }
2953
2954         mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
2955
2956         return result;
2957 }
2958 #endif
2959
2960 static guint64
2961 read_enum_value (const char *mem, int type)
2962 {
2963         switch (type) {
2964         case MONO_TYPE_BOOLEAN:
2965         case MONO_TYPE_U1:
2966                 return *(guint8*)mem;
2967         case MONO_TYPE_I1:
2968                 return *(gint8*)mem;
2969         case MONO_TYPE_CHAR:
2970         case MONO_TYPE_U2:
2971                 return *(guint16*)mem;
2972         case MONO_TYPE_I2:
2973                 return *(gint16*)mem;
2974         case MONO_TYPE_U4:
2975                 return *(guint32*)mem;
2976         case MONO_TYPE_I4:
2977                 return *(gint32*)mem;
2978         case MONO_TYPE_U8:
2979                 return *(guint64*)mem;
2980         case MONO_TYPE_I8:
2981                 return *(gint64*)mem;
2982         default:
2983                 g_assert_not_reached ();
2984         }
2985         return 0;
2986 }
2987
2988 static void
2989 write_enum_value (char *mem, int type, guint64 value)
2990 {
2991         switch (type) {
2992         case MONO_TYPE_U1:
2993         case MONO_TYPE_I1: {
2994                 guint8 *p = (guint8*)mem;
2995                 *p = value;
2996                 break;
2997         }
2998         case MONO_TYPE_U2:
2999         case MONO_TYPE_I2: {
3000                 guint16 *p = (void*)mem;
3001                 *p = value;
3002                 break;
3003         }
3004         case MONO_TYPE_U4:
3005         case MONO_TYPE_I4: {
3006                 guint32 *p = (void*)mem;
3007                 *p = value;
3008                 break;
3009         }
3010         case MONO_TYPE_U8:
3011         case MONO_TYPE_I8: {
3012                 guint64 *p = (void*)mem;
3013                 *p = value;
3014                 break;
3015         }
3016         default:
3017                 g_assert_not_reached ();
3018         }
3019         return;
3020 }
3021
3022 ICALL_EXPORT MonoObject *
3023 ves_icall_System_Enum_ToObject (MonoReflectionType *enumType, guint64 value)
3024 {
3025         MonoDomain *domain; 
3026         MonoClass *enumc;
3027         MonoObject *res;
3028         MonoType *etype;
3029
3030         domain = mono_object_domain (enumType); 
3031         enumc = mono_class_from_mono_type (enumType->type);
3032
3033         mono_class_init_or_throw (enumc);
3034
3035         etype = mono_class_enum_basetype (enumc);
3036
3037         res = mono_object_new (domain, enumc);
3038         write_enum_value ((char *)res + sizeof (MonoObject), etype->type, value);
3039
3040         return res;
3041 }
3042
3043 ICALL_EXPORT MonoBoolean
3044 ves_icall_System_Enum_InternalHasFlag (MonoObject *a, MonoObject *b)
3045 {
3046         int size = mono_class_value_size (a->vtable->klass, NULL);
3047         guint64 a_val = 0, b_val = 0;
3048
3049         memcpy (&a_val, mono_object_unbox (a), size);
3050         memcpy (&b_val, mono_object_unbox (b), size);
3051
3052         return (a_val & b_val) == b_val;
3053 }
3054
3055 ICALL_EXPORT MonoObject *
3056 ves_icall_System_Enum_get_value (MonoObject *this)
3057 {
3058         MonoObject *res;
3059         MonoClass *enumc;
3060         gpointer dst;
3061         gpointer src;
3062         int size;
3063
3064         if (!this)
3065                 return NULL;
3066
3067         g_assert (this->vtable->klass->enumtype);
3068         
3069         enumc = mono_class_from_mono_type (mono_class_enum_basetype (this->vtable->klass));
3070         res = mono_object_new (mono_object_domain (this), enumc);
3071         dst = (char *)res + sizeof (MonoObject);
3072         src = (char *)this + sizeof (MonoObject);
3073         size = mono_class_value_size (enumc, NULL);
3074
3075         memcpy (dst, src, size);
3076
3077         return res;
3078 }
3079
3080 ICALL_EXPORT MonoReflectionType *
3081 ves_icall_System_Enum_get_underlying_type (MonoReflectionType *type)
3082 {
3083         MonoType *etype;
3084         MonoClass *klass;
3085
3086         klass = mono_class_from_mono_type (type->type);
3087         mono_class_init_or_throw (klass);
3088
3089         etype = mono_class_enum_basetype (klass);
3090         if (!etype) {
3091                 mono_set_pending_exception (mono_get_exception_argument ("enumType", "Type provided must be an Enum."));
3092                 return NULL;
3093         }
3094
3095         return mono_type_get_object (mono_object_domain (type), etype);
3096 }
3097
3098 ICALL_EXPORT int
3099 ves_icall_System_Enum_compare_value_to (MonoObject *this, MonoObject *other)
3100 {
3101         gpointer tdata = (char *)this + sizeof (MonoObject);
3102         gpointer odata = (char *)other + sizeof (MonoObject);
3103         MonoType *basetype = mono_class_enum_basetype (this->vtable->klass);
3104         g_assert (basetype);
3105
3106         if (other == NULL)
3107                 return 1;
3108
3109         if (this->vtable->klass != other->vtable->klass)
3110                 return 2;
3111
3112 #define COMPARE_ENUM_VALUES(ENUM_TYPE) do { \
3113                 ENUM_TYPE me = *((ENUM_TYPE*)tdata); \
3114                 ENUM_TYPE other = *((ENUM_TYPE*)odata); \
3115                 if (me == other) \
3116                         return 0; \
3117                 return me > other ? 1 : -1; \
3118         } while (0)
3119
3120         switch (basetype->type) {
3121                 case MONO_TYPE_U1:
3122                         COMPARE_ENUM_VALUES (guint8);
3123                 case MONO_TYPE_I1:
3124                         COMPARE_ENUM_VALUES (gint8);
3125                 case MONO_TYPE_CHAR:
3126                 case MONO_TYPE_U2:
3127                         COMPARE_ENUM_VALUES (guint16);
3128                 case MONO_TYPE_I2:
3129                         COMPARE_ENUM_VALUES (gint16);
3130                 case MONO_TYPE_U4:
3131                         COMPARE_ENUM_VALUES (guint32);
3132                 case MONO_TYPE_I4:
3133                         COMPARE_ENUM_VALUES (gint32);
3134                 case MONO_TYPE_U8:
3135                         COMPARE_ENUM_VALUES (guint64);
3136                 case MONO_TYPE_I8:
3137                         COMPARE_ENUM_VALUES (gint64);
3138         }
3139 #undef COMPARE_ENUM_VALUES
3140         /* indicates that the enum was of an unsupported unerlying type */
3141         return 3;
3142 }
3143
3144 ICALL_EXPORT int
3145 ves_icall_System_Enum_get_hashcode (MonoObject *this)
3146 {
3147         gpointer data = (char *)this + sizeof (MonoObject);
3148         MonoType *basetype = mono_class_enum_basetype (this->vtable->klass);
3149         g_assert (basetype);
3150
3151         switch (basetype->type) {
3152                 case MONO_TYPE_I1:      
3153                         return *((gint8*)data);
3154                 case MONO_TYPE_U1:
3155                         return *((guint8*)data);
3156                 case MONO_TYPE_CHAR:
3157                 case MONO_TYPE_U2:
3158                         return *((guint16*)data);
3159                 
3160                 case MONO_TYPE_I2:
3161                         return *((gint16*)data);
3162                 case MONO_TYPE_U4:
3163                         return *((guint32*)data);
3164                 case MONO_TYPE_I4:
3165                         return *((gint32*)data);
3166                 case MONO_TYPE_U8:
3167                 case MONO_TYPE_I8: {
3168                         gint64 value = *((gint64*)data);
3169                         return (gint)(value & 0xffffffff) ^ (int)(value >> 32);
3170                 }
3171                 default:
3172                         g_error ("Implement type 0x%02x in get_hashcode", basetype->type);
3173         }
3174         return 0;
3175 }
3176
3177 ICALL_EXPORT MonoBoolean
3178 ves_icall_System_Enum_GetEnumValuesAndNames (MonoReflectionType *type, MonoArray **values, MonoArray **names)
3179 {
3180         MonoDomain *domain = mono_object_domain (type); 
3181         MonoClass *enumc = mono_class_from_mono_type (type->type);
3182         guint j = 0, nvalues, crow;
3183         gpointer iter;
3184         MonoClassField *field;
3185         int base_type;
3186         guint64 field_value, previous_value = 0;
3187         gboolean sorted = TRUE;
3188
3189         mono_class_init_or_throw (enumc);
3190
3191         if (!enumc->enumtype) {
3192                 mono_set_pending_exception (mono_get_exception_argument ("enumType", "Type provided must be an Enum."));
3193                 return TRUE;
3194         }
3195
3196         base_type = mono_class_enum_basetype (enumc)->type;
3197
3198         nvalues = mono_class_num_fields (enumc) ? mono_class_num_fields (enumc) - 1 : 0;
3199         *names = mono_array_new (domain, mono_defaults.string_class, nvalues);
3200         *values = mono_array_new (domain, mono_defaults.uint64_class, nvalues);
3201
3202         crow = -1;
3203         iter = NULL;
3204         while ((field = mono_class_get_fields (enumc, &iter))) {
3205                 const char *p;
3206                 int len;
3207                 MonoTypeEnum def_type;
3208
3209                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3210                         continue;
3211                 if (strcmp ("value__", mono_field_get_name (field)) == 0)
3212                         continue;
3213                 if (mono_field_is_deleted (field))
3214                         continue;
3215                 mono_array_setref (*names, j, mono_string_new (domain, mono_field_get_name (field)));
3216
3217                 p = mono_class_get_field_default_value (field, &def_type);
3218                 len = mono_metadata_decode_blob_size (p, &p);
3219
3220                 field_value = read_enum_value (p, base_type);
3221                 mono_array_set (*values, guint64, j, field_value);
3222
3223                 if (previous_value > field_value)
3224                         sorted = FALSE;
3225
3226                 previous_value = field_value;
3227                 ++j;
3228         }
3229
3230         return sorted;
3231 }
3232
3233 enum {
3234         BFLAGS_IgnoreCase = 1,
3235         BFLAGS_DeclaredOnly = 2,
3236         BFLAGS_Instance = 4,
3237         BFLAGS_Static = 8,
3238         BFLAGS_Public = 0x10,
3239         BFLAGS_NonPublic = 0x20,
3240         BFLAGS_FlattenHierarchy = 0x40,
3241         BFLAGS_InvokeMethod = 0x100,
3242         BFLAGS_CreateInstance = 0x200,
3243         BFLAGS_GetField = 0x400,
3244         BFLAGS_SetField = 0x800,
3245         BFLAGS_GetProperty = 0x1000,
3246         BFLAGS_SetProperty = 0x2000,
3247         BFLAGS_ExactBinding = 0x10000,
3248         BFLAGS_SuppressChangeType = 0x20000,
3249         BFLAGS_OptionalParamBinding = 0x40000
3250 };
3251
3252 ICALL_EXPORT MonoReflectionField *
3253 ves_icall_Type_GetField (MonoReflectionType *type, MonoString *name, guint32 bflags)
3254 {
3255         MonoDomain *domain; 
3256         MonoClass *startklass, *klass;
3257         int match;
3258         MonoClassField *field;
3259         gpointer iter;
3260         char *utf8_name;
3261         int (*compare_func) (const char *s1, const char *s2) = NULL;
3262         domain = ((MonoObject *)type)->vtable->domain;
3263         klass = startklass = mono_class_from_mono_type (type->type);
3264
3265         if (!name) {
3266                 mono_set_pending_exception (mono_get_exception_argument_null ("name"));
3267                 return NULL;
3268         }
3269         if (type->type->byref)
3270                 return NULL;
3271
3272         compare_func = (bflags & BFLAGS_IgnoreCase) ? mono_utf8_strcasecmp : strcmp;
3273
3274 handle_parent:
3275         if (klass->exception_type != MONO_EXCEPTION_NONE) {
3276                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
3277                 return NULL;
3278         }
3279
3280         iter = NULL;
3281         while ((field = mono_class_get_fields_lazy (klass, &iter))) {
3282                 guint32 flags = mono_field_get_flags (field);
3283                 match = 0;
3284
3285                 if (mono_field_is_deleted_with_flags (field, flags))
3286                         continue;
3287                 if ((flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
3288                         if (bflags & BFLAGS_Public)
3289                                 match++;
3290                 } else if ((klass == startklass) || (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) != FIELD_ATTRIBUTE_PRIVATE) {
3291                         if (bflags & BFLAGS_NonPublic) {
3292                                 match++;
3293                         }
3294                 }
3295                 if (!match)
3296                         continue;
3297                 match = 0;
3298                 if (flags & FIELD_ATTRIBUTE_STATIC) {
3299                         if (bflags & BFLAGS_Static)
3300                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3301                                         match++;
3302                 } else {
3303                         if (bflags & BFLAGS_Instance)
3304                                 match++;
3305                 }
3306
3307                 if (!match)
3308                         continue;
3309                 
3310                 utf8_name = mono_string_to_utf8 (name);
3311
3312                 if (compare_func (mono_field_get_name (field), utf8_name)) {
3313                         g_free (utf8_name);
3314                         continue;
3315                 }
3316                 g_free (utf8_name);
3317                 
3318                 return mono_field_get_object (domain, klass, field);
3319         }
3320         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3321                 goto handle_parent;
3322
3323         return NULL;
3324 }
3325
3326 ICALL_EXPORT MonoArray*
3327 ves_icall_Type_GetFields_internal (MonoReflectionType *type, guint32 bflags, MonoReflectionType *reftype)
3328 {
3329         MonoDomain *domain; 
3330         MonoClass *startklass, *klass, *refklass;
3331         MonoArray *res;
3332         MonoObject *member;
3333         int i, match;
3334         gpointer iter;
3335         MonoClassField *field;
3336         MonoPtrArray tmp_array;
3337
3338         domain = ((MonoObject *)type)->vtable->domain;
3339         if (type->type->byref)
3340                 return mono_array_new (domain, mono_defaults.field_info_class, 0);
3341         klass = startklass = mono_class_from_mono_type (type->type);
3342         refklass = mono_class_from_mono_type (reftype->type);
3343
3344         mono_ptr_array_init (tmp_array, 2);
3345         
3346 handle_parent:  
3347         if (klass->exception_type != MONO_EXCEPTION_NONE) {
3348                 mono_ptr_array_destroy (tmp_array);
3349                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
3350                 return NULL;
3351         }
3352
3353         iter = NULL;
3354         while ((field = mono_class_get_fields_lazy (klass, &iter))) {
3355                 guint32 flags = mono_field_get_flags (field);
3356                 match = 0;
3357                 if (mono_field_is_deleted_with_flags (field, flags))
3358                         continue;
3359                 if ((flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
3360                         if (bflags & BFLAGS_Public)
3361                                 match++;
3362                 } else if ((klass == startklass) || (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) != FIELD_ATTRIBUTE_PRIVATE) {
3363                         if (bflags & BFLAGS_NonPublic) {
3364                                 match++;
3365                         }
3366                 }
3367                 if (!match)
3368                         continue;
3369                 match = 0;
3370                 if (flags & FIELD_ATTRIBUTE_STATIC) {
3371                         if (bflags & BFLAGS_Static)
3372                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3373                                         match++;
3374                 } else {
3375                         if (bflags & BFLAGS_Instance)
3376                                 match++;
3377                 }
3378
3379                 if (!match)
3380                         continue;
3381                 member = (MonoObject*)mono_field_get_object (domain, refklass, field);
3382                 mono_ptr_array_append (tmp_array, member);
3383         }
3384         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3385                 goto handle_parent;
3386
3387         res = mono_array_new_cached (domain, mono_defaults.field_info_class, mono_ptr_array_size (tmp_array));
3388
3389         for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3390                 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3391
3392         mono_ptr_array_destroy (tmp_array);
3393
3394         return res;
3395 }
3396
3397 static gboolean
3398 method_nonpublic (MonoMethod* method, gboolean start_klass)
3399 {
3400         switch (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) {
3401                 case METHOD_ATTRIBUTE_ASSEM:
3402                         return (start_klass || mono_defaults.generic_ilist_class);
3403                 case METHOD_ATTRIBUTE_PRIVATE:
3404                         return start_klass;
3405                 case METHOD_ATTRIBUTE_PUBLIC:
3406                         return FALSE;
3407                 default:
3408                         return TRUE;
3409         }
3410 }
3411
3412 GPtrArray*
3413 mono_class_get_methods_by_name (MonoClass *klass, const char *name, guint32 bflags, gboolean ignore_case, gboolean allow_ctors, MonoException **ex)
3414 {
3415         GPtrArray *array;
3416         MonoClass *startklass;
3417         MonoMethod *method;
3418         gpointer iter;
3419         int len, match, nslots;
3420         /*FIXME, use MonoBitSet*/
3421         guint32 method_slots_default [8];
3422         guint32 *method_slots = NULL;
3423         int (*compare_func) (const char *s1, const char *s2) = NULL;
3424
3425         array = g_ptr_array_new ();
3426         startklass = klass;
3427         *ex = NULL;
3428
3429         len = 0;
3430         if (name != NULL)
3431                 compare_func = (ignore_case) ? mono_utf8_strcasecmp : strcmp;
3432
3433         /* An optimization for calls made from Delegate:CreateDelegate () */
3434         if (klass->delegate && name && !strcmp (name, "Invoke") && (bflags == (BFLAGS_Public | BFLAGS_Static | BFLAGS_Instance))) {
3435                 method = mono_get_delegate_invoke (klass);
3436                 if (mono_loader_get_last_error ())
3437                         goto loader_error;
3438
3439                 g_ptr_array_add (array, method);
3440                 return array;
3441         }
3442
3443         mono_class_setup_methods (klass);
3444         mono_class_setup_vtable (klass);
3445         if (klass->exception_type != MONO_EXCEPTION_NONE || mono_loader_get_last_error ())
3446                 goto loader_error;
3447
3448         if (is_generic_parameter (&klass->byval_arg))
3449                 nslots = mono_class_get_vtable_size (klass->parent);
3450         else
3451                 nslots = MONO_CLASS_IS_INTERFACE (klass) ? mono_class_num_methods (klass) : mono_class_get_vtable_size (klass);
3452         if (nslots >= sizeof (method_slots_default) * 8) {
3453                 method_slots = g_new0 (guint32, nslots / 32 + 1);
3454         } else {
3455                 method_slots = method_slots_default;
3456                 memset (method_slots, 0, sizeof (method_slots_default));
3457         }
3458 handle_parent:
3459         mono_class_setup_methods (klass);
3460         mono_class_setup_vtable (klass);
3461         if (klass->exception_type != MONO_EXCEPTION_NONE || mono_loader_get_last_error ())
3462                 goto loader_error;              
3463
3464         iter = NULL;
3465         while ((method = mono_class_get_methods (klass, &iter))) {
3466                 match = 0;
3467                 if (method->slot != -1) {
3468                         g_assert (method->slot < nslots);
3469                         if (method_slots [method->slot >> 5] & (1 << (method->slot & 0x1f)))
3470                                 continue;
3471                         if (!(method->flags & METHOD_ATTRIBUTE_NEW_SLOT))
3472                                 method_slots [method->slot >> 5] |= 1 << (method->slot & 0x1f);
3473                 }
3474
3475                 if (!allow_ctors && method->name [0] == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0))
3476                         continue;
3477                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3478                         if (bflags & BFLAGS_Public)
3479                                 match++;
3480                 } else if ((bflags & BFLAGS_NonPublic) && method_nonpublic (method, (klass == startklass))) {
3481                                 match++;
3482                 }
3483                 if (!match)
3484                         continue;
3485                 match = 0;
3486                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3487                         if (bflags & BFLAGS_Static)
3488                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3489                                         match++;
3490                 } else {
3491                         if (bflags & BFLAGS_Instance)
3492                                 match++;
3493                 }
3494
3495                 if (!match)
3496                         continue;
3497
3498                 if (name != NULL) {
3499                         if (compare_func (name, method->name))
3500                                 continue;
3501                 }
3502                 
3503                 match = 0;
3504                 g_ptr_array_add (array, method);
3505         }
3506         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3507                 goto handle_parent;
3508         if (method_slots != method_slots_default)
3509                 g_free (method_slots);
3510
3511         return array;
3512
3513 loader_error:
3514         if (method_slots != method_slots_default)
3515                 g_free (method_slots);
3516         g_ptr_array_free (array, TRUE);
3517
3518         if (klass->exception_type != MONO_EXCEPTION_NONE) {
3519                 *ex = mono_class_get_exception_for_failure (klass);
3520         } else {
3521                 *ex = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
3522                 mono_loader_clear_error ();
3523         }
3524         return NULL;
3525 }
3526
3527 ICALL_EXPORT MonoArray*
3528 ves_icall_Type_GetMethodsByName (MonoReflectionType *type, MonoString *name, guint32 bflags, MonoBoolean ignore_case, MonoReflectionType *reftype)
3529 {
3530         static MonoClass *MethodInfo_array;
3531         MonoDomain *domain; 
3532         MonoArray *res;
3533         MonoVTable *array_vtable;
3534         MonoException *ex = NULL;
3535         const char *mname = NULL;
3536         GPtrArray *method_array;
3537         MonoClass *klass, *refklass;
3538         int i;
3539
3540         if (!MethodInfo_array) {
3541                 MonoClass *klass = mono_array_class_get (mono_defaults.method_info_class, 1);
3542                 mono_memory_barrier ();
3543                 MethodInfo_array = klass;
3544         }
3545
3546         klass = mono_class_from_mono_type (type->type);
3547         refklass = mono_class_from_mono_type (reftype->type);
3548         domain = ((MonoObject *)type)->vtable->domain;
3549         array_vtable = mono_class_vtable_full (domain, MethodInfo_array, TRUE);
3550         if (type->type->byref)
3551                 return mono_array_new_specific (array_vtable, 0);
3552
3553         if (name)
3554                 mname = mono_string_to_utf8 (name);
3555
3556         method_array = mono_class_get_methods_by_name (klass, mname, bflags, ignore_case, FALSE, &ex);
3557         g_free ((char*)mname);
3558         if (ex) {
3559                 mono_set_pending_exception (ex);
3560                 return NULL;
3561         }
3562
3563         res = mono_array_new_specific (array_vtable, method_array->len);
3564
3565         for (i = 0; i < method_array->len; ++i) {
3566                 MonoMethod *method = g_ptr_array_index (method_array, i);
3567                 mono_array_setref (res, i, mono_method_get_object (domain, method, refklass));
3568         }
3569
3570         g_ptr_array_free (method_array, TRUE);
3571         return res;
3572 }
3573
3574 ICALL_EXPORT MonoArray*
3575 ves_icall_Type_GetConstructors_internal (MonoReflectionType *type, guint32 bflags, MonoReflectionType *reftype)
3576 {
3577         MonoDomain *domain; 
3578         static MonoClass *System_Reflection_ConstructorInfo;
3579         MonoClass *startklass, *klass, *refklass;
3580         MonoArray *res;
3581         MonoMethod *method;
3582         MonoObject *member;
3583         int i, match;
3584         gpointer iter = NULL;
3585         MonoPtrArray tmp_array;
3586         
3587         mono_ptr_array_init (tmp_array, 4); /*FIXME, guestimating*/
3588
3589         domain = ((MonoObject *)type)->vtable->domain;
3590         if (type->type->byref)
3591                 return mono_array_new_cached (domain, mono_defaults.method_info_class, 0);
3592         klass = startklass = mono_class_from_mono_type (type->type);
3593         refklass = mono_class_from_mono_type (reftype->type);
3594
3595         if (!System_Reflection_ConstructorInfo)
3596                 System_Reflection_ConstructorInfo = mono_class_from_name (
3597                         mono_defaults.corlib, "System.Reflection", "ConstructorInfo");
3598
3599         mono_class_setup_methods (klass);
3600         if (klass->exception_type != MONO_EXCEPTION_NONE) {
3601                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
3602                 return NULL;
3603         }
3604
3605         iter = NULL;
3606         while ((method = mono_class_get_methods (klass, &iter))) {
3607                 match = 0;
3608                 if (strcmp (method->name, ".ctor") && strcmp (method->name, ".cctor"))
3609                         continue;
3610                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3611                         if (bflags & BFLAGS_Public)
3612                                 match++;
3613                 } else {
3614                         if (bflags & BFLAGS_NonPublic)
3615                                 match++;
3616                 }
3617                 if (!match)
3618                         continue;
3619                 match = 0;
3620                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3621                         if (bflags & BFLAGS_Static)
3622                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3623                                         match++;
3624                 } else {
3625                         if (bflags & BFLAGS_Instance)
3626                                 match++;
3627                 }
3628
3629                 if (!match)
3630                         continue;
3631                 member = (MonoObject*)mono_method_get_object (domain, method, refklass);
3632
3633                 mono_ptr_array_append (tmp_array, member);
3634         }
3635
3636         res = mono_array_new_cached (domain, System_Reflection_ConstructorInfo, mono_ptr_array_size (tmp_array));
3637
3638         for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3639                 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3640
3641         mono_ptr_array_destroy (tmp_array);
3642
3643         return res;
3644 }
3645
3646 static guint
3647 property_hash (gconstpointer data)
3648 {
3649         MonoProperty *prop = (MonoProperty*)data;
3650
3651         return g_str_hash (prop->name);
3652 }
3653
3654 static gboolean
3655 property_equal (MonoProperty *prop1, MonoProperty *prop2)
3656 {
3657         // Properties are hide-by-name-and-signature
3658         if (!g_str_equal (prop1->name, prop2->name))
3659                 return FALSE;
3660
3661         if (prop1->get && prop2->get && !mono_metadata_signature_equal (mono_method_signature (prop1->get), mono_method_signature (prop2->get)))
3662                 return FALSE;
3663         if (prop1->set && prop2->set && !mono_metadata_signature_equal (mono_method_signature (prop1->set), mono_method_signature (prop2->set)))
3664                 return FALSE;
3665         return TRUE;
3666 }
3667
3668 static gboolean
3669 property_accessor_nonpublic (MonoMethod* accessor, gboolean start_klass)
3670 {
3671         if (!accessor)
3672                 return FALSE;
3673
3674         return method_nonpublic (accessor, start_klass);
3675 }
3676
3677 ICALL_EXPORT MonoArray*
3678 ves_icall_Type_GetPropertiesByName (MonoReflectionType *type, MonoString *name, guint32 bflags, MonoBoolean ignore_case, MonoReflectionType *reftype)
3679 {
3680         MonoException *ex;
3681         MonoDomain *domain; 
3682         static MonoClass *System_Reflection_PropertyInfo;
3683         MonoClass *startklass, *klass;
3684         MonoArray *res;
3685         MonoMethod *method;
3686         MonoProperty *prop;
3687         int i, match;
3688         guint32 flags;
3689         gchar *propname = NULL;
3690         int (*compare_func) (const char *s1, const char *s2) = NULL;
3691         gpointer iter;
3692         GHashTable *properties = NULL;
3693         MonoPtrArray tmp_array;
3694
3695         mono_ptr_array_init (tmp_array, 8); /*This the average for ASP.NET types*/
3696
3697         if (!System_Reflection_PropertyInfo)
3698                 System_Reflection_PropertyInfo = mono_class_from_name (
3699                         mono_defaults.corlib, "System.Reflection", "PropertyInfo");
3700
3701         domain = ((MonoObject *)type)->vtable->domain;
3702         if (type->type->byref)
3703                 return mono_array_new_cached (domain, System_Reflection_PropertyInfo, 0);
3704         klass = startklass = mono_class_from_mono_type (type->type);
3705
3706         if (name != NULL) {
3707                 propname = mono_string_to_utf8 (name);
3708                 compare_func = (ignore_case) ? mono_utf8_strcasecmp : strcmp;
3709         }
3710
3711         properties = g_hash_table_new (property_hash, (GEqualFunc)property_equal);
3712 handle_parent:
3713         mono_class_setup_methods (klass);
3714         mono_class_setup_vtable (klass);
3715         if (klass->exception_type != MONO_EXCEPTION_NONE || mono_loader_get_last_error ())
3716                 goto loader_error;
3717
3718         iter = NULL;
3719         while ((prop = mono_class_get_properties (klass, &iter))) {
3720                 match = 0;
3721                 method = prop->get;
3722                 if (!method)
3723                         method = prop->set;
3724                 if (method)
3725                         flags = method->flags;
3726                 else
3727                         flags = 0;
3728                 if ((prop->get && ((prop->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)) ||
3729                         (prop->set && ((prop->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC))) {
3730                         if (bflags & BFLAGS_Public)
3731                                 match++;
3732                 } else if (bflags & BFLAGS_NonPublic) {
3733                         if (property_accessor_nonpublic(prop->get, startklass == klass) ||
3734                                 property_accessor_nonpublic(prop->set, startklass == klass)) {
3735                                 match++;
3736                         }
3737                 }
3738                 if (!match)
3739                         continue;
3740                 match = 0;
3741                 if (flags & METHOD_ATTRIBUTE_STATIC) {
3742                         if (bflags & BFLAGS_Static)
3743                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3744                                         match++;
3745                 } else {
3746                         if (bflags & BFLAGS_Instance)
3747                                 match++;
3748                 }
3749
3750                 if (!match)
3751                         continue;
3752                 match = 0;
3753
3754                 if (name != NULL) {
3755                         if (compare_func (propname, prop->name))
3756                                 continue;
3757                 }
3758                 
3759                 if (g_hash_table_lookup (properties, prop))
3760                         continue;
3761
3762                 mono_ptr_array_append (tmp_array, mono_property_get_object (domain, startklass, prop));
3763                 
3764                 g_hash_table_insert (properties, prop, prop);
3765         }
3766         if ((!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent)))
3767                 goto handle_parent;
3768
3769         g_hash_table_destroy (properties);
3770         g_free (propname);
3771
3772         res = mono_array_new_cached (domain, System_Reflection_PropertyInfo, mono_ptr_array_size (tmp_array));
3773         for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3774                 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3775
3776         mono_ptr_array_destroy (tmp_array);
3777
3778         return res;
3779
3780 loader_error:
3781         if (properties)
3782                 g_hash_table_destroy (properties);
3783         if (name)
3784                 g_free (propname);
3785         mono_ptr_array_destroy (tmp_array);
3786
3787         if (klass->exception_type != MONO_EXCEPTION_NONE) {
3788                 ex = mono_class_get_exception_for_failure (klass);
3789         } else {
3790                 ex = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
3791                 mono_loader_clear_error ();
3792         }
3793         mono_set_pending_exception (ex);
3794         return NULL;
3795 }
3796
3797 ICALL_EXPORT MonoReflectionEvent *
3798 ves_icall_MonoType_GetEvent (MonoReflectionType *type, MonoString *name, guint32 bflags)
3799 {
3800         MonoDomain *domain;
3801         MonoClass *klass, *startklass;
3802         gpointer iter;
3803         MonoEvent *event;
3804         MonoMethod *method;
3805         gchar *event_name;
3806         int (*compare_func) (const char *s1, const char *s2);
3807
3808         event_name = mono_string_to_utf8 (name);
3809         if (type->type->byref)
3810                 return NULL;
3811         klass = startklass = mono_class_from_mono_type (type->type);
3812         domain = mono_object_domain (type);
3813
3814         mono_class_init_or_throw (klass);
3815
3816         compare_func = (bflags & BFLAGS_IgnoreCase) ? mono_utf8_strcasecmp : strcmp;
3817 handle_parent:  
3818         if (klass->exception_type != MONO_EXCEPTION_NONE) {
3819                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
3820                 return NULL;
3821         }
3822
3823         iter = NULL;
3824         while ((event = mono_class_get_events (klass, &iter))) {
3825                 if (compare_func (event->name, event_name))
3826                         continue;
3827
3828                 method = event->add;
3829                 if (!method)
3830                         method = event->remove;
3831                 if (!method)
3832                         method = event->raise;
3833                 if (method) {
3834                         if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3835                                 if (!(bflags & BFLAGS_Public))
3836                                         continue;
3837                         } else {
3838                                 if (!(bflags & BFLAGS_NonPublic))
3839                                         continue;
3840                                 if ((klass != startklass) && (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PRIVATE)
3841                                         continue;
3842                         }
3843
3844                         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3845                                 if (!(bflags & BFLAGS_Static))
3846                                         continue;
3847                                 if (!(bflags & BFLAGS_FlattenHierarchy) && (klass != startklass))
3848                                         continue;
3849                         } else {
3850                                 if (!(bflags & BFLAGS_Instance))
3851                                         continue;
3852                         }
3853                 } else 
3854                         if (!(bflags & BFLAGS_NonPublic))
3855                                 continue;
3856                 
3857                 g_free (event_name);
3858                 return mono_event_get_object (domain, startklass, event);
3859         }
3860
3861         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3862                 goto handle_parent;
3863
3864         g_free (event_name);
3865         return NULL;
3866 }
3867
3868 static guint
3869 event_hash (gconstpointer data)
3870 {
3871         MonoEvent *event = (MonoEvent*)data;
3872
3873         return g_str_hash (event->name);
3874 }
3875
3876 static gboolean
3877 event_equal (MonoEvent *event1, MonoEvent *event2)
3878 {
3879         // Events are hide-by-name
3880         return g_str_equal (event1->name, event2->name);
3881 }
3882
3883 ICALL_EXPORT MonoArray*
3884 ves_icall_Type_GetEvents_internal (MonoReflectionType *type, guint32 bflags, MonoReflectionType *reftype)
3885 {
3886         MonoException *ex;
3887         MonoDomain *domain; 
3888         static MonoClass *System_Reflection_EventInfo;
3889         MonoClass *startklass, *klass;
3890         MonoArray *res;
3891         MonoMethod *method;
3892         MonoEvent *event;
3893         int i, match;
3894         gpointer iter;
3895         GHashTable *events = NULL;
3896         MonoPtrArray tmp_array;
3897
3898         mono_ptr_array_init (tmp_array, 4);
3899
3900         if (!System_Reflection_EventInfo)
3901                 System_Reflection_EventInfo = mono_class_from_name (
3902                         mono_defaults.corlib, "System.Reflection", "EventInfo");
3903
3904         domain = mono_object_domain (type);
3905         if (type->type->byref)
3906                 return mono_array_new_cached (domain, System_Reflection_EventInfo, 0);
3907         klass = startklass = mono_class_from_mono_type (type->type);
3908
3909         events = g_hash_table_new (event_hash, (GEqualFunc)event_equal);
3910 handle_parent:
3911         mono_class_setup_methods (klass);
3912         mono_class_setup_vtable (klass);
3913         if (klass->exception_type != MONO_EXCEPTION_NONE || mono_loader_get_last_error ())
3914                 goto loader_error;
3915
3916         iter = NULL;
3917         while ((event = mono_class_get_events (klass, &iter))) {
3918                 match = 0;
3919                 method = event->add;
3920                 if (!method)
3921                         method = event->remove;
3922                 if (!method)
3923                         method = event->raise;
3924                 if (method) {
3925                         if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3926                                 if (bflags & BFLAGS_Public)
3927                                         match++;
3928                         } else if ((klass == startklass) || (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) {
3929                                 if (bflags & BFLAGS_NonPublic)
3930                                         match++;
3931                         }
3932                 }
3933                 else
3934                         if (bflags & BFLAGS_NonPublic)
3935                                 match ++;
3936                 if (!match)
3937                         continue;
3938                 match = 0;
3939                 if (method) {
3940                         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3941                                 if (bflags & BFLAGS_Static)
3942                                         if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3943                                                 match++;
3944                         } else {
3945                                 if (bflags & BFLAGS_Instance)
3946                                         match++;
3947                         }
3948                 }
3949                 else
3950                         if (bflags & BFLAGS_Instance)
3951                                 match ++;
3952                 if (!match)
3953                         continue;
3954
3955                 if (g_hash_table_lookup (events, event))
3956                         continue;
3957
3958                 mono_ptr_array_append (tmp_array, mono_event_get_object (domain, startklass, event));
3959
3960                 g_hash_table_insert (events, event, event);
3961         }
3962         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3963                 goto handle_parent;
3964
3965         g_hash_table_destroy (events);
3966
3967         res = mono_array_new_cached (domain, System_Reflection_EventInfo, mono_ptr_array_size (tmp_array));
3968
3969         for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3970                 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3971
3972         mono_ptr_array_destroy (tmp_array);
3973
3974         return res;
3975
3976 loader_error:
3977         mono_ptr_array_destroy (tmp_array);
3978         if (klass->exception_type != MONO_EXCEPTION_NONE) {
3979                 ex = mono_class_get_exception_for_failure (klass);
3980         } else {
3981                 ex = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
3982                 mono_loader_clear_error ();
3983         }
3984         mono_set_pending_exception (ex);
3985         return NULL;
3986 }
3987
3988 ICALL_EXPORT MonoReflectionType *
3989 ves_icall_Type_GetNestedType (MonoReflectionType *type, MonoString *name, guint32 bflags)
3990 {
3991         MonoDomain *domain; 
3992         MonoClass *klass;
3993         MonoClass *nested;
3994         char *str;
3995         gpointer iter;
3996         
3997         if (name == NULL) {
3998                 mono_set_pending_exception (mono_get_exception_argument_null ("name"));
3999                 return NULL;
4000         }
4001         
4002         domain = ((MonoObject *)type)->vtable->domain;
4003         if (type->type->byref)
4004                 return NULL;
4005         klass = mono_class_from_mono_type (type->type);
4006
4007         str = mono_string_to_utf8 (name);
4008
4009  handle_parent:
4010         if (klass->exception_type != MONO_EXCEPTION_NONE) {
4011                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
4012                 return NULL;
4013         }
4014
4015         /*
4016          * If a nested type is generic, return its generic type definition.
4017          * Note that this means that the return value is essentially a
4018          * nested type of the generic type definition of @klass.
4019          *
4020          * A note in MSDN claims that a generic type definition can have
4021          * nested types that aren't generic.  In any case, the container of that
4022          * nested type would be the generic type definition.
4023          */
4024         if (klass->generic_class)
4025                 klass = klass->generic_class->container_class;
4026
4027         iter = NULL;
4028         while ((nested = mono_class_get_nested_types (klass, &iter))) {
4029                 int match = 0;
4030                 if ((nested->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
4031                         if (bflags & BFLAGS_Public)
4032                                 match++;
4033                 } else {
4034                         if (bflags & BFLAGS_NonPublic)
4035                                 match++;
4036                 }
4037                 if (!match)
4038                         continue;
4039                 if (strcmp (nested->name, str) == 0){
4040                         g_free (str);
4041                         return mono_type_get_object (domain, &nested->byval_arg);
4042                 }
4043         }
4044         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
4045                 goto handle_parent;
4046         g_free (str);
4047         return NULL;
4048 }
4049
4050 ICALL_EXPORT MonoArray*
4051 ves_icall_Type_GetNestedTypes (MonoReflectionType *type, guint32 bflags)
4052 {
4053         MonoDomain *domain; 
4054         MonoClass *klass;
4055         MonoArray *res;
4056         MonoObject *member;
4057         int i, match;
4058         MonoClass *nested;
4059         gpointer iter;
4060         MonoPtrArray tmp_array;
4061
4062         domain = ((MonoObject *)type)->vtable->domain;
4063         if (type->type->byref)
4064                 return mono_array_new (domain, mono_defaults.monotype_class, 0);
4065         klass = mono_class_from_mono_type (type->type);
4066
4067         /*
4068          * If a nested type is generic, return its generic type definition.
4069          * Note that this means that the return value is essentially the set
4070          * of nested types of the generic type definition of @klass.
4071          *
4072          * A note in MSDN claims that a generic type definition can have
4073          * nested types that aren't generic.  In any case, the container of that
4074          * nested type would be the generic type definition.
4075          */
4076         if (klass->generic_class)
4077                 klass = klass->generic_class->container_class;
4078
4079         mono_ptr_array_init (tmp_array, 1);
4080         iter = NULL;
4081         while ((nested = mono_class_get_nested_types (klass, &iter))) {
4082                 match = 0;
4083                 if ((nested->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
4084                         if (bflags & BFLAGS_Public)
4085                                 match++;
4086                 } else {
4087                         if (bflags & BFLAGS_NonPublic)
4088                                 match++;
4089                 }
4090                 if (!match)
4091                         continue;
4092                 member = (MonoObject*)mono_type_get_object (domain, &nested->byval_arg);
4093                 mono_ptr_array_append (tmp_array, member);
4094         }
4095
4096         res = mono_array_new_cached (domain, mono_defaults.monotype_class, mono_ptr_array_size (tmp_array));
4097
4098         for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
4099                 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
4100
4101         mono_ptr_array_destroy (tmp_array);
4102
4103         return res;
4104 }
4105
4106 ICALL_EXPORT MonoReflectionType*
4107 ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssembly *assembly, MonoReflectionModule *module, MonoString *name, MonoBoolean throwOnError, MonoBoolean ignoreCase)
4108 {
4109         gchar *str;
4110         MonoType *type = NULL;
4111         MonoTypeNameParse info;
4112         gboolean type_resolve;
4113
4114         /* On MS.NET, this does not fire a TypeResolve event */
4115         type_resolve = TRUE;
4116         str = mono_string_to_utf8 (name);
4117         /*g_print ("requested type %s in %s\n", str, assembly->assembly->aname.name);*/
4118         if (!mono_reflection_parse_type (str, &info)) {
4119                 g_free (str);
4120                 mono_reflection_free_type_info (&info);
4121                 if (throwOnError) {
4122                         /* uhm: this is a parse error, though... */
4123                         mono_set_pending_exception (mono_get_exception_type_load (name, NULL));
4124                         return NULL;
4125                 }
4126                 /*g_print ("failed parse\n");*/
4127                 return NULL;
4128         }
4129
4130         if (info.assembly.name) {
4131                 g_free (str);
4132                 mono_reflection_free_type_info (&info);
4133                 if (throwOnError) {
4134                         /* 1.0 and 2.0 throw different exceptions */
4135                         if (mono_defaults.generic_ilist_class)
4136                                 mono_set_pending_exception (mono_get_exception_argument (NULL, "Type names passed to Assembly.GetType() must not specify an assembly."));
4137                         else
4138                                 mono_set_pending_exception (mono_get_exception_type_load (name, NULL));
4139                         return NULL;
4140                 }
4141                 return NULL;
4142         }
4143
4144         if (module != NULL) {
4145                 if (module->image)
4146                         type = mono_reflection_get_type (module->image, &info, ignoreCase, &type_resolve);
4147                 else
4148                         type = NULL;
4149         }
4150         else
4151                 if (assembly_is_dynamic (assembly->assembly)) {
4152                         /* Enumerate all modules */
4153                         MonoReflectionAssemblyBuilder *abuilder = (MonoReflectionAssemblyBuilder*)assembly;
4154                         int i;
4155
4156                         type = NULL;
4157                         if (abuilder->modules) {
4158                                 for (i = 0; i < mono_array_length (abuilder->modules); ++i) {
4159                                         MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
4160                                         type = mono_reflection_get_type (&mb->dynamic_image->image, &info, ignoreCase, &type_resolve);
4161                                         if (type)
4162                                                 break;
4163                                 }
4164                         }
4165
4166                         if (!type && abuilder->loaded_modules) {
4167                                 for (i = 0; i < mono_array_length (abuilder->loaded_modules); ++i) {
4168                                         MonoReflectionModule *mod = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
4169                                         type = mono_reflection_get_type (mod->image, &info, ignoreCase, &type_resolve);
4170                                         if (type)
4171                                                 break;
4172                                 }
4173                         }
4174                 }
4175                 else
4176                         type = mono_reflection_get_type (assembly->assembly->image, &info, ignoreCase, &type_resolve);
4177         g_free (str);
4178         mono_reflection_free_type_info (&info);
4179         if (!type) {
4180                 MonoException *e = NULL;
4181                 
4182                 if (throwOnError)
4183                         e = mono_get_exception_type_load (name, NULL);
4184
4185                 if (mono_loader_get_last_error () && mono_defaults.generic_ilist_class)
4186                         e = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
4187
4188                 mono_loader_clear_error ();
4189
4190                 if (e != NULL)
4191                         mono_set_pending_exception (e);
4192                 return NULL;
4193         } else if (mono_loader_get_last_error ()) {
4194                 if (throwOnError) {
4195                         mono_set_pending_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
4196                         return NULL;
4197                 }
4198                 mono_loader_clear_error ();
4199         }
4200
4201         if (type->type == MONO_TYPE_CLASS) {
4202                 MonoClass *klass = mono_type_get_class (type);
4203
4204                 if (mono_security_enabled () && !klass->exception_type)
4205                         /* Some security problems are detected during generic vtable construction */
4206                         mono_class_setup_vtable (klass);
4207
4208                 /* need to report exceptions ? */
4209                 if (throwOnError && klass->exception_type) {
4210                         /* report SecurityException (or others) that occured when loading the assembly */
4211                         MonoException *exc = mono_class_get_exception_for_failure (klass);
4212                         mono_loader_clear_error ();
4213                         mono_set_pending_exception (exc);
4214                         return NULL;
4215                 } else if (mono_security_enabled () && klass->exception_type == MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND) {
4216                         return NULL;
4217                 }
4218         }
4219
4220         /* g_print ("got it\n"); */
4221         return mono_type_get_object (mono_object_domain (assembly), type);
4222 }
4223
4224 static gboolean
4225 replace_shadow_path (MonoDomain *domain, gchar *dirname, gchar **filename)
4226 {
4227         gchar *content;
4228         gchar *shadow_ini_file;
4229         gsize len;
4230
4231         /* Check for shadow-copied assembly */
4232         if (mono_is_shadow_copy_enabled (domain, dirname)) {
4233                 shadow_ini_file = g_build_filename (dirname, "__AssemblyInfo__.ini", NULL);
4234                 content = NULL;
4235                 if (!g_file_get_contents (shadow_ini_file, &content, &len, NULL) ||
4236                         !g_file_test (content, G_FILE_TEST_IS_REGULAR)) {
4237                         if (content) {
4238                                 g_free (content);
4239                                 content = NULL;
4240                         }
4241                 }
4242                 g_free (shadow_ini_file);
4243                 if (content != NULL) {
4244                         if (*filename)
4245                                 g_free (*filename);
4246                         *filename = content;
4247                         return TRUE;
4248                 }
4249         }
4250         return FALSE;
4251 }
4252
4253 ICALL_EXPORT MonoString *
4254 ves_icall_System_Reflection_Assembly_get_code_base (MonoReflectionAssembly *assembly, MonoBoolean escaped)
4255 {
4256         MonoDomain *domain = mono_object_domain (assembly); 
4257         MonoAssembly *mass = assembly->assembly;
4258         MonoString *res = NULL;
4259         gchar *uri;
4260         gchar *absolute;
4261         gchar *dirname;
4262         
4263         if (g_path_is_absolute (mass->image->name)) {
4264                 absolute = g_strdup (mass->image->name);
4265                 dirname = g_path_get_dirname (absolute);
4266         } else {
4267                 absolute = g_build_filename (mass->basedir, mass->image->name, NULL);
4268                 dirname = g_strdup (mass->basedir);
4269         }
4270
4271         replace_shadow_path (domain, dirname, &absolute);
4272         g_free (dirname);
4273 #if HOST_WIN32
4274         {
4275                 gint i;
4276                 for (i = strlen (absolute) - 1; i >= 0; i--)
4277                         if (absolute [i] == '\\')
4278                                 absolute [i] = '/';
4279         }
4280 #endif
4281         if (escaped) {
4282                 uri = g_filename_to_uri (absolute, NULL, NULL);
4283         } else {
4284                 const char *prepend = "file://";
4285 #if HOST_WIN32
4286                 if (*absolute == '/' && *(absolute + 1) == '/') {
4287                         prepend = "file:";
4288                 } else {
4289                         prepend = "file:///";
4290                 }
4291 #endif
4292                 uri = g_strconcat (prepend, absolute, NULL);
4293         }
4294
4295         if (uri) {
4296                 res = mono_string_new (domain, uri);
4297                 g_free (uri);
4298         }
4299         g_free (absolute);
4300         return res;
4301 }
4302
4303 ICALL_EXPORT MonoBoolean
4304 ves_icall_System_Reflection_Assembly_get_global_assembly_cache (MonoReflectionAssembly *assembly)
4305 {
4306         MonoAssembly *mass = assembly->assembly;
4307
4308         return mass->in_gac;
4309 }
4310
4311 ICALL_EXPORT MonoReflectionAssembly*
4312 ves_icall_System_Reflection_Assembly_load_with_partial_name (MonoString *mname, MonoObject *evidence)
4313 {
4314         gchar *name;
4315         MonoAssembly *res;
4316         MonoImageOpenStatus status;
4317         
4318         name = mono_string_to_utf8 (mname);
4319         res = mono_assembly_load_with_partial_name (name, &status);
4320
4321         g_free (name);
4322
4323         if (res == NULL)
4324                 return NULL;
4325         return mono_assembly_get_object (mono_domain_get (), res);
4326 }
4327
4328 ICALL_EXPORT MonoString *
4329 ves_icall_System_Reflection_Assembly_get_location (MonoReflectionAssembly *assembly)
4330 {
4331         MonoDomain *domain = mono_object_domain (assembly); 
4332         MonoString *res;
4333
4334         res = mono_string_new (domain, mono_image_get_filename (assembly->assembly->image));
4335
4336         return res;
4337 }
4338
4339 ICALL_EXPORT MonoBoolean
4340 ves_icall_System_Reflection_Assembly_get_ReflectionOnly (MonoReflectionAssembly *assembly)
4341 {
4342         return assembly->assembly->ref_only;
4343 }
4344
4345 ICALL_EXPORT MonoString *
4346 ves_icall_System_Reflection_Assembly_InternalImageRuntimeVersion (MonoReflectionAssembly *assembly)
4347 {
4348         MonoDomain *domain = mono_object_domain (assembly); 
4349
4350         return mono_string_new (domain, assembly->assembly->image->version);
4351 }
4352
4353 ICALL_EXPORT MonoReflectionMethod*
4354 ves_icall_System_Reflection_Assembly_get_EntryPoint (MonoReflectionAssembly *assembly) 
4355 {
4356         MonoError error;
4357         MonoMethod *method;
4358         guint32 token = mono_image_get_entry_point (assembly->assembly->image);
4359
4360         if (!token)
4361                 return NULL;
4362         method = mono_get_method_checked (assembly->assembly->image, token, NULL, NULL, &error);
4363         mono_error_raise_exception (&error);
4364
4365         return mono_method_get_object (mono_object_domain (assembly), method, NULL);
4366 }
4367
4368 ICALL_EXPORT MonoReflectionModule*
4369 ves_icall_System_Reflection_Assembly_GetManifestModuleInternal (MonoReflectionAssembly *assembly) 
4370 {
4371         return mono_module_get_object (mono_object_domain (assembly), assembly->assembly->image);
4372 }
4373
4374 ICALL_EXPORT MonoArray*
4375 ves_icall_System_Reflection_Assembly_GetManifestResourceNames (MonoReflectionAssembly *assembly) 
4376 {
4377         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4378         MonoArray *result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, table->rows);
4379         int i;
4380         const char *val;
4381
4382         for (i = 0; i < table->rows; ++i) {
4383                 val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_MANIFEST_NAME));
4384                 mono_array_setref (result, i, mono_string_new (mono_object_domain (assembly), val));
4385         }
4386         return result;
4387 }
4388
4389 static MonoObject*
4390 create_version (MonoDomain *domain, guint32 major, guint32 minor, guint32 build, guint32 revision)
4391 {
4392         static MonoClass *System_Version = NULL;
4393         static MonoMethod *create_version = NULL;
4394         MonoObject *result;
4395         gpointer args [4];
4396         
4397         if (!System_Version) {
4398                 System_Version = mono_class_from_name (mono_defaults.corlib, "System", "Version");
4399                 g_assert (System_Version);
4400         }
4401
4402         if (!create_version) {
4403                 MonoMethodDesc *desc = mono_method_desc_new (":.ctor(int,int,int,int)", FALSE);
4404                 create_version = mono_method_desc_search_in_class (desc, System_Version);
4405                 g_assert (create_version);
4406                 mono_method_desc_free (desc);
4407         }
4408
4409         args [0] = &major;
4410         args [1] = &minor;
4411         args [2] = &build;
4412         args [3] = &revision;
4413         result = mono_object_new (domain, System_Version);
4414         mono_runtime_invoke (create_version, result, args, NULL);
4415
4416         return result;
4417 }
4418
4419 ICALL_EXPORT MonoArray*
4420 ves_icall_System_Reflection_Assembly_GetReferencedAssemblies (MonoReflectionAssembly *assembly) 
4421 {
4422         static MonoClass *System_Reflection_AssemblyName;
4423         MonoArray *result;
4424         MonoDomain *domain = mono_object_domain (assembly);
4425         int i, count = 0;
4426         static MonoMethod *create_culture = NULL;
4427         MonoImage *image = assembly->assembly->image;
4428         MonoTableInfo *t;
4429
4430         if (!System_Reflection_AssemblyName)
4431                 System_Reflection_AssemblyName = mono_class_from_name (
4432                         mono_defaults.corlib, "System.Reflection", "AssemblyName");
4433
4434         t = &assembly->assembly->image->tables [MONO_TABLE_ASSEMBLYREF];
4435         count = t->rows;
4436
4437         result = mono_array_new (domain, System_Reflection_AssemblyName, count);
4438
4439         if (count > 0 && !create_culture) {
4440                 MonoMethodDesc *desc = mono_method_desc_new (
4441                         "System.Globalization.CultureInfo:CreateCulture(string,bool)", TRUE);
4442                 create_culture = mono_method_desc_search_in_image (desc, mono_defaults.corlib);
4443                 g_assert (create_culture);
4444                 mono_method_desc_free (desc);
4445         }
4446
4447         for (i = 0; i < count; i++) {
4448                 MonoReflectionAssemblyName *aname;
4449                 guint32 cols [MONO_ASSEMBLYREF_SIZE];
4450
4451                 mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE);
4452
4453                 aname = (MonoReflectionAssemblyName *) mono_object_new (
4454                         domain, System_Reflection_AssemblyName);
4455
4456                 MONO_OBJECT_SETREF (aname, name, mono_string_new (domain, mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_NAME])));
4457
4458                 aname->major = cols [MONO_ASSEMBLYREF_MAJOR_VERSION];
4459                 aname->minor = cols [MONO_ASSEMBLYREF_MINOR_VERSION];
4460                 aname->build = cols [MONO_ASSEMBLYREF_BUILD_NUMBER];
4461                 aname->revision = cols [MONO_ASSEMBLYREF_REV_NUMBER];
4462                 aname->flags = cols [MONO_ASSEMBLYREF_FLAGS];
4463                 aname->versioncompat = 1; /* SameMachine (default) */
4464                 aname->hashalg = ASSEMBLY_HASH_SHA1; /* SHA1 (default) */
4465                 MONO_OBJECT_SETREF (aname, version, create_version (domain, aname->major, aname->minor, aname->build, aname->revision));
4466
4467                 if (create_culture) {
4468                         gpointer args [2];
4469                         MonoBoolean assembly_ref = 1;
4470                         args [0] = mono_string_new (domain, mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_CULTURE]));
4471                         args [1] = &assembly_ref;
4472                         MONO_OBJECT_SETREF (aname, cultureInfo, mono_runtime_invoke (create_culture, NULL, args, NULL));
4473                 }
4474                 
4475                 if (cols [MONO_ASSEMBLYREF_PUBLIC_KEY]) {
4476                         const gchar *pkey_ptr = mono_metadata_blob_heap (image, cols [MONO_ASSEMBLYREF_PUBLIC_KEY]);
4477                         guint32 pkey_len = mono_metadata_decode_blob_size (pkey_ptr, &pkey_ptr);
4478
4479                         if ((cols [MONO_ASSEMBLYREF_FLAGS] & ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG)) {
4480                                 /* public key token isn't copied - the class library will 
4481                                 automatically generate it from the public key if required */
4482                                 MONO_OBJECT_SETREF (aname, publicKey, mono_array_new (domain, mono_defaults.byte_class, pkey_len));
4483                                 memcpy (mono_array_addr (aname->publicKey, guint8, 0), pkey_ptr, pkey_len);
4484                         } else {
4485                                 MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, pkey_len));
4486                                 memcpy (mono_array_addr (aname->keyToken, guint8, 0), pkey_ptr, pkey_len);
4487                         }
4488                 } else {
4489                         MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, 0));
4490                 }
4491                 
4492                 /* note: this function doesn't return the codebase on purpose (i.e. it can
4493                          be used under partial trust as path information isn't present). */
4494
4495                 mono_array_setref (result, i, aname);
4496         }
4497         return result;
4498 }
4499
4500 /* move this in some file in mono/util/ */
4501 static char *
4502 g_concat_dir_and_file (const char *dir, const char *file)
4503 {
4504         g_return_val_if_fail (dir != NULL, NULL);
4505         g_return_val_if_fail (file != NULL, NULL);
4506
4507         /*
4508          * If the directory name doesn't have a / on the end, we need
4509          * to add one so we get a proper path to the file
4510          */
4511         if (dir [strlen(dir) - 1] != G_DIR_SEPARATOR)
4512                 return g_strconcat (dir, G_DIR_SEPARATOR_S, file, NULL);
4513         else
4514                 return g_strconcat (dir, file, NULL);
4515 }
4516
4517 ICALL_EXPORT void *
4518 ves_icall_System_Reflection_Assembly_GetManifestResourceInternal (MonoReflectionAssembly *assembly, MonoString *name, gint32 *size, MonoReflectionModule **ref_module) 
4519 {
4520         char *n = mono_string_to_utf8 (name);
4521         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4522         guint32 i;
4523         guint32 cols [MONO_MANIFEST_SIZE];
4524         guint32 impl, file_idx;
4525         const char *val;
4526         MonoImage *module;
4527
4528         for (i = 0; i < table->rows; ++i) {
4529                 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
4530                 val = mono_metadata_string_heap (assembly->assembly->image, cols [MONO_MANIFEST_NAME]);
4531                 if (strcmp (val, n) == 0)
4532                         break;
4533         }
4534         g_free (n);
4535         if (i == table->rows)
4536                 return NULL;
4537         /* FIXME */
4538         impl = cols [MONO_MANIFEST_IMPLEMENTATION];
4539         if (impl) {
4540                 /*
4541                  * this code should only be called after obtaining the 
4542                  * ResourceInfo and handling the other cases.
4543                  */
4544                 g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE);
4545                 file_idx = impl >> MONO_IMPLEMENTATION_BITS;
4546
4547                 module = mono_image_load_file_for_image (assembly->assembly->image, file_idx);
4548                 if (!module)
4549                         return NULL;
4550         }
4551         else
4552                 module = assembly->assembly->image;
4553
4554         mono_gc_wbarrier_generic_store (ref_module, (MonoObject*) mono_module_get_object (mono_domain_get (), module));
4555
4556         return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], (guint32*)size);
4557 }
4558
4559 ICALL_EXPORT gboolean
4560 ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal (MonoReflectionAssembly *assembly, MonoString *name, MonoManifestResourceInfo *info)
4561 {
4562         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4563         int i;
4564         guint32 cols [MONO_MANIFEST_SIZE];
4565         guint32 file_cols [MONO_FILE_SIZE];
4566         const char *val;
4567         char *n;
4568
4569         n = mono_string_to_utf8 (name);
4570         for (i = 0; i < table->rows; ++i) {
4571                 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
4572                 val = mono_metadata_string_heap (assembly->assembly->image, cols [MONO_MANIFEST_NAME]);
4573                 if (strcmp (val, n) == 0)
4574                         break;
4575         }
4576         g_free (n);
4577         if (i == table->rows)
4578                 return FALSE;
4579
4580         if (!cols [MONO_MANIFEST_IMPLEMENTATION]) {
4581                 info->location = RESOURCE_LOCATION_EMBEDDED | RESOURCE_LOCATION_IN_MANIFEST;
4582         }
4583         else {
4584                 switch (cols [MONO_MANIFEST_IMPLEMENTATION] & MONO_IMPLEMENTATION_MASK) {
4585                 case MONO_IMPLEMENTATION_FILE:
4586                         i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
4587                         table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
4588                         mono_metadata_decode_row (table, i - 1, file_cols, MONO_FILE_SIZE);
4589                         val = mono_metadata_string_heap (assembly->assembly->image, file_cols [MONO_FILE_NAME]);
4590                         MONO_OBJECT_SETREF (info, filename, mono_string_new (mono_object_domain (assembly), val));
4591                         if (file_cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA)
4592                                 info->location = 0;
4593                         else
4594                                 info->location = RESOURCE_LOCATION_EMBEDDED;
4595                         break;
4596
4597                 case MONO_IMPLEMENTATION_ASSEMBLYREF:
4598                         i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
4599                         mono_assembly_load_reference (assembly->assembly->image, i - 1);
4600                         if (assembly->assembly->image->references [i - 1] == (gpointer)-1) {
4601                                 char *msg = g_strdup_printf ("Assembly %d referenced from assembly %s not found ", i - 1, assembly->assembly->image->name);
4602                                 MonoException *ex = mono_get_exception_file_not_found2 (msg, NULL);
4603                                 g_free (msg);
4604                                 mono_set_pending_exception (ex);
4605                                 return FALSE;
4606                         }
4607                         MONO_OBJECT_SETREF (info, assembly, mono_assembly_get_object (mono_domain_get (), assembly->assembly->image->references [i - 1]));
4608
4609                         /* Obtain info recursively */
4610                         ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal (info->assembly, name, info);
4611                         info->location |= RESOURCE_LOCATION_ANOTHER_ASSEMBLY;
4612                         break;
4613
4614                 case MONO_IMPLEMENTATION_EXP_TYPE:
4615                         g_assert_not_reached ();
4616                         break;
4617                 }
4618         }
4619
4620         return TRUE;
4621 }
4622
4623 ICALL_EXPORT MonoObject*
4624 ves_icall_System_Reflection_Assembly_GetFilesInternal (MonoReflectionAssembly *assembly, MonoString *name, MonoBoolean resource_modules) 
4625 {
4626         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
4627         MonoArray *result = NULL;
4628         int i, count;
4629         const char *val;
4630         char *n;
4631
4632         /* check hash if needed */
4633         if (name) {
4634                 n = mono_string_to_utf8 (name);
4635                 for (i = 0; i < table->rows; ++i) {
4636                         val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
4637                         if (strcmp (val, n) == 0) {
4638                                 MonoString *fn;
4639                                 g_free (n);
4640                                 n = g_concat_dir_and_file (assembly->assembly->basedir, val);
4641                                 fn = mono_string_new (mono_object_domain (assembly), n);
4642                                 g_free (n);
4643                                 return (MonoObject*)fn;
4644                         }
4645                 }
4646                 g_free (n);
4647                 return NULL;
4648         }
4649
4650         count = 0;
4651         for (i = 0; i < table->rows; ++i) {
4652                 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA))
4653                         count ++;
4654         }
4655
4656         result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, count);
4657
4658         count = 0;
4659         for (i = 0; i < table->rows; ++i) {
4660                 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
4661                         val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
4662                         n = g_concat_dir_and_file (assembly->assembly->basedir, val);
4663                         mono_array_setref (result, count, mono_string_new (mono_object_domain (assembly), n));
4664                         g_free (n);
4665                         count ++;
4666                 }
4667         }
4668         return (MonoObject*)result;
4669 }
4670
4671 ICALL_EXPORT MonoArray*
4672 ves_icall_System_Reflection_Assembly_GetModulesInternal (MonoReflectionAssembly *assembly)
4673 {
4674         MonoDomain *domain = mono_domain_get();
4675         MonoArray *res;
4676         MonoClass *klass;
4677         int i, j, file_count = 0;
4678         MonoImage **modules;
4679         guint32 module_count, real_module_count;
4680         MonoTableInfo *table;
4681         guint32 cols [MONO_FILE_SIZE];
4682         MonoImage *image = assembly->assembly->image;
4683
4684         g_assert (image != NULL);
4685         g_assert (!assembly_is_dynamic (assembly->assembly));
4686
4687         table = &image->tables [MONO_TABLE_FILE];
4688         file_count = table->rows;
4689
4690         modules = image->modules;
4691         module_count = image->module_count;
4692
4693         real_module_count = 0;
4694         for (i = 0; i < module_count; ++i)
4695                 if (modules [i])
4696                         real_module_count ++;
4697
4698         klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Module");
4699         res = mono_array_new (domain, klass, 1 + real_module_count + file_count);
4700
4701         mono_array_setref (res, 0, mono_module_get_object (domain, image));
4702         j = 1;
4703         for (i = 0; i < module_count; ++i)
4704                 if (modules [i]) {
4705                         mono_array_setref (res, j, mono_module_get_object (domain, modules[i]));
4706                         ++j;
4707                 }
4708
4709         for (i = 0; i < file_count; ++i, ++j) {
4710                 mono_metadata_decode_row (table, i, cols, MONO_FILE_SIZE);
4711                 if (cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA)
4712                         mono_array_setref (res, j, mono_module_file_get_object (domain, image, i));
4713                 else {
4714                         MonoImage *m = mono_image_load_file_for_image (image, i + 1);
4715                         if (!m) {
4716                                 MonoString *fname = mono_string_new (mono_domain_get (), mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
4717                                 mono_set_pending_exception (mono_get_exception_file_not_found2 (NULL, fname));
4718                                 return NULL;
4719                         }
4720                         mono_array_setref (res, j, mono_module_get_object (domain, m));
4721                 }
4722         }
4723
4724         return res;
4725 }
4726
4727 ICALL_EXPORT MonoReflectionMethod*
4728 ves_icall_GetCurrentMethod (void) 
4729 {
4730         MonoMethod *m = mono_method_get_last_managed ();
4731
4732         while (m->is_inflated)
4733                 m = ((MonoMethodInflated*)m)->declaring;
4734
4735         return mono_method_get_object (mono_domain_get (), m, NULL);
4736 }
4737
4738
4739 static MonoMethod*
4740 mono_method_get_equivalent_method (MonoMethod *method, MonoClass *klass)
4741 {
4742         int offset = -1, i;
4743         if (method->is_inflated && ((MonoMethodInflated*)method)->context.method_inst) {
4744                 MonoError error;
4745                 MonoMethod *result;
4746                 MonoMethodInflated *inflated = (MonoMethodInflated*)method;
4747                 //method is inflated, we should inflate it on the other class
4748                 MonoGenericContext ctx;
4749                 ctx.method_inst = inflated->context.method_inst;
4750                 ctx.class_inst = inflated->context.class_inst;
4751                 if (klass->generic_class)
4752                         ctx.class_inst = klass->generic_class->context.class_inst;
4753                 else if (klass->generic_container)
4754                         ctx.class_inst = klass->generic_container->context.class_inst;
4755                 result = mono_class_inflate_generic_method_full_checked (inflated->declaring, klass, &ctx, &error);
4756                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4757                 return result;
4758         }
4759
4760         mono_class_setup_methods (method->klass);
4761         if (method->klass->exception_type)
4762                 return NULL;
4763         for (i = 0; i < method->klass->method.count; ++i) {
4764                 if (method->klass->methods [i] == method) {
4765                         offset = i;
4766                         break;
4767                 }       
4768         }
4769         mono_class_setup_methods (klass);
4770         if (klass->exception_type)
4771                 return NULL;
4772         g_assert (offset >= 0 && offset < klass->method.count);
4773         return klass->methods [offset];
4774 }
4775
4776 ICALL_EXPORT MonoReflectionMethod*
4777 ves_icall_System_Reflection_MethodBase_GetMethodFromHandleInternalType (MonoMethod *method, MonoType *type)
4778 {
4779         MonoClass *klass;
4780         if (type) {
4781                 klass = mono_class_from_mono_type (type);
4782                 if (mono_class_get_generic_type_definition (method->klass) != mono_class_get_generic_type_definition (klass)) 
4783                         return NULL;
4784                 if (method->klass != klass) {
4785                         method = mono_method_get_equivalent_method (method, klass);
4786                         if (!method)
4787                                 return NULL;
4788                 }
4789         } else
4790                 klass = method->klass;
4791         return mono_method_get_object (mono_domain_get (), method, klass);
4792 }
4793
4794 ICALL_EXPORT MonoReflectionMethod*
4795 ves_icall_System_Reflection_MethodBase_GetMethodFromHandleInternal (MonoMethod *method)
4796 {
4797         return mono_method_get_object (mono_domain_get (), method, NULL);
4798 }
4799
4800 ICALL_EXPORT MonoReflectionMethodBody*
4801 ves_icall_System_Reflection_MethodBase_GetMethodBodyInternal (MonoMethod *method)
4802 {
4803         return mono_method_body_get_object (mono_domain_get (), method);
4804 }
4805
4806 ICALL_EXPORT MonoReflectionAssembly*
4807 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (void)
4808 {
4809         MonoMethod *dest = NULL;
4810
4811         mono_stack_walk_no_il (get_executing, &dest);
4812         g_assert (dest);
4813         return mono_assembly_get_object (mono_domain_get (), dest->klass->image->assembly);
4814 }
4815
4816
4817 ICALL_EXPORT MonoReflectionAssembly*
4818 ves_icall_System_Reflection_Assembly_GetEntryAssembly (void)
4819 {
4820         MonoDomain* domain = mono_domain_get ();
4821
4822         if (!domain->entry_assembly)
4823                 return NULL;
4824
4825         return mono_assembly_get_object (domain, domain->entry_assembly);
4826 }
4827
4828 ICALL_EXPORT MonoReflectionAssembly*
4829 ves_icall_System_Reflection_Assembly_GetCallingAssembly (void)
4830 {
4831         MonoMethod *m;
4832         MonoMethod *dest;
4833
4834         dest = NULL;
4835         mono_stack_walk_no_il (get_executing, &dest);
4836         m = dest;
4837         mono_stack_walk_no_il (get_caller, &dest);
4838         if (!dest)
4839                 dest = m;
4840         return mono_assembly_get_object (mono_domain_get (), dest->klass->image->assembly);
4841 }
4842
4843 ICALL_EXPORT MonoString *
4844 ves_icall_System_MonoType_getFullName (MonoReflectionType *object, gboolean full_name,
4845                                        gboolean assembly_qualified)
4846 {
4847         MonoDomain *domain = mono_object_domain (object); 
4848         MonoTypeNameFormat format;
4849         MonoString *res;
4850         gchar *name;
4851
4852         if (full_name)
4853                 format = assembly_qualified ?
4854                         MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED :
4855                         MONO_TYPE_NAME_FORMAT_FULL_NAME;
4856         else
4857                 format = MONO_TYPE_NAME_FORMAT_REFLECTION;
4858  
4859         name = mono_type_get_name_full (object->type, format);
4860         if (!name)
4861                 return NULL;
4862
4863         if (full_name && (object->type->type == MONO_TYPE_VAR || object->type->type == MONO_TYPE_MVAR)) {
4864                 g_free (name);
4865                 return NULL;
4866         }
4867
4868         res = mono_string_new (domain, name);
4869         g_free (name);
4870
4871         return res;
4872 }
4873
4874 ICALL_EXPORT int
4875 vell_icall_MonoType_get_core_clr_security_level (MonoReflectionType *this)
4876 {
4877         MonoClass *klass = mono_class_from_mono_type (this->type);
4878         mono_class_init_or_throw (klass);
4879         return mono_security_core_clr_class_level (klass);
4880 }
4881
4882 static void
4883 fill_reflection_assembly_name (MonoDomain *domain, MonoReflectionAssemblyName *aname, MonoAssemblyName *name, const char *absolute, gboolean by_default_version, gboolean default_publickey, gboolean default_token)
4884 {
4885         static MonoMethod *create_culture = NULL;
4886         gpointer args [2];
4887         guint32 pkey_len;
4888         const char *pkey_ptr;
4889         gchar *codebase;
4890         MonoBoolean assembly_ref = 0;
4891
4892         MONO_OBJECT_SETREF (aname, name, mono_string_new (domain, name->name));
4893         aname->major = name->major;
4894         aname->minor = name->minor;
4895         aname->build = name->build;
4896         aname->flags = name->flags;
4897         aname->revision = name->revision;
4898         aname->hashalg = name->hash_alg;
4899         aname->versioncompat = 1; /* SameMachine (default) */
4900         aname->processor_architecture = name->arch;
4901
4902         if (by_default_version)
4903                 MONO_OBJECT_SETREF (aname, version, create_version (domain, name->major, name->minor, name->build, name->revision));
4904
4905         codebase = NULL;
4906         if (absolute != NULL && *absolute != '\0') {
4907                 const gchar *prepend = "file://";
4908                 gchar *result;
4909
4910                 codebase = g_strdup (absolute);
4911
4912 #if HOST_WIN32
4913                 {
4914                         gint i;
4915                         for (i = strlen (codebase) - 1; i >= 0; i--)
4916                                 if (codebase [i] == '\\')
4917                                         codebase [i] = '/';
4918
4919                         if (*codebase == '/' && *(codebase + 1) == '/') {
4920                                 prepend = "file:";
4921                         } else {
4922                                 prepend = "file:///";
4923                         }
4924                 }
4925 #endif
4926                 result = g_strconcat (prepend, codebase, NULL);
4927                 g_free (codebase);
4928                 codebase = result;
4929         }
4930
4931         if (codebase) {
4932                 MONO_OBJECT_SETREF (aname, codebase, mono_string_new (domain, codebase));
4933                 g_free (codebase);
4934         }
4935
4936         if (!create_culture) {
4937                 MonoMethodDesc *desc = mono_method_desc_new ("System.Globalization.CultureInfo:CreateCulture(string,bool)", TRUE);
4938                 create_culture = mono_method_desc_search_in_image (desc, mono_defaults.corlib);
4939                 g_assert (create_culture);
4940                 mono_method_desc_free (desc);
4941         }
4942
4943         if (name->culture) {
4944                 args [0] = mono_string_new (domain, name->culture);
4945                 args [1] = &assembly_ref;
4946                 MONO_OBJECT_SETREF (aname, cultureInfo, mono_runtime_invoke (create_culture, NULL, args, NULL));
4947         }
4948
4949         if (name->public_key) {
4950                 pkey_ptr = (char*)name->public_key;
4951                 pkey_len = mono_metadata_decode_blob_size (pkey_ptr, &pkey_ptr);
4952
4953                 MONO_OBJECT_SETREF (aname, publicKey, mono_array_new (domain, mono_defaults.byte_class, pkey_len));
4954                 memcpy (mono_array_addr (aname->publicKey, guint8, 0), pkey_ptr, pkey_len);
4955                 aname->flags |= ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG;
4956         } else if (default_publickey) {
4957                 MONO_OBJECT_SETREF (aname, publicKey, mono_array_new (domain, mono_defaults.byte_class, 0));
4958                 aname->flags |= ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG;
4959         }
4960
4961         /* MonoAssemblyName keeps the public key token as an hexadecimal string */
4962         if (name->public_key_token [0]) {
4963                 int i, j;
4964                 char *p;
4965
4966                 MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, 8));
4967                 p = mono_array_addr (aname->keyToken, char, 0);
4968
4969                 for (i = 0, j = 0; i < 8; i++) {
4970                         *p = g_ascii_xdigit_value (name->public_key_token [j++]) << 4;
4971                         *p |= g_ascii_xdigit_value (name->public_key_token [j++]);
4972                         p++;
4973                 }
4974         } else if (default_token) {
4975                 MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, 0));
4976         }
4977 }
4978
4979 ICALL_EXPORT MonoString *
4980 ves_icall_System_Reflection_Assembly_get_fullName (MonoReflectionAssembly *assembly)
4981 {
4982         MonoDomain *domain = mono_object_domain (assembly); 
4983         MonoAssembly *mass = assembly->assembly;
4984         MonoString *res;
4985         gchar *name;
4986
4987         name = mono_stringify_assembly_name (&mass->aname);
4988         res = mono_string_new (domain, name);
4989         g_free (name);
4990
4991         return res;
4992 }
4993
4994 ICALL_EXPORT void
4995 ves_icall_System_Reflection_Assembly_FillName (MonoReflectionAssembly *assembly, MonoReflectionAssemblyName *aname)
4996 {
4997         gchar *absolute;
4998         MonoAssembly *mass = assembly->assembly;
4999
5000         if (g_path_is_absolute (mass->image->name)) {
5001                 fill_reflection_assembly_name (mono_object_domain (assembly),
5002                         aname, &mass->aname, mass->image->name, TRUE,
5003                         TRUE, TRUE);
5004                 return;
5005         }
5006         absolute = g_build_filename (mass->basedir, mass->image->name, NULL);
5007
5008         fill_reflection_assembly_name (mono_object_domain (assembly),
5009                 aname, &mass->aname, absolute, TRUE, TRUE,
5010                 TRUE);
5011
5012         g_free (absolute);
5013 }
5014
5015 ICALL_EXPORT void
5016 ves_icall_System_Reflection_Assembly_InternalGetAssemblyName (MonoString *fname, MonoReflectionAssemblyName *aname)
5017 {
5018         char *filename;
5019         MonoImageOpenStatus status = MONO_IMAGE_OK;
5020         gboolean res;
5021         MonoImage *image;
5022         MonoAssemblyName name;
5023         char *dirname;
5024
5025         filename = mono_string_to_utf8 (fname);
5026
5027         dirname = g_path_get_dirname (filename);
5028         replace_shadow_path (mono_domain_get (), dirname, &filename);
5029         g_free (dirname);
5030
5031         image = mono_image_open (filename, &status);
5032
5033         if (!image){
5034                 MonoException *exc;
5035
5036                 g_free (filename);
5037                 if (status == MONO_IMAGE_IMAGE_INVALID)
5038                         exc = mono_get_exception_bad_image_format2 (NULL, fname);
5039                 else
5040                         exc = mono_get_exception_file_not_found2 (NULL, fname);
5041                 mono_set_pending_exception (exc);
5042                 return;
5043         }
5044
5045         res = mono_assembly_fill_assembly_name (image, &name);
5046         if (!res) {
5047                 mono_image_close (image);
5048                 g_free (filename);
5049                 mono_set_pending_exception (mono_get_exception_argument ("assemblyFile", "The file does not contain a manifest"));
5050                 return;
5051         }
5052
5053         fill_reflection_assembly_name (mono_domain_get (), aname, &name, filename,
5054                 TRUE, FALSE, TRUE);
5055
5056         g_free (filename);
5057         mono_image_close (image);
5058 }
5059
5060 ICALL_EXPORT MonoBoolean
5061 ves_icall_System_Reflection_Assembly_LoadPermissions (MonoReflectionAssembly *assembly,
5062         char **minimum, guint32 *minLength, char **optional, guint32 *optLength, char **refused, guint32 *refLength)
5063 {
5064         MonoBoolean result = FALSE;
5065         MonoDeclSecurityEntry entry;
5066
5067         /* SecurityAction.RequestMinimum */
5068         if (mono_declsec_get_assembly_action (assembly->assembly, SECURITY_ACTION_REQMIN, &entry)) {
5069                 *minimum = entry.blob;
5070                 *minLength = entry.size;
5071                 result = TRUE;
5072         }
5073         /* SecurityAction.RequestOptional */
5074         if (mono_declsec_get_assembly_action (assembly->assembly, SECURITY_ACTION_REQOPT, &entry)) {
5075                 *optional = entry.blob;
5076                 *optLength = entry.size;
5077                 result = TRUE;
5078         }
5079         /* SecurityAction.RequestRefuse */
5080         if (mono_declsec_get_assembly_action (assembly->assembly, SECURITY_ACTION_REQREFUSE, &entry)) {
5081                 *refused = entry.blob;
5082                 *refLength = entry.size;
5083                 result = TRUE;
5084         }
5085
5086         return result;  
5087 }
5088
5089 static gboolean
5090 mono_module_type_is_visible (MonoTableInfo *tdef, MonoImage *image, int type)
5091 {
5092         guint32 attrs, visibility;
5093         do {
5094                 attrs = mono_metadata_decode_row_col (tdef, type - 1, MONO_TYPEDEF_FLAGS);
5095                 visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
5096                 if (visibility != TYPE_ATTRIBUTE_PUBLIC && visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC)
5097                         return FALSE;
5098
5099         } while ((type = mono_metadata_token_index (mono_metadata_nested_in_typedef (image, type))));
5100
5101         return TRUE;
5102 }
5103
5104 static MonoArray*
5105 mono_module_get_types (MonoDomain *domain, MonoImage *image, MonoArray **exceptions, MonoBoolean exportedOnly)
5106 {
5107         MonoArray *res;
5108         MonoClass *klass;
5109         MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
5110         int i, count;
5111
5112         /* we start the count from 1 because we skip the special type <Module> */
5113         if (exportedOnly) {
5114                 count = 0;
5115                 for (i = 1; i < tdef->rows; ++i) {
5116                         if (mono_module_type_is_visible (tdef, image, i + 1))
5117                                 count++;
5118                 }
5119         } else {
5120                 count = tdef->rows - 1;
5121         }
5122         res = mono_array_new (domain, mono_defaults.monotype_class, count);
5123         *exceptions = mono_array_new (domain, mono_defaults.exception_class, count);
5124         count = 0;
5125         for (i = 1; i < tdef->rows; ++i) {
5126                 if (!exportedOnly || mono_module_type_is_visible (tdef, image, i + 1)) {
5127                         MonoError error;
5128                         klass = mono_class_get_checked (image, (i + 1) | MONO_TOKEN_TYPE_DEF, &error);
5129                         g_assert (!mono_loader_get_last_error ()); /* Plug any leaks */
5130                         
5131                         if (klass) {
5132                                 mono_array_setref (res, count, mono_type_get_object (domain, &klass->byval_arg));
5133                         } else {
5134                                 MonoException *ex = mono_error_convert_to_exception (&error);
5135                                 mono_array_setref (*exceptions, count, ex);
5136                         }
5137                         count++;
5138                 }
5139         }
5140         
5141         return res;
5142 }
5143
5144 ICALL_EXPORT MonoArray*
5145 ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssembly *assembly, MonoBoolean exportedOnly)
5146 {
5147         MonoArray *res = NULL;
5148         MonoArray *exceptions = NULL;
5149         MonoImage *image = NULL;
5150         MonoTableInfo *table = NULL;
5151         MonoDomain *domain;
5152         GList *list = NULL;
5153         int i, len, ex_count;
5154
5155         domain = mono_object_domain (assembly);
5156
5157         g_assert (!assembly_is_dynamic (assembly->assembly));
5158         image = assembly->assembly->image;
5159         table = &image->tables [MONO_TABLE_FILE];
5160         res = mono_module_get_types (domain, image, &exceptions, exportedOnly);
5161
5162         /* Append data from all modules in the assembly */
5163         for (i = 0; i < table->rows; ++i) {
5164                 if (!(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
5165                         MonoImage *loaded_image = mono_assembly_load_module (image->assembly, i + 1);
5166                         if (loaded_image) {
5167                                 MonoArray *ex2;
5168                                 MonoArray *res2 = mono_module_get_types (domain, loaded_image, &ex2, exportedOnly);
5169                                 /* Append the new types to the end of the array */
5170                                 if (mono_array_length (res2) > 0) {
5171                                         guint32 len1, len2;
5172                                         MonoArray *res3, *ex3;
5173
5174                                         len1 = mono_array_length (res);
5175                                         len2 = mono_array_length (res2);
5176
5177                                         res3 = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
5178                                         mono_array_memcpy_refs (res3, 0, res, 0, len1);
5179                                         mono_array_memcpy_refs (res3, len1, res2, 0, len2);
5180                                         res = res3;
5181
5182                                         ex3 = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
5183                                         mono_array_memcpy_refs (ex3, 0, exceptions, 0, len1);
5184                                         mono_array_memcpy_refs (ex3, len1, ex2, 0, len2);
5185                                         exceptions = ex3;
5186                                 }
5187                         }
5188                 }
5189         }
5190
5191         /* the ReflectionTypeLoadException must have all the types (Types property), 
5192          * NULL replacing types which throws an exception. The LoaderException must
5193          * contain all exceptions for NULL items.
5194          */
5195
5196         len = mono_array_length (res);
5197
5198         ex_count = 0;
5199         for (i = 0; i < len; i++) {
5200                 MonoReflectionType *t = mono_array_get (res, gpointer, i);
5201                 MonoClass *klass;
5202
5203                 if (t) {
5204                         klass = mono_type_get_class (t->type);
5205                         if ((klass != NULL) && klass->exception_type) {
5206                                 /* keep the class in the list */
5207                                 list = g_list_append (list, klass);
5208                                 /* and replace Type with NULL */
5209                                 mono_array_setref (res, i, NULL);
5210                         }
5211                 } else {
5212                         ex_count ++;
5213                 }
5214         }
5215
5216         if (list || ex_count) {
5217                 GList *tmp = NULL;
5218                 MonoException *exc = NULL;
5219                 MonoArray *exl = NULL;
5220                 int j, length = g_list_length (list) + ex_count;
5221
5222                 mono_loader_clear_error ();
5223
5224                 exl = mono_array_new (domain, mono_defaults.exception_class, length);
5225                 /* Types for which mono_class_get_checked () succeeded */
5226                 for (i = 0, tmp = list; tmp; i++, tmp = tmp->next) {
5227                         MonoException *exc = mono_class_get_exception_for_failure (tmp->data);
5228                         mono_array_setref (exl, i, exc);
5229                 }
5230                 /* Types for which it don't */
5231                 for (j = 0; j < mono_array_length (exceptions); ++j) {
5232                         MonoException *exc = mono_array_get (exceptions, MonoException*, j);
5233                         if (exc) {
5234                                 g_assert (i < length);
5235                                 mono_array_setref (exl, i, exc);
5236                                 i ++;
5237                         }
5238                 }
5239                 g_list_free (list);
5240                 list = NULL;
5241
5242                 exc = mono_get_exception_reflection_type_load (res, exl);
5243                 mono_loader_clear_error ();
5244                 mono_set_pending_exception (exc);
5245                 return NULL;
5246         }
5247                 
5248         return res;
5249 }
5250
5251 ICALL_EXPORT gboolean
5252 ves_icall_System_Reflection_AssemblyName_ParseName (MonoReflectionAssemblyName *name, MonoString *assname)
5253 {
5254         MonoAssemblyName aname;
5255         MonoDomain *domain = mono_object_domain (name);
5256         char *val;
5257         gboolean is_version_defined;
5258         gboolean is_token_defined;
5259
5260         aname.public_key = NULL;
5261         val = mono_string_to_utf8 (assname);
5262         if (!mono_assembly_name_parse_full (val, &aname, TRUE, &is_version_defined, &is_token_defined)) {
5263                 g_free ((guint8*) aname.public_key);
5264                 g_free (val);
5265                 return FALSE;
5266         }
5267         
5268         fill_reflection_assembly_name (domain, name, &aname, "", is_version_defined,
5269                 FALSE, is_token_defined);
5270
5271         mono_assembly_name_free (&aname);
5272         g_free ((guint8*) aname.public_key);
5273         g_free (val);
5274
5275         return TRUE;
5276 }
5277
5278 ICALL_EXPORT MonoReflectionType*
5279 ves_icall_System_Reflection_Module_GetGlobalType (MonoReflectionModule *module)
5280 {
5281         MonoError error;
5282         MonoDomain *domain = mono_object_domain (module); 
5283         MonoClass *klass;
5284
5285         g_assert (module->image);
5286
5287         if (image_is_dynamic (module->image) && ((MonoDynamicImage*)(module->image))->initial_image)
5288                 /* These images do not have a global type */
5289                 return NULL;
5290
5291         klass = mono_class_get_checked (module->image, 1 | MONO_TOKEN_TYPE_DEF, &error);
5292         mono_error_raise_exception (&error);
5293         return mono_type_get_object (domain, &klass->byval_arg);
5294 }
5295
5296 ICALL_EXPORT void
5297 ves_icall_System_Reflection_Module_Close (MonoReflectionModule *module)
5298 {
5299         /*if (module->image)
5300                 mono_image_close (module->image);*/
5301 }
5302
5303 ICALL_EXPORT MonoString*
5304 ves_icall_System_Reflection_Module_GetGuidInternal (MonoReflectionModule *module)
5305 {
5306         MonoDomain *domain = mono_object_domain (module); 
5307
5308         g_assert (module->image);
5309         return mono_string_new (domain, module->image->guid);
5310 }
5311
5312 ICALL_EXPORT gpointer
5313 ves_icall_System_Reflection_Module_GetHINSTANCE (MonoReflectionModule *module)
5314 {
5315 #ifdef HOST_WIN32
5316         if (module->image && module->image->is_module_handle)
5317                 return module->image->raw_data;
5318 #endif
5319
5320         return (gpointer) (-1);
5321 }
5322
5323 ICALL_EXPORT void
5324 ves_icall_System_Reflection_Module_GetPEKind (MonoImage *image, gint32 *pe_kind, gint32 *machine)
5325 {
5326         if (image_is_dynamic (image)) {
5327                 MonoDynamicImage *dyn = (MonoDynamicImage*)image;
5328                 *pe_kind = dyn->pe_kind;
5329                 *machine = dyn->machine;
5330         }
5331         else {
5332                 *pe_kind = ((MonoCLIImageInfo*)(image->image_info))->cli_cli_header.ch_flags & 0x3;
5333                 *machine = ((MonoCLIImageInfo*)(image->image_info))->cli_header.coff.coff_machine;
5334         }
5335 }
5336
5337 ICALL_EXPORT gint32
5338 ves_icall_System_Reflection_Module_GetMDStreamVersion (MonoImage *image)
5339 {
5340         return (image->md_version_major << 16) | (image->md_version_minor);
5341 }
5342
5343 ICALL_EXPORT MonoArray*
5344 ves_icall_System_Reflection_Module_InternalGetTypes (MonoReflectionModule *module)
5345 {
5346         MonoArray *exceptions;
5347         int i;
5348
5349         if (!module->image)
5350                 return mono_array_new (mono_object_domain (module), mono_defaults.monotype_class, 0);
5351         else {
5352                 MonoArray *res = mono_module_get_types (mono_object_domain (module), module->image, &exceptions, FALSE);
5353                 for (i = 0; i < mono_array_length (exceptions); ++i) {
5354                         MonoException *ex = mono_array_get (exceptions, MonoException *, i);
5355                         if (ex) {
5356                                 mono_set_pending_exception (ex);
5357                                 return NULL;
5358                         }
5359                 }
5360                 return res;
5361         }
5362 }
5363
5364 static gboolean
5365 mono_memberref_is_method (MonoImage *image, guint32 token)
5366 {
5367         if (!image_is_dynamic (image)) {
5368                 guint32 cols [MONO_MEMBERREF_SIZE];
5369                 const char *sig;
5370                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
5371                 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
5372                 mono_metadata_decode_blob_size (sig, &sig);
5373                 return (*sig != 0x6);
5374         } else {
5375                 MonoClass *handle_class;
5376
5377                 if (!mono_lookup_dynamic_token_class (image, token, FALSE, &handle_class, NULL))
5378                         return FALSE;
5379
5380                 return mono_defaults.methodhandle_class == handle_class;
5381         }
5382 }
5383
5384 static void
5385 init_generic_context_from_args (MonoGenericContext *context, MonoArray *type_args, MonoArray *method_args)
5386 {
5387         if (type_args)
5388                 context->class_inst = mono_metadata_get_generic_inst (mono_array_length (type_args),
5389                                                                       mono_array_addr (type_args, MonoType*, 0));
5390         else
5391                 context->class_inst = NULL;
5392         if (method_args)
5393                 context->method_inst = mono_metadata_get_generic_inst (mono_array_length (method_args),
5394                                                                        mono_array_addr (method_args, MonoType*, 0));
5395         else
5396                 context->method_inst = NULL;
5397 }
5398
5399 ICALL_EXPORT MonoType*
5400 ves_icall_System_Reflection_Module_ResolveTypeToken (MonoImage *image, guint32 token, MonoArray *type_args, MonoArray *method_args, MonoResolveTokenError *resolve_error)
5401 {
5402         MonoClass *klass;
5403         int table = mono_metadata_token_table (token);
5404         int index = mono_metadata_token_index (token);
5405         MonoGenericContext context;
5406         MonoError error;
5407
5408         *resolve_error = ResolveTokenError_Other;
5409
5410         /* Validate token */
5411         if ((table != MONO_TABLE_TYPEDEF) && (table != MONO_TABLE_TYPEREF) && 
5412                 (table != MONO_TABLE_TYPESPEC)) {
5413                 *resolve_error = ResolveTokenError_BadTable;
5414                 return NULL;
5415         }
5416
5417         if (image_is_dynamic (image)) {
5418                 if ((table == MONO_TABLE_TYPEDEF) || (table == MONO_TABLE_TYPEREF)) {
5419                         klass = mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
5420                         return klass ? &klass->byval_arg : NULL;
5421                 }
5422
5423                 init_generic_context_from_args (&context, type_args, method_args);
5424                 klass = mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context);
5425                 return klass ? &klass->byval_arg : NULL;
5426         }
5427
5428         if ((index <= 0) || (index > image->tables [table].rows)) {
5429                 *resolve_error = ResolveTokenError_OutOfRange;
5430                 return NULL;
5431         }
5432
5433         init_generic_context_from_args (&context, type_args, method_args);
5434         klass = mono_class_get_checked (image, token, &error);
5435         if (klass)
5436                 klass = mono_class_inflate_generic_class_checked (klass, &context, &error);
5437         mono_error_raise_exception (&error);
5438
5439         if (klass)
5440                 return &klass->byval_arg;
5441         else
5442                 return NULL;
5443 }
5444
5445 ICALL_EXPORT MonoMethod*
5446 ves_icall_System_Reflection_Module_ResolveMethodToken (MonoImage *image, guint32 token, MonoArray *type_args, MonoArray *method_args, MonoResolveTokenError *resolve_error)
5447 {
5448         MonoError error;
5449         int table = mono_metadata_token_table (token);
5450         int index = mono_metadata_token_index (token);
5451         MonoGenericContext context;
5452         MonoMethod *method;
5453
5454         *resolve_error = ResolveTokenError_Other;
5455
5456         /* Validate token */
5457         if ((table != MONO_TABLE_METHOD) && (table != MONO_TABLE_METHODSPEC) && 
5458                 (table != MONO_TABLE_MEMBERREF)) {
5459                 *resolve_error = ResolveTokenError_BadTable;
5460                 return NULL;
5461         }
5462
5463         if (image_is_dynamic (image)) {
5464                 if (table == MONO_TABLE_METHOD)
5465                         return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
5466
5467                 if ((table == MONO_TABLE_MEMBERREF) && !(mono_memberref_is_method (image, token))) {
5468                         *resolve_error = ResolveTokenError_BadTable;
5469                         return NULL;
5470                 }
5471
5472                 init_generic_context_from_args (&context, type_args, method_args);
5473                 return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context);
5474         }
5475
5476         if ((index <= 0) || (index > image->tables [table].rows)) {
5477                 *resolve_error = ResolveTokenError_OutOfRange;
5478                 return NULL;
5479         }
5480         if ((table == MONO_TABLE_MEMBERREF) && (!mono_memberref_is_method (image, token))) {
5481                 *resolve_error = ResolveTokenError_BadTable;
5482                 return NULL;
5483         }
5484
5485         init_generic_context_from_args (&context, type_args, method_args);
5486         method = mono_get_method_checked (image, token, NULL, &context, &error);
5487         mono_error_raise_exception (&error);
5488
5489         return method;
5490 }
5491
5492 ICALL_EXPORT MonoString*
5493 ves_icall_System_Reflection_Module_ResolveStringToken (MonoImage *image, guint32 token, MonoResolveTokenError *error)
5494 {
5495         int index = mono_metadata_token_index (token);
5496
5497         *error = ResolveTokenError_Other;
5498
5499         /* Validate token */
5500         if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
5501                 *error = ResolveTokenError_BadTable;
5502                 return NULL;
5503         }
5504
5505         if (image_is_dynamic (image))
5506                 return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
5507
5508         if ((index <= 0) || (index >= image->heap_us.size)) {
5509                 *error = ResolveTokenError_OutOfRange;
5510                 return NULL;
5511         }
5512
5513         /* FIXME: What to do if the index points into the middle of a string ? */
5514
5515         return mono_ldstr (mono_domain_get (), image, index);
5516 }
5517
5518 ICALL_EXPORT MonoClassField*
5519 ves_icall_System_Reflection_Module_ResolveFieldToken (MonoImage *image, guint32 token, MonoArray *type_args, MonoArray *method_args, MonoResolveTokenError *resolve_error)
5520 {
5521         MonoError error;
5522         MonoClass *klass;
5523         int table = mono_metadata_token_table (token);
5524         int index = mono_metadata_token_index (token);
5525         MonoGenericContext context;
5526         MonoClassField *field;
5527
5528         *resolve_error = ResolveTokenError_Other;
5529
5530         /* Validate token */
5531         if ((table != MONO_TABLE_FIELD) && (table != MONO_TABLE_MEMBERREF)) {
5532                 *resolve_error = ResolveTokenError_BadTable;
5533                 return NULL;
5534         }
5535
5536         if (image_is_dynamic (image)) {
5537                 if (table == MONO_TABLE_FIELD)
5538                         return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
5539
5540                 if (mono_memberref_is_method (image, token)) {
5541                         *resolve_error = ResolveTokenError_BadTable;
5542                         return NULL;
5543                 }
5544
5545                 init_generic_context_from_args (&context, type_args, method_args);
5546                 return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context);
5547         }
5548
5549         if ((index <= 0) || (index > image->tables [table].rows)) {
5550                 *resolve_error = ResolveTokenError_OutOfRange;
5551                 return NULL;
5552         }
5553         if ((table == MONO_TABLE_MEMBERREF) && (mono_memberref_is_method (image, token))) {
5554                 *resolve_error = ResolveTokenError_BadTable;
5555                 return NULL;
5556         }
5557
5558         init_generic_context_from_args (&context, type_args, method_args);
5559         field = mono_field_from_token_checked (image, token, &klass, &context, &error);
5560         mono_error_raise_exception (&error);
5561         
5562         return field;
5563 }
5564
5565
5566 ICALL_EXPORT MonoObject*
5567 ves_icall_System_Reflection_Module_ResolveMemberToken (MonoImage *image, guint32 token, MonoArray *type_args, MonoArray *method_args, MonoResolveTokenError *error)
5568 {
5569         int table = mono_metadata_token_table (token);
5570
5571         *error = ResolveTokenError_Other;
5572
5573         switch (table) {
5574         case MONO_TABLE_TYPEDEF:
5575         case MONO_TABLE_TYPEREF:
5576         case MONO_TABLE_TYPESPEC: {
5577                 MonoType *t = ves_icall_System_Reflection_Module_ResolveTypeToken (image, token, type_args, method_args, error);
5578                 if (t)
5579                         return (MonoObject*)mono_type_get_object (mono_domain_get (), t);
5580                 else
5581                         return NULL;
5582         }
5583         case MONO_TABLE_METHOD:
5584         case MONO_TABLE_METHODSPEC: {
5585                 MonoMethod *m = ves_icall_System_Reflection_Module_ResolveMethodToken (image, token, type_args, method_args, error);
5586                 if (m)
5587                         return (MonoObject*)mono_method_get_object (mono_domain_get (), m, m->klass);
5588                 else
5589                         return NULL;
5590         }               
5591         case MONO_TABLE_FIELD: {
5592                 MonoClassField *f = ves_icall_System_Reflection_Module_ResolveFieldToken (image, token, type_args, method_args, error);
5593                 if (f)
5594                         return (MonoObject*)mono_field_get_object (mono_domain_get (), f->parent, f);
5595                 else
5596                         return NULL;
5597         }
5598         case MONO_TABLE_MEMBERREF:
5599                 if (mono_memberref_is_method (image, token)) {
5600                         MonoMethod *m = ves_icall_System_Reflection_Module_ResolveMethodToken (image, token, type_args, method_args, error);
5601                         if (m)
5602                                 return (MonoObject*)mono_method_get_object (mono_domain_get (), m, m->klass);
5603                         else
5604                                 return NULL;
5605                 }
5606                 else {
5607                         MonoClassField *f = ves_icall_System_Reflection_Module_ResolveFieldToken (image, token, type_args, method_args, error);
5608                         if (f)
5609                                 return (MonoObject*)mono_field_get_object (mono_domain_get (), f->parent, f);
5610                         else
5611                                 return NULL;
5612                 }
5613                 break;
5614
5615         default:
5616                 *error = ResolveTokenError_BadTable;
5617         }
5618
5619         return NULL;
5620 }
5621
5622 ICALL_EXPORT MonoArray*
5623 ves_icall_System_Reflection_Module_ResolveSignature (MonoImage *image, guint32 token, MonoResolveTokenError *error)
5624 {
5625         int table = mono_metadata_token_table (token);
5626         int idx = mono_metadata_token_index (token);
5627         MonoTableInfo *tables = image->tables;
5628         guint32 sig, len;
5629         const char *ptr;
5630         MonoArray *res;
5631
5632         *error = ResolveTokenError_OutOfRange;
5633
5634         /* FIXME: Support other tables ? */
5635         if (table != MONO_TABLE_STANDALONESIG)
5636                 return NULL;
5637
5638         if (image_is_dynamic (image))
5639                 return NULL;
5640
5641         if ((idx == 0) || (idx > tables [MONO_TABLE_STANDALONESIG].rows))
5642                 return NULL;
5643
5644         sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
5645
5646         ptr = mono_metadata_blob_heap (image, sig);
5647         len = mono_metadata_decode_blob_size (ptr, &ptr);
5648
5649         res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, len);
5650         memcpy (mono_array_addr (res, guint8, 0), ptr, len);
5651         return res;
5652 }
5653
5654 ICALL_EXPORT MonoReflectionType*
5655 ves_icall_ModuleBuilder_create_modified_type (MonoReflectionTypeBuilder *tb, MonoString *smodifiers)
5656 {
5657         MonoClass *klass;
5658         int isbyref = 0, rank;
5659         char *str = mono_string_to_utf8 (smodifiers);
5660         char *p;
5661
5662         klass = mono_class_from_mono_type (tb->type.type);
5663         p = str;
5664         /* logic taken from mono_reflection_parse_type(): keep in sync */
5665         while (*p) {
5666                 switch (*p) {
5667                 case '&':
5668                         if (isbyref) { /* only one level allowed by the spec */
5669                                 g_free (str);
5670                                 return NULL;
5671                         }
5672                         isbyref = 1;
5673                         p++;
5674                         g_free (str);
5675                         return mono_type_get_object (mono_object_domain (tb), &klass->this_arg);
5676                         break;
5677                 case '*':
5678                         klass = mono_ptr_class_get (&klass->byval_arg);
5679                         mono_class_init (klass);
5680                         p++;
5681                         break;
5682                 case '[':
5683                         rank = 1;
5684                         p++;
5685                         while (*p) {
5686                                 if (*p == ']')
5687                                         break;
5688                                 if (*p == ',')
5689                                         rank++;
5690                                 else if (*p != '*') { /* '*' means unknown lower bound */
5691                                         g_free (str);
5692                                         return NULL;
5693                                 }
5694                                 ++p;
5695                         }
5696                         if (*p != ']') {
5697                                 g_free (str);
5698                                 return NULL;
5699                         }
5700                         p++;
5701                         klass = mono_array_class_get (klass, rank);
5702                         mono_class_init (klass);
5703                         break;
5704                 default:
5705                         break;
5706                 }
5707         }
5708         g_free (str);
5709         return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
5710 }
5711
5712 ICALL_EXPORT MonoBoolean
5713 ves_icall_Type_IsArrayImpl (MonoReflectionType *t)
5714 {
5715         MonoType *type;
5716         MonoBoolean res;
5717
5718         type = t->type;
5719         res = !type->byref && (type->type == MONO_TYPE_ARRAY || type->type == MONO_TYPE_SZARRAY);
5720
5721         return res;
5722 }
5723
5724 static void
5725 check_for_invalid_type (MonoClass *klass)
5726 {
5727         char *name;
5728         MonoString *str;
5729         if (klass->byval_arg.type != MONO_TYPE_TYPEDBYREF)
5730                 return;
5731
5732         name = mono_type_get_full_name (klass);
5733         str =  mono_string_new (mono_domain_get (), name);
5734         g_free (name);
5735         mono_raise_exception ((MonoException*)mono_get_exception_type_load (str, NULL));
5736
5737 }
5738 ICALL_EXPORT MonoReflectionType *
5739 ves_icall_Type_make_array_type (MonoReflectionType *type, int rank)
5740 {
5741         MonoClass *klass, *aklass;
5742
5743         klass = mono_class_from_mono_type (type->type);
5744         check_for_invalid_type (klass);
5745
5746         if (rank == 0) //single dimentional array
5747                 aklass = mono_array_class_get (klass, 1);
5748         else
5749                 aklass = mono_bounded_array_class_get (klass, rank, TRUE);
5750
5751         return mono_type_get_object (mono_object_domain (type), &aklass->byval_arg);
5752 }
5753
5754 ICALL_EXPORT MonoReflectionType *
5755 ves_icall_Type_make_byref_type (MonoReflectionType *type)
5756 {
5757         MonoClass *klass;
5758
5759         klass = mono_class_from_mono_type (type->type);
5760         mono_class_init_or_throw (klass);
5761         check_for_invalid_type (klass);
5762
5763         return mono_type_get_object (mono_object_domain (type), &klass->this_arg);
5764 }
5765
5766 ICALL_EXPORT MonoReflectionType *
5767 ves_icall_Type_MakePointerType (MonoReflectionType *type)
5768 {
5769         MonoClass *klass, *pklass;
5770
5771         klass = mono_class_from_mono_type (type->type);
5772         mono_class_init_or_throw (klass);
5773         check_for_invalid_type (klass);
5774
5775         pklass = mono_ptr_class_get (type->type);
5776
5777         return mono_type_get_object (mono_object_domain (type), &pklass->byval_arg);
5778 }
5779
5780 ICALL_EXPORT MonoObject *
5781 ves_icall_System_Delegate_CreateDelegate_internal (MonoReflectionType *type, MonoObject *target,
5782                                                    MonoReflectionMethod *info, MonoBoolean throwOnBindFailure)
5783 {
5784         MonoClass *delegate_class = mono_class_from_mono_type (type->type);
5785         MonoObject *delegate;
5786         gpointer func;
5787         MonoMethod *method = info->method;
5788
5789         mono_class_init_or_throw (delegate_class);
5790
5791         mono_assert (delegate_class->parent == mono_defaults.multicastdelegate_class);
5792
5793         if (mono_security_core_clr_enabled ()) {
5794                 if (!mono_security_core_clr_ensure_delegate_creation (method, throwOnBindFailure))
5795                         return NULL;
5796         }
5797
5798         delegate = mono_object_new (mono_object_domain (type), delegate_class);
5799
5800         if (method_is_dynamic (method)) {
5801                 /* Creating a trampoline would leak memory */
5802                 func = mono_compile_method (method);
5803         } else {
5804                 if (target && method->flags & METHOD_ATTRIBUTE_VIRTUAL && method->klass != mono_object_class (target))
5805                         method = mono_object_get_virtual_method (target, method);
5806                 func = mono_create_ftnptr (mono_domain_get (),
5807                         mono_runtime_create_jump_trampoline (mono_domain_get (), method, TRUE));
5808         }
5809
5810         mono_delegate_ctor_with_method (delegate, target, func, method);
5811
5812         return delegate;
5813 }
5814
5815 ICALL_EXPORT void
5816 ves_icall_System_Delegate_SetMulticastInvoke (MonoDelegate *this)
5817 {
5818         /* Reset the invoke impl to the default one */
5819         this->invoke_impl = mono_runtime_create_delegate_trampoline (this->object.vtable->klass);
5820 }
5821
5822 /*
5823  * Magic number to convert a time which is relative to
5824  * Jan 1, 1970 into a value which is relative to Jan 1, 0001.
5825  */
5826 #define EPOCH_ADJUST    ((guint64)62135596800LL)
5827
5828 /*
5829  * Magic number to convert FILETIME base Jan 1, 1601 to DateTime - base Jan, 1, 0001
5830  */
5831 #define FILETIME_ADJUST ((guint64)504911232000000000LL)
5832
5833 #ifdef HOST_WIN32
5834 /* convert a SYSTEMTIME which is of the form "last thursday in october" to a real date */
5835 static void
5836 convert_to_absolute_date(SYSTEMTIME *date)
5837 {
5838 #define IS_LEAP(y) ((y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0))
5839         static int days_in_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
5840         static int leap_days_in_month[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
5841         /* from the calendar FAQ */
5842         int a = (14 - date->wMonth) / 12;
5843         int y = date->wYear - a;
5844         int m = date->wMonth + 12 * a - 2;
5845         int d = (1 + y + y/4 - y/100 + y/400 + (31*m)/12) % 7;
5846
5847         /* d is now the day of the week for the first of the month (0 == Sunday) */
5848
5849         int day_of_week = date->wDayOfWeek;
5850
5851         /* set day_in_month to the first day in the month which falls on day_of_week */    
5852         int day_in_month = 1 + (day_of_week - d);
5853         if (day_in_month <= 0)
5854                 day_in_month += 7;
5855
5856         /* wDay is 1 for first weekday in month, 2 for 2nd ... 5 means last - so work that out allowing for days in the month */
5857         date->wDay = day_in_month + (date->wDay - 1) * 7;
5858         if (date->wDay > (IS_LEAP(date->wYear) ? leap_days_in_month[date->wMonth - 1] : days_in_month[date->wMonth - 1]))
5859                 date->wDay -= 7;
5860 }
5861 #endif
5862
5863 #ifndef HOST_WIN32
5864 /*
5865  * Return's the offset from GMT of a local time.
5866  * 
5867  *  tm is a local time
5868  *  t  is the same local time as seconds.
5869  */
5870 static int 
5871 gmt_offset(struct tm *tm, time_t t)
5872 {
5873 #if defined (HAVE_TM_GMTOFF)
5874         return tm->tm_gmtoff;
5875 #else
5876         struct tm g;
5877         time_t t2;
5878         g = *gmtime(&t);
5879         g.tm_isdst = tm->tm_isdst;
5880         t2 = mktime(&g);
5881         return (int)difftime(t, t2);
5882 #endif
5883 }
5884 #endif
5885 /*
5886  * This is heavily based on zdump.c from glibc 2.2.
5887  *
5888  *  * data[0]:  start of daylight saving time (in DateTime ticks).
5889  *  * data[1]:  end of daylight saving time (in DateTime ticks).
5890  *  * data[2]:  utcoffset (in TimeSpan ticks).
5891  *  * data[3]:  additional offset when daylight saving (in TimeSpan ticks).
5892  *  * name[0]:  name of this timezone when not daylight saving.
5893  *  * name[1]:  name of this timezone when daylight saving.
5894  *
5895  *  FIXME: This only works with "standard" Unix dates (years between 1900 and 2100) while
5896  *         the class library allows years between 1 and 9999.
5897  *
5898  *  Returns true on success and zero on failure.
5899  */
5900 ICALL_EXPORT guint32
5901 ves_icall_System_CurrentSystemTimeZone_GetTimeZoneData (guint32 year, MonoArray **data, MonoArray **names)
5902 {
5903 #ifndef HOST_WIN32
5904         MonoDomain *domain = mono_domain_get ();
5905         struct tm start, tt;
5906         time_t t;
5907
5908         long int gmtoff, gmtoff_after, gmtoff_st, gmtoff_ds;
5909         int day, transitioned;
5910         char tzone [64];
5911
5912         gmtoff_st = gmtoff_ds = transitioned = 0;
5913
5914         MONO_CHECK_ARG_NULL (data, 0);
5915         MONO_CHECK_ARG_NULL (names, 0);
5916
5917         mono_gc_wbarrier_generic_store (data, (MonoObject*) mono_array_new (domain, mono_defaults.int64_class, 4));
5918         mono_gc_wbarrier_generic_store (names, (MonoObject*) mono_array_new (domain, mono_defaults.string_class, 2));
5919
5920         /* 
5921          * no info is better than crashing: we'll need our own tz data
5922          * to make this work properly, anyway. The range is probably
5923          * reduced to 1970 .. 2037 because that is what mktime is
5924          * guaranteed to support (we get into an infinite loop
5925          * otherwise).
5926          */
5927
5928         memset (&start, 0, sizeof (start));
5929
5930         start.tm_mday = 1;
5931         start.tm_year = year-1900;
5932
5933         t = mktime (&start);
5934
5935         if ((year < 1970) || (year > 2037) || (t == -1)) {
5936                 t = time (NULL);
5937                 tt = *localtime (&t);
5938                 strftime (tzone, sizeof (tzone), "%Z", &tt);
5939                 mono_array_setref ((*names), 0, mono_string_new (domain, tzone));
5940                 mono_array_setref ((*names), 1, mono_string_new (domain, tzone));
5941                 return 1;
5942         }
5943
5944         gmtoff = gmt_offset (&start, t);
5945
5946         /* For each day of the year, calculate the tm_gmtoff. */
5947         for (day = 0; day < 365 && transitioned < 2; day++) {
5948
5949                 t += 3600*24;
5950                 tt = *localtime (&t);
5951
5952         gmtoff_after = gmt_offset(&tt, t);
5953
5954                 /* Daylight saving starts or ends here. */
5955                 if (gmtoff_after != gmtoff) {
5956                         struct tm tt1;
5957                         time_t t1;
5958
5959                         /* Try to find the exact hour when daylight saving starts/ends. */
5960                         t1 = t;
5961                         do {
5962                                 t1 -= 3600;
5963                                 tt1 = *localtime (&t1);
5964                         } while (gmt_offset (&tt1, t1) != gmtoff);
5965
5966                         /* Try to find the exact minute when daylight saving starts/ends. */
5967                         do {
5968                                 t1 += 60;
5969                                 tt1 = *localtime (&t1);
5970                         } while (gmt_offset (&tt1, t1) == gmtoff);
5971                         t1+=gmtoff;
5972                         strftime (tzone, sizeof (tzone), "%Z", &tt);
5973                         
5974                         /* Write data, if we're already in daylight saving, we're done. */
5975                         if (tt.tm_isdst) {
5976                                 mono_array_setref ((*names), 1, mono_string_new (domain, tzone));
5977                                 mono_array_set ((*data), gint64, 0, ((gint64)t1 + EPOCH_ADJUST) * 10000000L);
5978                                 if (gmtoff_ds == 0) {
5979                                         gmtoff_st = gmtoff;
5980                                         gmtoff_ds = gmtoff_after;
5981                                 }
5982                                 transitioned++;
5983                         } else {
5984                                 time_t te;
5985                                 te = mktime (&tt);
5986                                 
5987                                 mono_array_setref ((*names), 0, mono_string_new (domain, tzone));
5988                                 mono_array_set ((*data), gint64, 1, ((gint64)t1 + EPOCH_ADJUST) * 10000000L);
5989                                 if (gmtoff_ds == 0) {
5990                                         gmtoff_st = gmtoff_after;
5991                                         gmtoff_ds = gmtoff;
5992                                 }
5993                                 transitioned++;
5994                         }
5995
5996                         /* This is only set once when we enter daylight saving. */
5997                         if (tt1.tm_isdst) {
5998                                 mono_array_set ((*data), gint64, 2, (gint64)gmtoff_st * 10000000L);
5999                                 mono_array_set ((*data), gint64, 3, (gint64)(gmtoff_ds - gmtoff_st) * 10000000L);
6000                         }
6001                         gmtoff = gmt_offset (&tt, t);
6002                 }
6003         }
6004
6005         if (transitioned < 2) {
6006                 strftime (tzone, sizeof (tzone), "%Z", &tt);
6007                 mono_array_setref ((*names), 0, mono_string_new (domain, tzone));
6008                 mono_array_setref ((*names), 1, mono_string_new (domain, tzone));
6009                 mono_array_set ((*data), gint64, 0, 0);
6010                 mono_array_set ((*data), gint64, 1, 0);
6011                 mono_array_set ((*data), gint64, 2, (gint64) gmtoff * 10000000L);
6012                 mono_array_set ((*data), gint64, 3, 0);
6013         }
6014
6015         return 1;
6016 #else
6017         MonoDomain *domain = mono_domain_get ();
6018         TIME_ZONE_INFORMATION tz_info;
6019         FILETIME ft;
6020         int i;
6021         int err, tz_id;
6022
6023         tz_id = GetTimeZoneInformation (&tz_info);
6024         if (tz_id == TIME_ZONE_ID_INVALID)
6025                 return 0;
6026
6027         MONO_CHECK_ARG_NULL (data, 0);
6028         MONO_CHECK_ARG_NULL (names, 0);
6029
6030         mono_gc_wbarrier_generic_store (data, mono_array_new (domain, mono_defaults.int64_class, 4));
6031         mono_gc_wbarrier_generic_store (names, mono_array_new (domain, mono_defaults.string_class, 2));
6032
6033         for (i = 0; i < 32; ++i)
6034                 if (!tz_info.DaylightName [i])
6035                         break;
6036         mono_array_setref ((*names), 1, mono_string_new_utf16 (domain, tz_info.DaylightName, i));
6037         for (i = 0; i < 32; ++i)
6038                 if (!tz_info.StandardName [i])
6039                         break;
6040         mono_array_setref ((*names), 0, mono_string_new_utf16 (domain, tz_info.StandardName, i));
6041
6042         if ((year <= 1601) || (year > 30827)) {
6043                 /*
6044                  * According to MSDN, the MS time functions can't handle dates outside
6045                  * this interval.
6046                  */
6047                 return 1;
6048         }
6049
6050         /* even if the timezone has no daylight savings it may have Bias (e.g. GMT+13 it seems) */
6051         if (tz_id != TIME_ZONE_ID_UNKNOWN) {
6052                 tz_info.StandardDate.wYear = year;
6053                 convert_to_absolute_date(&tz_info.StandardDate);
6054                 err = SystemTimeToFileTime (&tz_info.StandardDate, &ft);
6055                 //g_assert(err);
6056                 if (err == 0)
6057                         return 0;
6058                 
6059                 mono_array_set ((*data), gint64, 1, FILETIME_ADJUST + (((guint64)ft.dwHighDateTime<<32) | ft.dwLowDateTime));
6060                 tz_info.DaylightDate.wYear = year;
6061                 convert_to_absolute_date(&tz_info.DaylightDate);
6062                 err = SystemTimeToFileTime (&tz_info.DaylightDate, &ft);
6063                 //g_assert(err);
6064                 if (err == 0)
6065                         return 0;
6066                 
6067                 mono_array_set ((*data), gint64, 0, FILETIME_ADJUST + (((guint64)ft.dwHighDateTime<<32) | ft.dwLowDateTime));
6068         }
6069         mono_array_set ((*data), gint64, 2, (tz_info.Bias + tz_info.StandardBias) * -600000000LL);
6070         mono_array_set ((*data), gint64, 3, (tz_info.DaylightBias - tz_info.StandardBias) * -600000000LL);
6071
6072         return 1;
6073 #endif
6074 }
6075
6076 /* System.Buffer */
6077
6078 static inline gint32 
6079 mono_array_get_byte_length (MonoArray *array)
6080 {
6081         MonoClass *klass;
6082         int length;
6083         int i;
6084
6085         klass = array->obj.vtable->klass;
6086
6087         if (array->bounds == NULL)
6088                 length = array->max_length;
6089         else {
6090                 length = 1;
6091                 for (i = 0; i < klass->rank; ++ i)
6092                         length *= array->bounds [i].length;
6093         }
6094
6095         switch (klass->element_class->byval_arg.type) {
6096         case MONO_TYPE_I1:
6097         case MONO_TYPE_U1:
6098         case MONO_TYPE_BOOLEAN:
6099                 return length;
6100         case MONO_TYPE_I2:
6101         case MONO_TYPE_U2:
6102         case MONO_TYPE_CHAR:
6103                 return length << 1;
6104         case MONO_TYPE_I4:
6105         case MONO_TYPE_U4:
6106         case MONO_TYPE_R4:
6107                 return length << 2;
6108         case MONO_TYPE_I:
6109         case MONO_TYPE_U:
6110                 return length * sizeof (gpointer);
6111         case MONO_TYPE_I8:
6112         case MONO_TYPE_U8:
6113         case MONO_TYPE_R8:
6114                 return length << 3;
6115         default:
6116                 return -1;
6117         }
6118 }
6119
6120 ICALL_EXPORT gint32 
6121 ves_icall_System_Buffer_ByteLengthInternal (MonoArray *array) 
6122 {
6123         return mono_array_get_byte_length (array);
6124 }
6125
6126 ICALL_EXPORT gint8 
6127 ves_icall_System_Buffer_GetByteInternal (MonoArray *array, gint32 idx) 
6128 {
6129         return mono_array_get (array, gint8, idx);
6130 }
6131
6132 ICALL_EXPORT void 
6133 ves_icall_System_Buffer_SetByteInternal (MonoArray *array, gint32 idx, gint8 value) 
6134 {
6135         mono_array_set (array, gint8, idx, value);
6136 }
6137
6138 ICALL_EXPORT MonoBoolean
6139 ves_icall_System_Buffer_BlockCopyInternal (MonoArray *src, gint32 src_offset, MonoArray *dest, gint32 dest_offset, gint32 count) 
6140 {
6141         guint8 *src_buf, *dest_buf;
6142
6143         /* This is called directly from the class libraries without going through the managed wrapper */
6144         MONO_CHECK_ARG_NULL (src, FALSE);
6145         MONO_CHECK_ARG_NULL (dest, FALSE);
6146
6147         /* watch out for integer overflow */
6148         if ((src_offset > mono_array_get_byte_length (src) - count) || (dest_offset > mono_array_get_byte_length (dest) - count))
6149                 return FALSE;
6150
6151         src_buf = (guint8 *)src->vector + src_offset;
6152         dest_buf = (guint8 *)dest->vector + dest_offset;
6153
6154         if (src != dest)
6155                 memcpy (dest_buf, src_buf, count);
6156         else
6157                 memmove (dest_buf, src_buf, count); /* Source and dest are the same array */
6158
6159         return TRUE;
6160 }
6161
6162 #ifndef DISABLE_REMOTING
6163 ICALL_EXPORT MonoObject *
6164 ves_icall_Remoting_RealProxy_GetTransparentProxy (MonoObject *this, MonoString *class_name)
6165 {
6166         MonoDomain *domain = mono_object_domain (this); 
6167         MonoObject *res;
6168         MonoRealProxy *rp = ((MonoRealProxy *)this);
6169         MonoTransparentProxy *tp;
6170         MonoType *type;
6171         MonoClass *klass;
6172
6173         res = mono_object_new (domain, mono_defaults.transparent_proxy_class);
6174         tp = (MonoTransparentProxy*) res;
6175         
6176         MONO_OBJECT_SETREF (tp, rp, rp);
6177         type = ((MonoReflectionType *)rp->class_to_proxy)->type;
6178         klass = mono_class_from_mono_type (type);
6179
6180         tp->custom_type_info = (mono_object_isinst (this, mono_defaults.iremotingtypeinfo_class) != NULL);
6181         tp->remote_class = mono_remote_class (domain, class_name, klass);
6182
6183         res->vtable = mono_remote_class_vtable (domain, tp->remote_class, rp);
6184         return res;
6185 }
6186
6187 ICALL_EXPORT MonoReflectionType *
6188 ves_icall_Remoting_RealProxy_InternalGetProxyType (MonoTransparentProxy *tp)
6189 {
6190         return mono_type_get_object (mono_object_domain (tp), &tp->remote_class->proxy_class->byval_arg);
6191 }
6192 #endif
6193
6194 /* System.Environment */
6195
6196 MonoString*
6197 ves_icall_System_Environment_get_UserName (void)
6198 {
6199         /* using glib is more portable */
6200         return mono_string_new (mono_domain_get (), g_get_user_name ());
6201 }
6202
6203
6204 ICALL_EXPORT MonoString *
6205 ves_icall_System_Environment_get_MachineName (void)
6206 {
6207 #if defined (HOST_WIN32)
6208         gunichar2 *buf;
6209         guint32 len;
6210         MonoString *result;
6211
6212         len = MAX_COMPUTERNAME_LENGTH + 1;
6213         buf = g_new (gunichar2, len);
6214
6215         result = NULL;
6216         if (GetComputerName (buf, (PDWORD) &len))
6217                 result = mono_string_new_utf16 (mono_domain_get (), buf, len);
6218
6219         g_free (buf);
6220         return result;
6221 #elif !defined(DISABLE_SOCKETS)
6222         gchar buf [256];
6223         MonoString *result;
6224
6225         if (gethostname (buf, sizeof (buf)) == 0)
6226                 result = mono_string_new (mono_domain_get (), buf);
6227         else
6228                 result = NULL;
6229         
6230         return result;
6231 #else
6232         return mono_string_new (mono_domain_get (), "mono");
6233 #endif
6234 }
6235
6236 ICALL_EXPORT int
6237 ves_icall_System_Environment_get_Platform (void)
6238 {
6239 #if defined (TARGET_WIN32)
6240         /* Win32NT */
6241         return 2;
6242 #elif defined(__MACH__)
6243         /* OSX */
6244         //
6245         // Notice that the value is hidden from user code, and only exposed
6246         // to mscorlib.   This is due to Mono's Unix/MacOS code predating the
6247         // define and making assumptions based on Unix/128/4 values before there
6248         // was a MacOS define.    Lots of code would assume that not-Unix meant
6249         // Windows, but in this case, it would be OSX. 
6250         //
6251         return 6;
6252 #else
6253         /* Unix */
6254         return 4;
6255 #endif
6256 }
6257
6258 ICALL_EXPORT MonoString *
6259 ves_icall_System_Environment_get_NewLine (void)
6260 {
6261 #if defined (HOST_WIN32)
6262         return mono_string_new (mono_domain_get (), "\r\n");
6263 #else
6264         return mono_string_new (mono_domain_get (), "\n");
6265 #endif
6266 }
6267
6268 ICALL_EXPORT MonoString *
6269 ves_icall_System_Environment_GetEnvironmentVariable (MonoString *name)
6270 {
6271         const gchar *value;
6272         gchar *utf8_name;
6273
6274         if (name == NULL)
6275                 return NULL;
6276
6277         utf8_name = mono_string_to_utf8 (name); /* FIXME: this should be ascii */
6278         value = g_getenv (utf8_name);
6279
6280         g_free (utf8_name);
6281
6282         if (value == 0)
6283                 return NULL;
6284         
6285         return mono_string_new (mono_domain_get (), value);
6286 }
6287
6288 /*
6289  * There is no standard way to get at environ.
6290  */
6291 #ifndef _MSC_VER
6292 #ifndef __MINGW32_VERSION
6293 #if defined(__APPLE__) && !defined (__arm__) && !defined (__aarch64__)
6294 /* Apple defines this in crt_externs.h but doesn't provide that header for 
6295  * arm-apple-darwin9.  We'll manually define the symbol on Apple as it does
6296  * in fact exist on all implementations (so far) 
6297  */
6298 gchar ***_NSGetEnviron(void);
6299 #define environ (*_NSGetEnviron())
6300 #else
6301 extern
6302 char **environ;
6303 #endif
6304 #endif
6305 #endif
6306
6307 ICALL_EXPORT MonoArray *
6308 ves_icall_System_Environment_GetEnvironmentVariableNames (void)
6309 {
6310 #ifdef HOST_WIN32
6311         MonoArray *names;
6312         MonoDomain *domain;
6313         MonoString *str;
6314         WCHAR* env_strings;
6315         WCHAR* env_string;
6316         WCHAR* equal_str;
6317         int n = 0;
6318
6319         env_strings = GetEnvironmentStrings();
6320
6321         if (env_strings) {
6322                 env_string = env_strings;
6323                 while (*env_string != '\0') {
6324                 /* weird case that MS seems to skip */
6325                         if (*env_string != '=')
6326                                 n++;
6327                         while (*env_string != '\0')
6328                                 env_string++;
6329                         env_string++;
6330                 }
6331         }
6332
6333         domain = mono_domain_get ();
6334         names = mono_array_new (domain, mono_defaults.string_class, n);
6335
6336         if (env_strings) {
6337                 n = 0;
6338                 env_string = env_strings;
6339                 while (*env_string != '\0') {
6340                         /* weird case that MS seems to skip */
6341                         if (*env_string != '=') {
6342                                 equal_str = wcschr(env_string, '=');
6343                                 g_assert(equal_str);
6344                                 str = mono_string_new_utf16 (domain, env_string, equal_str-env_string);
6345                                 mono_array_setref (names, n, str);
6346                                 n++;
6347                         }
6348                         while (*env_string != '\0')
6349                                 env_string++;
6350                         env_string++;
6351                 }
6352
6353                 FreeEnvironmentStrings (env_strings);
6354         }
6355
6356         return names;
6357
6358 #else
6359         MonoArray *names;
6360         MonoDomain *domain;
6361         MonoString *str;
6362         gchar **e, **parts;
6363         int n;
6364
6365         n = 0;
6366         for (e = environ; *e != 0; ++ e)
6367                 ++ n;
6368
6369         domain = mono_domain_get ();
6370         names = mono_array_new (domain, mono_defaults.string_class, n);
6371
6372         n = 0;
6373         for (e = environ; *e != 0; ++ e) {
6374                 parts = g_strsplit (*e, "=", 2);
6375                 if (*parts != 0) {
6376                         str = mono_string_new (domain, *parts);
6377                         mono_array_setref (names, n, str);
6378                 }
6379
6380                 g_strfreev (parts);
6381
6382                 ++ n;
6383         }
6384
6385         return names;
6386 #endif
6387 }
6388
6389 /*
6390  * If your platform lacks setenv/unsetenv, you must upgrade your glib.
6391  */
6392 #if !GLIB_CHECK_VERSION(2,4,0)
6393 #define g_setenv(a,b,c)   setenv(a,b,c)
6394 #define g_unsetenv(a) unsetenv(a)
6395 #endif
6396
6397 ICALL_EXPORT void
6398 ves_icall_System_Environment_InternalSetEnvironmentVariable (MonoString *name, MonoString *value)
6399 {
6400 #ifdef HOST_WIN32
6401         gunichar2 *utf16_name, *utf16_value;
6402 #else
6403         gchar *utf8_name, *utf8_value;
6404         MonoError error;
6405 #endif
6406
6407 #ifdef HOST_WIN32
6408         utf16_name = mono_string_to_utf16 (name);
6409         if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
6410                 SetEnvironmentVariable (utf16_name, NULL);
6411                 g_free (utf16_name);
6412                 return;
6413         }
6414
6415         utf16_value = mono_string_to_utf16 (value);
6416
6417         SetEnvironmentVariable (utf16_name, utf16_value);
6418
6419         g_free (utf16_name);
6420         g_free (utf16_value);
6421 #else
6422         utf8_name = mono_string_to_utf8 (name); /* FIXME: this should be ascii */
6423
6424         if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
6425                 g_unsetenv (utf8_name);
6426                 g_free (utf8_name);
6427                 return;
6428         }
6429
6430         utf8_value = mono_string_to_utf8_checked (value, &error);
6431         if (!mono_error_ok (&error)) {
6432                 g_free (utf8_name);
6433                 mono_error_raise_exception (&error);
6434         }
6435         g_setenv (utf8_name, utf8_value, TRUE);
6436
6437         g_free (utf8_name);
6438         g_free (utf8_value);
6439 #endif
6440 }
6441
6442 ICALL_EXPORT void
6443 ves_icall_System_Environment_Exit (int result)
6444 {
6445         mono_environment_exitcode_set (result);
6446
6447 /* FIXME: There are some cleanup hangs that should be worked out, but
6448  * if the program is going to exit, everything will be cleaned up when
6449  * NaCl exits anyway.
6450  */
6451 #ifndef __native_client__
6452         if (!mono_runtime_try_shutdown ())
6453                 mono_thread_exit ();
6454
6455         /* Suspend all managed threads since the runtime is going away */
6456         mono_thread_suspend_all_other_threads ();
6457
6458         mono_runtime_quit ();
6459 #endif
6460
6461         /* we may need to do some cleanup here... */
6462         exit (result);
6463 }
6464
6465 ICALL_EXPORT MonoString*
6466 ves_icall_System_Environment_GetGacPath (void)
6467 {
6468         return mono_string_new (mono_domain_get (), mono_assembly_getrootdir ());
6469 }
6470
6471 ICALL_EXPORT MonoString*
6472 ves_icall_System_Environment_GetWindowsFolderPath (int folder)
6473 {
6474 #if defined (HOST_WIN32)
6475         #ifndef CSIDL_FLAG_CREATE
6476                 #define CSIDL_FLAG_CREATE       0x8000
6477         #endif
6478
6479         WCHAR path [MAX_PATH];
6480         /* Create directory if no existing */
6481         if (SUCCEEDED (SHGetFolderPathW (NULL, folder | CSIDL_FLAG_CREATE, NULL, 0, path))) {
6482                 int len = 0;
6483                 while (path [len])
6484                         ++ len;
6485                 return mono_string_new_utf16 (mono_domain_get (), path, len);
6486         }
6487 #else
6488         g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
6489 #endif
6490         return mono_string_new (mono_domain_get (), "");
6491 }
6492
6493 ICALL_EXPORT MonoArray *
6494 ves_icall_System_Environment_GetLogicalDrives (void)
6495 {
6496         gunichar2 buf [256], *ptr, *dname;
6497         gunichar2 *u16;
6498         guint initial_size = 127, size = 128;
6499         gint ndrives;
6500         MonoArray *result;
6501         MonoString *drivestr;
6502         MonoDomain *domain = mono_domain_get ();
6503         gint len;
6504
6505         buf [0] = '\0';
6506         ptr = buf;
6507
6508         while (size > initial_size) {
6509                 size = (guint) GetLogicalDriveStrings (initial_size, ptr);
6510                 if (size > initial_size) {
6511                         if (ptr != buf)
6512                                 g_free (ptr);
6513                         ptr = g_malloc0 ((size + 1) * sizeof (gunichar2));
6514                         initial_size = size;
6515                         size++;
6516                 }
6517         }
6518
6519         /* Count strings */
6520         dname = ptr;
6521         ndrives = 0;
6522         do {
6523                 while (*dname++);
6524                 ndrives++;
6525         } while (*dname);
6526
6527         dname = ptr;
6528         result = mono_array_new (domain, mono_defaults.string_class, ndrives);
6529         ndrives = 0;
6530         do {
6531                 len = 0;
6532                 u16 = dname;
6533                 while (*u16) { u16++; len ++; }
6534                 drivestr = mono_string_new_utf16 (domain, dname, len);
6535                 mono_array_setref (result, ndrives++, drivestr);
6536                 while (*dname++);
6537         } while (*dname);
6538
6539         if (ptr != buf)
6540                 g_free (ptr);
6541
6542         return result;
6543 }
6544
6545 ICALL_EXPORT MonoString *
6546 ves_icall_System_IO_DriveInfo_GetDriveFormat (MonoString *path)
6547 {
6548         gunichar2 volume_name [MAX_PATH + 1];
6549         
6550         if (GetVolumeInformation (mono_string_chars (path), NULL, 0, NULL, NULL, NULL, volume_name, MAX_PATH + 1) == FALSE)
6551                 return NULL;
6552         return mono_string_from_utf16 (volume_name);
6553 }
6554
6555 ICALL_EXPORT MonoString *
6556 ves_icall_System_Environment_InternalGetHome (void)
6557 {
6558         return mono_string_new (mono_domain_get (), g_get_home_dir ());
6559 }
6560
6561 static const char *encodings [] = {
6562         (char *) 1,
6563                 "ascii", "us_ascii", "us", "ansi_x3.4_1968",
6564                 "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
6565                 "iso_ir_6", "iso646_us", "iso_646.irv:1991",
6566         (char *) 2,
6567                 "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
6568                 "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
6569                 "x_unicode_2_0_utf_7",
6570         (char *) 3,
6571                 "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
6572                 "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
6573         (char *) 4,
6574                 "utf_16", "UTF_16LE", "ucs_2", "unicode",
6575                 "iso_10646_ucs2",
6576         (char *) 5,
6577                 "unicodefffe", "utf_16be",
6578         (char *) 6,
6579                 "iso_8859_1",
6580         (char *) 0
6581 };
6582
6583 /*
6584  * Returns the internal codepage, if the value of "int_code_page" is
6585  * 1 at entry, and we can not compute a suitable code page number,
6586  * returns the code page as a string
6587  */
6588 ICALL_EXPORT MonoString*
6589 ves_icall_System_Text_EncodingHelper_InternalCodePage (gint32 *int_code_page) 
6590 {
6591         const char *cset;
6592         const char *p;
6593         char *c;
6594         char *codepage = NULL;
6595         int code;
6596         int want_name = *int_code_page;
6597         int i;
6598         
6599         *int_code_page = -1;
6600
6601         g_get_charset (&cset);
6602         c = codepage = strdup (cset);
6603         for (c = codepage; *c; c++){
6604                 if (isascii (*c) && isalpha (*c))
6605                         *c = tolower (*c);
6606                 if (*c == '-')
6607                         *c = '_';
6608         }
6609         /* g_print ("charset: %s\n", cset); */
6610         
6611         /* handle some common aliases */
6612         p = encodings [0];
6613         code = 0;
6614         for (i = 0; p != 0; ){
6615                 if ((gssize) p < 7){
6616                         code = (gssize) p;
6617                         p = encodings [++i];
6618                         continue;
6619                 }
6620                 if (strcmp (p, codepage) == 0){
6621                         *int_code_page = code;
6622                         break;
6623                 }
6624                 p = encodings [++i];
6625         }
6626         
6627         if (strstr (codepage, "utf_8") != NULL)
6628                 *int_code_page |= 0x10000000;
6629         free (codepage);
6630         
6631         if (want_name && *int_code_page == -1)
6632                 return mono_string_new (mono_domain_get (), cset);
6633         else
6634                 return NULL;
6635 }
6636
6637 ICALL_EXPORT MonoBoolean
6638 ves_icall_System_Environment_get_HasShutdownStarted (void)
6639 {
6640         if (mono_runtime_is_shutting_down ())
6641                 return TRUE;
6642
6643         if (mono_domain_is_unloading (mono_domain_get ()))
6644                 return TRUE;
6645
6646         return FALSE;
6647 }
6648
6649 ICALL_EXPORT void
6650 ves_icall_System_Environment_BroadcastSettingChange (void)
6651 {
6652 #ifdef HOST_WIN32
6653         SendMessageTimeout (HWND_BROADCAST, WM_SETTINGCHANGE, (WPARAM)NULL, (LPARAM)L"Environment", SMTO_ABORTIFHUNG, 2000, 0);
6654 #endif
6655 }
6656
6657 ICALL_EXPORT void
6658 ves_icall_MonoMethodMessage_InitMessage (MonoMethodMessage *this, 
6659                                          MonoReflectionMethod *method,
6660                                          MonoArray *out_args)
6661 {
6662         mono_message_init (mono_object_domain (this), this, method, out_args);
6663 }
6664
6665 #ifndef DISABLE_REMOTING
6666 ICALL_EXPORT MonoBoolean
6667 ves_icall_IsTransparentProxy (MonoObject *proxy)
6668 {
6669         if (!proxy)
6670                 return 0;
6671
6672         if (proxy->vtable->klass == mono_defaults.transparent_proxy_class)
6673                 return 1;
6674
6675         return 0;
6676 }
6677
6678 ICALL_EXPORT MonoReflectionMethod *
6679 ves_icall_Remoting_RemotingServices_GetVirtualMethod (
6680         MonoReflectionType *rtype, MonoReflectionMethod *rmethod)
6681 {
6682         MonoClass *klass;
6683         MonoMethod *method;
6684         MonoMethod **vtable;
6685         MonoMethod *res = NULL;
6686
6687         MONO_CHECK_ARG_NULL (rtype, NULL);
6688         MONO_CHECK_ARG_NULL (rmethod, NULL);
6689
6690         method = rmethod->method;
6691         klass = mono_class_from_mono_type (rtype->type);
6692         mono_class_init_or_throw (klass);
6693
6694         if (MONO_CLASS_IS_INTERFACE (klass))
6695                 return NULL;
6696
6697         if (method->flags & METHOD_ATTRIBUTE_STATIC)
6698                 return NULL;
6699
6700         if ((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6701                 if (klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE))
6702                         return rmethod;
6703                 else
6704                         return NULL;
6705         }
6706
6707         mono_class_setup_vtable (klass);
6708         vtable = klass->vtable;
6709
6710         if (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6711                 gboolean variance_used = FALSE;
6712                 /*MS fails with variant interfaces but it's the right thing to do anyway.*/
6713                 int offs = mono_class_interface_offset_with_variance (klass, method->klass, &variance_used);
6714                 if (offs >= 0)
6715                         res = vtable [offs + method->slot];
6716         } else {
6717                 if (!(klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE)))
6718                         return NULL;
6719
6720                 if (method->slot != -1)
6721                         res = vtable [method->slot];
6722         }
6723
6724         if (!res)
6725                 return NULL;
6726
6727         return mono_method_get_object (mono_domain_get (), res, NULL);
6728 }
6729
6730 ICALL_EXPORT void
6731 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionType *type, MonoBoolean enable)
6732 {
6733         MonoClass *klass;
6734         MonoVTable* vtable;
6735
6736         klass = mono_class_from_mono_type (type->type);
6737         vtable = mono_class_vtable_full (mono_domain_get (), klass, TRUE);
6738
6739         mono_vtable_set_is_remote (vtable, enable);
6740 }
6741
6742 #else /* DISABLE_REMOTING */
6743
6744 ICALL_EXPORT void
6745 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionType *type, MonoBoolean enable)
6746 {
6747         g_assert_not_reached ();
6748 }
6749
6750 #endif
6751
6752 ICALL_EXPORT MonoObject *
6753 ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance (MonoReflectionType *type)
6754 {
6755         MonoClass *klass;
6756         MonoDomain *domain;
6757         
6758         domain = mono_object_domain (type);
6759         klass = mono_class_from_mono_type (type->type);
6760         mono_class_init_or_throw (klass);
6761
6762         if (MONO_CLASS_IS_INTERFACE (klass) || (klass->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
6763                 mono_set_pending_exception (mono_get_exception_argument ("type", "Type cannot be instantiated"));
6764                 return NULL;
6765         }
6766
6767         if (klass->rank >= 1) {
6768                 g_assert (klass->rank == 1);
6769                 return (MonoObject *) mono_array_new (domain, klass->element_class, 0);
6770         } else {
6771                 /* Bypass remoting object creation check */
6772                 return mono_object_new_alloc_specific (mono_class_vtable_full (domain, klass, TRUE));
6773         }
6774 }
6775
6776 ICALL_EXPORT MonoString *
6777 ves_icall_System_IO_get_temp_path (void)
6778 {
6779         return mono_string_new (mono_domain_get (), g_get_tmp_dir ());
6780 }
6781
6782 #ifndef PLATFORM_NO_DRIVEINFO
6783 ICALL_EXPORT MonoBoolean
6784 ves_icall_System_IO_DriveInfo_GetDiskFreeSpace (MonoString *path_name, guint64 *free_bytes_avail,
6785                                                 guint64 *total_number_of_bytes, guint64 *total_number_of_free_bytes,
6786                                                 gint32 *error)
6787 {
6788         gboolean result;
6789         ULARGE_INTEGER wapi_free_bytes_avail;
6790         ULARGE_INTEGER wapi_total_number_of_bytes;
6791         ULARGE_INTEGER wapi_total_number_of_free_bytes;
6792
6793         *error = ERROR_SUCCESS;
6794         result = GetDiskFreeSpaceEx (mono_string_chars (path_name), &wapi_free_bytes_avail, &wapi_total_number_of_bytes,
6795                                      &wapi_total_number_of_free_bytes);
6796
6797         if (result) {
6798                 *free_bytes_avail = wapi_free_bytes_avail.QuadPart;
6799                 *total_number_of_bytes = wapi_total_number_of_bytes.QuadPart;
6800                 *total_number_of_free_bytes = wapi_total_number_of_free_bytes.QuadPart;
6801         } else {
6802                 *free_bytes_avail = 0;
6803                 *total_number_of_bytes = 0;
6804                 *total_number_of_free_bytes = 0;
6805                 *error = GetLastError ();
6806         }
6807
6808         return result;
6809 }
6810
6811 ICALL_EXPORT guint32
6812 ves_icall_System_IO_DriveInfo_GetDriveType (MonoString *root_path_name)
6813 {
6814         return GetDriveType (mono_string_chars (root_path_name));
6815 }
6816 #endif
6817
6818 ICALL_EXPORT gpointer
6819 ves_icall_RuntimeMethod_GetFunctionPointer (MonoMethod *method)
6820 {
6821         return mono_compile_method (method);
6822 }
6823
6824 ICALL_EXPORT MonoString *
6825 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (void)
6826 {
6827         MonoString *mcpath;
6828         gchar *path;
6829
6830         path = g_build_path (G_DIR_SEPARATOR_S, mono_get_config_dir (), "mono", mono_get_runtime_info ()->framework_version, "machine.config", NULL);
6831
6832 #if defined (HOST_WIN32)
6833         /* Avoid mixing '/' and '\\' */
6834         {
6835                 gint i;
6836                 for (i = strlen (path) - 1; i >= 0; i--)
6837                         if (path [i] == '/')
6838                                 path [i] = '\\';
6839         }
6840 #endif
6841         mcpath = mono_string_new (mono_domain_get (), path);
6842         g_free (path);
6843
6844         return mcpath;
6845 }
6846
6847 static MonoString *
6848 get_bundled_app_config (void)
6849 {
6850         const gchar *app_config;
6851         MonoDomain *domain;
6852         MonoString *file;
6853         gchar *config_file_name, *config_file_path;
6854         gsize len;
6855         gchar *module;
6856
6857         domain = mono_domain_get ();
6858         file = domain->setup->configuration_file;
6859         if (!file)
6860                 return NULL;
6861
6862         // Retrieve config file and remove the extension
6863         config_file_name = mono_string_to_utf8 (file);
6864         config_file_path = mono_portability_find_file (config_file_name, TRUE);
6865         if (!config_file_path)
6866                 config_file_path = config_file_name;
6867         len = strlen (config_file_path) - strlen (".config");
6868         module = g_malloc0 (len + 1);
6869         memcpy (module, config_file_path, len);
6870         // Get the config file from the module name
6871         app_config = mono_config_string_for_assembly_file (module);
6872         // Clean-up
6873         g_free (module);
6874         if (config_file_name != config_file_path)
6875                 g_free (config_file_name);
6876         g_free (config_file_path);
6877
6878         if (!app_config)
6879                 return NULL;
6880
6881         return mono_string_new (mono_domain_get (), app_config);
6882 }
6883
6884 static MonoString *
6885 get_bundled_machine_config (void)
6886 {
6887         const gchar *machine_config;
6888
6889         machine_config = mono_get_machine_config ();
6890
6891         if (!machine_config)
6892                 return NULL;
6893
6894         return mono_string_new (mono_domain_get (), machine_config);
6895 }
6896
6897 ICALL_EXPORT MonoString *
6898 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (void)
6899 {
6900         MonoString *ipath;
6901         gchar *path;
6902
6903         path = g_path_get_dirname (mono_get_config_dir ());
6904
6905 #if defined (HOST_WIN32)
6906         /* Avoid mixing '/' and '\\' */
6907         {
6908                 gint i;
6909                 for (i = strlen (path) - 1; i >= 0; i--)
6910                         if (path [i] == '/')
6911                                 path [i] = '\\';
6912         }
6913 #endif
6914         ipath = mono_string_new (mono_domain_get (), path);
6915         g_free (path);
6916
6917         return ipath;
6918 }
6919
6920 ICALL_EXPORT gboolean
6921 ves_icall_get_resources_ptr (MonoReflectionAssembly *assembly, gpointer *result, gint32 *size)
6922 {
6923         MonoPEResourceDataEntry *entry;
6924         MonoImage *image;
6925
6926         if (!assembly || !result || !size)
6927                 return FALSE;
6928
6929         *result = NULL;
6930         *size = 0;
6931         image = assembly->assembly->image;
6932         entry = mono_image_lookup_resource (image, MONO_PE_RESOURCE_ID_ASPNET_STRING, 0, NULL);
6933         if (!entry)
6934                 return FALSE;
6935
6936         *result = mono_image_rva_map (image, entry->rde_data_offset);
6937         if (!(*result)) {
6938                 g_free (entry);
6939                 return FALSE;
6940         }
6941         *size = entry->rde_size;
6942         g_free (entry);
6943         return TRUE;
6944 }
6945
6946 ICALL_EXPORT MonoBoolean
6947 ves_icall_System_Diagnostics_Debugger_IsAttached_internal (void)
6948 {
6949         return mono_is_debugger_attached ();
6950 }
6951
6952 ICALL_EXPORT MonoBoolean
6953 ves_icall_System_Diagnostics_Debugger_IsLogging (void)
6954 {
6955         if (mono_get_runtime_callbacks ()->debug_log_is_enabled)
6956                 return mono_get_runtime_callbacks ()->debug_log_is_enabled ();
6957         else
6958                 return FALSE;
6959 }
6960
6961 ICALL_EXPORT void
6962 ves_icall_System_Diagnostics_Debugger_Log (int level, MonoString *category, MonoString *message)
6963 {
6964         if (mono_get_runtime_callbacks ()->debug_log)
6965                 mono_get_runtime_callbacks ()->debug_log (level, category, message);
6966 }
6967
6968 ICALL_EXPORT void
6969 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (MonoString *message)
6970 {
6971 #if defined (HOST_WIN32)
6972         OutputDebugString (mono_string_chars (message));
6973 #else
6974         g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
6975 #endif
6976 }
6977
6978 /* Only used for value types */
6979 ICALL_EXPORT MonoObject *
6980 ves_icall_System_Activator_CreateInstanceInternal (MonoReflectionType *type)
6981 {
6982         MonoClass *klass;
6983         MonoDomain *domain;
6984         
6985         domain = mono_object_domain (type);
6986         klass = mono_class_from_mono_type (type->type);
6987         mono_class_init_or_throw (klass);
6988
6989         if (mono_class_is_nullable (klass))
6990                 /* No arguments -> null */
6991                 return NULL;
6992
6993         return mono_object_new (domain, klass);
6994 }
6995
6996 ICALL_EXPORT MonoReflectionMethod *
6997 ves_icall_MonoMethod_get_base_method (MonoReflectionMethod *m, gboolean definition)
6998 {
6999         MonoClass *klass, *parent;
7000         MonoMethod *method = m->method;
7001         MonoMethod *result = NULL;
7002         int slot;
7003
7004         if (method->klass == NULL)
7005                 return m;
7006
7007         if (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
7008             MONO_CLASS_IS_INTERFACE (method->klass) ||
7009             method->flags & METHOD_ATTRIBUTE_NEW_SLOT)
7010                 return m;
7011
7012         slot = mono_method_get_vtable_slot (method);
7013         if (slot == -1)
7014                 return m;
7015
7016         klass = method->klass;
7017         if (klass->generic_class)
7018                 klass = klass->generic_class->container_class;
7019
7020         if (definition) {
7021                 /* At the end of the loop, klass points to the eldest class that has this virtual function slot. */
7022                 for (parent = klass->parent; parent != NULL; parent = parent->parent) {
7023                         mono_class_setup_vtable (parent);
7024                         if (parent->vtable_size <= slot)
7025                                 break;
7026                         klass = parent;
7027                 }
7028         } else {
7029                 klass = klass->parent;
7030                 if (!klass)
7031                         return m;
7032         }
7033
7034         if (klass == method->klass)
7035                 return m;
7036
7037         /*This is possible if definition == FALSE.
7038          * Do it here to be really sure we don't read invalid memory.
7039          */
7040         if (slot >= klass->vtable_size)
7041                 return m;
7042
7043         mono_class_setup_vtable (klass);
7044
7045         result = klass->vtable [slot];
7046         if (result == NULL) {
7047                 /* It is an abstract method */
7048                 gpointer iter = NULL;
7049                 while ((result = mono_class_get_methods (klass, &iter)))
7050                         if (result->slot == slot)
7051                                 break;
7052         }
7053
7054         if (result == NULL)
7055                 return m;
7056
7057         return mono_method_get_object (mono_domain_get (), result, NULL);
7058 }
7059
7060 ICALL_EXPORT MonoString*
7061 ves_icall_MonoMethod_get_name (MonoReflectionMethod *m)
7062 {
7063         MonoMethod *method = m->method;
7064
7065         MONO_OBJECT_SETREF (m, name, mono_string_new (mono_object_domain (m), method->name));
7066         return m->name;
7067 }
7068
7069 ICALL_EXPORT void
7070 mono_ArgIterator_Setup (MonoArgIterator *iter, char* argsp, char* start)
7071 {
7072         iter->sig = *(MonoMethodSignature**)argsp;
7073         
7074         g_assert (iter->sig->sentinelpos <= iter->sig->param_count);
7075         g_assert (iter->sig->call_convention == MONO_CALL_VARARG);
7076
7077         iter->next_arg = 0;
7078         /* FIXME: it's not documented what start is exactly... */
7079         if (start) {
7080                 iter->args = start;
7081         } else {
7082                 iter->args = argsp + sizeof (gpointer);
7083         }
7084         iter->num_args = iter->sig->param_count - iter->sig->sentinelpos;
7085
7086         /* g_print ("sig %p, param_count: %d, sent: %d\n", iter->sig, iter->sig->param_count, iter->sig->sentinelpos); */
7087 }
7088
7089 ICALL_EXPORT MonoTypedRef
7090 mono_ArgIterator_IntGetNextArg (MonoArgIterator *iter)
7091 {
7092         guint32 i, arg_size;
7093         gint32 align;
7094         MonoTypedRef res;
7095
7096         i = iter->sig->sentinelpos + iter->next_arg;
7097
7098         g_assert (i < iter->sig->param_count);
7099
7100         res.type = iter->sig->params [i];
7101         res.klass = mono_class_from_mono_type (res.type);
7102         arg_size = mono_type_stack_size (res.type, &align);
7103 #if defined(__arm__) || defined(__mips__)
7104         iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
7105 #endif
7106         res.value = iter->args;
7107 #if defined(__native_client__) && SIZEOF_REGISTER == 8
7108         /* Values are stored as 8 byte register sized objects, but 'value'
7109          * is dereferenced as a pointer in other routines.
7110          */
7111         res.value = (char*)res.value + 4;
7112 #endif
7113 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
7114         if (arg_size <= sizeof (gpointer)) {
7115                 int dummy;
7116                 int padding = arg_size - mono_type_size (res.type, &dummy);
7117                 res.value = (guint8*)res.value + padding;
7118         }
7119 #endif
7120         iter->args = (char*)iter->args + arg_size;
7121         iter->next_arg++;
7122
7123         /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
7124
7125         return res;
7126 }
7127
7128 ICALL_EXPORT MonoTypedRef
7129 mono_ArgIterator_IntGetNextArgT (MonoArgIterator *iter, MonoType *type)
7130 {
7131         guint32 i, arg_size;
7132         gint32 align;
7133         MonoTypedRef res;
7134
7135         i = iter->sig->sentinelpos + iter->next_arg;
7136
7137         g_assert (i < iter->sig->param_count);
7138
7139         while (i < iter->sig->param_count) {
7140                 if (!mono_metadata_type_equal (type, iter->sig->params [i]))
7141                         continue;
7142                 res.type = iter->sig->params [i];
7143                 res.klass = mono_class_from_mono_type (res.type);
7144                 /* FIXME: endianess issue... */
7145                 arg_size = mono_type_stack_size (res.type, &align);
7146 #if defined(__arm__) || defined(__mips__)
7147                 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
7148 #endif
7149                 res.value = iter->args;
7150                 iter->args = (char*)iter->args + arg_size;
7151                 iter->next_arg++;
7152                 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
7153                 return res;
7154         }
7155         /* g_print ("arg type 0x%02x not found\n", res.type->type); */
7156
7157         res.type = NULL;
7158         res.value = NULL;
7159         res.klass = NULL;
7160         return res;
7161 }
7162
7163 ICALL_EXPORT MonoType*
7164 mono_ArgIterator_IntGetNextArgType (MonoArgIterator *iter)
7165 {
7166         gint i;
7167         
7168         i = iter->sig->sentinelpos + iter->next_arg;
7169
7170         g_assert (i < iter->sig->param_count);
7171
7172         return iter->sig->params [i];
7173 }
7174
7175 ICALL_EXPORT MonoObject*
7176 mono_TypedReference_ToObject (MonoTypedRef tref)
7177 {
7178         if (MONO_TYPE_IS_REFERENCE (tref.type)) {
7179                 MonoObject** objp = tref.value;
7180                 return *objp;
7181         }
7182
7183         return mono_value_box (mono_domain_get (), tref.klass, tref.value);
7184 }
7185
7186 ICALL_EXPORT MonoObject*
7187 mono_TypedReference_ToObjectInternal (MonoType *type, gpointer value, MonoClass *klass)
7188 {
7189         if (MONO_TYPE_IS_REFERENCE (type)) {
7190                 MonoObject** objp = value;
7191                 return *objp;
7192         }
7193
7194         return mono_value_box (mono_domain_get (), klass, value);
7195 }
7196
7197 static void
7198 prelink_method (MonoMethod *method)
7199 {
7200         const char *exc_class, *exc_arg;
7201         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7202                 return;
7203         mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7204         if (exc_class) {
7205                 mono_raise_exception( 
7206                         mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg ) );
7207         }
7208         /* create the wrapper, too? */
7209 }
7210
7211 ICALL_EXPORT void
7212 ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethod *method)
7213 {
7214         prelink_method (method->method);
7215 }
7216
7217 ICALL_EXPORT void
7218 ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll (MonoReflectionType *type)
7219 {
7220         MonoClass *klass = mono_class_from_mono_type (type->type);
7221         MonoMethod* m;
7222         gpointer iter = NULL;
7223
7224         mono_class_init_or_throw (klass);
7225
7226         while ((m = mono_class_get_methods (klass, &iter)))
7227                 prelink_method (m);
7228 }
7229
7230 /* These parameters are "readonly" in corlib/System/NumberFormatter.cs */
7231 ICALL_EXPORT void
7232 ves_icall_System_NumberFormatter_GetFormatterTables (guint64 const **mantissas,
7233                                             gint32 const **exponents,
7234                                             gunichar2 const **digitLowerTable,
7235                                             gunichar2 const **digitUpperTable,
7236                                             gint64 const **tenPowersList,
7237                                             gint32 const **decHexDigits)
7238 {
7239         *mantissas = Formatter_MantissaBitsTable;
7240         *exponents = Formatter_TensExponentTable;
7241         *digitLowerTable = Formatter_DigitLowerTable;
7242         *digitUpperTable = Formatter_DigitUpperTable;
7243         *tenPowersList = Formatter_TenPowersList;
7244         *decHexDigits = Formatter_DecHexDigits;
7245 }
7246
7247 /* These parameters are "readonly" in corlib/System/Globalization/TextInfo.cs */
7248 ICALL_EXPORT void
7249 ves_icall_System_Globalization_TextInfo_GetDataTablePointersLite (
7250                                             guint16 const **to_lower_data_low,
7251                                             guint16 const **to_lower_data_high,
7252                                             guint16 const **to_upper_data_low,
7253                                             guint16 const **to_upper_data_high)
7254 {
7255         *to_lower_data_low = ToLowerDataLow;
7256         *to_lower_data_high = ToLowerDataHigh;
7257         *to_upper_data_low = ToUpperDataLow;
7258         *to_upper_data_high = ToUpperDataHigh;
7259 }
7260
7261 /*
7262  * We return NULL for no modifiers so the corlib code can return Type.EmptyTypes
7263  * and avoid useless allocations.
7264  * 
7265  * MAY THROW
7266  */
7267 static MonoArray*
7268 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional)
7269 {
7270         MonoArray *res;
7271         int i, count = 0;
7272         for (i = 0; i < type->num_mods; ++i) {
7273                 if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required))
7274                         count++;
7275         }
7276         if (!count)
7277                 return NULL;
7278         res = mono_array_new (mono_domain_get (), mono_defaults.systemtype_class, count);
7279         count = 0;
7280         for (i = 0; i < type->num_mods; ++i) {
7281                 if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required)) {
7282                         MonoError error;
7283                         MonoClass *klass = mono_class_get_checked (image, type->modifiers [i].token, &error);
7284                         mono_error_raise_exception (&error); /* this is safe, no cleanup needed on callers */ 
7285                         mono_array_setref (res, count, mono_type_get_object (mono_domain_get (), &klass->byval_arg));
7286                         count++;
7287                 }
7288         }
7289         return res;
7290 }
7291
7292 ICALL_EXPORT MonoArray*
7293 param_info_get_type_modifiers (MonoReflectionParameter *param, MonoBoolean optional)
7294 {
7295         MonoType *type = param->ClassImpl->type;
7296         MonoClass *member_class = mono_object_class (param->MemberImpl);
7297         MonoMethod *method = NULL;
7298         MonoImage *image;
7299         int pos;
7300         MonoMethodSignature *sig;
7301
7302         if (mono_class_is_reflection_method_or_constructor (member_class)) {
7303                 MonoReflectionMethod *rmethod = (MonoReflectionMethod*)param->MemberImpl;
7304                 method = rmethod->method;
7305         } else if (member_class->image == mono_defaults.corlib && !strcmp ("MonoProperty", member_class->name)) {
7306                 MonoReflectionProperty *prop = (MonoReflectionProperty *)param->MemberImpl;
7307                 if (!(method = prop->property->get))
7308                         method = prop->property->set;
7309                 g_assert (method);      
7310         } else {
7311                 char *type_name = mono_type_get_full_name (member_class);
7312                 char *msg = g_strdup_printf ("Custom modifiers on a ParamInfo with member %s are not supported", type_name);
7313                 MonoException *ex = mono_get_exception_not_supported  (msg);
7314                 g_free (type_name);
7315                 g_free (msg);
7316                 mono_set_pending_exception (ex);
7317                 return NULL;
7318         }
7319
7320         image = method->klass->image;
7321         pos = param->PositionImpl;
7322         sig = mono_method_signature (method);
7323         if (pos == -1)
7324                 type = sig->ret;
7325         else
7326                 type = sig->params [pos];
7327
7328         return type_array_from_modifiers (image, type, optional);
7329 }
7330
7331 static MonoType*
7332 get_property_type (MonoProperty *prop)
7333 {
7334         MonoMethodSignature *sig;
7335         if (prop->get) {
7336                 sig = mono_method_signature (prop->get);
7337                 return sig->ret;
7338         } else if (prop->set) {
7339                 sig = mono_method_signature (prop->set);
7340                 return sig->params [sig->param_count - 1];
7341         }
7342         return NULL;
7343 }
7344
7345 ICALL_EXPORT MonoArray*
7346 property_info_get_type_modifiers (MonoReflectionProperty *property, MonoBoolean optional)
7347 {
7348         MonoType *type = get_property_type (property->property);
7349         MonoImage *image = property->klass->image;
7350
7351         if (!type)
7352                 return NULL;
7353         return type_array_from_modifiers (image, type, optional);
7354 }
7355
7356 /*
7357  *Construct a MonoType suited to be used to decode a constant blob object.
7358  *
7359  * @type is the target type which will be constructed
7360  * @blob_type is the blob type, for example, that comes from the constant table
7361  * @real_type is the expected constructed type.
7362  */
7363 static void
7364 mono_type_from_blob_type (MonoType *type, MonoTypeEnum blob_type, MonoType *real_type)
7365 {
7366         type->type = blob_type;
7367         type->data.klass = NULL;
7368         if (blob_type == MONO_TYPE_CLASS)
7369                 type->data.klass = mono_defaults.object_class;
7370         else if (real_type->type == MONO_TYPE_VALUETYPE && real_type->data.klass->enumtype) {
7371                 /* For enums, we need to use the base type */
7372                 type->type = MONO_TYPE_VALUETYPE;
7373                 type->data.klass = mono_class_from_mono_type (real_type);
7374         } else
7375                 type->data.klass = mono_class_from_mono_type (real_type);
7376 }
7377
7378 ICALL_EXPORT MonoObject*
7379 property_info_get_default_value (MonoReflectionProperty *property)
7380 {
7381         MonoType blob_type;
7382         MonoProperty *prop = property->property;
7383         MonoType *type = get_property_type (prop);
7384         MonoDomain *domain = mono_object_domain (property); 
7385         MonoTypeEnum def_type;
7386         const char *def_value;
7387         MonoObject *o;
7388
7389         mono_class_init (prop->parent);
7390
7391         if (!(prop->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT)) {
7392                 mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
7393                 return NULL;
7394         }
7395
7396         def_value = mono_class_get_property_default_value (prop, &def_type);
7397
7398         mono_type_from_blob_type (&blob_type, def_type, type);
7399         o = mono_get_object_from_blob (domain, &blob_type, def_value);
7400
7401         return o;
7402 }
7403
7404 ICALL_EXPORT MonoBoolean
7405 custom_attrs_defined_internal (MonoObject *obj, MonoReflectionType *attr_type)
7406 {
7407         MonoClass *attr_class = mono_class_from_mono_type (attr_type->type);
7408         MonoCustomAttrInfo *cinfo;
7409         gboolean found;
7410
7411         mono_class_init_or_throw (attr_class);
7412
7413         cinfo = mono_reflection_get_custom_attrs_info (obj);
7414         if (!cinfo)
7415                 return FALSE;
7416         found = mono_custom_attrs_has_attr (cinfo, attr_class);
7417         if (!cinfo->cached)
7418                 mono_custom_attrs_free (cinfo);
7419         return found;
7420 }
7421
7422 ICALL_EXPORT MonoArray*
7423 custom_attrs_get_by_type (MonoObject *obj, MonoReflectionType *attr_type)
7424 {
7425         MonoClass *attr_class = attr_type ? mono_class_from_mono_type (attr_type->type) : NULL;
7426         MonoArray *res;
7427         MonoError error;
7428
7429         if (attr_class)
7430                 mono_class_init_or_throw (attr_class);
7431
7432         res = mono_reflection_get_custom_attrs_by_type (obj, attr_class, &error);
7433         mono_error_raise_exception (&error);
7434
7435         if (mono_loader_get_last_error ()) {
7436                 mono_set_pending_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
7437                 return NULL;
7438         } else {
7439                 return res;
7440         }
7441 }
7442
7443 ICALL_EXPORT MonoString*
7444 ves_icall_Mono_Runtime_GetDisplayName (void)
7445 {
7446         char *info;
7447         MonoString *display_name;
7448
7449         info = mono_get_runtime_callbacks ()->get_runtime_build_info ();
7450         display_name = mono_string_new (mono_domain_get (), info);
7451         g_free (info);
7452         return display_name;
7453 }
7454
7455 ICALL_EXPORT MonoString*
7456 ves_icall_System_ComponentModel_Win32Exception_W32ErrorMessage (guint32 code)
7457 {
7458         MonoString *message;
7459         guint32 ret;
7460         gunichar2 buf[256];
7461         
7462         ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
7463                              FORMAT_MESSAGE_IGNORE_INSERTS, NULL, code, 0,
7464                              buf, 255, NULL);
7465         if (ret == 0) {
7466                 message = mono_string_new (mono_domain_get (), "Error looking up error string");
7467         } else {
7468                 message = mono_string_new_utf16 (mono_domain_get (), buf, ret);
7469         }
7470         
7471         return message;
7472 }
7473
7474 ICALL_EXPORT int
7475 ves_icall_System_StackFrame_GetILOffsetFromFile (MonoString *path, int methodToken, int nativeOffset)
7476 {
7477         guint32 il_offset;
7478         char *path_str = mono_string_to_utf8 (path);
7479
7480         if (!seq_point_data_get_il_offset (path_str, methodToken, nativeOffset, &il_offset))
7481                 il_offset = -1;
7482
7483         g_free (path_str);
7484
7485         return il_offset;
7486 }
7487
7488 #ifndef DISABLE_ICALL_TABLES
7489
7490 #define ICALL_TYPE(id,name,first)
7491 #define ICALL(id,name,func) Icall_ ## id,
7492
7493 enum {
7494 #include "metadata/icall-def.h"
7495         Icall_last
7496 };
7497
7498 #undef ICALL_TYPE
7499 #undef ICALL
7500 #define ICALL_TYPE(id,name,first) Icall_type_ ## id,
7501 #define ICALL(id,name,func)
7502 enum {
7503 #include "metadata/icall-def.h"
7504         Icall_type_num
7505 };
7506
7507 #undef ICALL_TYPE
7508 #undef ICALL
7509 #define ICALL_TYPE(id,name,firstic) {(Icall_ ## firstic)},
7510 #define ICALL(id,name,func)
7511 typedef struct {
7512         guint16 first_icall;
7513 } IcallTypeDesc;
7514
7515 static const IcallTypeDesc
7516 icall_type_descs [] = {
7517 #include "metadata/icall-def.h"
7518         {Icall_last}
7519 };
7520
7521 #define icall_desc_num_icalls(desc) ((desc) [1].first_icall - (desc) [0].first_icall)
7522
7523 #undef ICALL_TYPE
7524 #define ICALL_TYPE(id,name,first)
7525 #undef ICALL
7526
7527 #ifdef HAVE_ARRAY_ELEM_INIT
7528 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
7529 #define MSGSTRFIELD1(line) str##line
7530
7531 static const struct msgstrtn_t {
7532 #define ICALL(id,name,func)
7533 #undef ICALL_TYPE
7534 #define ICALL_TYPE(id,name,first) char MSGSTRFIELD(__LINE__) [sizeof (name)];
7535 #include "metadata/icall-def.h"
7536 #undef ICALL_TYPE
7537 } icall_type_names_str = {
7538 #define ICALL_TYPE(id,name,first) (name),
7539 #include "metadata/icall-def.h"
7540 #undef ICALL_TYPE
7541 };
7542 static const guint16 icall_type_names_idx [] = {
7543 #define ICALL_TYPE(id,name,first) [Icall_type_ ## id] = offsetof (struct msgstrtn_t, MSGSTRFIELD(__LINE__)),
7544 #include "metadata/icall-def.h"
7545 #undef ICALL_TYPE
7546 };
7547 #define icall_type_name_get(id) ((const char*)&icall_type_names_str + icall_type_names_idx [(id)])
7548
7549 static const struct msgstr_t {
7550 #undef ICALL
7551 #define ICALL_TYPE(id,name,first)
7552 #define ICALL(id,name,func) char MSGSTRFIELD(__LINE__) [sizeof (name)];
7553 #include "metadata/icall-def.h"
7554 #undef ICALL
7555 } icall_names_str = {
7556 #define ICALL(id,name,func) (name),
7557 #include "metadata/icall-def.h"
7558 #undef ICALL
7559 };
7560 static const guint16 icall_names_idx [] = {
7561 #define ICALL(id,name,func) [Icall_ ## id] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
7562 #include "metadata/icall-def.h"
7563 #undef ICALL
7564 };
7565 #define icall_name_get(id) ((const char*)&icall_names_str + icall_names_idx [(id)])
7566
7567 #else
7568
7569 #undef ICALL_TYPE
7570 #undef ICALL
7571 #define ICALL_TYPE(id,name,first) name,
7572 #define ICALL(id,name,func)
7573 static const char* const
7574 icall_type_names [] = {
7575 #include "metadata/icall-def.h"
7576         NULL
7577 };
7578
7579 #define icall_type_name_get(id) (icall_type_names [(id)])
7580
7581 #undef ICALL_TYPE
7582 #undef ICALL
7583 #define ICALL_TYPE(id,name,first)
7584 #define ICALL(id,name,func) name,
7585 static const char* const
7586 icall_names [] = {
7587 #include "metadata/icall-def.h"
7588         NULL
7589 };
7590 #define icall_name_get(id) icall_names [(id)]
7591
7592 #endif /* !HAVE_ARRAY_ELEM_INIT */
7593
7594 #undef ICALL_TYPE
7595 #undef ICALL
7596 #define ICALL_TYPE(id,name,first)
7597 #define ICALL(id,name,func) func,
7598 static const gconstpointer
7599 icall_functions [] = {
7600 #include "metadata/icall-def.h"
7601         NULL
7602 };
7603
7604 #ifdef ENABLE_ICALL_SYMBOL_MAP
7605 #undef ICALL_TYPE
7606 #undef ICALL
7607 #define ICALL_TYPE(id,name,first)
7608 #define ICALL(id,name,func) #func,
7609 static const gconstpointer
7610 icall_symbols [] = {
7611 #include "metadata/icall-def.h"
7612         NULL
7613 };
7614 #endif
7615
7616 #endif /* DISABLE_ICALL_TABLES */
7617
7618 static mono_mutex_t icall_mutex;
7619 static GHashTable *icall_hash = NULL;
7620 static GHashTable *jit_icall_hash_name = NULL;
7621 static GHashTable *jit_icall_hash_addr = NULL;
7622
7623 void
7624 mono_icall_init (void)
7625 {
7626 #ifndef DISABLE_ICALL_TABLES
7627         int i = 0;
7628
7629         /* check that tables are sorted: disable in release */
7630         if (TRUE) {
7631                 int j;
7632                 const char *prev_class = NULL;
7633                 const char *prev_method;
7634                 
7635                 for (i = 0; i < Icall_type_num; ++i) {
7636                         const IcallTypeDesc *desc;
7637                         int num_icalls;
7638                         prev_method = NULL;
7639                         if (prev_class && strcmp (prev_class, icall_type_name_get (i)) >= 0)
7640                                 g_print ("class %s should come before class %s\n", icall_type_name_get (i), prev_class);
7641                         prev_class = icall_type_name_get (i);
7642                         desc = &icall_type_descs [i];
7643                         num_icalls = icall_desc_num_icalls (desc);
7644                         /*g_print ("class %s has %d icalls starting at %d\n", prev_class, num_icalls, desc->first_icall);*/
7645                         for (j = 0; j < num_icalls; ++j) {
7646                                 const char *methodn = icall_name_get (desc->first_icall + j);
7647                                 if (prev_method && strcmp (prev_method, methodn) >= 0)
7648                                         g_print ("method %s should come before method %s\n", methodn, prev_method);
7649                                 prev_method = methodn;
7650                         }
7651                 }
7652         }
7653 #endif
7654
7655         icall_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7656         mono_mutex_init (&icall_mutex);
7657 }
7658
7659 static void
7660 mono_icall_lock (void)
7661 {
7662         mono_locks_mutex_acquire (&icall_mutex, IcallLock);
7663 }
7664
7665 static void
7666 mono_icall_unlock (void)
7667 {
7668         mono_locks_mutex_release (&icall_mutex, IcallLock);
7669 }
7670
7671 void
7672 mono_icall_cleanup (void)
7673 {
7674         g_hash_table_destroy (icall_hash);
7675         g_hash_table_destroy (jit_icall_hash_name);
7676         g_hash_table_destroy (jit_icall_hash_addr);
7677         mono_mutex_destroy (&icall_mutex);
7678 }
7679
7680 void
7681 mono_add_internal_call (const char *name, gconstpointer method)
7682 {
7683         mono_icall_lock ();
7684
7685         g_hash_table_insert (icall_hash, g_strdup (name), (gpointer) method);
7686
7687         mono_icall_unlock ();
7688 }
7689
7690 #ifndef DISABLE_ICALL_TABLES
7691
7692 #ifdef HAVE_ARRAY_ELEM_INIT
7693 static int
7694 compare_method_imap (const void *key, const void *elem)
7695 {
7696         const char* method_name = (const char*)&icall_names_str + (*(guint16*)elem);
7697         return strcmp (key, method_name);
7698 }
7699
7700 static gpointer
7701 find_method_icall (const IcallTypeDesc *imap, const char *name)
7702 {
7703         const guint16 *nameslot = mono_binary_search (name, icall_names_idx + imap->first_icall, icall_desc_num_icalls (imap), sizeof (icall_names_idx [0]), compare_method_imap);
7704         if (!nameslot)
7705                 return NULL;
7706         return (gpointer)icall_functions [(nameslot - &icall_names_idx [0])];
7707 }
7708
7709 static int
7710 compare_class_imap (const void *key, const void *elem)
7711 {
7712         const char* class_name = (const char*)&icall_type_names_str + (*(guint16*)elem);
7713         return strcmp (key, class_name);
7714 }
7715
7716 static const IcallTypeDesc*
7717 find_class_icalls (const char *name)
7718 {
7719         const guint16 *nameslot = mono_binary_search (name, icall_type_names_idx, Icall_type_num, sizeof (icall_type_names_idx [0]), compare_class_imap);
7720         if (!nameslot)
7721                 return NULL;
7722         return &icall_type_descs [nameslot - &icall_type_names_idx [0]];
7723 }
7724
7725 #else /* HAVE_ARRAY_ELEM_INIT */
7726
7727 static int
7728 compare_method_imap (const void *key, const void *elem)
7729 {
7730         const char** method_name = (const char**)elem;
7731         return strcmp (key, *method_name);
7732 }
7733
7734 static gpointer
7735 find_method_icall (const IcallTypeDesc *imap, const char *name)
7736 {
7737         const char **nameslot = mono_binary_search (name, icall_names + imap->first_icall, icall_desc_num_icalls (imap), sizeof (icall_names [0]), compare_method_imap);
7738         if (!nameslot)
7739                 return NULL;
7740         return (gpointer)icall_functions [(nameslot - icall_names)];
7741 }
7742
7743 static int
7744 compare_class_imap (const void *key, const void *elem)
7745 {
7746         const char** class_name = (const char**)elem;
7747         return strcmp (key, *class_name);
7748 }
7749
7750 static const IcallTypeDesc*
7751 find_class_icalls (const char *name)
7752 {
7753         const char **nameslot = mono_binary_search (name, icall_type_names, Icall_type_num, sizeof (icall_type_names [0]), compare_class_imap);
7754         if (!nameslot)
7755                 return NULL;
7756         return &icall_type_descs [nameslot - icall_type_names];
7757 }
7758
7759 #endif /* HAVE_ARRAY_ELEM_INIT */
7760
7761 #endif /* DISABLE_ICALL_TABLES */
7762
7763 /* 
7764  * we should probably export this as an helper (handle nested types).
7765  * Returns the number of chars written in buf.
7766  */
7767 static int
7768 concat_class_name (char *buf, int bufsize, MonoClass *klass)
7769 {
7770         int nspacelen, cnamelen;
7771         nspacelen = strlen (klass->name_space);
7772         cnamelen = strlen (klass->name);
7773         if (nspacelen + cnamelen + 2 > bufsize)
7774                 return 0;
7775         if (nspacelen) {
7776                 memcpy (buf, klass->name_space, nspacelen);
7777                 buf [nspacelen ++] = '.';
7778         }
7779         memcpy (buf + nspacelen, klass->name, cnamelen);
7780         buf [nspacelen + cnamelen] = 0;
7781         return nspacelen + cnamelen;
7782 }
7783
7784 #ifdef DISABLE_ICALL_TABLES
7785 static void
7786 no_icall_table (void)
7787 {
7788         g_assert_not_reached ();
7789 }
7790 #endif
7791
7792 gpointer
7793 mono_lookup_internal_call (MonoMethod *method)
7794 {
7795         char *sigstart;
7796         char *tmpsig;
7797         char mname [2048];
7798         int typelen = 0, mlen, siglen;
7799         gpointer res;
7800 #ifndef DISABLE_ICALL_TABLES
7801         const IcallTypeDesc *imap = NULL;
7802 #endif
7803
7804         g_assert (method != NULL);
7805
7806         if (method->is_inflated)
7807                 method = ((MonoMethodInflated *) method)->declaring;
7808
7809         if (method->klass->nested_in) {
7810                 int pos = concat_class_name (mname, sizeof (mname)-2, method->klass->nested_in);
7811                 if (!pos)
7812                         return NULL;
7813
7814                 mname [pos++] = '/';
7815                 mname [pos] = 0;
7816
7817                 typelen = concat_class_name (mname+pos, sizeof (mname)-pos-1, method->klass);
7818                 if (!typelen)
7819                         return NULL;
7820
7821                 typelen += pos;
7822         } else {
7823                 typelen = concat_class_name (mname, sizeof (mname), method->klass);
7824                 if (!typelen)
7825                         return NULL;
7826         }
7827
7828 #ifndef DISABLE_ICALL_TABLES
7829         imap = find_class_icalls (mname);
7830 #endif
7831
7832         mname [typelen] = ':';
7833         mname [typelen + 1] = ':';
7834
7835         mlen = strlen (method->name);
7836         memcpy (mname + typelen + 2, method->name, mlen);
7837         sigstart = mname + typelen + 2 + mlen;
7838         *sigstart = 0;
7839
7840         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
7841         siglen = strlen (tmpsig);
7842         if (typelen + mlen + siglen + 6 > sizeof (mname))
7843                 return NULL;
7844         sigstart [0] = '(';
7845         memcpy (sigstart + 1, tmpsig, siglen);
7846         sigstart [siglen + 1] = ')';
7847         sigstart [siglen + 2] = 0;
7848         g_free (tmpsig);
7849         
7850         mono_icall_lock ();
7851
7852         res = g_hash_table_lookup (icall_hash, mname);
7853         if (res) {
7854                 mono_icall_unlock ();;
7855                 return res;
7856         }
7857         /* try without signature */
7858         *sigstart = 0;
7859         res = g_hash_table_lookup (icall_hash, mname);
7860         if (res) {
7861                 mono_icall_unlock ();
7862                 return res;
7863         }
7864
7865 #ifdef DISABLE_ICALL_TABLES
7866         mono_icall_unlock ();
7867         /* Fail only when the result is actually used */
7868         /* mono_marshal_get_native_wrapper () depends on this */
7869         if (method->klass == mono_defaults.string_class && !strcmp (method->name, ".ctor"))
7870                 return ves_icall_System_String_ctor_RedirectToCreateString;
7871         else
7872                 return no_icall_table;
7873 #else
7874         /* it wasn't found in the static call tables */
7875         if (!imap) {
7876                 mono_icall_unlock ();
7877                 return NULL;
7878         }
7879         res = find_method_icall (imap, sigstart - mlen);
7880         if (res) {
7881                 mono_icall_unlock ();
7882                 return res;
7883         }
7884         /* try _with_ signature */
7885         *sigstart = '(';
7886         res = find_method_icall (imap, sigstart - mlen);
7887         if (res) {
7888                 mono_icall_unlock ();
7889                 return res;
7890         }
7891
7892         g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", mname);
7893         g_print ("\nYour mono runtime and class libraries are out of sync.\n");
7894         g_print ("The out of sync library is: %s\n", method->klass->image->name);
7895         g_print ("\nWhen you update one from git you need to update, compile and install\nthe other too.\n");
7896         g_print ("Do not report this as a bug unless you're sure you have updated correctly:\nyou probably have a broken mono install.\n");
7897         g_print ("If you see other errors or faults after this message they are probably related\n");
7898         g_print ("and you need to fix your mono install first.\n");
7899
7900         mono_icall_unlock ();
7901
7902         return NULL;
7903 #endif
7904 }
7905
7906 #ifdef ENABLE_ICALL_SYMBOL_MAP
7907 static int
7908 func_cmp (gconstpointer key, gconstpointer p)
7909 {
7910         return (gsize)key - (gsize)*(gsize*)p;
7911 }
7912 #endif
7913
7914 /*
7915  * mono_lookup_icall_symbol:
7916  *
7917  *   Given the icall METHOD, returns its C symbol.
7918  */
7919 const char*
7920 mono_lookup_icall_symbol (MonoMethod *m)
7921 {
7922 #ifdef DISABLE_ICALL_TABLES
7923         g_assert_not_reached ();
7924         return NULL;
7925 #else
7926 #ifdef ENABLE_ICALL_SYMBOL_MAP
7927         gpointer func;
7928         int i;
7929         gpointer slot;
7930         static gconstpointer *functions_sorted;
7931         static const char**symbols_sorted;
7932         static gboolean inited;
7933
7934         if (!inited) {
7935                 gboolean changed;
7936
7937                 functions_sorted = g_malloc (G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7938                 memcpy (functions_sorted, icall_functions, G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7939                 symbols_sorted = g_malloc (G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7940                 memcpy (symbols_sorted, icall_symbols, G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7941                 /* Bubble sort the two arrays */
7942                 changed = TRUE;
7943                 while (changed) {
7944                         changed = FALSE;
7945                         for (i = 0; i < G_N_ELEMENTS (icall_functions) - 1; ++i) {
7946                                 if (functions_sorted [i] > functions_sorted [i + 1]) {
7947                                         gconstpointer tmp;
7948
7949                                         tmp = functions_sorted [i];
7950                                         functions_sorted [i] = functions_sorted [i + 1];
7951                                         functions_sorted [i + 1] = tmp;
7952                                         tmp = symbols_sorted [i];
7953                                         symbols_sorted [i] = symbols_sorted [i + 1];
7954                                         symbols_sorted [i + 1] = tmp;
7955                                         changed = TRUE;
7956                                 }
7957                         }
7958                 }
7959         }
7960
7961         func = mono_lookup_internal_call (m);
7962         if (!func)
7963                 return NULL;
7964         slot = mono_binary_search (func, functions_sorted, G_N_ELEMENTS (icall_functions), sizeof (gpointer), func_cmp);
7965         if (!slot)
7966                 return NULL;
7967         g_assert (slot);
7968         return symbols_sorted [(gpointer*)slot - (gpointer*)functions_sorted];
7969 #else
7970         fprintf (stderr, "icall symbol maps not enabled, pass --enable-icall-symbol-map to configure.\n");
7971         g_assert_not_reached ();
7972         return 0;
7973 #endif
7974 #endif
7975 }
7976
7977 static MonoType*
7978 type_from_typename (char *typename)
7979 {
7980         MonoClass *klass = NULL;        /* assignment to shut GCC warning up */
7981
7982         if (!strcmp (typename, "int"))
7983                 klass = mono_defaults.int_class;
7984         else if (!strcmp (typename, "ptr"))
7985                 klass = mono_defaults.int_class;
7986         else if (!strcmp (typename, "void"))
7987                 klass = mono_defaults.void_class;
7988         else if (!strcmp (typename, "int32"))
7989                 klass = mono_defaults.int32_class;
7990         else if (!strcmp (typename, "uint32"))
7991                 klass = mono_defaults.uint32_class;
7992         else if (!strcmp (typename, "int8"))
7993                 klass = mono_defaults.sbyte_class;
7994         else if (!strcmp (typename, "uint8"))
7995                 klass = mono_defaults.byte_class;
7996         else if (!strcmp (typename, "int16"))
7997                 klass = mono_defaults.int16_class;
7998         else if (!strcmp (typename, "uint16"))
7999                 klass = mono_defaults.uint16_class;
8000         else if (!strcmp (typename, "long"))
8001                 klass = mono_defaults.int64_class;
8002         else if (!strcmp (typename, "ulong"))
8003                 klass = mono_defaults.uint64_class;
8004         else if (!strcmp (typename, "float"))
8005                 klass = mono_defaults.single_class;
8006         else if (!strcmp (typename, "double"))
8007                 klass = mono_defaults.double_class;
8008         else if (!strcmp (typename, "object"))
8009                 klass = mono_defaults.object_class;
8010         else if (!strcmp (typename, "obj"))
8011                 klass = mono_defaults.object_class;
8012         else if (!strcmp (typename, "string"))
8013                 klass = mono_defaults.string_class;
8014         else if (!strcmp (typename, "bool"))
8015                 klass = mono_defaults.boolean_class;
8016         else if (!strcmp (typename, "boolean"))
8017                 klass = mono_defaults.boolean_class;
8018         else {
8019                 g_error ("%s", typename);
8020                 g_assert_not_reached ();
8021         }
8022         return &klass->byval_arg;
8023 }
8024
8025 /**
8026  * LOCKING: Take the corlib image lock.
8027  */
8028 MonoMethodSignature*
8029 mono_create_icall_signature (const char *sigstr)
8030 {
8031         gchar **parts;
8032         int i, len;
8033         gchar **tmp;
8034         MonoMethodSignature *res, *res2;
8035         MonoImage *corlib = mono_defaults.corlib;
8036
8037         mono_image_lock (corlib);
8038         res = g_hash_table_lookup (corlib->helper_signatures, sigstr);
8039         mono_image_unlock (corlib);
8040
8041         if (res)
8042                 return res;
8043
8044         parts = g_strsplit (sigstr, " ", 256);
8045
8046         tmp = parts;
8047         len = 0;
8048         while (*tmp) {
8049                 len ++;
8050                 tmp ++;
8051         }
8052
8053         res = mono_metadata_signature_alloc (corlib, len - 1);
8054         res->pinvoke = 1;
8055
8056 #ifdef HOST_WIN32
8057         /* 
8058          * Under windows, the default pinvoke calling convention is STDCALL but
8059          * we need CDECL.
8060          */
8061         res->call_convention = MONO_CALL_C;
8062 #endif
8063
8064         res->ret = type_from_typename (parts [0]);
8065         for (i = 1; i < len; ++i) {
8066                 res->params [i - 1] = type_from_typename (parts [i]);
8067         }
8068
8069         g_strfreev (parts);
8070
8071         mono_image_lock (corlib);
8072         res2 = g_hash_table_lookup (corlib->helper_signatures, sigstr);
8073         if (res2)
8074                 res = res2; /*Value is allocated in the image pool*/
8075         else
8076                 g_hash_table_insert (corlib->helper_signatures, (gpointer)sigstr, res);
8077         mono_image_unlock (corlib);
8078
8079         return res;
8080 }
8081
8082 MonoJitICallInfo *
8083 mono_find_jit_icall_by_name (const char *name)
8084 {
8085         MonoJitICallInfo *info;
8086         g_assert (jit_icall_hash_name);
8087
8088         mono_icall_lock ();
8089         info = g_hash_table_lookup (jit_icall_hash_name, name);
8090         mono_icall_unlock ();
8091         return info;
8092 }
8093
8094 MonoJitICallInfo *
8095 mono_find_jit_icall_by_addr (gconstpointer addr)
8096 {
8097         MonoJitICallInfo *info;
8098         g_assert (jit_icall_hash_addr);
8099
8100         mono_icall_lock ();
8101         info = g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
8102         mono_icall_unlock ();
8103
8104         return info;
8105 }
8106
8107 /*
8108  * mono_get_jit_icall_info:
8109  *
8110  *   Return the hashtable mapping JIT icall names to MonoJitICallInfo structures. The
8111  * caller should access it while holding the icall lock.
8112  */
8113 GHashTable*
8114 mono_get_jit_icall_info (void)
8115 {
8116         return jit_icall_hash_name;
8117 }
8118
8119 /*
8120  * mono_lookup_jit_icall_symbol:
8121  *
8122  *   Given the jit icall NAME, returns its C symbol if possible, or NULL.
8123  */
8124 const char*
8125 mono_lookup_jit_icall_symbol (const char *name)
8126 {
8127         MonoJitICallInfo *info;
8128         const char *res = NULL;
8129
8130         mono_icall_lock ();
8131         info = g_hash_table_lookup (jit_icall_hash_name, name);
8132         if (info)
8133                 res = info->c_symbol;
8134         mono_icall_unlock ();
8135         return res;
8136 }
8137
8138 void
8139 mono_register_jit_icall_wrapper (MonoJitICallInfo *info, gconstpointer wrapper)
8140 {
8141         mono_icall_lock ();
8142         g_hash_table_insert (jit_icall_hash_addr, (gpointer)wrapper, info);
8143         mono_icall_unlock ();
8144 }
8145
8146 /*
8147  * If NO_RAISE is set, that means the icall is not calling mono_raise_exception () directly or indirectly. The JIT might be able to call these
8148  * icalls without wrappers in some cases.
8149  */
8150 MonoJitICallInfo *
8151 mono_register_jit_icall_full (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save, gboolean no_raise, const char *c_symbol)
8152 {
8153         MonoJitICallInfo *info;
8154         
8155         g_assert (func);
8156         g_assert (name);
8157
8158         mono_icall_lock ();
8159
8160         if (!jit_icall_hash_name) {
8161                 jit_icall_hash_name = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free);
8162                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
8163         }
8164
8165         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
8166                 g_warning ("jit icall already defined \"%s\"\n", name);
8167                 g_assert_not_reached ();
8168         }
8169
8170         info = g_new0 (MonoJitICallInfo, 1);
8171         
8172         info->name = name;
8173         info->func = func;
8174         info->sig = sig;
8175         info->c_symbol = c_symbol;
8176         info->no_raise = no_raise;
8177
8178         if (is_save) {
8179                 info->wrapper = func;
8180         } else {
8181                 info->wrapper = NULL;
8182         }
8183
8184         g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
8185         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
8186
8187         mono_icall_unlock ();
8188         return info;
8189 }
8190
8191 MonoJitICallInfo *
8192 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
8193 {
8194         return mono_register_jit_icall_full (func, name, sig, is_save, FALSE, NULL);
8195 }
8196