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