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