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