Merge pull request #1952 from esdrubal/proc_name
[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);
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); /*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); /*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);
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);
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 /* System.Buffer */
5620
5621 static inline gint32 
5622 mono_array_get_byte_length (MonoArray *array)
5623 {
5624         MonoClass *klass;
5625         int length;
5626         int i;
5627
5628         klass = array->obj.vtable->klass;
5629
5630         if (array->bounds == NULL)
5631                 length = array->max_length;
5632         else {
5633                 length = 1;
5634                 for (i = 0; i < klass->rank; ++ i)
5635                         length *= array->bounds [i].length;
5636         }
5637
5638         switch (klass->element_class->byval_arg.type) {
5639         case MONO_TYPE_I1:
5640         case MONO_TYPE_U1:
5641         case MONO_TYPE_BOOLEAN:
5642                 return length;
5643         case MONO_TYPE_I2:
5644         case MONO_TYPE_U2:
5645         case MONO_TYPE_CHAR:
5646                 return length << 1;
5647         case MONO_TYPE_I4:
5648         case MONO_TYPE_U4:
5649         case MONO_TYPE_R4:
5650                 return length << 2;
5651         case MONO_TYPE_I:
5652         case MONO_TYPE_U:
5653                 return length * sizeof (gpointer);
5654         case MONO_TYPE_I8:
5655         case MONO_TYPE_U8:
5656         case MONO_TYPE_R8:
5657                 return length << 3;
5658         default:
5659                 return -1;
5660         }
5661 }
5662
5663 ICALL_EXPORT gint32 
5664 ves_icall_System_Buffer_ByteLengthInternal (MonoArray *array) 
5665 {
5666         return mono_array_get_byte_length (array);
5667 }
5668
5669 ICALL_EXPORT gint8 
5670 ves_icall_System_Buffer_GetByteInternal (MonoArray *array, gint32 idx) 
5671 {
5672         return mono_array_get (array, gint8, idx);
5673 }
5674
5675 ICALL_EXPORT void 
5676 ves_icall_System_Buffer_SetByteInternal (MonoArray *array, gint32 idx, gint8 value) 
5677 {
5678         mono_array_set (array, gint8, idx, value);
5679 }
5680
5681 ICALL_EXPORT MonoBoolean
5682 ves_icall_System_Buffer_BlockCopyInternal (MonoArray *src, gint32 src_offset, MonoArray *dest, gint32 dest_offset, gint32 count) 
5683 {
5684         guint8 *src_buf, *dest_buf;
5685
5686         if (count < 0) {
5687                 mono_set_pending_exception (mono_get_exception_argument ("count", "is negative"));
5688                 return FALSE;
5689         }
5690
5691         g_assert (count >= 0);
5692
5693         /* This is called directly from the class libraries without going through the managed wrapper */
5694         MONO_CHECK_ARG_NULL (src, FALSE);
5695         MONO_CHECK_ARG_NULL (dest, FALSE);
5696
5697         /* watch out for integer overflow */
5698         if ((src_offset > mono_array_get_byte_length (src) - count) || (dest_offset > mono_array_get_byte_length (dest) - count))
5699                 return FALSE;
5700
5701         src_buf = (guint8 *)src->vector + src_offset;
5702         dest_buf = (guint8 *)dest->vector + dest_offset;
5703
5704         if (src != dest)
5705                 memcpy (dest_buf, src_buf, count);
5706         else
5707                 memmove (dest_buf, src_buf, count); /* Source and dest are the same array */
5708
5709         return TRUE;
5710 }
5711
5712 #ifndef DISABLE_REMOTING
5713 ICALL_EXPORT MonoObject *
5714 ves_icall_Remoting_RealProxy_GetTransparentProxy (MonoObject *this_obj, MonoString *class_name)
5715 {
5716         MonoDomain *domain = mono_object_domain (this_obj); 
5717         MonoObject *res;
5718         MonoRealProxy *rp = ((MonoRealProxy *)this_obj);
5719         MonoTransparentProxy *tp;
5720         MonoType *type;
5721         MonoClass *klass;
5722
5723         res = mono_object_new (domain, mono_defaults.transparent_proxy_class);
5724         tp = (MonoTransparentProxy*) res;
5725         
5726         MONO_OBJECT_SETREF (tp, rp, rp);
5727         type = ((MonoReflectionType *)rp->class_to_proxy)->type;
5728         klass = mono_class_from_mono_type (type);
5729
5730         tp->custom_type_info = (mono_object_isinst (this_obj, mono_defaults.iremotingtypeinfo_class) != NULL);
5731         tp->remote_class = mono_remote_class (domain, class_name, klass);
5732
5733         res->vtable = mono_remote_class_vtable (domain, tp->remote_class, rp);
5734         return res;
5735 }
5736
5737 ICALL_EXPORT MonoReflectionType *
5738 ves_icall_Remoting_RealProxy_InternalGetProxyType (MonoTransparentProxy *tp)
5739 {
5740         return mono_type_get_object (mono_object_domain (tp), &tp->remote_class->proxy_class->byval_arg);
5741 }
5742 #endif
5743
5744 /* System.Environment */
5745
5746 MonoString*
5747 ves_icall_System_Environment_get_UserName (void)
5748 {
5749         /* using glib is more portable */
5750         return mono_string_new (mono_domain_get (), g_get_user_name ());
5751 }
5752
5753
5754 ICALL_EXPORT MonoString *
5755 ves_icall_System_Environment_get_MachineName (void)
5756 {
5757 #if defined (HOST_WIN32)
5758         gunichar2 *buf;
5759         guint32 len;
5760         MonoString *result;
5761
5762         len = MAX_COMPUTERNAME_LENGTH + 1;
5763         buf = g_new (gunichar2, len);
5764
5765         result = NULL;
5766         if (GetComputerName (buf, (PDWORD) &len))
5767                 result = mono_string_new_utf16 (mono_domain_get (), buf, len);
5768
5769         g_free (buf);
5770         return result;
5771 #elif !defined(DISABLE_SOCKETS)
5772         gchar buf [256];
5773         MonoString *result;
5774
5775         if (gethostname (buf, sizeof (buf)) == 0)
5776                 result = mono_string_new (mono_domain_get (), buf);
5777         else
5778                 result = NULL;
5779         
5780         return result;
5781 #else
5782         return mono_string_new (mono_domain_get (), "mono");
5783 #endif
5784 }
5785
5786 ICALL_EXPORT int
5787 ves_icall_System_Environment_get_Platform (void)
5788 {
5789 #if defined (TARGET_WIN32)
5790         /* Win32NT */
5791         return 2;
5792 #elif defined(__MACH__)
5793         /* OSX */
5794         //
5795         // Notice that the value is hidden from user code, and only exposed
5796         // to mscorlib.   This is due to Mono's Unix/MacOS code predating the
5797         // define and making assumptions based on Unix/128/4 values before there
5798         // was a MacOS define.    Lots of code would assume that not-Unix meant
5799         // Windows, but in this case, it would be OSX. 
5800         //
5801         return 6;
5802 #else
5803         /* Unix */
5804         return 4;
5805 #endif
5806 }
5807
5808 ICALL_EXPORT MonoString *
5809 ves_icall_System_Environment_get_NewLine (void)
5810 {
5811 #if defined (HOST_WIN32)
5812         return mono_string_new (mono_domain_get (), "\r\n");
5813 #else
5814         return mono_string_new (mono_domain_get (), "\n");
5815 #endif
5816 }
5817
5818 ICALL_EXPORT MonoString *
5819 ves_icall_System_Environment_GetEnvironmentVariable (MonoString *name)
5820 {
5821         const gchar *value;
5822         gchar *utf8_name;
5823
5824         if (name == NULL)
5825                 return NULL;
5826
5827         utf8_name = mono_string_to_utf8 (name); /* FIXME: this should be ascii */
5828         value = g_getenv (utf8_name);
5829
5830         g_free (utf8_name);
5831
5832         if (value == 0)
5833                 return NULL;
5834         
5835         return mono_string_new (mono_domain_get (), value);
5836 }
5837
5838 /*
5839  * There is no standard way to get at environ.
5840  */
5841 #ifndef _MSC_VER
5842 #ifndef __MINGW32_VERSION
5843 #if defined(__APPLE__) && !defined (__arm__) && !defined (__aarch64__)
5844 /* Apple defines this in crt_externs.h but doesn't provide that header for 
5845  * arm-apple-darwin9.  We'll manually define the symbol on Apple as it does
5846  * in fact exist on all implementations (so far) 
5847  */
5848 gchar ***_NSGetEnviron(void);
5849 #define environ (*_NSGetEnviron())
5850 #else
5851 extern
5852 char **environ;
5853 #endif
5854 #endif
5855 #endif
5856
5857 ICALL_EXPORT MonoArray *
5858 ves_icall_System_Environment_GetEnvironmentVariableNames (void)
5859 {
5860 #ifdef HOST_WIN32
5861         MonoArray *names;
5862         MonoDomain *domain;
5863         MonoString *str;
5864         WCHAR* env_strings;
5865         WCHAR* env_string;
5866         WCHAR* equal_str;
5867         int n = 0;
5868
5869         env_strings = GetEnvironmentStrings();
5870
5871         if (env_strings) {
5872                 env_string = env_strings;
5873                 while (*env_string != '\0') {
5874                 /* weird case that MS seems to skip */
5875                         if (*env_string != '=')
5876                                 n++;
5877                         while (*env_string != '\0')
5878                                 env_string++;
5879                         env_string++;
5880                 }
5881         }
5882
5883         domain = mono_domain_get ();
5884         names = mono_array_new (domain, mono_defaults.string_class, n);
5885
5886         if (env_strings) {
5887                 n = 0;
5888                 env_string = env_strings;
5889                 while (*env_string != '\0') {
5890                         /* weird case that MS seems to skip */
5891                         if (*env_string != '=') {
5892                                 equal_str = wcschr(env_string, '=');
5893                                 g_assert(equal_str);
5894                                 str = mono_string_new_utf16 (domain, env_string, equal_str-env_string);
5895                                 mono_array_setref (names, n, str);
5896                                 n++;
5897                         }
5898                         while (*env_string != '\0')
5899                                 env_string++;
5900                         env_string++;
5901                 }
5902
5903                 FreeEnvironmentStrings (env_strings);
5904         }
5905
5906         return names;
5907
5908 #else
5909         MonoArray *names;
5910         MonoDomain *domain;
5911         MonoString *str;
5912         gchar **e, **parts;
5913         int n;
5914
5915         n = 0;
5916         for (e = environ; *e != 0; ++ e)
5917                 ++ n;
5918
5919         domain = mono_domain_get ();
5920         names = mono_array_new (domain, mono_defaults.string_class, n);
5921
5922         n = 0;
5923         for (e = environ; *e != 0; ++ e) {
5924                 parts = g_strsplit (*e, "=", 2);
5925                 if (*parts != 0) {
5926                         str = mono_string_new (domain, *parts);
5927                         mono_array_setref (names, n, str);
5928                 }
5929
5930                 g_strfreev (parts);
5931
5932                 ++ n;
5933         }
5934
5935         return names;
5936 #endif
5937 }
5938
5939 /*
5940  * If your platform lacks setenv/unsetenv, you must upgrade your glib.
5941  */
5942 #if !GLIB_CHECK_VERSION(2,4,0)
5943 #define g_setenv(a,b,c)   setenv(a,b,c)
5944 #define g_unsetenv(a) unsetenv(a)
5945 #endif
5946
5947 ICALL_EXPORT void
5948 ves_icall_System_Environment_InternalSetEnvironmentVariable (MonoString *name, MonoString *value)
5949 {
5950 #ifdef HOST_WIN32
5951         gunichar2 *utf16_name, *utf16_value;
5952 #else
5953         gchar *utf8_name, *utf8_value;
5954         MonoError error;
5955 #endif
5956
5957 #ifdef HOST_WIN32
5958         utf16_name = mono_string_to_utf16 (name);
5959         if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
5960                 SetEnvironmentVariable (utf16_name, NULL);
5961                 g_free (utf16_name);
5962                 return;
5963         }
5964
5965         utf16_value = mono_string_to_utf16 (value);
5966
5967         SetEnvironmentVariable (utf16_name, utf16_value);
5968
5969         g_free (utf16_name);
5970         g_free (utf16_value);
5971 #else
5972         utf8_name = mono_string_to_utf8 (name); /* FIXME: this should be ascii */
5973
5974         if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
5975                 g_unsetenv (utf8_name);
5976                 g_free (utf8_name);
5977                 return;
5978         }
5979
5980         utf8_value = mono_string_to_utf8_checked (value, &error);
5981         if (!mono_error_ok (&error)) {
5982                 g_free (utf8_name);
5983                 mono_error_raise_exception (&error);
5984         }
5985         g_setenv (utf8_name, utf8_value, TRUE);
5986
5987         g_free (utf8_name);
5988         g_free (utf8_value);
5989 #endif
5990 }
5991
5992 ICALL_EXPORT void
5993 ves_icall_System_Environment_Exit (int result)
5994 {
5995         mono_environment_exitcode_set (result);
5996
5997 /* FIXME: There are some cleanup hangs that should be worked out, but
5998  * if the program is going to exit, everything will be cleaned up when
5999  * NaCl exits anyway.
6000  */
6001 #ifndef __native_client__
6002         if (!mono_runtime_try_shutdown ())
6003                 mono_thread_exit ();
6004
6005         /* Suspend all managed threads since the runtime is going away */
6006         mono_thread_suspend_all_other_threads ();
6007
6008         mono_runtime_quit ();
6009 #endif
6010
6011         /* we may need to do some cleanup here... */
6012         exit (result);
6013 }
6014
6015 ICALL_EXPORT MonoString*
6016 ves_icall_System_Environment_GetGacPath (void)
6017 {
6018         return mono_string_new (mono_domain_get (), mono_assembly_getrootdir ());
6019 }
6020
6021 ICALL_EXPORT MonoString*
6022 ves_icall_System_Environment_GetWindowsFolderPath (int folder)
6023 {
6024 #if defined (HOST_WIN32)
6025         #ifndef CSIDL_FLAG_CREATE
6026                 #define CSIDL_FLAG_CREATE       0x8000
6027         #endif
6028
6029         WCHAR path [MAX_PATH];
6030         /* Create directory if no existing */
6031         if (SUCCEEDED (SHGetFolderPathW (NULL, folder | CSIDL_FLAG_CREATE, NULL, 0, path))) {
6032                 int len = 0;
6033                 while (path [len])
6034                         ++ len;
6035                 return mono_string_new_utf16 (mono_domain_get (), path, len);
6036         }
6037 #else
6038         g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
6039 #endif
6040         return mono_string_new (mono_domain_get (), "");
6041 }
6042
6043 ICALL_EXPORT MonoArray *
6044 ves_icall_System_Environment_GetLogicalDrives (void)
6045 {
6046         gunichar2 buf [256], *ptr, *dname;
6047         gunichar2 *u16;
6048         guint initial_size = 127, size = 128;
6049         gint ndrives;
6050         MonoArray *result;
6051         MonoString *drivestr;
6052         MonoDomain *domain = mono_domain_get ();
6053         gint len;
6054
6055         buf [0] = '\0';
6056         ptr = buf;
6057
6058         while (size > initial_size) {
6059                 size = (guint) GetLogicalDriveStrings (initial_size, ptr);
6060                 if (size > initial_size) {
6061                         if (ptr != buf)
6062                                 g_free (ptr);
6063                         ptr = g_malloc0 ((size + 1) * sizeof (gunichar2));
6064                         initial_size = size;
6065                         size++;
6066                 }
6067         }
6068
6069         /* Count strings */
6070         dname = ptr;
6071         ndrives = 0;
6072         do {
6073                 while (*dname++);
6074                 ndrives++;
6075         } while (*dname);
6076
6077         dname = ptr;
6078         result = mono_array_new (domain, mono_defaults.string_class, ndrives);
6079         ndrives = 0;
6080         do {
6081                 len = 0;
6082                 u16 = dname;
6083                 while (*u16) { u16++; len ++; }
6084                 drivestr = mono_string_new_utf16 (domain, dname, len);
6085                 mono_array_setref (result, ndrives++, drivestr);
6086                 while (*dname++);
6087         } while (*dname);
6088
6089         if (ptr != buf)
6090                 g_free (ptr);
6091
6092         return result;
6093 }
6094
6095 ICALL_EXPORT MonoString *
6096 ves_icall_System_IO_DriveInfo_GetDriveFormat (MonoString *path)
6097 {
6098         gunichar2 volume_name [MAX_PATH + 1];
6099         
6100         if (GetVolumeInformation (mono_string_chars (path), NULL, 0, NULL, NULL, NULL, volume_name, MAX_PATH + 1) == FALSE)
6101                 return NULL;
6102         return mono_string_from_utf16 (volume_name);
6103 }
6104
6105 ICALL_EXPORT MonoString *
6106 ves_icall_System_Environment_InternalGetHome (void)
6107 {
6108         return mono_string_new (mono_domain_get (), g_get_home_dir ());
6109 }
6110
6111 static const char *encodings [] = {
6112         (char *) 1,
6113                 "ascii", "us_ascii", "us", "ansi_x3.4_1968",
6114                 "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
6115                 "iso_ir_6", "iso646_us", "iso_646.irv:1991",
6116         (char *) 2,
6117                 "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
6118                 "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
6119                 "x_unicode_2_0_utf_7",
6120         (char *) 3,
6121                 "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
6122                 "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
6123         (char *) 4,
6124                 "utf_16", "UTF_16LE", "ucs_2", "unicode",
6125                 "iso_10646_ucs2",
6126         (char *) 5,
6127                 "unicodefffe", "utf_16be",
6128         (char *) 6,
6129                 "iso_8859_1",
6130         (char *) 0
6131 };
6132
6133 /*
6134  * Returns the internal codepage, if the value of "int_code_page" is
6135  * 1 at entry, and we can not compute a suitable code page number,
6136  * returns the code page as a string
6137  */
6138 ICALL_EXPORT MonoString*
6139 ves_icall_System_Text_EncodingHelper_InternalCodePage (gint32 *int_code_page) 
6140 {
6141         const char *cset;
6142         const char *p;
6143         char *c;
6144         char *codepage = NULL;
6145         int code;
6146         int want_name = *int_code_page;
6147         int i;
6148         
6149         *int_code_page = -1;
6150
6151         g_get_charset (&cset);
6152         c = codepage = strdup (cset);
6153         for (c = codepage; *c; c++){
6154                 if (isascii (*c) && isalpha (*c))
6155                         *c = tolower (*c);
6156                 if (*c == '-')
6157                         *c = '_';
6158         }
6159         /* g_print ("charset: %s\n", cset); */
6160         
6161         /* handle some common aliases */
6162         p = encodings [0];
6163         code = 0;
6164         for (i = 0; p != 0; ){
6165                 if ((gssize) p < 7){
6166                         code = (gssize) p;
6167                         p = encodings [++i];
6168                         continue;
6169                 }
6170                 if (strcmp (p, codepage) == 0){
6171                         *int_code_page = code;
6172                         break;
6173                 }
6174                 p = encodings [++i];
6175         }
6176         
6177         if (strstr (codepage, "utf_8") != NULL)
6178                 *int_code_page |= 0x10000000;
6179         free (codepage);
6180         
6181         if (want_name && *int_code_page == -1)
6182                 return mono_string_new (mono_domain_get (), cset);
6183         else
6184                 return NULL;
6185 }
6186
6187 ICALL_EXPORT MonoBoolean
6188 ves_icall_System_Environment_get_HasShutdownStarted (void)
6189 {
6190         if (mono_runtime_is_shutting_down ())
6191                 return TRUE;
6192
6193         if (mono_domain_is_unloading (mono_domain_get ()))
6194                 return TRUE;
6195
6196         return FALSE;
6197 }
6198
6199 ICALL_EXPORT void
6200 ves_icall_System_Environment_BroadcastSettingChange (void)
6201 {
6202 #ifdef HOST_WIN32
6203         SendMessageTimeout (HWND_BROADCAST, WM_SETTINGCHANGE, (WPARAM)NULL, (LPARAM)L"Environment", SMTO_ABORTIFHUNG, 2000, 0);
6204 #endif
6205 }
6206
6207 ICALL_EXPORT gint32
6208 ves_icall_System_Runtime_Versioning_VersioningHelper_GetRuntimeId (void)
6209 {
6210         return 9;
6211 }
6212
6213 ICALL_EXPORT void
6214 ves_icall_MonoMethodMessage_InitMessage (MonoMethodMessage *this_obj, 
6215                                          MonoReflectionMethod *method,
6216                                          MonoArray *out_args)
6217 {
6218         mono_message_init (mono_object_domain (this_obj), this_obj, method, out_args);
6219 }
6220
6221 #ifndef DISABLE_REMOTING
6222 ICALL_EXPORT MonoBoolean
6223 ves_icall_IsTransparentProxy (MonoObject *proxy)
6224 {
6225         if (!proxy)
6226                 return 0;
6227
6228         if (proxy->vtable->klass == mono_defaults.transparent_proxy_class)
6229                 return 1;
6230
6231         return 0;
6232 }
6233
6234 ICALL_EXPORT MonoReflectionMethod *
6235 ves_icall_Remoting_RemotingServices_GetVirtualMethod (
6236         MonoReflectionType *rtype, MonoReflectionMethod *rmethod)
6237 {
6238         MonoClass *klass;
6239         MonoMethod *method;
6240         MonoMethod **vtable;
6241         MonoMethod *res = NULL;
6242
6243         MONO_CHECK_ARG_NULL (rtype, NULL);
6244         MONO_CHECK_ARG_NULL (rmethod, NULL);
6245
6246         method = rmethod->method;
6247         klass = mono_class_from_mono_type (rtype->type);
6248         mono_class_init_or_throw (klass);
6249
6250         if (MONO_CLASS_IS_INTERFACE (klass))
6251                 return NULL;
6252
6253         if (method->flags & METHOD_ATTRIBUTE_STATIC)
6254                 return NULL;
6255
6256         if ((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6257                 if (klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE))
6258                         return rmethod;
6259                 else
6260                         return NULL;
6261         }
6262
6263         mono_class_setup_vtable (klass);
6264         vtable = klass->vtable;
6265
6266         if (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6267                 gboolean variance_used = FALSE;
6268                 /*MS fails with variant interfaces but it's the right thing to do anyway.*/
6269                 int offs = mono_class_interface_offset_with_variance (klass, method->klass, &variance_used);
6270                 if (offs >= 0)
6271                         res = vtable [offs + method->slot];
6272         } else {
6273                 if (!(klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE)))
6274                         return NULL;
6275
6276                 if (method->slot != -1)
6277                         res = vtable [method->slot];
6278         }
6279
6280         if (!res)
6281                 return NULL;
6282
6283         return mono_method_get_object (mono_domain_get (), res, NULL);
6284 }
6285
6286 ICALL_EXPORT void
6287 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionType *type, MonoBoolean enable)
6288 {
6289         MonoClass *klass;
6290         MonoVTable* vtable;
6291
6292         klass = mono_class_from_mono_type (type->type);
6293         vtable = mono_class_vtable_full (mono_domain_get (), klass, TRUE);
6294
6295         mono_vtable_set_is_remote (vtable, enable);
6296 }
6297
6298 #else /* DISABLE_REMOTING */
6299
6300 ICALL_EXPORT void
6301 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionType *type, MonoBoolean enable)
6302 {
6303         g_assert_not_reached ();
6304 }
6305
6306 #endif
6307
6308 ICALL_EXPORT MonoObject *
6309 ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance (MonoReflectionType *type)
6310 {
6311         MonoClass *klass;
6312         MonoDomain *domain;
6313         
6314         domain = mono_object_domain (type);
6315         klass = mono_class_from_mono_type (type->type);
6316         mono_class_init_or_throw (klass);
6317
6318         if (MONO_CLASS_IS_INTERFACE (klass) || (klass->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
6319                 mono_set_pending_exception (mono_get_exception_argument ("type", "Type cannot be instantiated"));
6320                 return NULL;
6321         }
6322
6323         if (klass->rank >= 1) {
6324                 g_assert (klass->rank == 1);
6325                 return (MonoObject *) mono_array_new (domain, klass->element_class, 0);
6326         } else {
6327                 /* Bypass remoting object creation check */
6328                 return mono_object_new_alloc_specific (mono_class_vtable_full (domain, klass, TRUE));
6329         }
6330 }
6331
6332 ICALL_EXPORT MonoString *
6333 ves_icall_System_IO_get_temp_path (void)
6334 {
6335         return mono_string_new (mono_domain_get (), g_get_tmp_dir ());
6336 }
6337
6338 #ifndef PLATFORM_NO_DRIVEINFO
6339 ICALL_EXPORT MonoBoolean
6340 ves_icall_System_IO_DriveInfo_GetDiskFreeSpace (MonoString *path_name, guint64 *free_bytes_avail,
6341                                                 guint64 *total_number_of_bytes, guint64 *total_number_of_free_bytes,
6342                                                 gint32 *error)
6343 {
6344         gboolean result;
6345         ULARGE_INTEGER wapi_free_bytes_avail;
6346         ULARGE_INTEGER wapi_total_number_of_bytes;
6347         ULARGE_INTEGER wapi_total_number_of_free_bytes;
6348
6349         *error = ERROR_SUCCESS;
6350         result = GetDiskFreeSpaceEx (mono_string_chars (path_name), &wapi_free_bytes_avail, &wapi_total_number_of_bytes,
6351                                      &wapi_total_number_of_free_bytes);
6352
6353         if (result) {
6354                 *free_bytes_avail = wapi_free_bytes_avail.QuadPart;
6355                 *total_number_of_bytes = wapi_total_number_of_bytes.QuadPart;
6356                 *total_number_of_free_bytes = wapi_total_number_of_free_bytes.QuadPart;
6357         } else {
6358                 *free_bytes_avail = 0;
6359                 *total_number_of_bytes = 0;
6360                 *total_number_of_free_bytes = 0;
6361                 *error = GetLastError ();
6362         }
6363
6364         return result;
6365 }
6366
6367 ICALL_EXPORT guint32
6368 ves_icall_System_IO_DriveInfo_GetDriveType (MonoString *root_path_name)
6369 {
6370         return GetDriveType (mono_string_chars (root_path_name));
6371 }
6372 #endif
6373
6374 ICALL_EXPORT gpointer
6375 ves_icall_RuntimeMethod_GetFunctionPointer (MonoMethod *method)
6376 {
6377         return mono_compile_method (method);
6378 }
6379
6380 ICALL_EXPORT MonoString *
6381 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (void)
6382 {
6383         MonoString *mcpath;
6384         gchar *path;
6385
6386         path = g_build_path (G_DIR_SEPARATOR_S, mono_get_config_dir (), "mono", mono_get_runtime_info ()->framework_version, "machine.config", NULL);
6387
6388 #if defined (HOST_WIN32)
6389         /* Avoid mixing '/' and '\\' */
6390         {
6391                 gint i;
6392                 for (i = strlen (path) - 1; i >= 0; i--)
6393                         if (path [i] == '/')
6394                                 path [i] = '\\';
6395         }
6396 #endif
6397         mcpath = mono_string_new (mono_domain_get (), path);
6398         g_free (path);
6399
6400         return mcpath;
6401 }
6402
6403 static MonoString *
6404 get_bundled_app_config (void)
6405 {
6406         const gchar *app_config;
6407         MonoDomain *domain;
6408         MonoString *file;
6409         gchar *config_file_name, *config_file_path;
6410         gsize len, config_file_path_length, config_ext_length;
6411         gchar *module;
6412
6413         domain = mono_domain_get ();
6414         file = domain->setup->configuration_file;
6415         if (!file || file->length == 0)
6416                 return NULL;
6417
6418         // Retrieve config file and remove the extension
6419         config_file_name = mono_string_to_utf8 (file);
6420         config_file_path = mono_portability_find_file (config_file_name, TRUE);
6421         if (!config_file_path)
6422                 config_file_path = config_file_name;
6423
6424         config_file_path_length = strlen (config_file_path);
6425         config_ext_length = strlen (".config");
6426         if (config_file_path_length <= config_ext_length)
6427                 return NULL;
6428
6429         len = config_file_path_length - config_ext_length;
6430         module = g_malloc0 (len + 1);
6431         memcpy (module, config_file_path, len);
6432         // Get the config file from the module name
6433         app_config = mono_config_string_for_assembly_file (module);
6434         // Clean-up
6435         g_free (module);
6436         if (config_file_name != config_file_path)
6437                 g_free (config_file_name);
6438         g_free (config_file_path);
6439
6440         if (!app_config)
6441                 return NULL;
6442
6443         return mono_string_new (mono_domain_get (), app_config);
6444 }
6445
6446 static MonoString *
6447 get_bundled_machine_config (void)
6448 {
6449         const gchar *machine_config;
6450
6451         machine_config = mono_get_machine_config ();
6452
6453         if (!machine_config)
6454                 return NULL;
6455
6456         return mono_string_new (mono_domain_get (), machine_config);
6457 }
6458
6459 ICALL_EXPORT MonoString *
6460 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (void)
6461 {
6462         MonoString *ipath;
6463         gchar *path;
6464
6465         path = g_path_get_dirname (mono_get_config_dir ());
6466
6467 #if defined (HOST_WIN32)
6468         /* Avoid mixing '/' and '\\' */
6469         {
6470                 gint i;
6471                 for (i = strlen (path) - 1; i >= 0; i--)
6472                         if (path [i] == '/')
6473                                 path [i] = '\\';
6474         }
6475 #endif
6476         ipath = mono_string_new (mono_domain_get (), path);
6477         g_free (path);
6478
6479         return ipath;
6480 }
6481
6482 ICALL_EXPORT gboolean
6483 ves_icall_get_resources_ptr (MonoReflectionAssembly *assembly, gpointer *result, gint32 *size)
6484 {
6485         MonoPEResourceDataEntry *entry;
6486         MonoImage *image;
6487
6488         if (!assembly || !result || !size)
6489                 return FALSE;
6490
6491         *result = NULL;
6492         *size = 0;
6493         image = assembly->assembly->image;
6494         entry = mono_image_lookup_resource (image, MONO_PE_RESOURCE_ID_ASPNET_STRING, 0, NULL);
6495         if (!entry)
6496                 return FALSE;
6497
6498         *result = mono_image_rva_map (image, entry->rde_data_offset);
6499         if (!(*result)) {
6500                 g_free (entry);
6501                 return FALSE;
6502         }
6503         *size = entry->rde_size;
6504         g_free (entry);
6505         return TRUE;
6506 }
6507
6508 ICALL_EXPORT MonoBoolean
6509 ves_icall_System_Diagnostics_Debugger_IsAttached_internal (void)
6510 {
6511         return mono_is_debugger_attached ();
6512 }
6513
6514 ICALL_EXPORT MonoBoolean
6515 ves_icall_System_Diagnostics_Debugger_IsLogging (void)
6516 {
6517         if (mono_get_runtime_callbacks ()->debug_log_is_enabled)
6518                 return mono_get_runtime_callbacks ()->debug_log_is_enabled ();
6519         else
6520                 return FALSE;
6521 }
6522
6523 ICALL_EXPORT void
6524 ves_icall_System_Diagnostics_Debugger_Log (int level, MonoString *category, MonoString *message)
6525 {
6526         if (mono_get_runtime_callbacks ()->debug_log)
6527                 mono_get_runtime_callbacks ()->debug_log (level, category, message);
6528 }
6529
6530 ICALL_EXPORT void
6531 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (MonoString *message)
6532 {
6533 #if defined (HOST_WIN32)
6534         OutputDebugString (mono_string_chars (message));
6535 #else
6536         g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
6537 #endif
6538 }
6539
6540 /* Only used for value types */
6541 ICALL_EXPORT MonoObject *
6542 ves_icall_System_Activator_CreateInstanceInternal (MonoReflectionType *type)
6543 {
6544         MonoClass *klass;
6545         MonoDomain *domain;
6546         
6547         domain = mono_object_domain (type);
6548         klass = mono_class_from_mono_type (type->type);
6549         mono_class_init_or_throw (klass);
6550
6551         if (mono_class_is_nullable (klass))
6552                 /* No arguments -> null */
6553                 return NULL;
6554
6555         return mono_object_new (domain, klass);
6556 }
6557
6558 ICALL_EXPORT MonoReflectionMethod *
6559 ves_icall_MonoMethod_get_base_method (MonoReflectionMethod *m, gboolean definition)
6560 {
6561         MonoClass *klass, *parent;
6562         MonoMethod *method = m->method;
6563         MonoMethod *result = NULL;
6564         int slot;
6565
6566         if (method->klass == NULL)
6567                 return m;
6568
6569         if (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
6570             MONO_CLASS_IS_INTERFACE (method->klass) ||
6571             method->flags & METHOD_ATTRIBUTE_NEW_SLOT)
6572                 return m;
6573
6574         slot = mono_method_get_vtable_slot (method);
6575         if (slot == -1)
6576                 return m;
6577
6578         klass = method->klass;
6579         if (klass->generic_class)
6580                 klass = klass->generic_class->container_class;
6581
6582         if (definition) {
6583                 /* At the end of the loop, klass points to the eldest class that has this virtual function slot. */
6584                 for (parent = klass->parent; parent != NULL; parent = parent->parent) {
6585                         mono_class_setup_vtable (parent);
6586                         if (parent->vtable_size <= slot)
6587                                 break;
6588                         klass = parent;
6589                 }
6590         } else {
6591                 klass = klass->parent;
6592                 if (!klass)
6593                         return m;
6594         }
6595
6596         if (klass == method->klass)
6597                 return m;
6598
6599         /*This is possible if definition == FALSE.
6600          * Do it here to be really sure we don't read invalid memory.
6601          */
6602         if (slot >= klass->vtable_size)
6603                 return m;
6604
6605         mono_class_setup_vtable (klass);
6606
6607         result = klass->vtable [slot];
6608         if (result == NULL) {
6609                 /* It is an abstract method */
6610                 gpointer iter = NULL;
6611                 while ((result = mono_class_get_methods (klass, &iter)))
6612                         if (result->slot == slot)
6613                                 break;
6614         }
6615
6616         if (result == NULL)
6617                 return m;
6618
6619         return mono_method_get_object (mono_domain_get (), result, NULL);
6620 }
6621
6622 ICALL_EXPORT MonoString*
6623 ves_icall_MonoMethod_get_name (MonoReflectionMethod *m)
6624 {
6625         MonoMethod *method = m->method;
6626
6627         MONO_OBJECT_SETREF (m, name, mono_string_new (mono_object_domain (m), method->name));
6628         return m->name;
6629 }
6630
6631 ICALL_EXPORT void
6632 mono_ArgIterator_Setup (MonoArgIterator *iter, char* argsp, char* start)
6633 {
6634         iter->sig = *(MonoMethodSignature**)argsp;
6635         
6636         g_assert (iter->sig->sentinelpos <= iter->sig->param_count);
6637         g_assert (iter->sig->call_convention == MONO_CALL_VARARG);
6638
6639         iter->next_arg = 0;
6640         /* FIXME: it's not documented what start is exactly... */
6641         if (start) {
6642                 iter->args = start;
6643         } else {
6644                 iter->args = argsp + sizeof (gpointer);
6645         }
6646         iter->num_args = iter->sig->param_count - iter->sig->sentinelpos;
6647
6648         /* g_print ("sig %p, param_count: %d, sent: %d\n", iter->sig, iter->sig->param_count, iter->sig->sentinelpos); */
6649 }
6650
6651 ICALL_EXPORT MonoTypedRef
6652 mono_ArgIterator_IntGetNextArg (MonoArgIterator *iter)
6653 {
6654         guint32 i, arg_size;
6655         gint32 align;
6656         MonoTypedRef res;
6657
6658         i = iter->sig->sentinelpos + iter->next_arg;
6659
6660         g_assert (i < iter->sig->param_count);
6661
6662         res.type = iter->sig->params [i];
6663         res.klass = mono_class_from_mono_type (res.type);
6664         arg_size = mono_type_stack_size (res.type, &align);
6665 #if defined(__arm__) || defined(__mips__)
6666         iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
6667 #endif
6668         res.value = iter->args;
6669 #if defined(__native_client__) && SIZEOF_REGISTER == 8
6670         /* Values are stored as 8 byte register sized objects, but 'value'
6671          * is dereferenced as a pointer in other routines.
6672          */
6673         res.value = (char*)res.value + 4;
6674 #endif
6675 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
6676         if (arg_size <= sizeof (gpointer)) {
6677                 int dummy;
6678                 int padding = arg_size - mono_type_size (res.type, &dummy);
6679                 res.value = (guint8*)res.value + padding;
6680         }
6681 #endif
6682         iter->args = (char*)iter->args + arg_size;
6683         iter->next_arg++;
6684
6685         /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
6686
6687         return res;
6688 }
6689
6690 ICALL_EXPORT MonoTypedRef
6691 mono_ArgIterator_IntGetNextArgT (MonoArgIterator *iter, MonoType *type)
6692 {
6693         guint32 i, arg_size;
6694         gint32 align;
6695         MonoTypedRef res;
6696
6697         i = iter->sig->sentinelpos + iter->next_arg;
6698
6699         g_assert (i < iter->sig->param_count);
6700
6701         while (i < iter->sig->param_count) {
6702                 if (!mono_metadata_type_equal (type, iter->sig->params [i]))
6703                         continue;
6704                 res.type = iter->sig->params [i];
6705                 res.klass = mono_class_from_mono_type (res.type);
6706                 /* FIXME: endianess issue... */
6707                 arg_size = mono_type_stack_size (res.type, &align);
6708 #if defined(__arm__) || defined(__mips__)
6709                 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
6710 #endif
6711                 res.value = iter->args;
6712                 iter->args = (char*)iter->args + arg_size;
6713                 iter->next_arg++;
6714                 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
6715                 return res;
6716         }
6717         /* g_print ("arg type 0x%02x not found\n", res.type->type); */
6718
6719         res.type = NULL;
6720         res.value = NULL;
6721         res.klass = NULL;
6722         return res;
6723 }
6724
6725 ICALL_EXPORT MonoType*
6726 mono_ArgIterator_IntGetNextArgType (MonoArgIterator *iter)
6727 {
6728         gint i;
6729         
6730         i = iter->sig->sentinelpos + iter->next_arg;
6731
6732         g_assert (i < iter->sig->param_count);
6733
6734         return iter->sig->params [i];
6735 }
6736
6737 ICALL_EXPORT MonoObject*
6738 mono_TypedReference_ToObject (MonoTypedRef* tref)
6739 {
6740         if (MONO_TYPE_IS_REFERENCE (tref->type)) {
6741                 MonoObject** objp = tref->value;
6742                 return *objp;
6743         }
6744
6745         return mono_value_box (mono_domain_get (), tref->klass, tref->value);
6746 }
6747
6748 ICALL_EXPORT MonoTypedRef
6749 mono_TypedReference_MakeTypedReferenceInternal (MonoObject *target, MonoArray *fields)
6750 {
6751         MonoTypedRef res;
6752         MonoReflectionField *f;
6753         MonoClass *klass;
6754         MonoType *ftype = NULL;
6755         guint8 *p = NULL;
6756         int i;
6757
6758         memset (&res, 0, sizeof (res));
6759
6760         g_assert (fields);
6761         g_assert (mono_array_length (fields) > 0);
6762
6763         klass = target->vtable->klass;
6764
6765         for (i = 0; i < mono_array_length (fields); ++i) {
6766                 f = mono_array_get (fields, MonoReflectionField*, i);
6767                 if (f == NULL) {
6768                         mono_set_pending_exception (mono_get_exception_argument_null ("field"));
6769                         return res;
6770                 }
6771                 if (f->field->parent != klass) {
6772                         mono_set_pending_exception (mono_get_exception_argument ("field", ""));
6773                         return res;
6774                 }
6775                 if (i == 0)
6776                         p = (guint8*)target + f->field->offset;
6777                 else
6778                         p += f->field->offset - sizeof (MonoObject);
6779                 klass = mono_class_from_mono_type (f->field->type);
6780                 ftype = f->field->type;
6781         }
6782
6783         res.type = ftype;
6784         res.klass = mono_class_from_mono_type (ftype);
6785         res.value = p;
6786
6787         return res;
6788 }
6789
6790 static void
6791 prelink_method (MonoMethod *method)
6792 {
6793         const char *exc_class, *exc_arg;
6794         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
6795                 return;
6796         mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
6797         if (exc_class) {
6798                 mono_raise_exception( 
6799                         mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg ) );
6800         }
6801         /* create the wrapper, too? */
6802 }
6803
6804 ICALL_EXPORT void
6805 ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethod *method)
6806 {
6807         prelink_method (method->method);
6808 }
6809
6810 ICALL_EXPORT void
6811 ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll (MonoReflectionType *type)
6812 {
6813         MonoClass *klass = mono_class_from_mono_type (type->type);
6814         MonoMethod* m;
6815         gpointer iter = NULL;
6816
6817         mono_class_init_or_throw (klass);
6818
6819         while ((m = mono_class_get_methods (klass, &iter)))
6820                 prelink_method (m);
6821 }
6822
6823 /* These parameters are "readonly" in corlib/System/NumberFormatter.cs */
6824 ICALL_EXPORT void
6825 ves_icall_System_NumberFormatter_GetFormatterTables (guint64 const **mantissas,
6826                                             gint32 const **exponents,
6827                                             gunichar2 const **digitLowerTable,
6828                                             gunichar2 const **digitUpperTable,
6829                                             gint64 const **tenPowersList,
6830                                             gint32 const **decHexDigits)
6831 {
6832         *mantissas = Formatter_MantissaBitsTable;
6833         *exponents = Formatter_TensExponentTable;
6834         *digitLowerTable = Formatter_DigitLowerTable;
6835         *digitUpperTable = Formatter_DigitUpperTable;
6836         *tenPowersList = Formatter_TenPowersList;
6837         *decHexDigits = Formatter_DecHexDigits;
6838 }
6839
6840 /*
6841  * We return NULL for no modifiers so the corlib code can return Type.EmptyTypes
6842  * and avoid useless allocations.
6843  * 
6844  * MAY THROW
6845  */
6846 static MonoArray*
6847 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional)
6848 {
6849         MonoArray *res;
6850         int i, count = 0;
6851         for (i = 0; i < type->num_mods; ++i) {
6852                 if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required))
6853                         count++;
6854         }
6855         if (!count)
6856                 return NULL;
6857         res = mono_array_new (mono_domain_get (), mono_defaults.systemtype_class, count);
6858         count = 0;
6859         for (i = 0; i < type->num_mods; ++i) {
6860                 if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required)) {
6861                         MonoError error;
6862                         MonoClass *klass = mono_class_get_checked (image, type->modifiers [i].token, &error);
6863                         mono_error_raise_exception (&error); /* this is safe, no cleanup needed on callers */ 
6864                         mono_array_setref (res, count, mono_type_get_object (mono_domain_get (), &klass->byval_arg));
6865                         count++;
6866                 }
6867         }
6868         return res;
6869 }
6870
6871 ICALL_EXPORT MonoArray*
6872 param_info_get_type_modifiers (MonoReflectionParameter *param, MonoBoolean optional)
6873 {
6874         MonoType *type = param->ClassImpl->type;
6875         MonoClass *member_class = mono_object_class (param->MemberImpl);
6876         MonoMethod *method = NULL;
6877         MonoImage *image;
6878         int pos;
6879         MonoMethodSignature *sig;
6880
6881         if (mono_class_is_reflection_method_or_constructor (member_class)) {
6882                 MonoReflectionMethod *rmethod = (MonoReflectionMethod*)param->MemberImpl;
6883                 method = rmethod->method;
6884         } else if (member_class->image == mono_defaults.corlib && !strcmp ("MonoProperty", member_class->name)) {
6885                 MonoReflectionProperty *prop = (MonoReflectionProperty *)param->MemberImpl;
6886                 if (!(method = prop->property->get))
6887                         method = prop->property->set;
6888                 g_assert (method);      
6889         } else {
6890                 char *type_name = mono_type_get_full_name (member_class);
6891                 char *msg = g_strdup_printf ("Custom modifiers on a ParamInfo with member %s are not supported", type_name);
6892                 MonoException *ex = mono_get_exception_not_supported  (msg);
6893                 g_free (type_name);
6894                 g_free (msg);
6895                 mono_set_pending_exception (ex);
6896                 return NULL;
6897         }
6898
6899         image = method->klass->image;
6900         pos = param->PositionImpl;
6901         sig = mono_method_signature (method);
6902         if (pos == -1)
6903                 type = sig->ret;
6904         else
6905                 type = sig->params [pos];
6906
6907         return type_array_from_modifiers (image, type, optional);
6908 }
6909
6910 static MonoType*
6911 get_property_type (MonoProperty *prop)
6912 {
6913         MonoMethodSignature *sig;
6914         if (prop->get) {
6915                 sig = mono_method_signature (prop->get);
6916                 return sig->ret;
6917         } else if (prop->set) {
6918                 sig = mono_method_signature (prop->set);
6919                 return sig->params [sig->param_count - 1];
6920         }
6921         return NULL;
6922 }
6923
6924 ICALL_EXPORT MonoArray*
6925 property_info_get_type_modifiers (MonoReflectionProperty *property, MonoBoolean optional)
6926 {
6927         MonoType *type = get_property_type (property->property);
6928         MonoImage *image = property->klass->image;
6929
6930         if (!type)
6931                 return NULL;
6932         return type_array_from_modifiers (image, type, optional);
6933 }
6934
6935 /*
6936  *Construct a MonoType suited to be used to decode a constant blob object.
6937  *
6938  * @type is the target type which will be constructed
6939  * @blob_type is the blob type, for example, that comes from the constant table
6940  * @real_type is the expected constructed type.
6941  */
6942 static void
6943 mono_type_from_blob_type (MonoType *type, MonoTypeEnum blob_type, MonoType *real_type)
6944 {
6945         type->type = blob_type;
6946         type->data.klass = NULL;
6947         if (blob_type == MONO_TYPE_CLASS)
6948                 type->data.klass = mono_defaults.object_class;
6949         else if (real_type->type == MONO_TYPE_VALUETYPE && real_type->data.klass->enumtype) {
6950                 /* For enums, we need to use the base type */
6951                 type->type = MONO_TYPE_VALUETYPE;
6952                 type->data.klass = mono_class_from_mono_type (real_type);
6953         } else
6954                 type->data.klass = mono_class_from_mono_type (real_type);
6955 }
6956
6957 ICALL_EXPORT MonoObject*
6958 property_info_get_default_value (MonoReflectionProperty *property)
6959 {
6960         MonoType blob_type;
6961         MonoProperty *prop = property->property;
6962         MonoType *type = get_property_type (prop);
6963         MonoDomain *domain = mono_object_domain (property); 
6964         MonoTypeEnum def_type;
6965         const char *def_value;
6966         MonoObject *o;
6967
6968         mono_class_init (prop->parent);
6969
6970         if (!(prop->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT)) {
6971                 mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
6972                 return NULL;
6973         }
6974
6975         def_value = mono_class_get_property_default_value (prop, &def_type);
6976
6977         mono_type_from_blob_type (&blob_type, def_type, type);
6978         o = mono_get_object_from_blob (domain, &blob_type, def_value);
6979
6980         return o;
6981 }
6982
6983 ICALL_EXPORT MonoBoolean
6984 custom_attrs_defined_internal (MonoObject *obj, MonoReflectionType *attr_type)
6985 {
6986         MonoClass *attr_class = mono_class_from_mono_type (attr_type->type);
6987         MonoCustomAttrInfo *cinfo;
6988         gboolean found;
6989
6990         mono_class_init_or_throw (attr_class);
6991
6992         cinfo = mono_reflection_get_custom_attrs_info (obj);
6993         if (!cinfo)
6994                 return FALSE;
6995         found = mono_custom_attrs_has_attr (cinfo, attr_class);
6996         if (!cinfo->cached)
6997                 mono_custom_attrs_free (cinfo);
6998         return found;
6999 }
7000
7001 ICALL_EXPORT MonoArray*
7002 custom_attrs_get_by_type (MonoObject *obj, MonoReflectionType *attr_type)
7003 {
7004         MonoClass *attr_class = attr_type ? mono_class_from_mono_type (attr_type->type) : NULL;
7005         MonoArray *res;
7006         MonoError error;
7007
7008         if (attr_class)
7009                 mono_class_init_or_throw (attr_class);
7010
7011         res = mono_reflection_get_custom_attrs_by_type (obj, attr_class, &error);
7012         mono_error_raise_exception (&error);
7013
7014         if (mono_loader_get_last_error ()) {
7015                 mono_set_pending_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
7016                 return NULL;
7017         } else {
7018                 return res;
7019         }
7020 }
7021
7022 ICALL_EXPORT MonoString*
7023 ves_icall_Mono_Runtime_GetDisplayName (void)
7024 {
7025         char *info;
7026         MonoString *display_name;
7027
7028         info = mono_get_runtime_callbacks ()->get_runtime_build_info ();
7029         display_name = mono_string_new (mono_domain_get (), info);
7030         g_free (info);
7031         return display_name;
7032 }
7033
7034 ICALL_EXPORT MonoString*
7035 ves_icall_System_ComponentModel_Win32Exception_W32ErrorMessage (guint32 code)
7036 {
7037         MonoString *message;
7038         guint32 ret;
7039         gunichar2 buf[256];
7040         
7041         ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
7042                              FORMAT_MESSAGE_IGNORE_INSERTS, NULL, code, 0,
7043                              buf, 255, NULL);
7044         if (ret == 0) {
7045                 message = mono_string_new (mono_domain_get (), "Error looking up error string");
7046         } else {
7047                 message = mono_string_new_utf16 (mono_domain_get (), buf, ret);
7048         }
7049         
7050         return message;
7051 }
7052
7053 ICALL_EXPORT int
7054 ves_icall_System_StackFrame_GetILOffsetFromFile (MonoString *path, guint32 method_token, guint32 method_index, int native_offset)
7055 {
7056         guint32 il_offset;
7057         char *path_str = mono_string_to_utf8 (path);
7058
7059         if (!mono_seq_point_data_get_il_offset (path_str, method_token, method_index, native_offset, &il_offset))
7060                 il_offset = -1;
7061
7062         g_free (path_str);
7063
7064         return il_offset;
7065 }
7066
7067 #ifndef DISABLE_ICALL_TABLES
7068
7069 #define ICALL_TYPE(id,name,first)
7070 #define ICALL(id,name,func) Icall_ ## id,
7071
7072 enum {
7073 #include "metadata/icall-def.h"
7074         Icall_last
7075 };
7076
7077 #undef ICALL_TYPE
7078 #undef ICALL
7079 #define ICALL_TYPE(id,name,first) Icall_type_ ## id,
7080 #define ICALL(id,name,func)
7081 enum {
7082 #include "metadata/icall-def.h"
7083         Icall_type_num
7084 };
7085
7086 #undef ICALL_TYPE
7087 #undef ICALL
7088 #define ICALL_TYPE(id,name,firstic) {(Icall_ ## firstic)},
7089 #define ICALL(id,name,func)
7090 typedef struct {
7091         guint16 first_icall;
7092 } IcallTypeDesc;
7093
7094 static const IcallTypeDesc
7095 icall_type_descs [] = {
7096 #include "metadata/icall-def.h"
7097         {Icall_last}
7098 };
7099
7100 #define icall_desc_num_icalls(desc) ((desc) [1].first_icall - (desc) [0].first_icall)
7101
7102 #undef ICALL_TYPE
7103 #define ICALL_TYPE(id,name,first)
7104 #undef ICALL
7105
7106 #ifdef HAVE_ARRAY_ELEM_INIT
7107 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
7108 #define MSGSTRFIELD1(line) str##line
7109
7110 static const struct msgstrtn_t {
7111 #define ICALL(id,name,func)
7112 #undef ICALL_TYPE
7113 #define ICALL_TYPE(id,name,first) char MSGSTRFIELD(__LINE__) [sizeof (name)];
7114 #include "metadata/icall-def.h"
7115 #undef ICALL_TYPE
7116 } icall_type_names_str = {
7117 #define ICALL_TYPE(id,name,first) (name),
7118 #include "metadata/icall-def.h"
7119 #undef ICALL_TYPE
7120 };
7121 static const guint16 icall_type_names_idx [] = {
7122 #define ICALL_TYPE(id,name,first) [Icall_type_ ## id] = offsetof (struct msgstrtn_t, MSGSTRFIELD(__LINE__)),
7123 #include "metadata/icall-def.h"
7124 #undef ICALL_TYPE
7125 };
7126 #define icall_type_name_get(id) ((const char*)&icall_type_names_str + icall_type_names_idx [(id)])
7127
7128 static const struct msgstr_t {
7129 #undef ICALL
7130 #define ICALL_TYPE(id,name,first)
7131 #define ICALL(id,name,func) char MSGSTRFIELD(__LINE__) [sizeof (name)];
7132 #include "metadata/icall-def.h"
7133 #undef ICALL
7134 } icall_names_str = {
7135 #define ICALL(id,name,func) (name),
7136 #include "metadata/icall-def.h"
7137 #undef ICALL
7138 };
7139 static const guint16 icall_names_idx [] = {
7140 #define ICALL(id,name,func) [Icall_ ## id] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
7141 #include "metadata/icall-def.h"
7142 #undef ICALL
7143 };
7144 #define icall_name_get(id) ((const char*)&icall_names_str + icall_names_idx [(id)])
7145
7146 #else
7147
7148 #undef ICALL_TYPE
7149 #undef ICALL
7150 #define ICALL_TYPE(id,name,first) name,
7151 #define ICALL(id,name,func)
7152 static const char* const
7153 icall_type_names [] = {
7154 #include "metadata/icall-def.h"
7155         NULL
7156 };
7157
7158 #define icall_type_name_get(id) (icall_type_names [(id)])
7159
7160 #undef ICALL_TYPE
7161 #undef ICALL
7162 #define ICALL_TYPE(id,name,first)
7163 #define ICALL(id,name,func) name,
7164 static const char* const
7165 icall_names [] = {
7166 #include "metadata/icall-def.h"
7167         NULL
7168 };
7169 #define icall_name_get(id) icall_names [(id)]
7170
7171 #endif /* !HAVE_ARRAY_ELEM_INIT */
7172
7173 #undef ICALL_TYPE
7174 #undef ICALL
7175 #define ICALL_TYPE(id,name,first)
7176 #define ICALL(id,name,func) func,
7177 static const gconstpointer
7178 icall_functions [] = {
7179 #include "metadata/icall-def.h"
7180         NULL
7181 };
7182
7183 #ifdef ENABLE_ICALL_SYMBOL_MAP
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_symbols [] = {
7190 #include "metadata/icall-def.h"
7191         NULL
7192 };
7193 #endif
7194
7195 #endif /* DISABLE_ICALL_TABLES */
7196
7197 static mono_mutex_t icall_mutex;
7198 static GHashTable *icall_hash = NULL;
7199 static GHashTable *jit_icall_hash_name = NULL;
7200 static GHashTable *jit_icall_hash_addr = NULL;
7201
7202 void
7203 mono_icall_init (void)
7204 {
7205 #ifndef DISABLE_ICALL_TABLES
7206         int i = 0;
7207
7208         /* check that tables are sorted: disable in release */
7209         if (TRUE) {
7210                 int j;
7211                 const char *prev_class = NULL;
7212                 const char *prev_method;
7213                 
7214                 for (i = 0; i < Icall_type_num; ++i) {
7215                         const IcallTypeDesc *desc;
7216                         int num_icalls;
7217                         prev_method = NULL;
7218                         if (prev_class && strcmp (prev_class, icall_type_name_get (i)) >= 0)
7219                                 g_print ("class %s should come before class %s\n", icall_type_name_get (i), prev_class);
7220                         prev_class = icall_type_name_get (i);
7221                         desc = &icall_type_descs [i];
7222                         num_icalls = icall_desc_num_icalls (desc);
7223                         /*g_print ("class %s has %d icalls starting at %d\n", prev_class, num_icalls, desc->first_icall);*/
7224                         for (j = 0; j < num_icalls; ++j) {
7225                                 const char *methodn = icall_name_get (desc->first_icall + j);
7226                                 if (prev_method && strcmp (prev_method, methodn) >= 0)
7227                                         g_print ("method %s should come before method %s\n", methodn, prev_method);
7228                                 prev_method = methodn;
7229                         }
7230                 }
7231         }
7232 #endif
7233
7234         icall_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7235         mono_mutex_init (&icall_mutex);
7236 }
7237
7238 static void
7239 mono_icall_lock (void)
7240 {
7241         mono_locks_mutex_acquire (&icall_mutex, IcallLock);
7242 }
7243
7244 static void
7245 mono_icall_unlock (void)
7246 {
7247         mono_locks_mutex_release (&icall_mutex, IcallLock);
7248 }
7249
7250 void
7251 mono_icall_cleanup (void)
7252 {
7253         g_hash_table_destroy (icall_hash);
7254         g_hash_table_destroy (jit_icall_hash_name);
7255         g_hash_table_destroy (jit_icall_hash_addr);
7256         mono_mutex_destroy (&icall_mutex);
7257 }
7258
7259 void
7260 mono_add_internal_call (const char *name, gconstpointer method)
7261 {
7262         mono_icall_lock ();
7263
7264         g_hash_table_insert (icall_hash, g_strdup (name), (gpointer) method);
7265
7266         mono_icall_unlock ();
7267 }
7268
7269 #ifndef DISABLE_ICALL_TABLES
7270
7271 #ifdef HAVE_ARRAY_ELEM_INIT
7272 static int
7273 compare_method_imap (const void *key, const void *elem)
7274 {
7275         const char* method_name = (const char*)&icall_names_str + (*(guint16*)elem);
7276         return strcmp (key, method_name);
7277 }
7278
7279 static gpointer
7280 find_method_icall (const IcallTypeDesc *imap, const char *name)
7281 {
7282         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);
7283         if (!nameslot)
7284                 return NULL;
7285         return (gpointer)icall_functions [(nameslot - &icall_names_idx [0])];
7286 }
7287
7288 static int
7289 compare_class_imap (const void *key, const void *elem)
7290 {
7291         const char* class_name = (const char*)&icall_type_names_str + (*(guint16*)elem);
7292         return strcmp (key, class_name);
7293 }
7294
7295 static const IcallTypeDesc*
7296 find_class_icalls (const char *name)
7297 {
7298         const guint16 *nameslot = mono_binary_search (name, icall_type_names_idx, Icall_type_num, sizeof (icall_type_names_idx [0]), compare_class_imap);
7299         if (!nameslot)
7300                 return NULL;
7301         return &icall_type_descs [nameslot - &icall_type_names_idx [0]];
7302 }
7303
7304 #else /* HAVE_ARRAY_ELEM_INIT */
7305
7306 static int
7307 compare_method_imap (const void *key, const void *elem)
7308 {
7309         const char** method_name = (const char**)elem;
7310         return strcmp (key, *method_name);
7311 }
7312
7313 static gpointer
7314 find_method_icall (const IcallTypeDesc *imap, const char *name)
7315 {
7316         const char **nameslot = mono_binary_search (name, icall_names + imap->first_icall, icall_desc_num_icalls (imap), sizeof (icall_names [0]), compare_method_imap);
7317         if (!nameslot)
7318                 return NULL;
7319         return (gpointer)icall_functions [(nameslot - icall_names)];
7320 }
7321
7322 static int
7323 compare_class_imap (const void *key, const void *elem)
7324 {
7325         const char** class_name = (const char**)elem;
7326         return strcmp (key, *class_name);
7327 }
7328
7329 static const IcallTypeDesc*
7330 find_class_icalls (const char *name)
7331 {
7332         const char **nameslot = mono_binary_search (name, icall_type_names, Icall_type_num, sizeof (icall_type_names [0]), compare_class_imap);
7333         if (!nameslot)
7334                 return NULL;
7335         return &icall_type_descs [nameslot - icall_type_names];
7336 }
7337
7338 #endif /* HAVE_ARRAY_ELEM_INIT */
7339
7340 #endif /* DISABLE_ICALL_TABLES */
7341
7342 /* 
7343  * we should probably export this as an helper (handle nested types).
7344  * Returns the number of chars written in buf.
7345  */
7346 static int
7347 concat_class_name (char *buf, int bufsize, MonoClass *klass)
7348 {
7349         int nspacelen, cnamelen;
7350         nspacelen = strlen (klass->name_space);
7351         cnamelen = strlen (klass->name);
7352         if (nspacelen + cnamelen + 2 > bufsize)
7353                 return 0;
7354         if (nspacelen) {
7355                 memcpy (buf, klass->name_space, nspacelen);
7356                 buf [nspacelen ++] = '.';
7357         }
7358         memcpy (buf + nspacelen, klass->name, cnamelen);
7359         buf [nspacelen + cnamelen] = 0;
7360         return nspacelen + cnamelen;
7361 }
7362
7363 #ifdef DISABLE_ICALL_TABLES
7364 static void
7365 no_icall_table (void)
7366 {
7367         g_assert_not_reached ();
7368 }
7369 #endif
7370
7371 gpointer
7372 mono_lookup_internal_call (MonoMethod *method)
7373 {
7374         char *sigstart;
7375         char *tmpsig;
7376         char mname [2048];
7377         int typelen = 0, mlen, siglen;
7378         gpointer res;
7379 #ifndef DISABLE_ICALL_TABLES
7380         const IcallTypeDesc *imap = NULL;
7381 #endif
7382
7383         g_assert (method != NULL);
7384
7385         if (method->is_inflated)
7386                 method = ((MonoMethodInflated *) method)->declaring;
7387
7388         if (method->klass->nested_in) {
7389                 int pos = concat_class_name (mname, sizeof (mname)-2, method->klass->nested_in);
7390                 if (!pos)
7391                         return NULL;
7392
7393                 mname [pos++] = '/';
7394                 mname [pos] = 0;
7395
7396                 typelen = concat_class_name (mname+pos, sizeof (mname)-pos-1, method->klass);
7397                 if (!typelen)
7398                         return NULL;
7399
7400                 typelen += pos;
7401         } else {
7402                 typelen = concat_class_name (mname, sizeof (mname), method->klass);
7403                 if (!typelen)
7404                         return NULL;
7405         }
7406
7407 #ifndef DISABLE_ICALL_TABLES
7408         imap = find_class_icalls (mname);
7409 #endif
7410
7411         mname [typelen] = ':';
7412         mname [typelen + 1] = ':';
7413
7414         mlen = strlen (method->name);
7415         memcpy (mname + typelen + 2, method->name, mlen);
7416         sigstart = mname + typelen + 2 + mlen;
7417         *sigstart = 0;
7418
7419         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
7420         siglen = strlen (tmpsig);
7421         if (typelen + mlen + siglen + 6 > sizeof (mname))
7422                 return NULL;
7423         sigstart [0] = '(';
7424         memcpy (sigstart + 1, tmpsig, siglen);
7425         sigstart [siglen + 1] = ')';
7426         sigstart [siglen + 2] = 0;
7427         g_free (tmpsig);
7428         
7429         mono_icall_lock ();
7430
7431         res = g_hash_table_lookup (icall_hash, mname);
7432         if (res) {
7433                 mono_icall_unlock ();;
7434                 return res;
7435         }
7436         /* try without signature */
7437         *sigstart = 0;
7438         res = g_hash_table_lookup (icall_hash, mname);
7439         if (res) {
7440                 mono_icall_unlock ();
7441                 return res;
7442         }
7443
7444 #ifdef DISABLE_ICALL_TABLES
7445         mono_icall_unlock ();
7446         /* Fail only when the result is actually used */
7447         /* mono_marshal_get_native_wrapper () depends on this */
7448         if (method->klass == mono_defaults.string_class && !strcmp (method->name, ".ctor"))
7449                 return ves_icall_System_String_ctor_RedirectToCreateString;
7450         else
7451                 return no_icall_table;
7452 #else
7453         /* it wasn't found in the static call tables */
7454         if (!imap) {
7455                 mono_icall_unlock ();
7456                 return NULL;
7457         }
7458         res = find_method_icall (imap, sigstart - mlen);
7459         if (res) {
7460                 mono_icall_unlock ();
7461                 return res;
7462         }
7463         /* try _with_ signature */
7464         *sigstart = '(';
7465         res = find_method_icall (imap, sigstart - mlen);
7466         if (res) {
7467                 mono_icall_unlock ();
7468                 return res;
7469         }
7470
7471         g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", mname);
7472         g_print ("\nYour mono runtime and class libraries are out of sync.\n");
7473         g_print ("The out of sync library is: %s\n", method->klass->image->name);
7474         g_print ("\nWhen you update one from git you need to update, compile and install\nthe other too.\n");
7475         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");
7476         g_print ("If you see other errors or faults after this message they are probably related\n");
7477         g_print ("and you need to fix your mono install first.\n");
7478
7479         mono_icall_unlock ();
7480
7481         return NULL;
7482 #endif
7483 }
7484
7485 #ifdef ENABLE_ICALL_SYMBOL_MAP
7486 static int
7487 func_cmp (gconstpointer key, gconstpointer p)
7488 {
7489         return (gsize)key - (gsize)*(gsize*)p;
7490 }
7491 #endif
7492
7493 /*
7494  * mono_lookup_icall_symbol:
7495  *
7496  *   Given the icall METHOD, returns its C symbol.
7497  */
7498 const char*
7499 mono_lookup_icall_symbol (MonoMethod *m)
7500 {
7501 #ifdef DISABLE_ICALL_TABLES
7502         g_assert_not_reached ();
7503         return NULL;
7504 #else
7505 #ifdef ENABLE_ICALL_SYMBOL_MAP
7506         gpointer func;
7507         int i;
7508         gpointer slot;
7509         static gconstpointer *functions_sorted;
7510         static const char**symbols_sorted;
7511         static gboolean inited;
7512
7513         if (!inited) {
7514                 gboolean changed;
7515
7516                 functions_sorted = g_malloc (G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7517                 memcpy (functions_sorted, icall_functions, G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7518                 symbols_sorted = g_malloc (G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7519                 memcpy (symbols_sorted, icall_symbols, G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7520                 /* Bubble sort the two arrays */
7521                 changed = TRUE;
7522                 while (changed) {
7523                         changed = FALSE;
7524                         for (i = 0; i < G_N_ELEMENTS (icall_functions) - 1; ++i) {
7525                                 if (functions_sorted [i] > functions_sorted [i + 1]) {
7526                                         gconstpointer tmp;
7527
7528                                         tmp = functions_sorted [i];
7529                                         functions_sorted [i] = functions_sorted [i + 1];
7530                                         functions_sorted [i + 1] = tmp;
7531                                         tmp = symbols_sorted [i];
7532                                         symbols_sorted [i] = symbols_sorted [i + 1];
7533                                         symbols_sorted [i + 1] = tmp;
7534                                         changed = TRUE;
7535                                 }
7536                         }
7537                 }
7538         }
7539
7540         func = mono_lookup_internal_call (m);
7541         if (!func)
7542                 return NULL;
7543         slot = mono_binary_search (func, functions_sorted, G_N_ELEMENTS (icall_functions), sizeof (gpointer), func_cmp);
7544         if (!slot)
7545                 return NULL;
7546         g_assert (slot);
7547         return symbols_sorted [(gpointer*)slot - (gpointer*)functions_sorted];
7548 #else
7549         fprintf (stderr, "icall symbol maps not enabled, pass --enable-icall-symbol-map to configure.\n");
7550         g_assert_not_reached ();
7551         return 0;
7552 #endif
7553 #endif
7554 }
7555
7556 static MonoType*
7557 type_from_typename (char *typename)
7558 {
7559         MonoClass *klass = NULL;        /* assignment to shut GCC warning up */
7560
7561         if (!strcmp (typename, "int"))
7562                 klass = mono_defaults.int_class;
7563         else if (!strcmp (typename, "ptr"))
7564                 klass = mono_defaults.int_class;
7565         else if (!strcmp (typename, "void"))
7566                 klass = mono_defaults.void_class;
7567         else if (!strcmp (typename, "int32"))
7568                 klass = mono_defaults.int32_class;
7569         else if (!strcmp (typename, "uint32"))
7570                 klass = mono_defaults.uint32_class;
7571         else if (!strcmp (typename, "int8"))
7572                 klass = mono_defaults.sbyte_class;
7573         else if (!strcmp (typename, "uint8"))
7574                 klass = mono_defaults.byte_class;
7575         else if (!strcmp (typename, "int16"))
7576                 klass = mono_defaults.int16_class;
7577         else if (!strcmp (typename, "uint16"))
7578                 klass = mono_defaults.uint16_class;
7579         else if (!strcmp (typename, "long"))
7580                 klass = mono_defaults.int64_class;
7581         else if (!strcmp (typename, "ulong"))
7582                 klass = mono_defaults.uint64_class;
7583         else if (!strcmp (typename, "float"))
7584                 klass = mono_defaults.single_class;
7585         else if (!strcmp (typename, "double"))
7586                 klass = mono_defaults.double_class;
7587         else if (!strcmp (typename, "object"))
7588                 klass = mono_defaults.object_class;
7589         else if (!strcmp (typename, "obj"))
7590                 klass = mono_defaults.object_class;
7591         else if (!strcmp (typename, "string"))
7592                 klass = mono_defaults.string_class;
7593         else if (!strcmp (typename, "bool"))
7594                 klass = mono_defaults.boolean_class;
7595         else if (!strcmp (typename, "boolean"))
7596                 klass = mono_defaults.boolean_class;
7597         else {
7598                 g_error ("%s", typename);
7599                 g_assert_not_reached ();
7600         }
7601         return &klass->byval_arg;
7602 }
7603
7604 /**
7605  * LOCKING: Take the corlib image lock.
7606  */
7607 MonoMethodSignature*
7608 mono_create_icall_signature (const char *sigstr)
7609 {
7610         gchar **parts;
7611         int i, len;
7612         gchar **tmp;
7613         MonoMethodSignature *res, *res2;
7614         MonoImage *corlib = mono_defaults.corlib;
7615
7616         mono_image_lock (corlib);
7617         res = g_hash_table_lookup (corlib->helper_signatures, sigstr);
7618         mono_image_unlock (corlib);
7619
7620         if (res)
7621                 return res;
7622
7623         parts = g_strsplit (sigstr, " ", 256);
7624
7625         tmp = parts;
7626         len = 0;
7627         while (*tmp) {
7628                 len ++;
7629                 tmp ++;
7630         }
7631
7632         res = mono_metadata_signature_alloc (corlib, len - 1);
7633         res->pinvoke = 1;
7634
7635 #ifdef HOST_WIN32
7636         /* 
7637          * Under windows, the default pinvoke calling convention is STDCALL but
7638          * we need CDECL.
7639          */
7640         res->call_convention = MONO_CALL_C;
7641 #endif
7642
7643         res->ret = type_from_typename (parts [0]);
7644         for (i = 1; i < len; ++i) {
7645                 res->params [i - 1] = type_from_typename (parts [i]);
7646         }
7647
7648         g_strfreev (parts);
7649
7650         mono_image_lock (corlib);
7651         res2 = g_hash_table_lookup (corlib->helper_signatures, sigstr);
7652         if (res2)
7653                 res = res2; /*Value is allocated in the image pool*/
7654         else
7655                 g_hash_table_insert (corlib->helper_signatures, (gpointer)sigstr, res);
7656         mono_image_unlock (corlib);
7657
7658         return res;
7659 }
7660
7661 MonoJitICallInfo *
7662 mono_find_jit_icall_by_name (const char *name)
7663 {
7664         MonoJitICallInfo *info;
7665         g_assert (jit_icall_hash_name);
7666
7667         mono_icall_lock ();
7668         info = g_hash_table_lookup (jit_icall_hash_name, name);
7669         mono_icall_unlock ();
7670         return info;
7671 }
7672
7673 MonoJitICallInfo *
7674 mono_find_jit_icall_by_addr (gconstpointer addr)
7675 {
7676         MonoJitICallInfo *info;
7677         g_assert (jit_icall_hash_addr);
7678
7679         mono_icall_lock ();
7680         info = g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
7681         mono_icall_unlock ();
7682
7683         return info;
7684 }
7685
7686 /*
7687  * mono_get_jit_icall_info:
7688  *
7689  *   Return the hashtable mapping JIT icall names to MonoJitICallInfo structures. The
7690  * caller should access it while holding the icall lock.
7691  */
7692 GHashTable*
7693 mono_get_jit_icall_info (void)
7694 {
7695         return jit_icall_hash_name;
7696 }
7697
7698 /*
7699  * mono_lookup_jit_icall_symbol:
7700  *
7701  *   Given the jit icall NAME, returns its C symbol if possible, or NULL.
7702  */
7703 const char*
7704 mono_lookup_jit_icall_symbol (const char *name)
7705 {
7706         MonoJitICallInfo *info;
7707         const char *res = NULL;
7708
7709         mono_icall_lock ();
7710         info = g_hash_table_lookup (jit_icall_hash_name, name);
7711         if (info)
7712                 res = info->c_symbol;
7713         mono_icall_unlock ();
7714         return res;
7715 }
7716
7717 void
7718 mono_register_jit_icall_wrapper (MonoJitICallInfo *info, gconstpointer wrapper)
7719 {
7720         mono_icall_lock ();
7721         g_hash_table_insert (jit_icall_hash_addr, (gpointer)wrapper, info);
7722         mono_icall_unlock ();
7723 }
7724
7725 /*
7726  * 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
7727  * icalls without wrappers in some cases.
7728  */
7729 MonoJitICallInfo *
7730 mono_register_jit_icall_full (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save, gboolean no_raise, const char *c_symbol)
7731 {
7732         MonoJitICallInfo *info;
7733         
7734         g_assert (func);
7735         g_assert (name);
7736
7737         mono_icall_lock ();
7738
7739         if (!jit_icall_hash_name) {
7740                 jit_icall_hash_name = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free);
7741                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
7742         }
7743
7744         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
7745                 g_warning ("jit icall already defined \"%s\"\n", name);
7746                 g_assert_not_reached ();
7747         }
7748
7749         info = g_new0 (MonoJitICallInfo, 1);
7750         
7751         info->name = name;
7752         info->func = func;
7753         info->sig = sig;
7754         info->c_symbol = c_symbol;
7755         info->no_raise = no_raise;
7756
7757         if (is_save) {
7758                 info->wrapper = func;
7759         } else {
7760                 info->wrapper = NULL;
7761         }
7762
7763         g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
7764         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
7765
7766         mono_icall_unlock ();
7767         return info;
7768 }
7769
7770 MonoJitICallInfo *
7771 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
7772 {
7773         return mono_register_jit_icall_full (func, name, sig, is_save, FALSE, NULL);
7774 }
7775