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