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