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