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