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