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