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