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