Merge pull request #1635 from alexrp/core-clr-properties
[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 MonoObject *
1810 ves_icall_MonoField_GetRawConstantValue (MonoReflectionField *this)
1811 {       
1812         MonoObject *o = NULL;
1813         MonoClassField *field = this->field;
1814         MonoClass *klass;
1815         MonoDomain *domain = mono_object_domain (this); 
1816         gchar *v;
1817         MonoTypeEnum def_type;
1818         const char *def_value;
1819         MonoType *t;
1820         MonoError error;
1821
1822         mono_class_init (field->parent);
1823
1824         t = mono_field_get_type_checked (field, &error);
1825         if (!mono_error_ok (&error))
1826                 mono_error_raise_exception (&error);
1827
1828         if (!(t->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT)) {
1829                 mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
1830                 return NULL;
1831         }
1832
1833         if (image_is_dynamic (field->parent->image)) {
1834                 MonoClass *klass = field->parent;
1835                 int fidx = field - klass->fields;
1836
1837                 g_assert (fidx >= 0 && fidx < klass->field.count);
1838                 g_assert (klass->ext);
1839                 g_assert (klass->ext->field_def_values);
1840                 def_type = klass->ext->field_def_values [fidx].def_type;
1841                 def_value = klass->ext->field_def_values [fidx].data;
1842                 if (def_type == MONO_TYPE_END) {
1843                         mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
1844                         return NULL;
1845                 }
1846         } else {
1847                 def_value = mono_class_get_field_default_value (field, &def_type);
1848                 /* FIXME, maybe we should try to raise TLE if field->parent is broken */
1849                 if (!def_value) {
1850                         mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
1851                         return NULL;
1852                 }
1853         }
1854
1855         /*FIXME unify this with reflection.c:mono_get_object_from_blob*/
1856         switch (def_type) {
1857         case MONO_TYPE_U1:
1858         case MONO_TYPE_I1:
1859         case MONO_TYPE_BOOLEAN:
1860         case MONO_TYPE_U2:
1861         case MONO_TYPE_I2:
1862         case MONO_TYPE_CHAR:
1863         case MONO_TYPE_U:
1864         case MONO_TYPE_I:
1865         case MONO_TYPE_U4:
1866         case MONO_TYPE_I4:
1867         case MONO_TYPE_R4:
1868         case MONO_TYPE_U8:
1869         case MONO_TYPE_I8:
1870         case MONO_TYPE_R8: {
1871                 MonoType *t;
1872
1873                 /* boxed value type */
1874                 t = g_new0 (MonoType, 1);
1875                 t->type = def_type;
1876                 klass = mono_class_from_mono_type (t);
1877                 g_free (t);
1878                 o = mono_object_new (domain, klass);
1879                 v = ((gchar *) o) + sizeof (MonoObject);
1880                 mono_get_constant_value_from_blob (domain, def_type, def_value, v);
1881                 break;
1882         }
1883         case MONO_TYPE_STRING:
1884         case MONO_TYPE_CLASS:
1885                 mono_get_constant_value_from_blob (domain, def_type, def_value, &o);
1886                 break;
1887         default:
1888                 g_assert_not_reached ();
1889         }
1890
1891         return o;
1892 }
1893
1894 ICALL_EXPORT MonoReflectionType*
1895 ves_icall_MonoField_ResolveType (MonoReflectionField *ref_field)
1896 {
1897         MonoError error;
1898         MonoClassField *field = ref_field->field;
1899         MonoType *type = mono_field_get_type_checked (field, &error);
1900         if (!mono_error_ok (&error))
1901                 mono_error_raise_exception (&error);
1902         return mono_type_get_object (mono_object_domain (ref_field), type);
1903 }
1904
1905 ICALL_EXPORT MonoReflectionType*
1906 ves_icall_MonoGenericMethod_get_ReflectedType (MonoReflectionGenericMethod *rmethod)
1907 {
1908         MonoMethod *method = rmethod->method.method;
1909
1910         return mono_type_get_object (mono_object_domain (rmethod), &method->klass->byval_arg);
1911 }
1912
1913 /* From MonoProperty.cs */
1914 typedef enum {
1915         PInfo_Attributes = 1,
1916         PInfo_GetMethod  = 1 << 1,
1917         PInfo_SetMethod  = 1 << 2,
1918         PInfo_ReflectedType = 1 << 3,
1919         PInfo_DeclaringType = 1 << 4,
1920         PInfo_Name = 1 << 5
1921 } PInfo;
1922
1923 ICALL_EXPORT void
1924 ves_icall_get_property_info (MonoReflectionProperty *property, MonoPropertyInfo *info, PInfo req_info)
1925 {
1926         MonoDomain *domain = mono_object_domain (property); 
1927
1928         if ((req_info & PInfo_ReflectedType) != 0)
1929                 MONO_STRUCT_SETREF (info, parent, mono_type_get_object (domain, &property->klass->byval_arg));
1930         if ((req_info & PInfo_DeclaringType) != 0)
1931                 MONO_STRUCT_SETREF (info, declaring_type, mono_type_get_object (domain, &property->property->parent->byval_arg));
1932
1933         if ((req_info & PInfo_Name) != 0)
1934                 MONO_STRUCT_SETREF (info, name, mono_string_new (domain, property->property->name));
1935
1936         if ((req_info & PInfo_Attributes) != 0)
1937                 info->attrs = property->property->attrs;
1938
1939         if ((req_info & PInfo_GetMethod) != 0)
1940                 MONO_STRUCT_SETREF (info, get, property->property->get ?
1941                                                         mono_method_get_object (domain, property->property->get, property->klass): NULL);
1942         
1943         if ((req_info & PInfo_SetMethod) != 0)
1944                 MONO_STRUCT_SETREF (info, set, property->property->set ?
1945                                                         mono_method_get_object (domain, property->property->set, property->klass): NULL);
1946         /* 
1947          * There may be other methods defined for properties, though, it seems they are not exposed 
1948          * in the reflection API 
1949          */
1950 }
1951
1952 ICALL_EXPORT void
1953 ves_icall_get_event_info (MonoReflectionMonoEvent *event, MonoEventInfo *info)
1954 {
1955         MonoDomain *domain = mono_object_domain (event); 
1956
1957         MONO_STRUCT_SETREF (info, reflected_type, mono_type_get_object (domain, &event->klass->byval_arg));
1958         MONO_STRUCT_SETREF (info, declaring_type, mono_type_get_object (domain, &event->event->parent->byval_arg));
1959
1960         MONO_STRUCT_SETREF (info, name, mono_string_new (domain, event->event->name));
1961         info->attrs = event->event->attrs;
1962         MONO_STRUCT_SETREF (info, add_method, event->event->add ? mono_method_get_object (domain, event->event->add, NULL): NULL);
1963         MONO_STRUCT_SETREF (info, remove_method, event->event->remove ? mono_method_get_object (domain, event->event->remove, NULL): NULL);
1964         MONO_STRUCT_SETREF (info, raise_method, event->event->raise ? mono_method_get_object (domain, event->event->raise, NULL): NULL);
1965
1966 #ifndef MONO_SMALL_CONFIG
1967         if (event->event->other) {
1968                 int i, n = 0;
1969                 while (event->event->other [n])
1970                         n++;
1971                 MONO_STRUCT_SETREF (info, other_methods, mono_array_new (domain, mono_defaults.method_info_class, n));
1972
1973                 for (i = 0; i < n; i++)
1974                         mono_array_setref (info->other_methods, i, mono_method_get_object (domain, event->event->other [i], NULL));
1975         }               
1976 #endif
1977 }
1978
1979 static void
1980 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
1981 {
1982         int i;
1983         MonoClass *ic;
1984
1985         mono_class_setup_interfaces (klass, error);
1986         if (!mono_error_ok (error))
1987                 return;
1988
1989         for (i = 0; i < klass->interface_count; i++) {
1990                 ic = klass->interfaces [i];
1991                 g_hash_table_insert (ifaces, ic, ic);
1992
1993                 collect_interfaces (ic, ifaces, error);
1994                 if (!mono_error_ok (error))
1995                         return;
1996         }
1997 }
1998
1999 typedef struct {
2000         MonoArray *iface_array;
2001         MonoGenericContext *context;
2002         MonoError *error;
2003         MonoDomain *domain;
2004         int next_idx;
2005 } FillIfaceArrayData;
2006
2007 static void
2008 fill_iface_array (gpointer key, gpointer value, gpointer user_data)
2009 {
2010         FillIfaceArrayData *data = user_data;
2011         MonoClass *ic = key;
2012         MonoType *ret = &ic->byval_arg, *inflated = NULL;
2013
2014         if (!mono_error_ok (data->error))
2015                 return;
2016
2017         if (data->context && ic->generic_class && ic->generic_class->context.class_inst->is_open) {
2018                 inflated = ret = mono_class_inflate_generic_type_checked (ret, data->context, data->error);
2019                 if (!mono_error_ok (data->error))
2020                         return;
2021         }
2022
2023         mono_array_setref (data->iface_array, data->next_idx++, mono_type_get_object (data->domain, ret));
2024
2025         if (inflated)
2026                 mono_metadata_free_type (inflated);
2027 }
2028
2029 ICALL_EXPORT MonoArray*
2030 ves_icall_Type_GetInterfaces (MonoReflectionType* type)
2031 {
2032         MonoError error;
2033         MonoClass *class = mono_class_from_mono_type (type->type);
2034         MonoClass *parent;
2035         FillIfaceArrayData data = { 0 };
2036         int len;
2037
2038         GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
2039
2040         if (class->generic_class && class->generic_class->context.class_inst->is_open) {
2041                 data.context = mono_class_get_context (class);
2042                 class = class->generic_class->container_class;
2043         }
2044
2045         for (parent = class; parent; parent = parent->parent) {
2046                 mono_class_setup_interfaces (parent, &error);
2047                 if (!mono_error_ok (&error))
2048                         goto fail;
2049                 collect_interfaces (parent, iface_hash, &error);
2050                 if (!mono_error_ok (&error))
2051                         goto fail;
2052         }
2053
2054         data.error = &error;
2055         data.domain = mono_object_domain (type);
2056
2057         len = g_hash_table_size (iface_hash);
2058         if (len == 0) {
2059                 g_hash_table_destroy (iface_hash);
2060                 if (!data.domain->empty_types)
2061                         data.domain->empty_types = mono_array_new_cached (data.domain, mono_defaults.monotype_class, 0);
2062                 return data.domain->empty_types;
2063         }
2064
2065         data.iface_array = mono_array_new_cached (data.domain, mono_defaults.monotype_class, len);
2066         g_hash_table_foreach (iface_hash, fill_iface_array, &data);
2067         if (!mono_error_ok (&error))
2068                 goto fail;
2069
2070         g_hash_table_destroy (iface_hash);
2071         return data.iface_array;
2072
2073 fail:
2074         g_hash_table_destroy (iface_hash);
2075         mono_error_raise_exception (&error);
2076         return NULL;
2077 }
2078
2079 ICALL_EXPORT void
2080 ves_icall_Type_GetInterfaceMapData (MonoReflectionType *type, MonoReflectionType *iface, MonoArray **targets, MonoArray **methods)
2081 {
2082         gboolean variance_used;
2083         MonoClass *class = mono_class_from_mono_type (type->type);
2084         MonoClass *iclass = mono_class_from_mono_type (iface->type);
2085         MonoReflectionMethod *member;
2086         MonoMethod* method;
2087         gpointer iter;
2088         int i = 0, len, ioffset;
2089         MonoDomain *domain;
2090
2091         mono_class_init_or_throw (class);
2092         mono_class_init_or_throw (iclass);
2093
2094         mono_class_setup_vtable (class);
2095
2096         ioffset = mono_class_interface_offset_with_variance (class, iclass, &variance_used);
2097         if (ioffset == -1)
2098                 return;
2099
2100         len = mono_class_num_methods (iclass);
2101         domain = mono_object_domain (type);
2102         mono_gc_wbarrier_generic_store (targets, (MonoObject*) mono_array_new (domain, mono_defaults.method_info_class, len));
2103         mono_gc_wbarrier_generic_store (methods, (MonoObject*) mono_array_new (domain, mono_defaults.method_info_class, len));
2104         iter = NULL;
2105         while ((method = mono_class_get_methods (iclass, &iter))) {
2106                 member = mono_method_get_object (domain, method, iclass);
2107                 mono_array_setref (*methods, i, member);
2108                 member = mono_method_get_object (domain, class->vtable [i + ioffset], class);
2109                 mono_array_setref (*targets, i, member);
2110                 
2111                 i ++;
2112         }
2113 }
2114
2115 ICALL_EXPORT void
2116 ves_icall_Type_GetPacking (MonoReflectionType *type, guint32 *packing, guint32 *size)
2117 {
2118         MonoClass *klass = mono_class_from_mono_type (type->type);
2119         mono_class_init_or_throw (klass);
2120
2121         if (image_is_dynamic (klass->image)) {
2122                 MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)type;
2123                 *packing = tb->packing_size;
2124                 *size = tb->class_size;
2125         } else {
2126                 mono_metadata_packing_from_typedef (klass->image, klass->type_token, packing, size);
2127         }
2128 }
2129
2130 ICALL_EXPORT MonoReflectionType*
2131 ves_icall_MonoType_GetElementType (MonoReflectionType *type)
2132 {
2133         MonoClass *class;
2134
2135         if (!type->type->byref && type->type->type == MONO_TYPE_SZARRAY)
2136                 return mono_type_get_object (mono_object_domain (type), &type->type->data.klass->byval_arg);
2137
2138         class = mono_class_from_mono_type (type->type);
2139         mono_class_init_or_throw (class);
2140
2141         // GetElementType should only return a type for:
2142         // Array Pointer PassedByRef
2143         if (type->type->byref)
2144                 return mono_type_get_object (mono_object_domain (type), &class->byval_arg);
2145         else if (class->element_class && MONO_CLASS_IS_ARRAY (class))
2146                 return mono_type_get_object (mono_object_domain (type), &class->element_class->byval_arg);
2147         else if (class->element_class && type->type->type == MONO_TYPE_PTR)
2148                 return mono_type_get_object (mono_object_domain (type), &class->element_class->byval_arg);
2149         else
2150                 return NULL;
2151 }
2152
2153 ICALL_EXPORT MonoReflectionType*
2154 ves_icall_get_type_parent (MonoReflectionType *type)
2155 {
2156         if (type->type->byref)
2157                 return NULL;
2158
2159         MonoClass *class = mono_class_from_mono_type (type->type);
2160         return class->parent ? mono_type_get_object (mono_object_domain (type), &class->parent->byval_arg): NULL;
2161 }
2162
2163 ICALL_EXPORT MonoBoolean
2164 ves_icall_type_ispointer (MonoReflectionType *type)
2165 {
2166         return type->type->type == MONO_TYPE_PTR;
2167 }
2168
2169 ICALL_EXPORT MonoBoolean
2170 ves_icall_type_isprimitive (MonoReflectionType *type)
2171 {
2172         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)));
2173 }
2174
2175 ICALL_EXPORT MonoBoolean
2176 ves_icall_type_isbyref (MonoReflectionType *type)
2177 {
2178         return type->type->byref;
2179 }
2180
2181 ICALL_EXPORT MonoBoolean
2182 ves_icall_type_iscomobject (MonoReflectionType *type)
2183 {
2184         MonoClass *klass = mono_class_from_mono_type (type->type);
2185         mono_class_init_or_throw (klass);
2186
2187         return mono_class_is_com_object (klass);
2188 }
2189
2190 ICALL_EXPORT MonoReflectionModule*
2191 ves_icall_MonoType_get_Module (MonoReflectionType *type)
2192 {
2193         MonoClass *class = mono_class_from_mono_type (type->type);
2194         return mono_module_get_object (mono_object_domain (type), class->image);
2195 }
2196
2197 ICALL_EXPORT MonoReflectionAssembly*
2198 ves_icall_MonoType_get_Assembly (MonoReflectionType *type)
2199 {
2200         MonoDomain *domain = mono_domain_get (); 
2201         MonoClass *class = mono_class_from_mono_type (type->type);
2202         return mono_assembly_get_object (domain, class->image->assembly);
2203 }
2204
2205 ICALL_EXPORT MonoReflectionType*
2206 ves_icall_MonoType_get_DeclaringType (MonoReflectionType *type)
2207 {
2208         MonoDomain *domain = mono_domain_get ();
2209         MonoClass *class;
2210
2211         if (type->type->byref)
2212                 return NULL;
2213         if (type->type->type == MONO_TYPE_VAR) {
2214                 MonoGenericContainer *param = mono_type_get_generic_param_owner (type->type);
2215                 class = param ? param->owner.klass : NULL;
2216         } else if (type->type->type == MONO_TYPE_MVAR) {
2217                 MonoGenericContainer *param = mono_type_get_generic_param_owner (type->type);
2218                 class = param ? param->owner.method->klass : NULL;
2219         } else {
2220                 class = mono_class_from_mono_type (type->type)->nested_in;
2221         }
2222
2223         return class ? mono_type_get_object (domain, &class->byval_arg) : NULL;
2224 }
2225
2226 ICALL_EXPORT MonoString*
2227 ves_icall_MonoType_get_Name (MonoReflectionType *type)
2228 {
2229         MonoDomain *domain = mono_domain_get (); 
2230         MonoClass *class = mono_class_from_mono_type (type->type);
2231
2232         if (type->type->byref) {
2233                 char *n = g_strdup_printf ("%s&", class->name);
2234                 MonoString *res = mono_string_new (domain, n);
2235
2236                 g_free (n);
2237
2238                 return res;
2239         } else {
2240                 return mono_string_new (domain, class->name);
2241         }
2242 }
2243
2244 ICALL_EXPORT MonoString*
2245 ves_icall_MonoType_get_Namespace (MonoReflectionType *type)
2246 {
2247         MonoDomain *domain = mono_domain_get (); 
2248         MonoClass *class = mono_class_from_mono_type (type->type);
2249
2250         while (class->nested_in)
2251                 class = class->nested_in;
2252
2253         if (class->name_space [0] == '\0')
2254                 return NULL;
2255         else
2256                 return mono_string_new (domain, class->name_space);
2257 }
2258
2259 ICALL_EXPORT gint32
2260 ves_icall_MonoType_GetArrayRank (MonoReflectionType *type)
2261 {
2262         MonoClass *class;
2263
2264         if (type->type->type != MONO_TYPE_ARRAY && type->type->type != MONO_TYPE_SZARRAY) {
2265                 mono_set_pending_exception (mono_get_exception_argument ("type", "Type must be an array type"));
2266                 return 0;
2267         }
2268
2269         class = mono_class_from_mono_type (type->type);
2270
2271         return class->rank;
2272 }
2273
2274 ICALL_EXPORT MonoArray*
2275 ves_icall_MonoType_GetGenericArguments (MonoReflectionType *type)
2276 {
2277         MonoArray *res;
2278         MonoClass *klass, *pklass;
2279         MonoDomain *domain = mono_object_domain (type);
2280         MonoVTable *array_vtable = mono_class_vtable_full (domain, mono_array_class_get_cached (mono_defaults.systemtype_class, 1), TRUE);
2281         int i;
2282
2283         klass = mono_class_from_mono_type (type->type);
2284
2285         if (klass->generic_container) {
2286                 MonoGenericContainer *container = klass->generic_container;
2287                 res = mono_array_new_specific (array_vtable, container->type_argc);
2288                 for (i = 0; i < container->type_argc; ++i) {
2289                         pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
2290                         mono_array_setref (res, i, mono_type_get_object (domain, &pklass->byval_arg));
2291                 }
2292         } else if (klass->generic_class) {
2293                 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2294                 res = mono_array_new_specific (array_vtable, inst->type_argc);
2295                 for (i = 0; i < inst->type_argc; ++i)
2296                         mono_array_setref (res, i, mono_type_get_object (domain, inst->type_argv [i]));
2297         } else {
2298                 res = mono_array_new_specific (array_vtable, 0);
2299         }
2300         return res;
2301 }
2302
2303 ICALL_EXPORT gboolean
2304 ves_icall_Type_get_IsGenericTypeDefinition (MonoReflectionType *type)
2305 {
2306         MonoClass *klass;
2307
2308         if (!IS_MONOTYPE (type))
2309                 return FALSE;
2310
2311         if (type->type->byref)
2312                 return FALSE;
2313
2314         klass = mono_class_from_mono_type (type->type);
2315         return klass->generic_container != NULL;
2316 }
2317
2318 ICALL_EXPORT MonoReflectionType*
2319 ves_icall_Type_GetGenericTypeDefinition_impl (MonoReflectionType *type)
2320 {
2321         MonoClass *klass;
2322
2323         if (type->type->byref)
2324                 return NULL;
2325
2326         klass = mono_class_from_mono_type (type->type);
2327
2328         if (klass->generic_container) {
2329                 return type; /* check this one */
2330         }
2331         if (klass->generic_class) {
2332                 MonoClass *generic_class = klass->generic_class->container_class;
2333                 gpointer tb;
2334
2335                 tb = mono_class_get_ref_info (generic_class);
2336
2337                 if (generic_class->wastypebuilder && tb)
2338                         return tb;
2339                 else
2340                         return mono_type_get_object (mono_object_domain (type), &generic_class->byval_arg);
2341         }
2342         return NULL;
2343 }
2344
2345 ICALL_EXPORT MonoReflectionType*
2346 ves_icall_Type_MakeGenericType (MonoReflectionType *type, MonoArray *type_array)
2347 {
2348         MonoClass *class;
2349         MonoType *geninst, **types;
2350         int i, count;
2351
2352         g_assert (IS_MONOTYPE (type));
2353         mono_class_init_or_throw (mono_class_from_mono_type (type->type));
2354
2355         count = mono_array_length (type_array);
2356         types = g_new0 (MonoType *, count);
2357
2358         for (i = 0; i < count; i++) {
2359                 MonoReflectionType *t = mono_array_get (type_array, gpointer, i);
2360                 types [i] = t->type;
2361         }
2362
2363         geninst = mono_reflection_bind_generic_parameters (type, count, types);
2364         g_free (types);
2365         if (!geninst)
2366                 return NULL;
2367
2368         class = mono_class_from_mono_type (geninst);
2369
2370         /*we might inflate to the GTD*/
2371         if (class->generic_class && !mono_verifier_class_is_valid_generic_instantiation (class)) {
2372                 mono_set_pending_exception (mono_get_exception_argument ("typeArguments", "Invalid generic arguments"));
2373                 return NULL;
2374         }
2375
2376         return mono_type_get_object (mono_object_domain (type), geninst);
2377 }
2378
2379 ICALL_EXPORT gboolean
2380 ves_icall_Type_get_IsGenericType (MonoReflectionType *type)
2381 {
2382         MonoClass *klass;
2383
2384         if (!IS_MONOTYPE (type))
2385                 return FALSE;
2386
2387         if (type->type->byref)
2388                 return FALSE;
2389
2390         klass = mono_class_from_mono_type (type->type);
2391         return klass->generic_class != NULL || klass->generic_container != NULL;
2392 }
2393
2394 ICALL_EXPORT gint32
2395 ves_icall_Type_GetGenericParameterPosition (MonoReflectionType *type)
2396 {
2397         if (!IS_MONOTYPE (type))
2398                 return -1;
2399
2400         if (is_generic_parameter (type->type))
2401                 return mono_type_get_generic_param_num (type->type);
2402         return -1;
2403 }
2404
2405 ICALL_EXPORT GenericParameterAttributes
2406 ves_icall_Type_GetGenericParameterAttributes (MonoReflectionType *type)
2407 {
2408         g_assert (IS_MONOTYPE (type));
2409         g_assert (is_generic_parameter (type->type));
2410         return mono_generic_param_info (type->type->data.generic_param)->flags;
2411 }
2412
2413 ICALL_EXPORT MonoArray *
2414 ves_icall_Type_GetGenericParameterConstraints (MonoReflectionType *type)
2415 {
2416         MonoGenericParamInfo *param_info;
2417         MonoDomain *domain;
2418         MonoClass **ptr;
2419         MonoArray *res;
2420         int i, count;
2421
2422         g_assert (IS_MONOTYPE (type));
2423
2424         domain = mono_object_domain (type);
2425         param_info = mono_generic_param_info (type->type->data.generic_param);
2426         for (count = 0, ptr = param_info->constraints; ptr && *ptr; ptr++, count++)
2427                 ;
2428
2429         res = mono_array_new (domain, mono_defaults.monotype_class, count);
2430         for (i = 0; i < count; i++)
2431                 mono_array_setref (res, i, mono_type_get_object (domain, &param_info->constraints [i]->byval_arg));
2432
2433
2434         return res;
2435 }
2436
2437 ICALL_EXPORT MonoBoolean
2438 ves_icall_MonoType_get_IsGenericParameter (MonoReflectionType *type)
2439 {
2440         return is_generic_parameter (type->type);
2441 }
2442
2443 ICALL_EXPORT MonoBoolean
2444 ves_icall_TypeBuilder_get_IsGenericParameter (MonoReflectionTypeBuilder *tb)
2445 {
2446         return is_generic_parameter (tb->type.type);
2447 }
2448
2449 ICALL_EXPORT void
2450 ves_icall_EnumBuilder_setup_enum_type (MonoReflectionType *enumtype,
2451                                                                            MonoReflectionType *t)
2452 {
2453         enumtype->type = t->type;
2454 }
2455
2456 ICALL_EXPORT MonoReflectionMethod*
2457 ves_icall_MonoType_GetCorrespondingInflatedMethod (MonoReflectionType *type, 
2458                                                    MonoReflectionMethod* generic)
2459 {
2460         MonoDomain *domain; 
2461         MonoClass *klass;
2462         MonoMethod *method;
2463         gpointer iter;
2464                 
2465         domain = ((MonoObject *)type)->vtable->domain;
2466
2467         klass = mono_class_from_mono_type (type->type);
2468         mono_class_init_or_throw (klass);
2469
2470         iter = NULL;
2471         while ((method = mono_class_get_methods (klass, &iter))) {
2472                 if (method->token == generic->method->token)
2473                         return mono_method_get_object (domain, method, klass);
2474         }
2475
2476         return NULL;
2477 }
2478
2479
2480
2481 ICALL_EXPORT MonoReflectionMethod *
2482 ves_icall_MonoType_get_DeclaringMethod (MonoReflectionType *ref_type)
2483 {
2484         MonoMethod *method;
2485         MonoType *type = ref_type->type;
2486
2487         if (type->byref || (type->type != MONO_TYPE_MVAR && type->type != MONO_TYPE_VAR)) {
2488                 mono_set_pending_exception (mono_get_exception_invalid_operation ("DeclaringMethod can only be used on generic arguments"));
2489                 return NULL;
2490         }
2491         if (type->type == MONO_TYPE_VAR)
2492                 return NULL;
2493
2494         method = mono_type_get_generic_param_owner (type)->owner.method;
2495         g_assert (method);
2496         return mono_method_get_object (mono_object_domain (ref_type), method, method->klass);
2497 }
2498
2499 ICALL_EXPORT MonoReflectionDllImportAttribute*
2500 ves_icall_MonoMethod_GetDllImportAttribute (MonoMethod *method)
2501 {
2502         static MonoClass *DllImportAttributeClass = NULL;
2503         MonoDomain *domain = mono_domain_get ();
2504         MonoReflectionDllImportAttribute *attr;
2505         MonoImage *image = method->klass->image;
2506         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
2507         MonoTableInfo *tables = image->tables;
2508         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
2509         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
2510         guint32 im_cols [MONO_IMPLMAP_SIZE];
2511         guint32 scope_token;
2512         const char *import = NULL;
2513         const char *scope = NULL;
2514         guint32 flags;
2515
2516         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
2517                 return NULL;
2518
2519         if (!DllImportAttributeClass) {
2520                 DllImportAttributeClass = 
2521                         mono_class_from_name (mono_defaults.corlib,
2522                                                                   "System.Runtime.InteropServices", "DllImportAttribute");
2523                 g_assert (DllImportAttributeClass);
2524         }
2525                                                                                                                 
2526         if (image_is_dynamic (method->klass->image)) {
2527                 MonoReflectionMethodAux *method_aux = 
2528                         g_hash_table_lookup (
2529                                                                           ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2530                 if (method_aux) {
2531                         import = method_aux->dllentry;
2532                         scope = method_aux->dll;
2533                 }
2534
2535                 if (!import || !scope) {
2536                         mono_set_pending_exception (mono_get_exception_argument ("method", "System.Reflection.Emit method with invalid pinvoke information"));
2537                         return NULL;
2538                 }
2539         }
2540         else {
2541                 if (piinfo->implmap_idx) {
2542                         mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
2543                         
2544                         piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
2545                         import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
2546                         scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
2547                         scope = mono_metadata_string_heap (image, scope_token);
2548                 }
2549         }
2550         flags = piinfo->piflags;
2551         
2552         attr = (MonoReflectionDllImportAttribute*)mono_object_new (domain, DllImportAttributeClass);
2553
2554         MONO_OBJECT_SETREF (attr, dll, mono_string_new (domain, scope));
2555         MONO_OBJECT_SETREF (attr, entry_point, mono_string_new (domain, import));
2556         attr->call_conv = (flags & 0x700) >> 8;
2557         attr->charset = ((flags & 0x6) >> 1) + 1;
2558         if (attr->charset == 1)
2559                 attr->charset = 2;
2560         attr->exact_spelling = (flags & 0x1) != 0;
2561         attr->set_last_error = (flags & 0x40) != 0;
2562         attr->best_fit_mapping = (flags & 0x30) == 0x10;
2563         attr->throw_on_unmappable = (flags & 0x3000) == 0x1000;
2564         attr->preserve_sig = FALSE;
2565
2566         return attr;
2567 }
2568
2569 ICALL_EXPORT MonoReflectionMethod *
2570 ves_icall_MonoMethod_GetGenericMethodDefinition (MonoReflectionMethod *method)
2571 {
2572         MonoMethodInflated *imethod;
2573         MonoMethod *result;
2574
2575         if (method->method->is_generic)
2576                 return method;
2577
2578         if (!method->method->is_inflated)
2579                 return NULL;
2580
2581         imethod = (MonoMethodInflated *) method->method;
2582
2583         result = imethod->declaring;
2584         /* Not a generic method.  */
2585         if (!result->is_generic)
2586                 return NULL;
2587
2588         if (image_is_dynamic (method->method->klass->image)) {
2589                 MonoDynamicImage *image = (MonoDynamicImage*)method->method->klass->image;
2590                 MonoReflectionMethod *res;
2591
2592                 /*
2593                  * FIXME: Why is this stuff needed at all ? Why can't the code below work for
2594                  * the dynamic case as well ?
2595                  */
2596                 mono_image_lock ((MonoImage*)image);
2597                 res = mono_g_hash_table_lookup (image->generic_def_objects, imethod);
2598                 mono_image_unlock ((MonoImage*)image);
2599
2600                 if (res)
2601                         return res;
2602         }
2603
2604         if (imethod->context.class_inst) {
2605                 MonoClass *klass = ((MonoMethod *) imethod)->klass;
2606                 /*Generic methods gets the context of the GTD.*/
2607                 if (mono_class_get_context (klass)) {
2608                         MonoError error;
2609                         result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
2610                         mono_error_raise_exception (&error);
2611                 }
2612         }
2613
2614         return mono_method_get_object (mono_object_domain (method), result, NULL);
2615 }
2616
2617 ICALL_EXPORT gboolean
2618 ves_icall_MonoMethod_get_IsGenericMethod (MonoReflectionMethod *method)
2619 {
2620         return mono_method_signature (method->method)->generic_param_count != 0;
2621 }
2622
2623 ICALL_EXPORT gboolean
2624 ves_icall_MonoMethod_get_IsGenericMethodDefinition (MonoReflectionMethod *method)
2625 {
2626         return method->method->is_generic;
2627 }
2628
2629 ICALL_EXPORT MonoArray*
2630 ves_icall_MonoMethod_GetGenericArguments (MonoReflectionMethod *method)
2631 {
2632         MonoArray *res;
2633         MonoDomain *domain;
2634         int count, i;
2635
2636         domain = mono_object_domain (method);
2637
2638         if (method->method->is_inflated) {
2639                 MonoGenericInst *inst = mono_method_get_context (method->method)->method_inst;
2640
2641                 if (inst) {
2642                         count = inst->type_argc;
2643                         res = mono_array_new (domain, mono_defaults.systemtype_class, count);
2644
2645                         for (i = 0; i < count; i++)
2646                                 mono_array_setref (res, i, mono_type_get_object (domain, inst->type_argv [i]));
2647
2648                         return res;
2649                 }
2650         }
2651
2652         count = mono_method_signature (method->method)->generic_param_count;
2653         res = mono_array_new (domain, mono_defaults.systemtype_class, count);
2654
2655         for (i = 0; i < count; i++) {
2656                 MonoGenericContainer *container = mono_method_get_generic_container (method->method);
2657                 MonoGenericParam *param = mono_generic_container_get_param (container, i);
2658                 MonoClass *pklass = mono_class_from_generic_parameter (
2659                         param, method->method->klass->image, TRUE);
2660                 mono_array_setref (res, i,
2661                                 mono_type_get_object (domain, &pklass->byval_arg));
2662         }
2663
2664         return res;
2665 }
2666
2667 ICALL_EXPORT MonoObject *
2668 ves_icall_InternalInvoke (MonoReflectionMethod *method, MonoObject *this, MonoArray *params, MonoException **exc) 
2669 {
2670         /* 
2671          * Invoke from reflection is supposed to always be a virtual call (the API
2672          * is stupid), mono_runtime_invoke_*() calls the provided method, allowing
2673          * greater flexibility.
2674          */
2675         MonoMethod *m = method->method;
2676         MonoMethodSignature *sig = mono_method_signature (m);
2677         MonoImage *image;
2678         int pcount;
2679         void *obj = this;
2680
2681         *exc = NULL;
2682
2683         if (mono_security_core_clr_enabled ())
2684                 mono_security_core_clr_ensure_reflection_access_method (m);
2685
2686         if (!(m->flags & METHOD_ATTRIBUTE_STATIC)) {
2687                 if (!mono_class_vtable_full (mono_object_domain (method), m->klass, FALSE)) {
2688                         mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_class_get_exception_for_failure (m->klass));
2689                         return NULL;
2690                 }
2691
2692                 if (this) {
2693                         if (!mono_object_isinst (this, m->klass)) {
2694                                 char *this_name = mono_type_get_full_name (mono_object_get_class (this));
2695                                 char *target_name = mono_type_get_full_name (m->klass);
2696                                 char *msg = g_strdup_printf ("Object of type '%s' doesn't match target type '%s'", this_name, target_name);
2697                                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", msg));
2698                                 g_free (msg);
2699                                 g_free (target_name);
2700                                 g_free (this_name);
2701                                 return NULL;
2702                         }
2703                         m = mono_object_get_virtual_method (this, m);
2704                         /* must pass the pointer to the value for valuetype methods */
2705                         if (m->klass->valuetype)
2706                                 obj = mono_object_unbox (this);
2707                 } else if (strcmp (m->name, ".ctor") && !m->wrapper_type) {
2708                         mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Non-static method requires a target."));
2709                         return NULL;
2710                 }
2711         }
2712
2713         if (sig->ret->byref) {
2714                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System", "NotSupportedException", "Cannot invoke method returning ByRef type via reflection"));
2715                 return NULL;
2716         }
2717
2718         pcount = params? mono_array_length (params): 0;
2719         if (pcount != sig->param_count) {
2720                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name (mono_defaults.corlib, "System.Reflection", "TargetParameterCountException"));
2721                 return NULL;
2722         }
2723
2724         if ((m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT) && !strcmp (m->name, ".ctor") && !this) {
2725                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Cannot invoke constructor of an abstract class."));
2726                 return NULL;
2727         }
2728
2729         image = m->klass->image;
2730         if (image->assembly->ref_only) {
2731                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_get_exception_invalid_operation ("It is illegal to invoke a method on a type loaded using the ReflectionOnly api."));
2732                 return NULL;
2733         }
2734
2735         if (image_is_dynamic (image) && !((MonoDynamicImage*)image)->run) {
2736                 mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_get_exception_not_supported ("Cannot invoke a method in a dynamic assembly without run access."));
2737                 return NULL;
2738         }
2739         
2740         if (m->klass->rank && !strcmp (m->name, ".ctor")) {
2741                 int i;
2742                 uintptr_t *lengths;
2743                 intptr_t *lower_bounds;
2744                 pcount = mono_array_length (params);
2745                 lengths = alloca (sizeof (uintptr_t) * pcount);
2746                 /* Note: the synthetized array .ctors have int32 as argument type */
2747                 for (i = 0; i < pcount; ++i)
2748                         lengths [i] = *(int32_t*) ((char*)mono_array_get (params, gpointer, i) + sizeof (MonoObject));
2749
2750                 if (m->klass->rank == 1 && sig->param_count == 2 && m->klass->element_class->rank) {
2751                         /* This is a ctor for jagged arrays. MS creates an array of arrays. */
2752                         MonoArray *arr = mono_array_new_full (mono_object_domain (params), m->klass, lengths, NULL);
2753
2754                         for (i = 0; i < mono_array_length (arr); ++i) {
2755                                 MonoArray *subarray = mono_array_new_full (mono_object_domain (params), m->klass->element_class, &lengths [1], NULL);
2756
2757                                 mono_array_setref_fast (arr, i, subarray);
2758                         }
2759                         return (MonoObject*)arr;
2760                 }
2761
2762                 if (m->klass->rank == pcount) {
2763                         /* Only lengths provided. */
2764                         lower_bounds = NULL;
2765                 } else {
2766                         g_assert (pcount == (m->klass->rank * 2));
2767                         /* lower bounds are first. */
2768                         lower_bounds = (intptr_t*)lengths;
2769                         lengths += m->klass->rank;
2770                 }
2771
2772                 return (MonoObject*)mono_array_new_full (mono_object_domain (params), m->klass, lengths, lower_bounds);
2773         }
2774         return mono_runtime_invoke_array (m, obj, params, NULL);
2775 }
2776
2777 #ifndef DISABLE_REMOTING
2778 ICALL_EXPORT MonoObject *
2779 ves_icall_InternalExecute (MonoReflectionMethod *method, MonoObject *this, MonoArray *params, MonoArray **outArgs) 
2780 {
2781         MonoDomain *domain = mono_object_domain (method); 
2782         MonoMethod *m = method->method;
2783         MonoMethodSignature *sig = mono_method_signature (m);
2784         MonoArray *out_args;
2785         MonoObject *result;
2786         int i, j, outarg_count = 0;
2787
2788         if (m->klass == mono_defaults.object_class) {
2789                 if (!strcmp (m->name, "FieldGetter")) {
2790                         MonoClass *k = this->vtable->klass;
2791                         MonoString *name;
2792                         char *str;
2793                         
2794                         /* If this is a proxy, then it must be a CBO */
2795                         if (k == mono_defaults.transparent_proxy_class) {
2796                                 MonoTransparentProxy *tp = (MonoTransparentProxy*) this;
2797                                 this = tp->rp->unwrapped_server;
2798                                 g_assert (this);
2799                                 k = this->vtable->klass;
2800                         }
2801                         
2802                         name = mono_array_get (params, MonoString *, 1);
2803                         str = mono_string_to_utf8 (name);
2804                 
2805                         do {
2806                                 MonoClassField* field = mono_class_get_field_from_name (k, str);
2807                                 if (field) {
2808                                         MonoClass *field_klass =  mono_class_from_mono_type (field->type);
2809                                         if (field_klass->valuetype)
2810                                                 result = mono_value_box (domain, field_klass, (char *)this + field->offset);
2811                                         else 
2812                                                 result = *((gpointer *)((char *)this + field->offset));
2813                                 
2814                                         out_args = mono_array_new (domain, mono_defaults.object_class, 1);
2815                                         mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
2816                                         mono_array_setref (out_args, 0, result);
2817                                         g_free (str);
2818                                         return NULL;
2819                                 }
2820                                 k = k->parent;
2821                         } while (k);
2822
2823                         g_free (str);
2824                         g_assert_not_reached ();
2825
2826                 } else if (!strcmp (m->name, "FieldSetter")) {
2827                         MonoClass *k = this->vtable->klass;
2828                         MonoString *name;
2829                         guint32 size;
2830                         gint32 align;
2831                         char *str;
2832                         
2833                         /* If this is a proxy, then it must be a CBO */
2834                         if (k == mono_defaults.transparent_proxy_class) {
2835                                 MonoTransparentProxy *tp = (MonoTransparentProxy*) this;
2836                                 this = tp->rp->unwrapped_server;
2837                                 g_assert (this);
2838                                 k = this->vtable->klass;
2839                         }
2840                         
2841                         name = mono_array_get (params, MonoString *, 1);
2842                         str = mono_string_to_utf8 (name);
2843                 
2844                         do {
2845                                 MonoClassField* field = mono_class_get_field_from_name (k, str);
2846                                 if (field) {
2847                                         MonoClass *field_klass =  mono_class_from_mono_type (field->type);
2848                                         MonoObject *val = mono_array_get (params, gpointer, 2);
2849
2850                                         if (field_klass->valuetype) {
2851                                                 size = mono_type_size (field->type, &align);
2852                                                 g_assert (size == mono_class_value_size (field_klass, NULL));
2853                                                 mono_gc_wbarrier_value_copy ((char *)this + field->offset, (char*)val + sizeof (MonoObject), 1, field_klass);
2854                                         } else {
2855                                                 mono_gc_wbarrier_set_field (this, (char*)this + field->offset, val);
2856                                         }
2857                                 
2858                                         out_args = mono_array_new (domain, mono_defaults.object_class, 0);
2859                                         mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
2860
2861                                         g_free (str);
2862                                         return NULL;
2863                                 }
2864                                 
2865                                 k = k->parent;
2866                         } while (k);
2867
2868                         g_free (str);
2869                         g_assert_not_reached ();
2870
2871                 }
2872         }
2873
2874         for (i = 0; i < mono_array_length (params); i++) {
2875                 if (sig->params [i]->byref) 
2876                         outarg_count++;
2877         }
2878
2879         out_args = mono_array_new (domain, mono_defaults.object_class, outarg_count);
2880         
2881         /* handle constructors only for objects already allocated */
2882         if (!strcmp (method->method->name, ".ctor"))
2883                 g_assert (this);
2884
2885         /* This can be called only on MBR objects, so no need to unbox for valuetypes. */
2886         g_assert (!method->method->klass->valuetype);
2887         result = mono_runtime_invoke_array (method->method, this, params, NULL);
2888
2889         for (i = 0, j = 0; i < mono_array_length (params); i++) {
2890                 if (sig->params [i]->byref) {
2891                         gpointer arg;
2892                         arg = mono_array_get (params, gpointer, i);
2893                         mono_array_setref (out_args, j, arg);
2894                         j++;
2895                 }
2896         }
2897
2898         mono_gc_wbarrier_generic_store (outArgs, (MonoObject*) out_args);
2899
2900         return result;
2901 }
2902 #endif
2903
2904 static guint64
2905 read_enum_value (const char *mem, int type)
2906 {
2907         switch (type) {
2908         case MONO_TYPE_BOOLEAN:
2909         case MONO_TYPE_U1:
2910                 return *(guint8*)mem;
2911         case MONO_TYPE_I1:
2912                 return *(gint8*)mem;
2913         case MONO_TYPE_CHAR:
2914         case MONO_TYPE_U2:
2915                 return read16 (mem);
2916         case MONO_TYPE_I2:
2917                 return (gint16) read16 (mem);
2918         case MONO_TYPE_U4:
2919                 return read32 (mem);
2920         case MONO_TYPE_I4:
2921                 return (gint32) read32 (mem);
2922         case MONO_TYPE_U8:
2923         case MONO_TYPE_I8:
2924                 return read64 (mem);
2925         default:
2926                 g_assert_not_reached ();
2927         }
2928         return 0;
2929 }
2930
2931 static void
2932 write_enum_value (char *mem, int type, guint64 value)
2933 {
2934         switch (type) {
2935         case MONO_TYPE_U1:
2936         case MONO_TYPE_I1: {
2937                 guint8 *p = (guint8*)mem;
2938                 *p = value;
2939                 break;
2940         }
2941         case MONO_TYPE_U2:
2942         case MONO_TYPE_I2: {
2943                 guint16 *p = (void*)mem;
2944                 *p = value;
2945                 break;
2946         }
2947         case MONO_TYPE_U4:
2948         case MONO_TYPE_I4: {
2949                 guint32 *p = (void*)mem;
2950                 *p = value;
2951                 break;
2952         }
2953         case MONO_TYPE_U8:
2954         case MONO_TYPE_I8: {
2955                 guint64 *p = (void*)mem;
2956                 *p = value;
2957                 break;
2958         }
2959         default:
2960                 g_assert_not_reached ();
2961         }
2962         return;
2963 }
2964
2965 ICALL_EXPORT MonoObject *
2966 ves_icall_System_Enum_ToObject (MonoReflectionType *enumType, guint64 value)
2967 {
2968         MonoDomain *domain; 
2969         MonoClass *enumc;
2970         MonoObject *res;
2971         MonoType *etype;
2972
2973         domain = mono_object_domain (enumType); 
2974         enumc = mono_class_from_mono_type (enumType->type);
2975
2976         mono_class_init_or_throw (enumc);
2977
2978         etype = mono_class_enum_basetype (enumc);
2979
2980         res = mono_object_new (domain, enumc);
2981         write_enum_value ((char *)res + sizeof (MonoObject), etype->type, value);
2982
2983         return res;
2984 }
2985
2986 ICALL_EXPORT MonoBoolean
2987 ves_icall_System_Enum_InternalHasFlag (MonoObject *a, MonoObject *b)
2988 {
2989         int size = mono_class_value_size (a->vtable->klass, NULL);
2990         guint64 a_val = 0, b_val = 0;
2991
2992         memcpy (&a_val, mono_object_unbox (a), size);
2993         memcpy (&b_val, mono_object_unbox (b), size);
2994
2995         return (a_val & b_val) == b_val;
2996 }
2997
2998 ICALL_EXPORT MonoObject *
2999 ves_icall_System_Enum_get_value (MonoObject *this)
3000 {
3001         MonoObject *res;
3002         MonoClass *enumc;
3003         gpointer dst;
3004         gpointer src;
3005         int size;
3006
3007         if (!this)
3008                 return NULL;
3009
3010         g_assert (this->vtable->klass->enumtype);
3011         
3012         enumc = mono_class_from_mono_type (mono_class_enum_basetype (this->vtable->klass));
3013         res = mono_object_new (mono_object_domain (this), enumc);
3014         dst = (char *)res + sizeof (MonoObject);
3015         src = (char *)this + sizeof (MonoObject);
3016         size = mono_class_value_size (enumc, NULL);
3017
3018         memcpy (dst, src, size);
3019
3020         return res;
3021 }
3022
3023 ICALL_EXPORT MonoReflectionType *
3024 ves_icall_System_Enum_get_underlying_type (MonoReflectionType *type)
3025 {
3026         MonoType *etype;
3027         MonoClass *klass;
3028
3029         klass = mono_class_from_mono_type (type->type);
3030         mono_class_init_or_throw (klass);
3031
3032         etype = mono_class_enum_basetype (klass);
3033         if (!etype) {
3034                 mono_set_pending_exception (mono_get_exception_argument ("enumType", "Type provided must be an Enum."));
3035                 return NULL;
3036         }
3037
3038         return mono_type_get_object (mono_object_domain (type), etype);
3039 }
3040
3041 ICALL_EXPORT int
3042 ves_icall_System_Enum_compare_value_to (MonoObject *this, MonoObject *other)
3043 {
3044         gpointer tdata = (char *)this + sizeof (MonoObject);
3045         gpointer odata = (char *)other + sizeof (MonoObject);
3046         MonoType *basetype = mono_class_enum_basetype (this->vtable->klass);
3047         g_assert (basetype);
3048
3049         if (other == NULL)
3050                 return 1;
3051
3052         if (this->vtable->klass != other->vtable->klass)
3053                 return 2;
3054
3055 #define COMPARE_ENUM_VALUES(ENUM_TYPE) do { \
3056                 ENUM_TYPE me = *((ENUM_TYPE*)tdata); \
3057                 ENUM_TYPE other = *((ENUM_TYPE*)odata); \
3058                 if (me == other) \
3059                         return 0; \
3060                 return me > other ? 1 : -1; \
3061         } while (0)
3062
3063         switch (basetype->type) {
3064                 case MONO_TYPE_U1:
3065                         COMPARE_ENUM_VALUES (guint8);
3066                 case MONO_TYPE_I1:
3067                         COMPARE_ENUM_VALUES (gint8);
3068                 case MONO_TYPE_CHAR:
3069                 case MONO_TYPE_U2:
3070                         COMPARE_ENUM_VALUES (guint16);
3071                 case MONO_TYPE_I2:
3072                         COMPARE_ENUM_VALUES (gint16);
3073                 case MONO_TYPE_U4:
3074                         COMPARE_ENUM_VALUES (guint32);
3075                 case MONO_TYPE_I4:
3076                         COMPARE_ENUM_VALUES (gint32);
3077                 case MONO_TYPE_U8:
3078                         COMPARE_ENUM_VALUES (guint64);
3079                 case MONO_TYPE_I8:
3080                         COMPARE_ENUM_VALUES (gint64);
3081                 default:
3082                         break;
3083         }
3084 #undef COMPARE_ENUM_VALUES
3085         /* indicates that the enum was of an unsupported unerlying type */
3086         return 3;
3087 }
3088
3089 ICALL_EXPORT int
3090 ves_icall_System_Enum_get_hashcode (MonoObject *this)
3091 {
3092         gpointer data = (char *)this + sizeof (MonoObject);
3093         MonoType *basetype = mono_class_enum_basetype (this->vtable->klass);
3094         g_assert (basetype);
3095
3096         switch (basetype->type) {
3097                 case MONO_TYPE_I1:      
3098                         return *((gint8*)data);
3099                 case MONO_TYPE_U1:
3100                         return *((guint8*)data);
3101                 case MONO_TYPE_CHAR:
3102                 case MONO_TYPE_U2:
3103                         return *((guint16*)data);
3104                 
3105                 case MONO_TYPE_I2:
3106                         return *((gint16*)data);
3107                 case MONO_TYPE_U4:
3108                         return *((guint32*)data);
3109                 case MONO_TYPE_I4:
3110                         return *((gint32*)data);
3111                 case MONO_TYPE_U8:
3112                 case MONO_TYPE_I8: {
3113                         gint64 value = *((gint64*)data);
3114                         return (gint)(value & 0xffffffff) ^ (int)(value >> 32);
3115                 }
3116                 default:
3117                         g_error ("Implement type 0x%02x in get_hashcode", basetype->type);
3118         }
3119         return 0;
3120 }
3121
3122 ICALL_EXPORT MonoBoolean
3123 ves_icall_System_Enum_GetEnumValuesAndNames (MonoReflectionType *type, MonoArray **values, MonoArray **names)
3124 {
3125         MonoDomain *domain = mono_object_domain (type); 
3126         MonoClass *enumc = mono_class_from_mono_type (type->type);
3127         guint j = 0, nvalues;
3128         gpointer iter;
3129         MonoClassField *field;
3130         int base_type;
3131         guint64 field_value, previous_value = 0;
3132         gboolean sorted = TRUE;
3133
3134         mono_class_init_or_throw (enumc);
3135
3136         if (!enumc->enumtype) {
3137                 mono_set_pending_exception (mono_get_exception_argument ("enumType", "Type provided must be an Enum."));
3138                 return TRUE;
3139         }
3140
3141         base_type = mono_class_enum_basetype (enumc)->type;
3142
3143         nvalues = mono_class_num_fields (enumc) ? mono_class_num_fields (enumc) - 1 : 0;
3144         *names = mono_array_new (domain, mono_defaults.string_class, nvalues);
3145         *values = mono_array_new (domain, mono_defaults.uint64_class, nvalues);
3146
3147         iter = NULL;
3148         while ((field = mono_class_get_fields (enumc, &iter))) {
3149                 const char *p;
3150                 MonoTypeEnum def_type;
3151
3152                 if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3153                         continue;
3154                 if (strcmp ("value__", mono_field_get_name (field)) == 0)
3155                         continue;
3156                 if (mono_field_is_deleted (field))
3157                         continue;
3158                 mono_array_setref (*names, j, mono_string_new (domain, mono_field_get_name (field)));
3159
3160                 p = mono_class_get_field_default_value (field, &def_type);
3161                 /* len = */ mono_metadata_decode_blob_size (p, &p);
3162
3163                 field_value = read_enum_value (p, base_type);
3164                 mono_array_set (*values, guint64, j, field_value);
3165
3166                 if (previous_value > field_value)
3167                         sorted = FALSE;
3168
3169                 previous_value = field_value;
3170                 ++j;
3171         }
3172
3173         return sorted;
3174 }
3175
3176 enum {
3177         BFLAGS_IgnoreCase = 1,
3178         BFLAGS_DeclaredOnly = 2,
3179         BFLAGS_Instance = 4,
3180         BFLAGS_Static = 8,
3181         BFLAGS_Public = 0x10,
3182         BFLAGS_NonPublic = 0x20,
3183         BFLAGS_FlattenHierarchy = 0x40,
3184         BFLAGS_InvokeMethod = 0x100,
3185         BFLAGS_CreateInstance = 0x200,
3186         BFLAGS_GetField = 0x400,
3187         BFLAGS_SetField = 0x800,
3188         BFLAGS_GetProperty = 0x1000,
3189         BFLAGS_SetProperty = 0x2000,
3190         BFLAGS_ExactBinding = 0x10000,
3191         BFLAGS_SuppressChangeType = 0x20000,
3192         BFLAGS_OptionalParamBinding = 0x40000
3193 };
3194
3195 ICALL_EXPORT MonoArray*
3196 ves_icall_Type_GetFields_internal (MonoReflectionType *type, MonoString *name, guint32 bflags, MonoReflectionType *reftype)
3197 {
3198         MonoDomain *domain; 
3199         MonoClass *startklass, *klass, *refklass;
3200         MonoArray *res;
3201         MonoObject *member;
3202         int i, match;
3203         gpointer iter;
3204         char *utf8_name = NULL;
3205         int (*compare_func) (const char *s1, const char *s2) = NULL;    
3206         MonoClassField *field;
3207         MonoPtrArray tmp_array;
3208
3209         domain = ((MonoObject *)type)->vtable->domain;
3210         if (type->type->byref)
3211                 return mono_array_new (domain, mono_defaults.field_info_class, 0);
3212
3213         klass = startklass = mono_class_from_mono_type (type->type);
3214         refklass = mono_class_from_mono_type (reftype->type);
3215
3216         mono_ptr_array_init (tmp_array, 2);
3217         
3218 handle_parent:  
3219         if (klass->exception_type != MONO_EXCEPTION_NONE) {
3220                 mono_ptr_array_destroy (tmp_array);
3221                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
3222                 return NULL;
3223         }
3224
3225         iter = NULL;
3226         while ((field = mono_class_get_fields_lazy (klass, &iter))) {
3227                 guint32 flags = mono_field_get_flags (field);
3228                 match = 0;
3229                 if (mono_field_is_deleted_with_flags (field, flags))
3230                         continue;
3231                 if ((flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) == FIELD_ATTRIBUTE_PUBLIC) {
3232                         if (bflags & BFLAGS_Public)
3233                                 match++;
3234                 } else if ((klass == startklass) || (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) != FIELD_ATTRIBUTE_PRIVATE) {
3235                         if (bflags & BFLAGS_NonPublic) {
3236                                 match++;
3237                         }
3238                 }
3239                 if (!match)
3240                         continue;
3241                 match = 0;
3242                 if (flags & FIELD_ATTRIBUTE_STATIC) {
3243                         if (bflags & BFLAGS_Static)
3244                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3245                                         match++;
3246                 } else {
3247                         if (bflags & BFLAGS_Instance)
3248                                 match++;
3249                 }
3250
3251                 if (!match)
3252                         continue;
3253
3254                 if (name != NULL) {
3255                         if (utf8_name == NULL) {
3256                                 utf8_name = mono_string_to_utf8 (name);
3257                                 compare_func = (bflags & BFLAGS_IgnoreCase) ? mono_utf8_strcasecmp : strcmp;
3258                         }
3259
3260                         if (compare_func (mono_field_get_name (field), utf8_name))
3261                                 continue;
3262                 }
3263
3264                 member = (MonoObject*)mono_field_get_object (domain, refklass, field);
3265                 mono_ptr_array_append (tmp_array, member);
3266         }
3267         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3268                 goto handle_parent;
3269
3270         res = mono_array_new_cached (domain, mono_defaults.field_info_class, mono_ptr_array_size (tmp_array));
3271
3272         for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3273                 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3274
3275         mono_ptr_array_destroy (tmp_array);
3276
3277         if (utf8_name != NULL)
3278                 g_free (utf8_name);
3279
3280         return res;
3281 }
3282
3283 static gboolean
3284 method_nonpublic (MonoMethod* method, gboolean start_klass)
3285 {
3286         switch (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) {
3287                 case METHOD_ATTRIBUTE_ASSEM:
3288                         return (start_klass || mono_defaults.generic_ilist_class);
3289                 case METHOD_ATTRIBUTE_PRIVATE:
3290                         return start_klass;
3291                 case METHOD_ATTRIBUTE_PUBLIC:
3292                         return FALSE;
3293                 default:
3294                         return TRUE;
3295         }
3296 }
3297
3298 GPtrArray*
3299 mono_class_get_methods_by_name (MonoClass *klass, const char *name, guint32 bflags, gboolean ignore_case, gboolean allow_ctors, MonoException **ex)
3300 {
3301         GPtrArray *array;
3302         MonoClass *startklass;
3303         MonoMethod *method;
3304         gpointer iter;
3305         int match, nslots;
3306         /*FIXME, use MonoBitSet*/
3307         guint32 method_slots_default [8];
3308         guint32 *method_slots = NULL;
3309         int (*compare_func) (const char *s1, const char *s2) = NULL;
3310
3311         array = g_ptr_array_new ();
3312         startklass = klass;
3313         *ex = NULL;
3314
3315         if (name != NULL)
3316                 compare_func = (ignore_case) ? mono_utf8_strcasecmp : strcmp;
3317
3318         /* An optimization for calls made from Delegate:CreateDelegate () */
3319         if (klass->delegate && name && !strcmp (name, "Invoke") && (bflags == (BFLAGS_Public | BFLAGS_Static | BFLAGS_Instance))) {
3320                 method = mono_get_delegate_invoke (klass);
3321                 if (mono_loader_get_last_error ())
3322                         goto loader_error;
3323
3324                 g_ptr_array_add (array, method);
3325                 return array;
3326         }
3327
3328         mono_class_setup_methods (klass);
3329         mono_class_setup_vtable (klass);
3330         if (klass->exception_type != MONO_EXCEPTION_NONE || mono_loader_get_last_error ())
3331                 goto loader_error;
3332
3333         if (is_generic_parameter (&klass->byval_arg))
3334                 nslots = mono_class_get_vtable_size (klass->parent);
3335         else
3336                 nslots = MONO_CLASS_IS_INTERFACE (klass) ? mono_class_num_methods (klass) : mono_class_get_vtable_size (klass);
3337         if (nslots >= sizeof (method_slots_default) * 8) {
3338                 method_slots = g_new0 (guint32, nslots / 32 + 1);
3339         } else {
3340                 method_slots = method_slots_default;
3341                 memset (method_slots, 0, sizeof (method_slots_default));
3342         }
3343 handle_parent:
3344         mono_class_setup_methods (klass);
3345         mono_class_setup_vtable (klass);
3346         if (klass->exception_type != MONO_EXCEPTION_NONE || mono_loader_get_last_error ())
3347                 goto loader_error;              
3348
3349         iter = NULL;
3350         while ((method = mono_class_get_methods (klass, &iter))) {
3351                 match = 0;
3352                 if (method->slot != -1) {
3353                         g_assert (method->slot < nslots);
3354                         if (method_slots [method->slot >> 5] & (1 << (method->slot & 0x1f)))
3355                                 continue;
3356                         if (!(method->flags & METHOD_ATTRIBUTE_NEW_SLOT))
3357                                 method_slots [method->slot >> 5] |= 1 << (method->slot & 0x1f);
3358                 }
3359
3360                 if (!allow_ctors && method->name [0] == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0))
3361                         continue;
3362                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3363                         if (bflags & BFLAGS_Public)
3364                                 match++;
3365                 } else if ((bflags & BFLAGS_NonPublic) && method_nonpublic (method, (klass == startklass))) {
3366                                 match++;
3367                 }
3368                 if (!match)
3369                         continue;
3370                 match = 0;
3371                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3372                         if (bflags & BFLAGS_Static)
3373                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3374                                         match++;
3375                 } else {
3376                         if (bflags & BFLAGS_Instance)
3377                                 match++;
3378                 }
3379
3380                 if (!match)
3381                         continue;
3382
3383                 if (name != NULL) {
3384                         if (compare_func (name, method->name))
3385                                 continue;
3386                 }
3387                 
3388                 match = 0;
3389                 g_ptr_array_add (array, method);
3390         }
3391         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3392                 goto handle_parent;
3393         if (method_slots != method_slots_default)
3394                 g_free (method_slots);
3395
3396         return array;
3397
3398 loader_error:
3399         if (method_slots != method_slots_default)
3400                 g_free (method_slots);
3401         g_ptr_array_free (array, TRUE);
3402
3403         if (klass->exception_type != MONO_EXCEPTION_NONE) {
3404                 *ex = mono_class_get_exception_for_failure (klass);
3405         } else {
3406                 *ex = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
3407                 mono_loader_clear_error ();
3408         }
3409         return NULL;
3410 }
3411
3412 ICALL_EXPORT MonoArray*
3413 ves_icall_Type_GetMethodsByName (MonoReflectionType *type, MonoString *name, guint32 bflags, MonoBoolean ignore_case, MonoReflectionType *reftype)
3414 {
3415         static MonoClass *MethodInfo_array;
3416         MonoDomain *domain; 
3417         MonoArray *res;
3418         MonoVTable *array_vtable;
3419         MonoException *ex = NULL;
3420         const char *mname = NULL;
3421         GPtrArray *method_array;
3422         MonoClass *klass, *refklass;
3423         int i;
3424
3425         if (!MethodInfo_array) {
3426                 MonoClass *klass = mono_array_class_get (mono_defaults.method_info_class, 1);
3427                 mono_memory_barrier ();
3428                 MethodInfo_array = klass;
3429         }
3430
3431         klass = mono_class_from_mono_type (type->type);
3432         refklass = mono_class_from_mono_type (reftype->type);
3433         domain = ((MonoObject *)type)->vtable->domain;
3434         array_vtable = mono_class_vtable_full (domain, MethodInfo_array, TRUE);
3435         if (type->type->byref)
3436                 return mono_array_new_specific (array_vtable, 0);
3437
3438         if (name)
3439                 mname = mono_string_to_utf8 (name);
3440
3441         method_array = mono_class_get_methods_by_name (klass, mname, bflags, ignore_case, FALSE, &ex);
3442         g_free ((char*)mname);
3443         if (ex) {
3444                 mono_set_pending_exception (ex);
3445                 return NULL;
3446         }
3447
3448         res = mono_array_new_specific (array_vtable, method_array->len);
3449
3450         for (i = 0; i < method_array->len; ++i) {
3451                 MonoMethod *method = g_ptr_array_index (method_array, i);
3452                 mono_array_setref (res, i, mono_method_get_object (domain, method, refklass));
3453         }
3454
3455         g_ptr_array_free (method_array, TRUE);
3456         return res;
3457 }
3458
3459 ICALL_EXPORT MonoArray*
3460 ves_icall_Type_GetConstructors_internal (MonoReflectionType *type, guint32 bflags, MonoReflectionType *reftype)
3461 {
3462         MonoDomain *domain; 
3463         static MonoClass *System_Reflection_ConstructorInfo;
3464         MonoClass *startklass, *klass, *refklass;
3465         MonoArray *res;
3466         MonoMethod *method;
3467         MonoObject *member;
3468         int i, match;
3469         gpointer iter = NULL;
3470         MonoPtrArray tmp_array;
3471         
3472         mono_ptr_array_init (tmp_array, 4); /*FIXME, guestimating*/
3473
3474         domain = ((MonoObject *)type)->vtable->domain;
3475         if (type->type->byref)
3476                 return mono_array_new_cached (domain, mono_defaults.method_info_class, 0);
3477         klass = startklass = mono_class_from_mono_type (type->type);
3478         refklass = mono_class_from_mono_type (reftype->type);
3479
3480         if (!System_Reflection_ConstructorInfo)
3481                 System_Reflection_ConstructorInfo = mono_class_from_name (
3482                         mono_defaults.corlib, "System.Reflection", "ConstructorInfo");
3483
3484         mono_class_setup_methods (klass);
3485         if (klass->exception_type != MONO_EXCEPTION_NONE) {
3486                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
3487                 return NULL;
3488         }
3489
3490         iter = NULL;
3491         while ((method = mono_class_get_methods (klass, &iter))) {
3492                 match = 0;
3493                 if (strcmp (method->name, ".ctor") && strcmp (method->name, ".cctor"))
3494                         continue;
3495                 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3496                         if (bflags & BFLAGS_Public)
3497                                 match++;
3498                 } else {
3499                         if (bflags & BFLAGS_NonPublic)
3500                                 match++;
3501                 }
3502                 if (!match)
3503                         continue;
3504                 match = 0;
3505                 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3506                         if (bflags & BFLAGS_Static)
3507                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3508                                         match++;
3509                 } else {
3510                         if (bflags & BFLAGS_Instance)
3511                                 match++;
3512                 }
3513
3514                 if (!match)
3515                         continue;
3516                 member = (MonoObject*)mono_method_get_object (domain, method, refklass);
3517
3518                 mono_ptr_array_append (tmp_array, member);
3519         }
3520
3521         res = mono_array_new_cached (domain, System_Reflection_ConstructorInfo, mono_ptr_array_size (tmp_array));
3522
3523         for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3524                 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3525
3526         mono_ptr_array_destroy (tmp_array);
3527
3528         return res;
3529 }
3530
3531 static guint
3532 property_hash (gconstpointer data)
3533 {
3534         MonoProperty *prop = (MonoProperty*)data;
3535
3536         return g_str_hash (prop->name);
3537 }
3538
3539 static gboolean
3540 property_equal (MonoProperty *prop1, MonoProperty *prop2)
3541 {
3542         // Properties are hide-by-name-and-signature
3543         if (!g_str_equal (prop1->name, prop2->name))
3544                 return FALSE;
3545
3546         if (prop1->get && prop2->get && !mono_metadata_signature_equal (mono_method_signature (prop1->get), mono_method_signature (prop2->get)))
3547                 return FALSE;
3548         if (prop1->set && prop2->set && !mono_metadata_signature_equal (mono_method_signature (prop1->set), mono_method_signature (prop2->set)))
3549                 return FALSE;
3550         return TRUE;
3551 }
3552
3553 static gboolean
3554 property_accessor_nonpublic (MonoMethod* accessor, gboolean start_klass)
3555 {
3556         if (!accessor)
3557                 return FALSE;
3558
3559         return method_nonpublic (accessor, start_klass);
3560 }
3561
3562 ICALL_EXPORT MonoArray*
3563 ves_icall_Type_GetPropertiesByName (MonoReflectionType *type, MonoString *name, guint32 bflags, MonoBoolean ignore_case, MonoReflectionType *reftype)
3564 {
3565         MonoException *ex;
3566         MonoDomain *domain; 
3567         static MonoClass *System_Reflection_PropertyInfo;
3568         MonoClass *startklass, *klass;
3569         MonoArray *res;
3570         MonoMethod *method;
3571         MonoProperty *prop;
3572         int i, match;
3573         guint32 flags;
3574         gchar *propname = NULL;
3575         int (*compare_func) (const char *s1, const char *s2) = NULL;
3576         gpointer iter;
3577         GHashTable *properties = NULL;
3578         MonoPtrArray tmp_array;
3579
3580         mono_ptr_array_init (tmp_array, 8); /*This the average for ASP.NET types*/
3581
3582         if (!System_Reflection_PropertyInfo)
3583                 System_Reflection_PropertyInfo = mono_class_from_name (
3584                         mono_defaults.corlib, "System.Reflection", "PropertyInfo");
3585
3586         domain = ((MonoObject *)type)->vtable->domain;
3587         if (type->type->byref)
3588                 return mono_array_new_cached (domain, System_Reflection_PropertyInfo, 0);
3589         klass = startklass = mono_class_from_mono_type (type->type);
3590
3591         if (name != NULL) {
3592                 propname = mono_string_to_utf8 (name);
3593                 compare_func = (ignore_case) ? mono_utf8_strcasecmp : strcmp;
3594         }
3595
3596         properties = g_hash_table_new (property_hash, (GEqualFunc)property_equal);
3597 handle_parent:
3598         mono_class_setup_methods (klass);
3599         mono_class_setup_vtable (klass);
3600         if (klass->exception_type != MONO_EXCEPTION_NONE || mono_loader_get_last_error ())
3601                 goto loader_error;
3602
3603         iter = NULL;
3604         while ((prop = mono_class_get_properties (klass, &iter))) {
3605                 match = 0;
3606                 method = prop->get;
3607                 if (!method)
3608                         method = prop->set;
3609                 if (method)
3610                         flags = method->flags;
3611                 else
3612                         flags = 0;
3613                 if ((prop->get && ((prop->get->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)) ||
3614                         (prop->set && ((prop->set->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC))) {
3615                         if (bflags & BFLAGS_Public)
3616                                 match++;
3617                 } else if (bflags & BFLAGS_NonPublic) {
3618                         if (property_accessor_nonpublic(prop->get, startklass == klass) ||
3619                                 property_accessor_nonpublic(prop->set, startklass == klass)) {
3620                                 match++;
3621                         }
3622                 }
3623                 if (!match)
3624                         continue;
3625                 match = 0;
3626                 if (flags & METHOD_ATTRIBUTE_STATIC) {
3627                         if (bflags & BFLAGS_Static)
3628                                 if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3629                                         match++;
3630                 } else {
3631                         if (bflags & BFLAGS_Instance)
3632                                 match++;
3633                 }
3634
3635                 if (!match)
3636                         continue;
3637                 match = 0;
3638
3639                 if (name != NULL) {
3640                         if (compare_func (propname, prop->name))
3641                                 continue;
3642                 }
3643                 
3644                 if (g_hash_table_lookup (properties, prop))
3645                         continue;
3646
3647                 mono_ptr_array_append (tmp_array, mono_property_get_object (domain, startklass, prop));
3648                 
3649                 g_hash_table_insert (properties, prop, prop);
3650         }
3651         if ((!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent)))
3652                 goto handle_parent;
3653
3654         g_hash_table_destroy (properties);
3655         g_free (propname);
3656
3657         res = mono_array_new_cached (domain, System_Reflection_PropertyInfo, mono_ptr_array_size (tmp_array));
3658         for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3659                 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3660
3661         mono_ptr_array_destroy (tmp_array);
3662
3663         return res;
3664
3665 loader_error:
3666         if (properties)
3667                 g_hash_table_destroy (properties);
3668         if (name)
3669                 g_free (propname);
3670         mono_ptr_array_destroy (tmp_array);
3671
3672         if (klass->exception_type != MONO_EXCEPTION_NONE) {
3673                 ex = mono_class_get_exception_for_failure (klass);
3674         } else {
3675                 ex = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
3676                 mono_loader_clear_error ();
3677         }
3678         mono_set_pending_exception (ex);
3679         return NULL;
3680 }
3681
3682 static guint
3683 event_hash (gconstpointer data)
3684 {
3685         MonoEvent *event = (MonoEvent*)data;
3686
3687         return g_str_hash (event->name);
3688 }
3689
3690 static gboolean
3691 event_equal (MonoEvent *event1, MonoEvent *event2)
3692 {
3693         // Events are hide-by-name
3694         return g_str_equal (event1->name, event2->name);
3695 }
3696
3697 ICALL_EXPORT MonoArray*
3698 ves_icall_Type_GetEvents_internal (MonoReflectionType *type, MonoString *name, guint32 bflags, MonoReflectionType *reftype)
3699 {
3700         MonoException *ex;
3701         MonoDomain *domain; 
3702         static MonoClass *System_Reflection_EventInfo;
3703         MonoClass *startklass, *klass;
3704         MonoArray *res;
3705         MonoMethod *method;
3706         MonoEvent *event;
3707         int i, match;
3708         gpointer iter;
3709         char *utf8_name = NULL;
3710         int (*compare_func) (const char *s1, const char *s2) = NULL;    
3711         GHashTable *events = NULL;
3712         MonoPtrArray tmp_array;
3713
3714         mono_ptr_array_init (tmp_array, 4);
3715
3716         if (!System_Reflection_EventInfo)
3717                 System_Reflection_EventInfo = mono_class_from_name (
3718                         mono_defaults.corlib, "System.Reflection", "EventInfo");
3719
3720         domain = mono_object_domain (type);
3721         if (type->type->byref)
3722                 return mono_array_new_cached (domain, System_Reflection_EventInfo, 0);
3723         klass = startklass = mono_class_from_mono_type (type->type);
3724
3725         events = g_hash_table_new (event_hash, (GEqualFunc)event_equal);
3726 handle_parent:
3727         mono_class_setup_methods (klass);
3728         mono_class_setup_vtable (klass);
3729         if (klass->exception_type != MONO_EXCEPTION_NONE || mono_loader_get_last_error ())
3730                 goto loader_error;
3731
3732         iter = NULL;
3733         while ((event = mono_class_get_events (klass, &iter))) {
3734                 match = 0;
3735                 method = event->add;
3736                 if (!method)
3737                         method = event->remove;
3738                 if (!method)
3739                         method = event->raise;
3740                 if (method) {
3741                         if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) {
3742                                 if (bflags & BFLAGS_Public)
3743                                         match++;
3744                         } else if ((klass == startklass) || (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE) {
3745                                 if (bflags & BFLAGS_NonPublic)
3746                                         match++;
3747                         }
3748                 }
3749                 else
3750                         if (bflags & BFLAGS_NonPublic)
3751                                 match ++;
3752                 if (!match)
3753                         continue;
3754                 match = 0;
3755                 if (method) {
3756                         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
3757                                 if (bflags & BFLAGS_Static)
3758                                         if ((bflags & BFLAGS_FlattenHierarchy) || (klass == startklass))
3759                                                 match++;
3760                         } else {
3761                                 if (bflags & BFLAGS_Instance)
3762                                         match++;
3763                         }
3764                 }
3765                 else
3766                         if (bflags & BFLAGS_Instance)
3767                                 match ++;
3768                 if (!match)
3769                         continue;
3770
3771                 if (name != NULL) {
3772                         if (utf8_name == NULL) {
3773                                 utf8_name = mono_string_to_utf8 (name);
3774                                 compare_func = (bflags & BFLAGS_IgnoreCase) ? mono_utf8_strcasecmp : strcmp;
3775                         }
3776
3777                         if (compare_func (event->name, utf8_name))
3778                                 continue;
3779                 }               
3780
3781                 if (g_hash_table_lookup (events, event))
3782                         continue;
3783
3784                 mono_ptr_array_append (tmp_array, mono_event_get_object (domain, startklass, event));
3785
3786                 g_hash_table_insert (events, event, event);
3787         }
3788         if (!(bflags & BFLAGS_DeclaredOnly) && (klass = klass->parent))
3789                 goto handle_parent;
3790
3791         g_hash_table_destroy (events);
3792
3793         res = mono_array_new_cached (domain, System_Reflection_EventInfo, mono_ptr_array_size (tmp_array));
3794
3795         for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3796                 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3797
3798         mono_ptr_array_destroy (tmp_array);
3799
3800         if (utf8_name != NULL)
3801                 g_free (utf8_name);
3802
3803         return res;
3804
3805 loader_error:
3806         mono_ptr_array_destroy (tmp_array);
3807         if (klass->exception_type != MONO_EXCEPTION_NONE) {
3808                 ex = mono_class_get_exception_for_failure (klass);
3809         } else {
3810                 ex = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
3811                 mono_loader_clear_error ();
3812         }
3813         mono_set_pending_exception (ex);
3814         return NULL;
3815 }
3816
3817 ICALL_EXPORT MonoArray*
3818 ves_icall_Type_GetNestedTypes (MonoReflectionType *type, MonoString *name, guint32 bflags)
3819 {
3820         MonoDomain *domain; 
3821         MonoClass *klass;
3822         MonoArray *res;
3823         MonoObject *member;
3824         int i, match;
3825         MonoClass *nested;
3826         gpointer iter;
3827         char *str = NULL;
3828         MonoPtrArray tmp_array;
3829
3830         domain = ((MonoObject *)type)->vtable->domain;
3831         if (type->type->byref)
3832                 return mono_array_new (domain, mono_defaults.monotype_class, 0);
3833         klass = mono_class_from_mono_type (type->type);
3834
3835         /*
3836          * If a nested type is generic, return its generic type definition.
3837          * Note that this means that the return value is essentially the set
3838          * of nested types of the generic type definition of @klass.
3839          *
3840          * A note in MSDN claims that a generic type definition can have
3841          * nested types that aren't generic.  In any case, the container of that
3842          * nested type would be the generic type definition.
3843          */
3844         if (klass->generic_class)
3845                 klass = klass->generic_class->container_class;
3846
3847         mono_ptr_array_init (tmp_array, 1);
3848         iter = NULL;
3849         while ((nested = mono_class_get_nested_types (klass, &iter))) {
3850                 match = 0;
3851                 if ((nested->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK) == TYPE_ATTRIBUTE_NESTED_PUBLIC) {
3852                         if (bflags & BFLAGS_Public)
3853                                 match++;
3854                 } else {
3855                         if (bflags & BFLAGS_NonPublic)
3856                                 match++;
3857                 }
3858                 if (!match)
3859                         continue;
3860
3861                 if (name != NULL) {
3862                         if (str == NULL)
3863                                 str = mono_string_to_utf8 (name);
3864
3865                         if (strcmp (nested->name, str))
3866                                 continue;
3867                 }
3868
3869                 member = (MonoObject*)mono_type_get_object (domain, &nested->byval_arg);
3870                 mono_ptr_array_append (tmp_array, member);
3871         }
3872
3873         res = mono_array_new_cached (domain, mono_defaults.monotype_class, mono_ptr_array_size (tmp_array));
3874
3875         for (i = 0; i < mono_ptr_array_size (tmp_array); ++i)
3876                 mono_array_setref (res, i, mono_ptr_array_get (tmp_array, i));
3877
3878         mono_ptr_array_destroy (tmp_array);
3879
3880         if (!str)
3881                 g_free (str);
3882
3883         return res;
3884 }
3885
3886 ICALL_EXPORT MonoReflectionType*
3887 ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssembly *assembly, MonoReflectionModule *module, MonoString *name, MonoBoolean throwOnError, MonoBoolean ignoreCase)
3888 {
3889         gchar *str;
3890         MonoType *type = NULL;
3891         MonoTypeNameParse info;
3892         gboolean type_resolve;
3893
3894         /* On MS.NET, this does not fire a TypeResolve event */
3895         type_resolve = TRUE;
3896         str = mono_string_to_utf8 (name);
3897         /*g_print ("requested type %s in %s\n", str, assembly->assembly->aname.name);*/
3898         if (!mono_reflection_parse_type (str, &info)) {
3899                 g_free (str);
3900                 mono_reflection_free_type_info (&info);
3901                 if (throwOnError) {
3902                         /* uhm: this is a parse error, though... */
3903                         mono_set_pending_exception (mono_get_exception_type_load (name, NULL));
3904                         return NULL;
3905                 }
3906                 /*g_print ("failed parse\n");*/
3907                 return NULL;
3908         }
3909
3910         if (info.assembly.name) {
3911                 g_free (str);
3912                 mono_reflection_free_type_info (&info);
3913                 if (throwOnError) {
3914                         /* 1.0 and 2.0 throw different exceptions */
3915                         if (mono_defaults.generic_ilist_class)
3916                                 mono_set_pending_exception (mono_get_exception_argument (NULL, "Type names passed to Assembly.GetType() must not specify an assembly."));
3917                         else
3918                                 mono_set_pending_exception (mono_get_exception_type_load (name, NULL));
3919                         return NULL;
3920                 }
3921                 return NULL;
3922         }
3923
3924         if (module != NULL) {
3925                 if (module->image)
3926                         type = mono_reflection_get_type (module->image, &info, ignoreCase, &type_resolve);
3927                 else
3928                         type = NULL;
3929         }
3930         else
3931                 if (assembly_is_dynamic (assembly->assembly)) {
3932                         /* Enumerate all modules */
3933                         MonoReflectionAssemblyBuilder *abuilder = (MonoReflectionAssemblyBuilder*)assembly;
3934                         int i;
3935
3936                         type = NULL;
3937                         if (abuilder->modules) {
3938                                 for (i = 0; i < mono_array_length (abuilder->modules); ++i) {
3939                                         MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
3940                                         type = mono_reflection_get_type (&mb->dynamic_image->image, &info, ignoreCase, &type_resolve);
3941                                         if (type)
3942                                                 break;
3943                                 }
3944                         }
3945
3946                         if (!type && abuilder->loaded_modules) {
3947                                 for (i = 0; i < mono_array_length (abuilder->loaded_modules); ++i) {
3948                                         MonoReflectionModule *mod = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
3949                                         type = mono_reflection_get_type (mod->image, &info, ignoreCase, &type_resolve);
3950                                         if (type)
3951                                                 break;
3952                                 }
3953                         }
3954                 }
3955                 else
3956                         type = mono_reflection_get_type (assembly->assembly->image, &info, ignoreCase, &type_resolve);
3957         g_free (str);
3958         mono_reflection_free_type_info (&info);
3959         if (!type) {
3960                 MonoException *e = NULL;
3961                 
3962                 if (throwOnError)
3963                         e = mono_get_exception_type_load (name, NULL);
3964
3965                 if (mono_loader_get_last_error () && mono_defaults.generic_ilist_class)
3966                         e = mono_loader_error_prepare_exception (mono_loader_get_last_error ());
3967
3968                 mono_loader_clear_error ();
3969
3970                 if (e != NULL)
3971                         mono_set_pending_exception (e);
3972                 return NULL;
3973         } else if (mono_loader_get_last_error ()) {
3974                 if (throwOnError) {
3975                         mono_set_pending_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
3976                         return NULL;
3977                 }
3978                 mono_loader_clear_error ();
3979         }
3980
3981         if (type->type == MONO_TYPE_CLASS) {
3982                 MonoClass *klass = mono_type_get_class (type);
3983
3984                 if (mono_security_enabled () && !klass->exception_type)
3985                         /* Some security problems are detected during generic vtable construction */
3986                         mono_class_setup_vtable (klass);
3987
3988                 /* need to report exceptions ? */
3989                 if (throwOnError && klass->exception_type) {
3990                         /* report SecurityException (or others) that occured when loading the assembly */
3991                         MonoException *exc = mono_class_get_exception_for_failure (klass);
3992                         mono_loader_clear_error ();
3993                         mono_set_pending_exception (exc);
3994                         return NULL;
3995                 } else if (mono_security_enabled () && klass->exception_type == MONO_EXCEPTION_SECURITY_INHERITANCEDEMAND) {
3996                         return NULL;
3997                 }
3998         }
3999
4000         /* g_print ("got it\n"); */
4001         return mono_type_get_object (mono_object_domain (assembly), type);
4002 }
4003
4004 static gboolean
4005 replace_shadow_path (MonoDomain *domain, gchar *dirname, gchar **filename)
4006 {
4007         gchar *content;
4008         gchar *shadow_ini_file;
4009         gsize len;
4010
4011         /* Check for shadow-copied assembly */
4012         if (mono_is_shadow_copy_enabled (domain, dirname)) {
4013                 shadow_ini_file = g_build_filename (dirname, "__AssemblyInfo__.ini", NULL);
4014                 content = NULL;
4015                 if (!g_file_get_contents (shadow_ini_file, &content, &len, NULL) ||
4016                         !g_file_test (content, G_FILE_TEST_IS_REGULAR)) {
4017                         if (content) {
4018                                 g_free (content);
4019                                 content = NULL;
4020                         }
4021                 }
4022                 g_free (shadow_ini_file);
4023                 if (content != NULL) {
4024                         if (*filename)
4025                                 g_free (*filename);
4026                         *filename = content;
4027                         return TRUE;
4028                 }
4029         }
4030         return FALSE;
4031 }
4032
4033 ICALL_EXPORT MonoString *
4034 ves_icall_System_Reflection_Assembly_get_code_base (MonoReflectionAssembly *assembly, MonoBoolean escaped)
4035 {
4036         MonoDomain *domain = mono_object_domain (assembly); 
4037         MonoAssembly *mass = assembly->assembly;
4038         MonoString *res = NULL;
4039         gchar *uri;
4040         gchar *absolute;
4041         gchar *dirname;
4042         
4043         if (g_path_is_absolute (mass->image->name)) {
4044                 absolute = g_strdup (mass->image->name);
4045                 dirname = g_path_get_dirname (absolute);
4046         } else {
4047                 absolute = g_build_filename (mass->basedir, mass->image->name, NULL);
4048                 dirname = g_strdup (mass->basedir);
4049         }
4050
4051         replace_shadow_path (domain, dirname, &absolute);
4052         g_free (dirname);
4053 #if HOST_WIN32
4054         {
4055                 gint i;
4056                 for (i = strlen (absolute) - 1; i >= 0; i--)
4057                         if (absolute [i] == '\\')
4058                                 absolute [i] = '/';
4059         }
4060 #endif
4061         if (escaped) {
4062                 uri = g_filename_to_uri (absolute, NULL, NULL);
4063         } else {
4064                 const char *prepend = "file://";
4065 #if HOST_WIN32
4066                 if (*absolute == '/' && *(absolute + 1) == '/') {
4067                         prepend = "file:";
4068                 } else {
4069                         prepend = "file:///";
4070                 }
4071 #endif
4072                 uri = g_strconcat (prepend, absolute, NULL);
4073         }
4074
4075         if (uri) {
4076                 res = mono_string_new (domain, uri);
4077                 g_free (uri);
4078         }
4079         g_free (absolute);
4080         return res;
4081 }
4082
4083 ICALL_EXPORT MonoBoolean
4084 ves_icall_System_Reflection_Assembly_get_global_assembly_cache (MonoReflectionAssembly *assembly)
4085 {
4086         MonoAssembly *mass = assembly->assembly;
4087
4088         return mass->in_gac;
4089 }
4090
4091 ICALL_EXPORT MonoReflectionAssembly*
4092 ves_icall_System_Reflection_Assembly_load_with_partial_name (MonoString *mname, MonoObject *evidence)
4093 {
4094         gchar *name;
4095         MonoAssembly *res;
4096         MonoImageOpenStatus status;
4097         
4098         name = mono_string_to_utf8 (mname);
4099         res = mono_assembly_load_with_partial_name (name, &status);
4100
4101         g_free (name);
4102
4103         if (res == NULL)
4104                 return NULL;
4105         return mono_assembly_get_object (mono_domain_get (), res);
4106 }
4107
4108 ICALL_EXPORT MonoString *
4109 ves_icall_System_Reflection_Assembly_get_location (MonoReflectionAssembly *assembly)
4110 {
4111         MonoDomain *domain = mono_object_domain (assembly); 
4112         MonoString *res;
4113
4114         res = mono_string_new (domain, mono_image_get_filename (assembly->assembly->image));
4115
4116         return res;
4117 }
4118
4119 ICALL_EXPORT MonoBoolean
4120 ves_icall_System_Reflection_Assembly_get_ReflectionOnly (MonoReflectionAssembly *assembly)
4121 {
4122         return assembly->assembly->ref_only;
4123 }
4124
4125 ICALL_EXPORT MonoString *
4126 ves_icall_System_Reflection_Assembly_InternalImageRuntimeVersion (MonoReflectionAssembly *assembly)
4127 {
4128         MonoDomain *domain = mono_object_domain (assembly); 
4129
4130         return mono_string_new (domain, assembly->assembly->image->version);
4131 }
4132
4133 ICALL_EXPORT MonoReflectionMethod*
4134 ves_icall_System_Reflection_Assembly_get_EntryPoint (MonoReflectionAssembly *assembly) 
4135 {
4136         MonoError error;
4137         MonoMethod *method;
4138         guint32 token = mono_image_get_entry_point (assembly->assembly->image);
4139
4140         if (!token)
4141                 return NULL;
4142         method = mono_get_method_checked (assembly->assembly->image, token, NULL, NULL, &error);
4143         mono_error_raise_exception (&error);
4144
4145         return mono_method_get_object (mono_object_domain (assembly), method, NULL);
4146 }
4147
4148 ICALL_EXPORT MonoReflectionModule*
4149 ves_icall_System_Reflection_Assembly_GetManifestModuleInternal (MonoReflectionAssembly *assembly) 
4150 {
4151         return mono_module_get_object (mono_object_domain (assembly), assembly->assembly->image);
4152 }
4153
4154 ICALL_EXPORT MonoArray*
4155 ves_icall_System_Reflection_Assembly_GetManifestResourceNames (MonoReflectionAssembly *assembly) 
4156 {
4157         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4158         MonoArray *result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, table->rows);
4159         int i;
4160         const char *val;
4161
4162         for (i = 0; i < table->rows; ++i) {
4163                 val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_MANIFEST_NAME));
4164                 mono_array_setref (result, i, mono_string_new (mono_object_domain (assembly), val));
4165         }
4166         return result;
4167 }
4168
4169 static MonoObject*
4170 create_version (MonoDomain *domain, guint32 major, guint32 minor, guint32 build, guint32 revision)
4171 {
4172         static MonoClass *System_Version = NULL;
4173         static MonoMethod *create_version = NULL;
4174         MonoObject *result;
4175         gpointer args [4];
4176         
4177         if (!System_Version) {
4178                 System_Version = mono_class_from_name (mono_defaults.corlib, "System", "Version");
4179                 g_assert (System_Version);
4180         }
4181
4182         if (!create_version) {
4183                 MonoMethodDesc *desc = mono_method_desc_new (":.ctor(int,int,int,int)", FALSE);
4184                 create_version = mono_method_desc_search_in_class (desc, System_Version);
4185                 g_assert (create_version);
4186                 mono_method_desc_free (desc);
4187         }
4188
4189         args [0] = &major;
4190         args [1] = &minor;
4191         args [2] = &build;
4192         args [3] = &revision;
4193         result = mono_object_new (domain, System_Version);
4194         mono_runtime_invoke (create_version, result, args, NULL);
4195
4196         return result;
4197 }
4198
4199 ICALL_EXPORT MonoArray*
4200 ves_icall_System_Reflection_Assembly_GetReferencedAssemblies (MonoReflectionAssembly *assembly) 
4201 {
4202         static MonoClass *System_Reflection_AssemblyName;
4203         MonoArray *result;
4204         MonoDomain *domain = mono_object_domain (assembly);
4205         int i, count = 0;
4206         static MonoMethod *create_culture = NULL;
4207         MonoImage *image = assembly->assembly->image;
4208         MonoTableInfo *t;
4209
4210         if (!System_Reflection_AssemblyName)
4211                 System_Reflection_AssemblyName = mono_class_from_name (
4212                         mono_defaults.corlib, "System.Reflection", "AssemblyName");
4213
4214         t = &assembly->assembly->image->tables [MONO_TABLE_ASSEMBLYREF];
4215         count = t->rows;
4216
4217         result = mono_array_new (domain, System_Reflection_AssemblyName, count);
4218
4219         if (count > 0 && !create_culture) {
4220                 MonoMethodDesc *desc = mono_method_desc_new (
4221                         "System.Globalization.CultureInfo:CreateCulture(string,bool)", TRUE);
4222                 create_culture = mono_method_desc_search_in_image (desc, mono_defaults.corlib);
4223                 g_assert (create_culture);
4224                 mono_method_desc_free (desc);
4225         }
4226
4227         for (i = 0; i < count; i++) {
4228                 MonoReflectionAssemblyName *aname;
4229                 guint32 cols [MONO_ASSEMBLYREF_SIZE];
4230
4231                 mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE);
4232
4233                 aname = (MonoReflectionAssemblyName *) mono_object_new (
4234                         domain, System_Reflection_AssemblyName);
4235
4236                 MONO_OBJECT_SETREF (aname, name, mono_string_new (domain, mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_NAME])));
4237
4238                 aname->major = cols [MONO_ASSEMBLYREF_MAJOR_VERSION];
4239                 aname->minor = cols [MONO_ASSEMBLYREF_MINOR_VERSION];
4240                 aname->build = cols [MONO_ASSEMBLYREF_BUILD_NUMBER];
4241                 aname->revision = cols [MONO_ASSEMBLYREF_REV_NUMBER];
4242                 aname->flags = cols [MONO_ASSEMBLYREF_FLAGS];
4243                 aname->versioncompat = 1; /* SameMachine (default) */
4244                 aname->hashalg = ASSEMBLY_HASH_SHA1; /* SHA1 (default) */
4245                 MONO_OBJECT_SETREF (aname, version, create_version (domain, aname->major, aname->minor, aname->build, aname->revision));
4246
4247                 if (create_culture) {
4248                         gpointer args [2];
4249                         MonoBoolean assembly_ref = 1;
4250                         args [0] = mono_string_new (domain, mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_CULTURE]));
4251                         args [1] = &assembly_ref;
4252                         MONO_OBJECT_SETREF (aname, cultureInfo, mono_runtime_invoke (create_culture, NULL, args, NULL));
4253                 }
4254                 
4255                 if (cols [MONO_ASSEMBLYREF_PUBLIC_KEY]) {
4256                         const gchar *pkey_ptr = mono_metadata_blob_heap (image, cols [MONO_ASSEMBLYREF_PUBLIC_KEY]);
4257                         guint32 pkey_len = mono_metadata_decode_blob_size (pkey_ptr, &pkey_ptr);
4258
4259                         if ((cols [MONO_ASSEMBLYREF_FLAGS] & ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG)) {
4260                                 /* public key token isn't copied - the class library will 
4261                                 automatically generate it from the public key if required */
4262                                 MONO_OBJECT_SETREF (aname, publicKey, mono_array_new (domain, mono_defaults.byte_class, pkey_len));
4263                                 memcpy (mono_array_addr (aname->publicKey, guint8, 0), pkey_ptr, pkey_len);
4264                         } else {
4265                                 MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, pkey_len));
4266                                 memcpy (mono_array_addr (aname->keyToken, guint8, 0), pkey_ptr, pkey_len);
4267                         }
4268                 } else {
4269                         MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, 0));
4270                 }
4271                 
4272                 /* note: this function doesn't return the codebase on purpose (i.e. it can
4273                          be used under partial trust as path information isn't present). */
4274
4275                 mono_array_setref (result, i, aname);
4276         }
4277         return result;
4278 }
4279
4280 /* move this in some file in mono/util/ */
4281 static char *
4282 g_concat_dir_and_file (const char *dir, const char *file)
4283 {
4284         g_return_val_if_fail (dir != NULL, NULL);
4285         g_return_val_if_fail (file != NULL, NULL);
4286
4287         /*
4288          * If the directory name doesn't have a / on the end, we need
4289          * to add one so we get a proper path to the file
4290          */
4291         if (dir [strlen(dir) - 1] != G_DIR_SEPARATOR)
4292                 return g_strconcat (dir, G_DIR_SEPARATOR_S, file, NULL);
4293         else
4294                 return g_strconcat (dir, file, NULL);
4295 }
4296
4297 ICALL_EXPORT void *
4298 ves_icall_System_Reflection_Assembly_GetManifestResourceInternal (MonoReflectionAssembly *assembly, MonoString *name, gint32 *size, MonoReflectionModule **ref_module) 
4299 {
4300         char *n = mono_string_to_utf8 (name);
4301         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4302         guint32 i;
4303         guint32 cols [MONO_MANIFEST_SIZE];
4304         guint32 impl, file_idx;
4305         const char *val;
4306         MonoImage *module;
4307
4308         for (i = 0; i < table->rows; ++i) {
4309                 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
4310                 val = mono_metadata_string_heap (assembly->assembly->image, cols [MONO_MANIFEST_NAME]);
4311                 if (strcmp (val, n) == 0)
4312                         break;
4313         }
4314         g_free (n);
4315         if (i == table->rows)
4316                 return NULL;
4317         /* FIXME */
4318         impl = cols [MONO_MANIFEST_IMPLEMENTATION];
4319         if (impl) {
4320                 /*
4321                  * this code should only be called after obtaining the 
4322                  * ResourceInfo and handling the other cases.
4323                  */
4324                 g_assert ((impl & MONO_IMPLEMENTATION_MASK) == MONO_IMPLEMENTATION_FILE);
4325                 file_idx = impl >> MONO_IMPLEMENTATION_BITS;
4326
4327                 module = mono_image_load_file_for_image (assembly->assembly->image, file_idx);
4328                 if (!module)
4329                         return NULL;
4330         }
4331         else
4332                 module = assembly->assembly->image;
4333
4334         mono_gc_wbarrier_generic_store (ref_module, (MonoObject*) mono_module_get_object (mono_domain_get (), module));
4335
4336         return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], (guint32*)size);
4337 }
4338
4339 ICALL_EXPORT gboolean
4340 ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal (MonoReflectionAssembly *assembly, MonoString *name, MonoManifestResourceInfo *info)
4341 {
4342         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE];
4343         int i;
4344         guint32 cols [MONO_MANIFEST_SIZE];
4345         guint32 file_cols [MONO_FILE_SIZE];
4346         const char *val;
4347         char *n;
4348
4349         n = mono_string_to_utf8 (name);
4350         for (i = 0; i < table->rows; ++i) {
4351                 mono_metadata_decode_row (table, i, cols, MONO_MANIFEST_SIZE);
4352                 val = mono_metadata_string_heap (assembly->assembly->image, cols [MONO_MANIFEST_NAME]);
4353                 if (strcmp (val, n) == 0)
4354                         break;
4355         }
4356         g_free (n);
4357         if (i == table->rows)
4358                 return FALSE;
4359
4360         if (!cols [MONO_MANIFEST_IMPLEMENTATION]) {
4361                 info->location = RESOURCE_LOCATION_EMBEDDED | RESOURCE_LOCATION_IN_MANIFEST;
4362         }
4363         else {
4364                 switch (cols [MONO_MANIFEST_IMPLEMENTATION] & MONO_IMPLEMENTATION_MASK) {
4365                 case MONO_IMPLEMENTATION_FILE:
4366                         i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
4367                         table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
4368                         mono_metadata_decode_row (table, i - 1, file_cols, MONO_FILE_SIZE);
4369                         val = mono_metadata_string_heap (assembly->assembly->image, file_cols [MONO_FILE_NAME]);
4370                         MONO_OBJECT_SETREF (info, filename, mono_string_new (mono_object_domain (assembly), val));
4371                         if (file_cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA)
4372                                 info->location = 0;
4373                         else
4374                                 info->location = RESOURCE_LOCATION_EMBEDDED;
4375                         break;
4376
4377                 case MONO_IMPLEMENTATION_ASSEMBLYREF:
4378                         i = cols [MONO_MANIFEST_IMPLEMENTATION] >> MONO_IMPLEMENTATION_BITS;
4379                         mono_assembly_load_reference (assembly->assembly->image, i - 1);
4380                         if (assembly->assembly->image->references [i - 1] == (gpointer)-1) {
4381                                 char *msg = g_strdup_printf ("Assembly %d referenced from assembly %s not found ", i - 1, assembly->assembly->image->name);
4382                                 MonoException *ex = mono_get_exception_file_not_found2 (msg, NULL);
4383                                 g_free (msg);
4384                                 mono_set_pending_exception (ex);
4385                                 return FALSE;
4386                         }
4387                         MONO_OBJECT_SETREF (info, assembly, mono_assembly_get_object (mono_domain_get (), assembly->assembly->image->references [i - 1]));
4388
4389                         /* Obtain info recursively */
4390                         ves_icall_System_Reflection_Assembly_GetManifestResourceInfoInternal (info->assembly, name, info);
4391                         info->location |= RESOURCE_LOCATION_ANOTHER_ASSEMBLY;
4392                         break;
4393
4394                 case MONO_IMPLEMENTATION_EXP_TYPE:
4395                         g_assert_not_reached ();
4396                         break;
4397                 }
4398         }
4399
4400         return TRUE;
4401 }
4402
4403 ICALL_EXPORT MonoObject*
4404 ves_icall_System_Reflection_Assembly_GetFilesInternal (MonoReflectionAssembly *assembly, MonoString *name, MonoBoolean resource_modules) 
4405 {
4406         MonoTableInfo *table = &assembly->assembly->image->tables [MONO_TABLE_FILE];
4407         MonoArray *result = NULL;
4408         int i, count;
4409         const char *val;
4410         char *n;
4411
4412         /* check hash if needed */
4413         if (name) {
4414                 n = mono_string_to_utf8 (name);
4415                 for (i = 0; i < table->rows; ++i) {
4416                         val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
4417                         if (strcmp (val, n) == 0) {
4418                                 MonoString *fn;
4419                                 g_free (n);
4420                                 n = g_concat_dir_and_file (assembly->assembly->basedir, val);
4421                                 fn = mono_string_new (mono_object_domain (assembly), n);
4422                                 g_free (n);
4423                                 return (MonoObject*)fn;
4424                         }
4425                 }
4426                 g_free (n);
4427                 return NULL;
4428         }
4429
4430         count = 0;
4431         for (i = 0; i < table->rows; ++i) {
4432                 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA))
4433                         count ++;
4434         }
4435
4436         result = mono_array_new (mono_object_domain (assembly), mono_defaults.string_class, count);
4437
4438         count = 0;
4439         for (i = 0; i < table->rows; ++i) {
4440                 if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
4441                         val = mono_metadata_string_heap (assembly->assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME));
4442                         n = g_concat_dir_and_file (assembly->assembly->basedir, val);
4443                         mono_array_setref (result, count, mono_string_new (mono_object_domain (assembly), n));
4444                         g_free (n);
4445                         count ++;
4446                 }
4447         }
4448         return (MonoObject*)result;
4449 }
4450
4451 ICALL_EXPORT MonoArray*
4452 ves_icall_System_Reflection_Assembly_GetModulesInternal (MonoReflectionAssembly *assembly)
4453 {
4454         MonoDomain *domain = mono_domain_get();
4455         MonoArray *res;
4456         MonoClass *klass;
4457         int i, j, file_count = 0;
4458         MonoImage **modules;
4459         guint32 module_count, real_module_count;
4460         MonoTableInfo *table;
4461         guint32 cols [MONO_FILE_SIZE];
4462         MonoImage *image = assembly->assembly->image;
4463
4464         g_assert (image != NULL);
4465         g_assert (!assembly_is_dynamic (assembly->assembly));
4466
4467         table = &image->tables [MONO_TABLE_FILE];
4468         file_count = table->rows;
4469
4470         modules = image->modules;
4471         module_count = image->module_count;
4472
4473         real_module_count = 0;
4474         for (i = 0; i < module_count; ++i)
4475                 if (modules [i])
4476                         real_module_count ++;
4477
4478         klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Module");
4479         res = mono_array_new (domain, klass, 1 + real_module_count + file_count);
4480
4481         mono_array_setref (res, 0, mono_module_get_object (domain, image));
4482         j = 1;
4483         for (i = 0; i < module_count; ++i)
4484                 if (modules [i]) {
4485                         mono_array_setref (res, j, mono_module_get_object (domain, modules[i]));
4486                         ++j;
4487                 }
4488
4489         for (i = 0; i < file_count; ++i, ++j) {
4490                 mono_metadata_decode_row (table, i, cols, MONO_FILE_SIZE);
4491                 if (cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA)
4492                         mono_array_setref (res, j, mono_module_file_get_object (domain, image, i));
4493                 else {
4494                         MonoImage *m = mono_image_load_file_for_image (image, i + 1);
4495                         if (!m) {
4496                                 MonoString *fname = mono_string_new (mono_domain_get (), mono_metadata_string_heap (image, cols [MONO_FILE_NAME]));
4497                                 mono_set_pending_exception (mono_get_exception_file_not_found2 (NULL, fname));
4498                                 return NULL;
4499                         }
4500                         mono_array_setref (res, j, mono_module_get_object (domain, m));
4501                 }
4502         }
4503
4504         return res;
4505 }
4506
4507 ICALL_EXPORT MonoReflectionMethod*
4508 ves_icall_GetCurrentMethod (void) 
4509 {
4510         MonoMethod *m = mono_method_get_last_managed ();
4511
4512         while (m->is_inflated)
4513                 m = ((MonoMethodInflated*)m)->declaring;
4514
4515         return mono_method_get_object (mono_domain_get (), m, NULL);
4516 }
4517
4518
4519 static MonoMethod*
4520 mono_method_get_equivalent_method (MonoMethod *method, MonoClass *klass)
4521 {
4522         int offset = -1, i;
4523         if (method->is_inflated && ((MonoMethodInflated*)method)->context.method_inst) {
4524                 MonoError error;
4525                 MonoMethod *result;
4526                 MonoMethodInflated *inflated = (MonoMethodInflated*)method;
4527                 //method is inflated, we should inflate it on the other class
4528                 MonoGenericContext ctx;
4529                 ctx.method_inst = inflated->context.method_inst;
4530                 ctx.class_inst = inflated->context.class_inst;
4531                 if (klass->generic_class)
4532                         ctx.class_inst = klass->generic_class->context.class_inst;
4533                 else if (klass->generic_container)
4534                         ctx.class_inst = klass->generic_container->context.class_inst;
4535                 result = mono_class_inflate_generic_method_full_checked (inflated->declaring, klass, &ctx, &error);
4536                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4537                 return result;
4538         }
4539
4540         mono_class_setup_methods (method->klass);
4541         if (method->klass->exception_type)
4542                 return NULL;
4543         for (i = 0; i < method->klass->method.count; ++i) {
4544                 if (method->klass->methods [i] == method) {
4545                         offset = i;
4546                         break;
4547                 }       
4548         }
4549         mono_class_setup_methods (klass);
4550         if (klass->exception_type)
4551                 return NULL;
4552         g_assert (offset >= 0 && offset < klass->method.count);
4553         return klass->methods [offset];
4554 }
4555
4556 ICALL_EXPORT MonoReflectionMethod*
4557 ves_icall_System_Reflection_MethodBase_GetMethodFromHandleInternalType (MonoMethod *method, MonoType *type)
4558 {
4559         MonoClass *klass;
4560         if (type) {
4561                 klass = mono_class_from_mono_type (type);
4562                 if (mono_class_get_generic_type_definition (method->klass) != mono_class_get_generic_type_definition (klass)) 
4563                         return NULL;
4564                 if (method->klass != klass) {
4565                         method = mono_method_get_equivalent_method (method, klass);
4566                         if (!method)
4567                                 return NULL;
4568                 }
4569         } else
4570                 klass = method->klass;
4571         return mono_method_get_object (mono_domain_get (), method, klass);
4572 }
4573
4574 ICALL_EXPORT MonoReflectionMethod*
4575 ves_icall_System_Reflection_MethodBase_GetMethodFromHandleInternal (MonoMethod *method)
4576 {
4577         return mono_method_get_object (mono_domain_get (), method, NULL);
4578 }
4579
4580 ICALL_EXPORT MonoReflectionMethodBody*
4581 ves_icall_System_Reflection_MethodBase_GetMethodBodyInternal (MonoMethod *method)
4582 {
4583         return mono_method_body_get_object (mono_domain_get (), method);
4584 }
4585
4586 ICALL_EXPORT MonoReflectionAssembly*
4587 ves_icall_System_Reflection_Assembly_GetExecutingAssembly (void)
4588 {
4589         MonoMethod *dest = NULL;
4590
4591         mono_stack_walk_no_il (get_executing, &dest);
4592         g_assert (dest);
4593         return mono_assembly_get_object (mono_domain_get (), dest->klass->image->assembly);
4594 }
4595
4596
4597 ICALL_EXPORT MonoReflectionAssembly*
4598 ves_icall_System_Reflection_Assembly_GetEntryAssembly (void)
4599 {
4600         MonoDomain* domain = mono_domain_get ();
4601
4602         if (!domain->entry_assembly)
4603                 return NULL;
4604
4605         return mono_assembly_get_object (domain, domain->entry_assembly);
4606 }
4607
4608 ICALL_EXPORT MonoReflectionAssembly*
4609 ves_icall_System_Reflection_Assembly_GetCallingAssembly (void)
4610 {
4611         MonoMethod *m;
4612         MonoMethod *dest;
4613
4614         dest = NULL;
4615         mono_stack_walk_no_il (get_executing, &dest);
4616         m = dest;
4617         mono_stack_walk_no_il (get_caller, &dest);
4618         if (!dest)
4619                 dest = m;
4620         return mono_assembly_get_object (mono_domain_get (), dest->klass->image->assembly);
4621 }
4622
4623 ICALL_EXPORT MonoString *
4624 ves_icall_System_MonoType_getFullName (MonoReflectionType *object, gboolean full_name,
4625                                        gboolean assembly_qualified)
4626 {
4627         MonoDomain *domain = mono_object_domain (object); 
4628         MonoTypeNameFormat format;
4629         MonoString *res;
4630         gchar *name;
4631
4632         if (full_name)
4633                 format = assembly_qualified ?
4634                         MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED :
4635                         MONO_TYPE_NAME_FORMAT_FULL_NAME;
4636         else
4637                 format = MONO_TYPE_NAME_FORMAT_REFLECTION;
4638  
4639         name = mono_type_get_name_full (object->type, format);
4640         if (!name)
4641                 return NULL;
4642
4643         if (full_name && (object->type->type == MONO_TYPE_VAR || object->type->type == MONO_TYPE_MVAR)) {
4644                 g_free (name);
4645                 return NULL;
4646         }
4647
4648         res = mono_string_new (domain, name);
4649         g_free (name);
4650
4651         return res;
4652 }
4653
4654 ICALL_EXPORT int
4655 vell_icall_MonoType_get_core_clr_security_level (MonoReflectionType *this)
4656 {
4657         MonoClass *klass = mono_class_from_mono_type (this->type);
4658         mono_class_init_or_throw (klass);
4659         return mono_security_core_clr_class_level (klass);
4660 }
4661
4662 ICALL_EXPORT int
4663 ves_icall_MonoField_get_core_clr_security_level (MonoReflectionField *this)
4664 {
4665         MonoClassField *field = this->field;
4666         return mono_security_core_clr_field_level (field, TRUE);
4667 }
4668
4669 ICALL_EXPORT int
4670 ves_icall_MonoMethod_get_core_clr_security_level (MonoReflectionMethod *this)
4671 {
4672         MonoMethod *method = this->method;
4673         return mono_security_core_clr_method_level (method, TRUE);
4674 }
4675
4676 static void
4677 fill_reflection_assembly_name (MonoDomain *domain, MonoReflectionAssemblyName *aname, MonoAssemblyName *name, const char *absolute, gboolean by_default_version, gboolean default_publickey, gboolean default_token)
4678 {
4679         static MonoMethod *create_culture = NULL;
4680         gpointer args [2];
4681         guint32 pkey_len;
4682         const char *pkey_ptr;
4683         gchar *codebase;
4684         MonoBoolean assembly_ref = 0;
4685
4686         MONO_OBJECT_SETREF (aname, name, mono_string_new (domain, name->name));
4687         aname->major = name->major;
4688         aname->minor = name->minor;
4689         aname->build = name->build;
4690         aname->flags = name->flags;
4691         aname->revision = name->revision;
4692         aname->hashalg = name->hash_alg;
4693         aname->versioncompat = 1; /* SameMachine (default) */
4694         aname->processor_architecture = name->arch;
4695
4696         if (by_default_version)
4697                 MONO_OBJECT_SETREF (aname, version, create_version (domain, name->major, name->minor, name->build, name->revision));
4698
4699         codebase = NULL;
4700         if (absolute != NULL && *absolute != '\0') {
4701                 const gchar *prepend = "file://";
4702                 gchar *result;
4703
4704                 codebase = g_strdup (absolute);
4705
4706 #if HOST_WIN32
4707                 {
4708                         gint i;
4709                         for (i = strlen (codebase) - 1; i >= 0; i--)
4710                                 if (codebase [i] == '\\')
4711                                         codebase [i] = '/';
4712
4713                         if (*codebase == '/' && *(codebase + 1) == '/') {
4714                                 prepend = "file:";
4715                         } else {
4716                                 prepend = "file:///";
4717                         }
4718                 }
4719 #endif
4720                 result = g_strconcat (prepend, codebase, NULL);
4721                 g_free (codebase);
4722                 codebase = result;
4723         }
4724
4725         if (codebase) {
4726                 MONO_OBJECT_SETREF (aname, codebase, mono_string_new (domain, codebase));
4727                 g_free (codebase);
4728         }
4729
4730         if (!create_culture) {
4731                 MonoMethodDesc *desc = mono_method_desc_new ("System.Globalization.CultureInfo:CreateCulture(string,bool)", TRUE);
4732                 create_culture = mono_method_desc_search_in_image (desc, mono_defaults.corlib);
4733                 g_assert (create_culture);
4734                 mono_method_desc_free (desc);
4735         }
4736
4737         if (name->culture) {
4738                 args [0] = mono_string_new (domain, name->culture);
4739                 args [1] = &assembly_ref;
4740                 MONO_OBJECT_SETREF (aname, cultureInfo, mono_runtime_invoke (create_culture, NULL, args, NULL));
4741         }
4742
4743         if (name->public_key) {
4744                 pkey_ptr = (char*)name->public_key;
4745                 pkey_len = mono_metadata_decode_blob_size (pkey_ptr, &pkey_ptr);
4746
4747                 MONO_OBJECT_SETREF (aname, publicKey, mono_array_new (domain, mono_defaults.byte_class, pkey_len));
4748                 memcpy (mono_array_addr (aname->publicKey, guint8, 0), pkey_ptr, pkey_len);
4749                 aname->flags |= ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG;
4750         } else if (default_publickey) {
4751                 MONO_OBJECT_SETREF (aname, publicKey, mono_array_new (domain, mono_defaults.byte_class, 0));
4752                 aname->flags |= ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG;
4753         }
4754
4755         /* MonoAssemblyName keeps the public key token as an hexadecimal string */
4756         if (name->public_key_token [0]) {
4757                 int i, j;
4758                 char *p;
4759
4760                 MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, 8));
4761                 p = mono_array_addr (aname->keyToken, char, 0);
4762
4763                 for (i = 0, j = 0; i < 8; i++) {
4764                         *p = g_ascii_xdigit_value (name->public_key_token [j++]) << 4;
4765                         *p |= g_ascii_xdigit_value (name->public_key_token [j++]);
4766                         p++;
4767                 }
4768         } else if (default_token) {
4769                 MONO_OBJECT_SETREF (aname, keyToken, mono_array_new (domain, mono_defaults.byte_class, 0));
4770         }
4771 }
4772
4773 ICALL_EXPORT MonoString *
4774 ves_icall_System_Reflection_Assembly_get_fullName (MonoReflectionAssembly *assembly)
4775 {
4776         MonoDomain *domain = mono_object_domain (assembly); 
4777         MonoAssembly *mass = assembly->assembly;
4778         MonoString *res;
4779         gchar *name;
4780
4781         name = mono_stringify_assembly_name (&mass->aname);
4782         res = mono_string_new (domain, name);
4783         g_free (name);
4784
4785         return res;
4786 }
4787
4788 ICALL_EXPORT void
4789 ves_icall_System_Reflection_Assembly_FillName (MonoReflectionAssembly *assembly, MonoReflectionAssemblyName *aname)
4790 {
4791         gchar *absolute;
4792         MonoAssembly *mass = assembly->assembly;
4793
4794         if (g_path_is_absolute (mass->image->name)) {
4795                 fill_reflection_assembly_name (mono_object_domain (assembly),
4796                         aname, &mass->aname, mass->image->name, TRUE,
4797                         TRUE, TRUE);
4798                 return;
4799         }
4800         absolute = g_build_filename (mass->basedir, mass->image->name, NULL);
4801
4802         fill_reflection_assembly_name (mono_object_domain (assembly),
4803                 aname, &mass->aname, absolute, TRUE, TRUE,
4804                 TRUE);
4805
4806         g_free (absolute);
4807 }
4808
4809 ICALL_EXPORT void
4810 ves_icall_System_Reflection_Assembly_InternalGetAssemblyName (MonoString *fname, MonoReflectionAssemblyName *aname)
4811 {
4812         char *filename;
4813         MonoImageOpenStatus status = MONO_IMAGE_OK;
4814         gboolean res;
4815         MonoImage *image;
4816         MonoAssemblyName name;
4817         char *dirname;
4818
4819         filename = mono_string_to_utf8 (fname);
4820
4821         dirname = g_path_get_dirname (filename);
4822         replace_shadow_path (mono_domain_get (), dirname, &filename);
4823         g_free (dirname);
4824
4825         image = mono_image_open (filename, &status);
4826
4827         if (!image){
4828                 MonoException *exc;
4829
4830                 g_free (filename);
4831                 if (status == MONO_IMAGE_IMAGE_INVALID)
4832                         exc = mono_get_exception_bad_image_format2 (NULL, fname);
4833                 else
4834                         exc = mono_get_exception_file_not_found2 (NULL, fname);
4835                 mono_set_pending_exception (exc);
4836                 return;
4837         }
4838
4839         res = mono_assembly_fill_assembly_name (image, &name);
4840         if (!res) {
4841                 mono_image_close (image);
4842                 g_free (filename);
4843                 mono_set_pending_exception (mono_get_exception_argument ("assemblyFile", "The file does not contain a manifest"));
4844                 return;
4845         }
4846
4847         fill_reflection_assembly_name (mono_domain_get (), aname, &name, filename,
4848                 TRUE, FALSE, TRUE);
4849
4850         g_free (filename);
4851         mono_image_close (image);
4852 }
4853
4854 ICALL_EXPORT MonoBoolean
4855 ves_icall_System_Reflection_Assembly_LoadPermissions (MonoReflectionAssembly *assembly,
4856         char **minimum, guint32 *minLength, char **optional, guint32 *optLength, char **refused, guint32 *refLength)
4857 {
4858         MonoBoolean result = FALSE;
4859         MonoDeclSecurityEntry entry;
4860
4861         /* SecurityAction.RequestMinimum */
4862         if (mono_declsec_get_assembly_action (assembly->assembly, SECURITY_ACTION_REQMIN, &entry)) {
4863                 *minimum = entry.blob;
4864                 *minLength = entry.size;
4865                 result = TRUE;
4866         }
4867         /* SecurityAction.RequestOptional */
4868         if (mono_declsec_get_assembly_action (assembly->assembly, SECURITY_ACTION_REQOPT, &entry)) {
4869                 *optional = entry.blob;
4870                 *optLength = entry.size;
4871                 result = TRUE;
4872         }
4873         /* SecurityAction.RequestRefuse */
4874         if (mono_declsec_get_assembly_action (assembly->assembly, SECURITY_ACTION_REQREFUSE, &entry)) {
4875                 *refused = entry.blob;
4876                 *refLength = entry.size;
4877                 result = TRUE;
4878         }
4879
4880         return result;  
4881 }
4882
4883 static gboolean
4884 mono_module_type_is_visible (MonoTableInfo *tdef, MonoImage *image, int type)
4885 {
4886         guint32 attrs, visibility;
4887         do {
4888                 attrs = mono_metadata_decode_row_col (tdef, type - 1, MONO_TYPEDEF_FLAGS);
4889                 visibility = attrs & TYPE_ATTRIBUTE_VISIBILITY_MASK;
4890                 if (visibility != TYPE_ATTRIBUTE_PUBLIC && visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC)
4891                         return FALSE;
4892
4893         } while ((type = mono_metadata_token_index (mono_metadata_nested_in_typedef (image, type))));
4894
4895         return TRUE;
4896 }
4897
4898 static MonoArray*
4899 mono_module_get_types (MonoDomain *domain, MonoImage *image, MonoArray **exceptions, MonoBoolean exportedOnly)
4900 {
4901         MonoArray *res;
4902         MonoClass *klass;
4903         MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
4904         int i, count;
4905
4906         /* we start the count from 1 because we skip the special type <Module> */
4907         if (exportedOnly) {
4908                 count = 0;
4909                 for (i = 1; i < tdef->rows; ++i) {
4910                         if (mono_module_type_is_visible (tdef, image, i + 1))
4911                                 count++;
4912                 }
4913         } else {
4914                 count = tdef->rows - 1;
4915         }
4916         res = mono_array_new (domain, mono_defaults.monotype_class, count);
4917         *exceptions = mono_array_new (domain, mono_defaults.exception_class, count);
4918         count = 0;
4919         for (i = 1; i < tdef->rows; ++i) {
4920                 if (!exportedOnly || mono_module_type_is_visible (tdef, image, i + 1)) {
4921                         MonoError error;
4922                         klass = mono_class_get_checked (image, (i + 1) | MONO_TOKEN_TYPE_DEF, &error);
4923                         g_assert (!mono_loader_get_last_error ()); /* Plug any leaks */
4924                         
4925                         if (klass) {
4926                                 mono_array_setref (res, count, mono_type_get_object (domain, &klass->byval_arg));
4927                         } else {
4928                                 MonoException *ex = mono_error_convert_to_exception (&error);
4929                                 mono_array_setref (*exceptions, count, ex);
4930                         }
4931                         count++;
4932                 }
4933         }
4934         
4935         return res;
4936 }
4937
4938 ICALL_EXPORT MonoArray*
4939 ves_icall_System_Reflection_Assembly_GetTypes (MonoReflectionAssembly *assembly, MonoBoolean exportedOnly)
4940 {
4941         MonoArray *res = NULL;
4942         MonoArray *exceptions = NULL;
4943         MonoImage *image = NULL;
4944         MonoTableInfo *table = NULL;
4945         MonoDomain *domain;
4946         GList *list = NULL;
4947         int i, len, ex_count;
4948
4949         domain = mono_object_domain (assembly);
4950
4951         g_assert (!assembly_is_dynamic (assembly->assembly));
4952         image = assembly->assembly->image;
4953         table = &image->tables [MONO_TABLE_FILE];
4954         res = mono_module_get_types (domain, image, &exceptions, exportedOnly);
4955
4956         /* Append data from all modules in the assembly */
4957         for (i = 0; i < table->rows; ++i) {
4958                 if (!(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) {
4959                         MonoImage *loaded_image = mono_assembly_load_module (image->assembly, i + 1);
4960                         if (loaded_image) {
4961                                 MonoArray *ex2;
4962                                 MonoArray *res2 = mono_module_get_types (domain, loaded_image, &ex2, exportedOnly);
4963                                 /* Append the new types to the end of the array */
4964                                 if (mono_array_length (res2) > 0) {
4965                                         guint32 len1, len2;
4966                                         MonoArray *res3, *ex3;
4967
4968                                         len1 = mono_array_length (res);
4969                                         len2 = mono_array_length (res2);
4970
4971                                         res3 = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
4972                                         mono_array_memcpy_refs (res3, 0, res, 0, len1);
4973                                         mono_array_memcpy_refs (res3, len1, res2, 0, len2);
4974                                         res = res3;
4975
4976                                         ex3 = mono_array_new (domain, mono_defaults.monotype_class, len1 + len2);
4977                                         mono_array_memcpy_refs (ex3, 0, exceptions, 0, len1);
4978                                         mono_array_memcpy_refs (ex3, len1, ex2, 0, len2);
4979                                         exceptions = ex3;
4980                                 }
4981                         }
4982                 }
4983         }
4984
4985         /* the ReflectionTypeLoadException must have all the types (Types property), 
4986          * NULL replacing types which throws an exception. The LoaderException must
4987          * contain all exceptions for NULL items.
4988          */
4989
4990         len = mono_array_length (res);
4991
4992         ex_count = 0;
4993         for (i = 0; i < len; i++) {
4994                 MonoReflectionType *t = mono_array_get (res, gpointer, i);
4995                 MonoClass *klass;
4996
4997                 if (t) {
4998                         klass = mono_type_get_class (t->type);
4999                         if ((klass != NULL) && klass->exception_type) {
5000                                 /* keep the class in the list */
5001                                 list = g_list_append (list, klass);
5002                                 /* and replace Type with NULL */
5003                                 mono_array_setref (res, i, NULL);
5004                         }
5005                 } else {
5006                         ex_count ++;
5007                 }
5008         }
5009
5010         if (list || ex_count) {
5011                 GList *tmp = NULL;
5012                 MonoException *exc = NULL;
5013                 MonoArray *exl = NULL;
5014                 int j, length = g_list_length (list) + ex_count;
5015
5016                 mono_loader_clear_error ();
5017
5018                 exl = mono_array_new (domain, mono_defaults.exception_class, length);
5019                 /* Types for which mono_class_get_checked () succeeded */
5020                 for (i = 0, tmp = list; tmp; i++, tmp = tmp->next) {
5021                         MonoException *exc = mono_class_get_exception_for_failure (tmp->data);
5022                         mono_array_setref (exl, i, exc);
5023                 }
5024                 /* Types for which it don't */
5025                 for (j = 0; j < mono_array_length (exceptions); ++j) {
5026                         MonoException *exc = mono_array_get (exceptions, MonoException*, j);
5027                         if (exc) {
5028                                 g_assert (i < length);
5029                                 mono_array_setref (exl, i, exc);
5030                                 i ++;
5031                         }
5032                 }
5033                 g_list_free (list);
5034                 list = NULL;
5035
5036                 exc = mono_get_exception_reflection_type_load (res, exl);
5037                 mono_loader_clear_error ();
5038                 mono_set_pending_exception (exc);
5039                 return NULL;
5040         }
5041                 
5042         return res;
5043 }
5044
5045 ICALL_EXPORT gboolean
5046 ves_icall_System_Reflection_AssemblyName_ParseName (MonoReflectionAssemblyName *name, MonoString *assname)
5047 {
5048         MonoAssemblyName aname;
5049         MonoDomain *domain = mono_object_domain (name);
5050         char *val;
5051         gboolean is_version_defined;
5052         gboolean is_token_defined;
5053
5054         aname.public_key = NULL;
5055         val = mono_string_to_utf8 (assname);
5056         if (!mono_assembly_name_parse_full (val, &aname, TRUE, &is_version_defined, &is_token_defined)) {
5057                 g_free ((guint8*) aname.public_key);
5058                 g_free (val);
5059                 return FALSE;
5060         }
5061         
5062         fill_reflection_assembly_name (domain, name, &aname, "", is_version_defined,
5063                 FALSE, is_token_defined);
5064
5065         mono_assembly_name_free (&aname);
5066         g_free ((guint8*) aname.public_key);
5067         g_free (val);
5068
5069         return TRUE;
5070 }
5071
5072 ICALL_EXPORT MonoReflectionType*
5073 ves_icall_System_Reflection_Module_GetGlobalType (MonoReflectionModule *module)
5074 {
5075         MonoError error;
5076         MonoDomain *domain = mono_object_domain (module); 
5077         MonoClass *klass;
5078
5079         g_assert (module->image);
5080
5081         if (image_is_dynamic (module->image) && ((MonoDynamicImage*)(module->image))->initial_image)
5082                 /* These images do not have a global type */
5083                 return NULL;
5084
5085         klass = mono_class_get_checked (module->image, 1 | MONO_TOKEN_TYPE_DEF, &error);
5086         mono_error_raise_exception (&error);
5087         return mono_type_get_object (domain, &klass->byval_arg);
5088 }
5089
5090 ICALL_EXPORT void
5091 ves_icall_System_Reflection_Module_Close (MonoReflectionModule *module)
5092 {
5093         /*if (module->image)
5094                 mono_image_close (module->image);*/
5095 }
5096
5097 ICALL_EXPORT MonoString*
5098 ves_icall_System_Reflection_Module_GetGuidInternal (MonoReflectionModule *module)
5099 {
5100         MonoDomain *domain = mono_object_domain (module); 
5101
5102         g_assert (module->image);
5103         return mono_string_new (domain, module->image->guid);
5104 }
5105
5106 ICALL_EXPORT gpointer
5107 ves_icall_System_Reflection_Module_GetHINSTANCE (MonoReflectionModule *module)
5108 {
5109 #ifdef HOST_WIN32
5110         if (module->image && module->image->is_module_handle)
5111                 return module->image->raw_data;
5112 #endif
5113
5114         return (gpointer) (-1);
5115 }
5116
5117 ICALL_EXPORT void
5118 ves_icall_System_Reflection_Module_GetPEKind (MonoImage *image, gint32 *pe_kind, gint32 *machine)
5119 {
5120         if (image_is_dynamic (image)) {
5121                 MonoDynamicImage *dyn = (MonoDynamicImage*)image;
5122                 *pe_kind = dyn->pe_kind;
5123                 *machine = dyn->machine;
5124         }
5125         else {
5126                 *pe_kind = ((MonoCLIImageInfo*)(image->image_info))->cli_cli_header.ch_flags & 0x3;
5127                 *machine = ((MonoCLIImageInfo*)(image->image_info))->cli_header.coff.coff_machine;
5128         }
5129 }
5130
5131 ICALL_EXPORT gint32
5132 ves_icall_System_Reflection_Module_GetMDStreamVersion (MonoImage *image)
5133 {
5134         return (image->md_version_major << 16) | (image->md_version_minor);
5135 }
5136
5137 ICALL_EXPORT MonoArray*
5138 ves_icall_System_Reflection_Module_InternalGetTypes (MonoReflectionModule *module)
5139 {
5140         MonoArray *exceptions;
5141         int i;
5142
5143         if (!module->image)
5144                 return mono_array_new (mono_object_domain (module), mono_defaults.monotype_class, 0);
5145         else {
5146                 MonoArray *res = mono_module_get_types (mono_object_domain (module), module->image, &exceptions, FALSE);
5147                 for (i = 0; i < mono_array_length (exceptions); ++i) {
5148                         MonoException *ex = mono_array_get (exceptions, MonoException *, i);
5149                         if (ex) {
5150                                 mono_set_pending_exception (ex);
5151                                 return NULL;
5152                         }
5153                 }
5154                 return res;
5155         }
5156 }
5157
5158 static gboolean
5159 mono_memberref_is_method (MonoImage *image, guint32 token)
5160 {
5161         if (!image_is_dynamic (image)) {
5162                 guint32 cols [MONO_MEMBERREF_SIZE];
5163                 const char *sig;
5164                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], mono_metadata_token_index (token) - 1, cols, MONO_MEMBERREF_SIZE);
5165                 sig = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
5166                 mono_metadata_decode_blob_size (sig, &sig);
5167                 return (*sig != 0x6);
5168         } else {
5169                 MonoClass *handle_class;
5170
5171                 if (!mono_lookup_dynamic_token_class (image, token, FALSE, &handle_class, NULL))
5172                         return FALSE;
5173
5174                 return mono_defaults.methodhandle_class == handle_class;
5175         }
5176 }
5177
5178 static void
5179 init_generic_context_from_args (MonoGenericContext *context, MonoArray *type_args, MonoArray *method_args)
5180 {
5181         if (type_args)
5182                 context->class_inst = mono_metadata_get_generic_inst (mono_array_length (type_args),
5183                                                                       mono_array_addr (type_args, MonoType*, 0));
5184         else
5185                 context->class_inst = NULL;
5186         if (method_args)
5187                 context->method_inst = mono_metadata_get_generic_inst (mono_array_length (method_args),
5188                                                                        mono_array_addr (method_args, MonoType*, 0));
5189         else
5190                 context->method_inst = NULL;
5191 }
5192
5193 ICALL_EXPORT MonoType*
5194 ves_icall_System_Reflection_Module_ResolveTypeToken (MonoImage *image, guint32 token, MonoArray *type_args, MonoArray *method_args, MonoResolveTokenError *resolve_error)
5195 {
5196         MonoClass *klass;
5197         int table = mono_metadata_token_table (token);
5198         int index = mono_metadata_token_index (token);
5199         MonoGenericContext context;
5200         MonoError error;
5201
5202         *resolve_error = ResolveTokenError_Other;
5203
5204         /* Validate token */
5205         if ((table != MONO_TABLE_TYPEDEF) && (table != MONO_TABLE_TYPEREF) && 
5206                 (table != MONO_TABLE_TYPESPEC)) {
5207                 *resolve_error = ResolveTokenError_BadTable;
5208                 return NULL;
5209         }
5210
5211         if (image_is_dynamic (image)) {
5212                 if ((table == MONO_TABLE_TYPEDEF) || (table == MONO_TABLE_TYPEREF)) {
5213                         klass = mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
5214                         return klass ? &klass->byval_arg : NULL;
5215                 }
5216
5217                 init_generic_context_from_args (&context, type_args, method_args);
5218                 klass = mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context);
5219                 return klass ? &klass->byval_arg : NULL;
5220         }
5221
5222         if ((index <= 0) || (index > image->tables [table].rows)) {
5223                 *resolve_error = ResolveTokenError_OutOfRange;
5224                 return NULL;
5225         }
5226
5227         init_generic_context_from_args (&context, type_args, method_args);
5228         klass = mono_class_get_checked (image, token, &error);
5229         if (klass)
5230                 klass = mono_class_inflate_generic_class_checked (klass, &context, &error);
5231         mono_error_raise_exception (&error);
5232
5233         if (klass)
5234                 return &klass->byval_arg;
5235         else
5236                 return NULL;
5237 }
5238
5239 ICALL_EXPORT MonoMethod*
5240 ves_icall_System_Reflection_Module_ResolveMethodToken (MonoImage *image, guint32 token, MonoArray *type_args, MonoArray *method_args, MonoResolveTokenError *resolve_error)
5241 {
5242         MonoError error;
5243         int table = mono_metadata_token_table (token);
5244         int index = mono_metadata_token_index (token);
5245         MonoGenericContext context;
5246         MonoMethod *method;
5247
5248         *resolve_error = ResolveTokenError_Other;
5249
5250         /* Validate token */
5251         if ((table != MONO_TABLE_METHOD) && (table != MONO_TABLE_METHODSPEC) && 
5252                 (table != MONO_TABLE_MEMBERREF)) {
5253                 *resolve_error = ResolveTokenError_BadTable;
5254                 return NULL;
5255         }
5256
5257         if (image_is_dynamic (image)) {
5258                 if (table == MONO_TABLE_METHOD)
5259                         return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
5260
5261                 if ((table == MONO_TABLE_MEMBERREF) && !(mono_memberref_is_method (image, token))) {
5262                         *resolve_error = ResolveTokenError_BadTable;
5263                         return NULL;
5264                 }
5265
5266                 init_generic_context_from_args (&context, type_args, method_args);
5267                 return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context);
5268         }
5269
5270         if ((index <= 0) || (index > image->tables [table].rows)) {
5271                 *resolve_error = ResolveTokenError_OutOfRange;
5272                 return NULL;
5273         }
5274         if ((table == MONO_TABLE_MEMBERREF) && (!mono_memberref_is_method (image, token))) {
5275                 *resolve_error = ResolveTokenError_BadTable;
5276                 return NULL;
5277         }
5278
5279         init_generic_context_from_args (&context, type_args, method_args);
5280         method = mono_get_method_checked (image, token, NULL, &context, &error);
5281         mono_error_raise_exception (&error);
5282
5283         return method;
5284 }
5285
5286 ICALL_EXPORT MonoString*
5287 ves_icall_System_Reflection_Module_ResolveStringToken (MonoImage *image, guint32 token, MonoResolveTokenError *error)
5288 {
5289         int index = mono_metadata_token_index (token);
5290
5291         *error = ResolveTokenError_Other;
5292
5293         /* Validate token */
5294         if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
5295                 *error = ResolveTokenError_BadTable;
5296                 return NULL;
5297         }
5298
5299         if (image_is_dynamic (image))
5300                 return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
5301
5302         if ((index <= 0) || (index >= image->heap_us.size)) {
5303                 *error = ResolveTokenError_OutOfRange;
5304                 return NULL;
5305         }
5306
5307         /* FIXME: What to do if the index points into the middle of a string ? */
5308
5309         return mono_ldstr (mono_domain_get (), image, index);
5310 }
5311
5312 ICALL_EXPORT MonoClassField*
5313 ves_icall_System_Reflection_Module_ResolveFieldToken (MonoImage *image, guint32 token, MonoArray *type_args, MonoArray *method_args, MonoResolveTokenError *resolve_error)
5314 {
5315         MonoError error;
5316         MonoClass *klass;
5317         int table = mono_metadata_token_table (token);
5318         int index = mono_metadata_token_index (token);
5319         MonoGenericContext context;
5320         MonoClassField *field;
5321
5322         *resolve_error = ResolveTokenError_Other;
5323
5324         /* Validate token */
5325         if ((table != MONO_TABLE_FIELD) && (table != MONO_TABLE_MEMBERREF)) {
5326                 *resolve_error = ResolveTokenError_BadTable;
5327                 return NULL;
5328         }
5329
5330         if (image_is_dynamic (image)) {
5331                 if (table == MONO_TABLE_FIELD)
5332                         return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, NULL);
5333
5334                 if (mono_memberref_is_method (image, token)) {
5335                         *resolve_error = ResolveTokenError_BadTable;
5336                         return NULL;
5337                 }
5338
5339                 init_generic_context_from_args (&context, type_args, method_args);
5340                 return mono_lookup_dynamic_token_class (image, token, FALSE, NULL, &context);
5341         }
5342
5343         if ((index <= 0) || (index > image->tables [table].rows)) {
5344                 *resolve_error = ResolveTokenError_OutOfRange;
5345                 return NULL;
5346         }
5347         if ((table == MONO_TABLE_MEMBERREF) && (mono_memberref_is_method (image, token))) {
5348                 *resolve_error = ResolveTokenError_BadTable;
5349                 return NULL;
5350         }
5351
5352         init_generic_context_from_args (&context, type_args, method_args);
5353         field = mono_field_from_token_checked (image, token, &klass, &context, &error);
5354         mono_error_raise_exception (&error);
5355         
5356         return field;
5357 }
5358
5359
5360 ICALL_EXPORT MonoObject*
5361 ves_icall_System_Reflection_Module_ResolveMemberToken (MonoImage *image, guint32 token, MonoArray *type_args, MonoArray *method_args, MonoResolveTokenError *error)
5362 {
5363         int table = mono_metadata_token_table (token);
5364
5365         *error = ResolveTokenError_Other;
5366
5367         switch (table) {
5368         case MONO_TABLE_TYPEDEF:
5369         case MONO_TABLE_TYPEREF:
5370         case MONO_TABLE_TYPESPEC: {
5371                 MonoType *t = ves_icall_System_Reflection_Module_ResolveTypeToken (image, token, type_args, method_args, error);
5372                 if (t)
5373                         return (MonoObject*)mono_type_get_object (mono_domain_get (), t);
5374                 else
5375                         return NULL;
5376         }
5377         case MONO_TABLE_METHOD:
5378         case MONO_TABLE_METHODSPEC: {
5379                 MonoMethod *m = ves_icall_System_Reflection_Module_ResolveMethodToken (image, token, type_args, method_args, error);
5380                 if (m)
5381                         return (MonoObject*)mono_method_get_object (mono_domain_get (), m, m->klass);
5382                 else
5383                         return NULL;
5384         }               
5385         case MONO_TABLE_FIELD: {
5386                 MonoClassField *f = ves_icall_System_Reflection_Module_ResolveFieldToken (image, token, type_args, method_args, error);
5387                 if (f)
5388                         return (MonoObject*)mono_field_get_object (mono_domain_get (), f->parent, f);
5389                 else
5390                         return NULL;
5391         }
5392         case MONO_TABLE_MEMBERREF:
5393                 if (mono_memberref_is_method (image, token)) {
5394                         MonoMethod *m = ves_icall_System_Reflection_Module_ResolveMethodToken (image, token, type_args, method_args, error);
5395                         if (m)
5396                                 return (MonoObject*)mono_method_get_object (mono_domain_get (), m, m->klass);
5397                         else
5398                                 return NULL;
5399                 }
5400                 else {
5401                         MonoClassField *f = ves_icall_System_Reflection_Module_ResolveFieldToken (image, token, type_args, method_args, error);
5402                         if (f)
5403                                 return (MonoObject*)mono_field_get_object (mono_domain_get (), f->parent, f);
5404                         else
5405                                 return NULL;
5406                 }
5407                 break;
5408
5409         default:
5410                 *error = ResolveTokenError_BadTable;
5411         }
5412
5413         return NULL;
5414 }
5415
5416 ICALL_EXPORT MonoArray*
5417 ves_icall_System_Reflection_Module_ResolveSignature (MonoImage *image, guint32 token, MonoResolveTokenError *error)
5418 {
5419         int table = mono_metadata_token_table (token);
5420         int idx = mono_metadata_token_index (token);
5421         MonoTableInfo *tables = image->tables;
5422         guint32 sig, len;
5423         const char *ptr;
5424         MonoArray *res;
5425
5426         *error = ResolveTokenError_OutOfRange;
5427
5428         /* FIXME: Support other tables ? */
5429         if (table != MONO_TABLE_STANDALONESIG)
5430                 return NULL;
5431
5432         if (image_is_dynamic (image))
5433                 return NULL;
5434
5435         if ((idx == 0) || (idx > tables [MONO_TABLE_STANDALONESIG].rows))
5436                 return NULL;
5437
5438         sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
5439
5440         ptr = mono_metadata_blob_heap (image, sig);
5441         len = mono_metadata_decode_blob_size (ptr, &ptr);
5442
5443         res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, len);
5444         memcpy (mono_array_addr (res, guint8, 0), ptr, len);
5445         return res;
5446 }
5447
5448 ICALL_EXPORT MonoReflectionType*
5449 ves_icall_ModuleBuilder_create_modified_type (MonoReflectionTypeBuilder *tb, MonoString *smodifiers)
5450 {
5451         MonoClass *klass;
5452         int isbyref = 0, rank;
5453         char *str = mono_string_to_utf8 (smodifiers);
5454         char *p;
5455
5456         klass = mono_class_from_mono_type (tb->type.type);
5457         p = str;
5458         /* logic taken from mono_reflection_parse_type(): keep in sync */
5459         while (*p) {
5460                 switch (*p) {
5461                 case '&':
5462                         if (isbyref) { /* only one level allowed by the spec */
5463                                 g_free (str);
5464                                 return NULL;
5465                         }
5466                         isbyref = 1;
5467                         p++;
5468                         g_free (str);
5469                         return mono_type_get_object (mono_object_domain (tb), &klass->this_arg);
5470                         break;
5471                 case '*':
5472                         klass = mono_ptr_class_get (&klass->byval_arg);
5473                         mono_class_init (klass);
5474                         p++;
5475                         break;
5476                 case '[':
5477                         rank = 1;
5478                         p++;
5479                         while (*p) {
5480                                 if (*p == ']')
5481                                         break;
5482                                 if (*p == ',')
5483                                         rank++;
5484                                 else if (*p != '*') { /* '*' means unknown lower bound */
5485                                         g_free (str);
5486                                         return NULL;
5487                                 }
5488                                 ++p;
5489                         }
5490                         if (*p != ']') {
5491                                 g_free (str);
5492                                 return NULL;
5493                         }
5494                         p++;
5495                         klass = mono_array_class_get (klass, rank);
5496                         mono_class_init (klass);
5497                         break;
5498                 default:
5499                         break;
5500                 }
5501         }
5502         g_free (str);
5503         return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
5504 }
5505
5506 ICALL_EXPORT MonoBoolean
5507 ves_icall_Type_IsArrayImpl (MonoReflectionType *t)
5508 {
5509         MonoType *type;
5510         MonoBoolean res;
5511
5512         type = t->type;
5513         res = !type->byref && (type->type == MONO_TYPE_ARRAY || type->type == MONO_TYPE_SZARRAY);
5514
5515         return res;
5516 }
5517
5518 static void
5519 check_for_invalid_type (MonoClass *klass)
5520 {
5521         char *name;
5522         MonoString *str;
5523         if (klass->byval_arg.type != MONO_TYPE_TYPEDBYREF)
5524                 return;
5525
5526         name = mono_type_get_full_name (klass);
5527         str =  mono_string_new (mono_domain_get (), name);
5528         g_free (name);
5529         mono_raise_exception ((MonoException*)mono_get_exception_type_load (str, NULL));
5530
5531 }
5532 ICALL_EXPORT MonoReflectionType *
5533 ves_icall_Type_make_array_type (MonoReflectionType *type, int rank)
5534 {
5535         MonoClass *klass, *aklass;
5536
5537         klass = mono_class_from_mono_type (type->type);
5538         check_for_invalid_type (klass);
5539
5540         if (rank == 0) //single dimentional array
5541                 aklass = mono_array_class_get (klass, 1);
5542         else
5543                 aklass = mono_bounded_array_class_get (klass, rank, TRUE);
5544
5545         return mono_type_get_object (mono_object_domain (type), &aklass->byval_arg);
5546 }
5547
5548 ICALL_EXPORT MonoReflectionType *
5549 ves_icall_Type_make_byref_type (MonoReflectionType *type)
5550 {
5551         MonoClass *klass;
5552
5553         klass = mono_class_from_mono_type (type->type);
5554         mono_class_init_or_throw (klass);
5555         check_for_invalid_type (klass);
5556
5557         return mono_type_get_object (mono_object_domain (type), &klass->this_arg);
5558 }
5559
5560 ICALL_EXPORT MonoReflectionType *
5561 ves_icall_Type_MakePointerType (MonoReflectionType *type)
5562 {
5563         MonoClass *klass, *pklass;
5564
5565         klass = mono_class_from_mono_type (type->type);
5566         mono_class_init_or_throw (klass);
5567         check_for_invalid_type (klass);
5568
5569         pklass = mono_ptr_class_get (type->type);
5570
5571         return mono_type_get_object (mono_object_domain (type), &pklass->byval_arg);
5572 }
5573
5574 ICALL_EXPORT MonoObject *
5575 ves_icall_System_Delegate_CreateDelegate_internal (MonoReflectionType *type, MonoObject *target,
5576                                                    MonoReflectionMethod *info, MonoBoolean throwOnBindFailure)
5577 {
5578         MonoClass *delegate_class = mono_class_from_mono_type (type->type);
5579         MonoObject *delegate;
5580         gpointer func;
5581         MonoMethod *method = info->method;
5582
5583         mono_class_init_or_throw (delegate_class);
5584
5585         mono_assert (delegate_class->parent == mono_defaults.multicastdelegate_class);
5586
5587         if (mono_security_core_clr_enabled ()) {
5588                 if (!mono_security_core_clr_ensure_delegate_creation (method, throwOnBindFailure))
5589                         return NULL;
5590         }
5591
5592         delegate = mono_object_new (mono_object_domain (type), delegate_class);
5593
5594         if (method_is_dynamic (method)) {
5595                 /* Creating a trampoline would leak memory */
5596                 func = mono_compile_method (method);
5597         } else {
5598                 if (target && method->flags & METHOD_ATTRIBUTE_VIRTUAL && method->klass != mono_object_class (target))
5599                         method = mono_object_get_virtual_method (target, method);
5600                 func = mono_create_ftnptr (mono_domain_get (),
5601                         mono_runtime_create_jump_trampoline (mono_domain_get (), method, TRUE));
5602         }
5603
5604         mono_delegate_ctor_with_method (delegate, target, func, method);
5605
5606         return delegate;
5607 }
5608
5609 ICALL_EXPORT void
5610 ves_icall_System_Delegate_SetMulticastInvoke (MonoDelegate *this)
5611 {
5612         /* Reset the invoke impl to the default one */
5613         this->invoke_impl = mono_runtime_create_delegate_trampoline (this->object.vtable->klass);
5614 }
5615
5616 /*
5617  * Magic number to convert a time which is relative to
5618  * Jan 1, 1970 into a value which is relative to Jan 1, 0001.
5619  */
5620 #define EPOCH_ADJUST    ((guint64)62135596800LL)
5621
5622 /*
5623  * Magic number to convert FILETIME base Jan 1, 1601 to DateTime - base Jan, 1, 0001
5624  */
5625 #define FILETIME_ADJUST ((guint64)504911232000000000LL)
5626
5627 #ifdef HOST_WIN32
5628 /* convert a SYSTEMTIME which is of the form "last thursday in october" to a real date */
5629 static void
5630 convert_to_absolute_date(SYSTEMTIME *date)
5631 {
5632 #define IS_LEAP(y) ((y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0))
5633         static int days_in_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
5634         static int leap_days_in_month[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
5635         /* from the calendar FAQ */
5636         int a = (14 - date->wMonth) / 12;
5637         int y = date->wYear - a;
5638         int m = date->wMonth + 12 * a - 2;
5639         int d = (1 + y + y/4 - y/100 + y/400 + (31*m)/12) % 7;
5640
5641         /* d is now the day of the week for the first of the month (0 == Sunday) */
5642
5643         int day_of_week = date->wDayOfWeek;
5644
5645         /* set day_in_month to the first day in the month which falls on day_of_week */    
5646         int day_in_month = 1 + (day_of_week - d);
5647         if (day_in_month <= 0)
5648                 day_in_month += 7;
5649
5650         /* wDay is 1 for first weekday in month, 2 for 2nd ... 5 means last - so work that out allowing for days in the month */
5651         date->wDay = day_in_month + (date->wDay - 1) * 7;
5652         if (date->wDay > (IS_LEAP(date->wYear) ? leap_days_in_month[date->wMonth - 1] : days_in_month[date->wMonth - 1]))
5653                 date->wDay -= 7;
5654 }
5655 #endif
5656
5657 #ifndef HOST_WIN32
5658 /*
5659  * Return's the offset from GMT of a local time.
5660  * 
5661  *  tm is a local time
5662  *  t  is the same local time as seconds.
5663  */
5664 static int 
5665 gmt_offset(struct tm *tm, time_t t)
5666 {
5667 #if defined (HAVE_TM_GMTOFF)
5668         return tm->tm_gmtoff;
5669 #else
5670         struct tm g;
5671         time_t t2;
5672         g = *gmtime(&t);
5673         g.tm_isdst = tm->tm_isdst;
5674         t2 = mktime(&g);
5675         return (int)difftime(t, t2);
5676 #endif
5677 }
5678 #endif
5679 /*
5680  * This is heavily based on zdump.c from glibc 2.2.
5681  *
5682  *  * data[0]:  start of daylight saving time (in DateTime ticks).
5683  *  * data[1]:  end of daylight saving time (in DateTime ticks).
5684  *  * data[2]:  utcoffset (in TimeSpan ticks).
5685  *  * data[3]:  additional offset when daylight saving (in TimeSpan ticks).
5686  *  * name[0]:  name of this timezone when not daylight saving.
5687  *  * name[1]:  name of this timezone when daylight saving.
5688  *
5689  *  FIXME: This only works with "standard" Unix dates (years between 1900 and 2100) while
5690  *         the class library allows years between 1 and 9999.
5691  *
5692  *  Returns true on success and zero on failure.
5693  */
5694 ICALL_EXPORT guint32
5695 ves_icall_System_CurrentSystemTimeZone_GetTimeZoneData (guint32 year, MonoArray **data, MonoArray **names)
5696 {
5697 #ifndef HOST_WIN32
5698         MonoDomain *domain = mono_domain_get ();
5699         struct tm start, tt;
5700         time_t t;
5701
5702         long int gmtoff, gmtoff_after, gmtoff_st, gmtoff_ds;
5703         int day, transitioned;
5704         char tzone [64];
5705
5706         gmtoff_st = gmtoff_ds = transitioned = 0;
5707
5708         MONO_CHECK_ARG_NULL (data, 0);
5709         MONO_CHECK_ARG_NULL (names, 0);
5710
5711         mono_gc_wbarrier_generic_store (data, (MonoObject*) mono_array_new (domain, mono_defaults.int64_class, 4));
5712         mono_gc_wbarrier_generic_store (names, (MonoObject*) mono_array_new (domain, mono_defaults.string_class, 2));
5713
5714         /* 
5715          * no info is better than crashing: we'll need our own tz data
5716          * to make this work properly, anyway. The range is probably
5717          * reduced to 1970 .. 2037 because that is what mktime is
5718          * guaranteed to support (we get into an infinite loop
5719          * otherwise).
5720          */
5721
5722         memset (&start, 0, sizeof (start));
5723
5724         start.tm_mday = 1;
5725         start.tm_year = year-1900;
5726
5727         t = mktime (&start);
5728
5729         if ((year < 1970) || (year > 2037) || (t == -1)) {
5730                 t = time (NULL);
5731                 tt = *localtime (&t);
5732                 strftime (tzone, sizeof (tzone), "%Z", &tt);
5733                 mono_array_setref ((*names), 0, mono_string_new (domain, tzone));
5734                 mono_array_setref ((*names), 1, mono_string_new (domain, tzone));
5735                 return 1;
5736         }
5737
5738         gmtoff = gmt_offset (&start, t);
5739
5740         /* For each day of the year, calculate the tm_gmtoff. */
5741         for (day = 0; day < 365 && transitioned < 2; day++) {
5742
5743                 t += 3600*24;
5744                 tt = *localtime (&t);
5745
5746         gmtoff_after = gmt_offset(&tt, t);
5747
5748                 /* Daylight saving starts or ends here. */
5749                 if (gmtoff_after != gmtoff) {
5750                         struct tm tt1;
5751                         time_t t1;
5752
5753                         /* Try to find the exact hour when daylight saving starts/ends. */
5754                         t1 = t;
5755                         do {
5756                                 t1 -= 3600;
5757                                 tt1 = *localtime (&t1);
5758                         } while (gmt_offset (&tt1, t1) != gmtoff);
5759
5760                         /* Try to find the exact minute when daylight saving starts/ends. */
5761                         do {
5762                                 t1 += 60;
5763                                 tt1 = *localtime (&t1);
5764                         } while (gmt_offset (&tt1, t1) == gmtoff);
5765                         t1+=gmtoff;
5766                         strftime (tzone, sizeof (tzone), "%Z", &tt);
5767                         
5768                         /* Write data, if we're already in daylight saving, we're done. */
5769                         if (tt.tm_isdst) {
5770                                 mono_array_setref ((*names), 1, mono_string_new (domain, tzone));
5771                                 mono_array_set ((*data), gint64, 0, ((gint64)t1 + EPOCH_ADJUST) * 10000000L);
5772                                 if (gmtoff_ds == 0) {
5773                                         gmtoff_st = gmtoff;
5774                                         gmtoff_ds = gmtoff_after;
5775                                 }
5776                                 transitioned++;
5777                         } else {
5778                                 mono_array_setref ((*names), 0, mono_string_new (domain, tzone));
5779                                 mono_array_set ((*data), gint64, 1, ((gint64)t1 + EPOCH_ADJUST) * 10000000L);
5780                                 if (gmtoff_ds == 0) {
5781                                         gmtoff_st = gmtoff_after;
5782                                         gmtoff_ds = gmtoff;
5783                                 }
5784                                 transitioned++;
5785                         }
5786
5787                         /* This is only set once when we enter daylight saving. */
5788                         if (tt1.tm_isdst) {
5789                                 mono_array_set ((*data), gint64, 2, (gint64)gmtoff_st * 10000000L);
5790                                 mono_array_set ((*data), gint64, 3, (gint64)(gmtoff_ds - gmtoff_st) * 10000000L);
5791                         }
5792                         gmtoff = gmt_offset (&tt, t);
5793                 }
5794         }
5795
5796         if (transitioned < 2) {
5797                 strftime (tzone, sizeof (tzone), "%Z", &tt);
5798                 mono_array_setref ((*names), 0, mono_string_new (domain, tzone));
5799                 mono_array_setref ((*names), 1, mono_string_new (domain, tzone));
5800                 mono_array_set ((*data), gint64, 0, 0);
5801                 mono_array_set ((*data), gint64, 1, 0);
5802                 mono_array_set ((*data), gint64, 2, (gint64) gmtoff * 10000000L);
5803                 mono_array_set ((*data), gint64, 3, 0);
5804         }
5805
5806         return 1;
5807 #else
5808         MonoDomain *domain = mono_domain_get ();
5809         TIME_ZONE_INFORMATION tz_info;
5810         FILETIME ft;
5811         int i;
5812         int err, tz_id;
5813
5814         tz_id = GetTimeZoneInformation (&tz_info);
5815         if (tz_id == TIME_ZONE_ID_INVALID)
5816                 return 0;
5817
5818         MONO_CHECK_ARG_NULL (data, 0);
5819         MONO_CHECK_ARG_NULL (names, 0);
5820
5821         mono_gc_wbarrier_generic_store (data, mono_array_new (domain, mono_defaults.int64_class, 4));
5822         mono_gc_wbarrier_generic_store (names, mono_array_new (domain, mono_defaults.string_class, 2));
5823
5824         for (i = 0; i < 32; ++i)
5825                 if (!tz_info.DaylightName [i])
5826                         break;
5827         mono_array_setref ((*names), 1, mono_string_new_utf16 (domain, tz_info.DaylightName, i));
5828         for (i = 0; i < 32; ++i)
5829                 if (!tz_info.StandardName [i])
5830                         break;
5831         mono_array_setref ((*names), 0, mono_string_new_utf16 (domain, tz_info.StandardName, i));
5832
5833         if ((year <= 1601) || (year > 30827)) {
5834                 /*
5835                  * According to MSDN, the MS time functions can't handle dates outside
5836                  * this interval.
5837                  */
5838                 return 1;
5839         }
5840
5841         /* even if the timezone has no daylight savings it may have Bias (e.g. GMT+13 it seems) */
5842         if (tz_id != TIME_ZONE_ID_UNKNOWN) {
5843                 tz_info.StandardDate.wYear = year;
5844                 convert_to_absolute_date(&tz_info.StandardDate);
5845                 err = SystemTimeToFileTime (&tz_info.StandardDate, &ft);
5846                 //g_assert(err);
5847                 if (err == 0)
5848                         return 0;
5849                 
5850                 mono_array_set ((*data), gint64, 1, FILETIME_ADJUST + (((guint64)ft.dwHighDateTime<<32) | ft.dwLowDateTime));
5851                 tz_info.DaylightDate.wYear = year;
5852                 convert_to_absolute_date(&tz_info.DaylightDate);
5853                 err = SystemTimeToFileTime (&tz_info.DaylightDate, &ft);
5854                 //g_assert(err);
5855                 if (err == 0)
5856                         return 0;
5857                 
5858                 mono_array_set ((*data), gint64, 0, FILETIME_ADJUST + (((guint64)ft.dwHighDateTime<<32) | ft.dwLowDateTime));
5859         }
5860         mono_array_set ((*data), gint64, 2, (tz_info.Bias + tz_info.StandardBias) * -600000000LL);
5861         mono_array_set ((*data), gint64, 3, (tz_info.DaylightBias - tz_info.StandardBias) * -600000000LL);
5862
5863         return 1;
5864 #endif
5865 }
5866
5867 /* System.Buffer */
5868
5869 static inline gint32 
5870 mono_array_get_byte_length (MonoArray *array)
5871 {
5872         MonoClass *klass;
5873         int length;
5874         int i;
5875
5876         klass = array->obj.vtable->klass;
5877
5878         if (array->bounds == NULL)
5879                 length = array->max_length;
5880         else {
5881                 length = 1;
5882                 for (i = 0; i < klass->rank; ++ i)
5883                         length *= array->bounds [i].length;
5884         }
5885
5886         switch (klass->element_class->byval_arg.type) {
5887         case MONO_TYPE_I1:
5888         case MONO_TYPE_U1:
5889         case MONO_TYPE_BOOLEAN:
5890                 return length;
5891         case MONO_TYPE_I2:
5892         case MONO_TYPE_U2:
5893         case MONO_TYPE_CHAR:
5894                 return length << 1;
5895         case MONO_TYPE_I4:
5896         case MONO_TYPE_U4:
5897         case MONO_TYPE_R4:
5898                 return length << 2;
5899         case MONO_TYPE_I:
5900         case MONO_TYPE_U:
5901                 return length * sizeof (gpointer);
5902         case MONO_TYPE_I8:
5903         case MONO_TYPE_U8:
5904         case MONO_TYPE_R8:
5905                 return length << 3;
5906         default:
5907                 return -1;
5908         }
5909 }
5910
5911 ICALL_EXPORT gint32 
5912 ves_icall_System_Buffer_ByteLengthInternal (MonoArray *array) 
5913 {
5914         return mono_array_get_byte_length (array);
5915 }
5916
5917 ICALL_EXPORT gint8 
5918 ves_icall_System_Buffer_GetByteInternal (MonoArray *array, gint32 idx) 
5919 {
5920         return mono_array_get (array, gint8, idx);
5921 }
5922
5923 ICALL_EXPORT void 
5924 ves_icall_System_Buffer_SetByteInternal (MonoArray *array, gint32 idx, gint8 value) 
5925 {
5926         mono_array_set (array, gint8, idx, value);
5927 }
5928
5929 ICALL_EXPORT MonoBoolean
5930 ves_icall_System_Buffer_BlockCopyInternal (MonoArray *src, gint32 src_offset, MonoArray *dest, gint32 dest_offset, gint32 count) 
5931 {
5932         guint8 *src_buf, *dest_buf;
5933
5934         /* This is called directly from the class libraries without going through the managed wrapper */
5935         MONO_CHECK_ARG_NULL (src, FALSE);
5936         MONO_CHECK_ARG_NULL (dest, FALSE);
5937
5938         /* watch out for integer overflow */
5939         if ((src_offset > mono_array_get_byte_length (src) - count) || (dest_offset > mono_array_get_byte_length (dest) - count))
5940                 return FALSE;
5941
5942         src_buf = (guint8 *)src->vector + src_offset;
5943         dest_buf = (guint8 *)dest->vector + dest_offset;
5944
5945         if (src != dest)
5946                 memcpy (dest_buf, src_buf, count);
5947         else
5948                 memmove (dest_buf, src_buf, count); /* Source and dest are the same array */
5949
5950         return TRUE;
5951 }
5952
5953 #ifndef DISABLE_REMOTING
5954 ICALL_EXPORT MonoObject *
5955 ves_icall_Remoting_RealProxy_GetTransparentProxy (MonoObject *this, MonoString *class_name)
5956 {
5957         MonoDomain *domain = mono_object_domain (this); 
5958         MonoObject *res;
5959         MonoRealProxy *rp = ((MonoRealProxy *)this);
5960         MonoTransparentProxy *tp;
5961         MonoType *type;
5962         MonoClass *klass;
5963
5964         res = mono_object_new (domain, mono_defaults.transparent_proxy_class);
5965         tp = (MonoTransparentProxy*) res;
5966         
5967         MONO_OBJECT_SETREF (tp, rp, rp);
5968         type = ((MonoReflectionType *)rp->class_to_proxy)->type;
5969         klass = mono_class_from_mono_type (type);
5970
5971         tp->custom_type_info = (mono_object_isinst (this, mono_defaults.iremotingtypeinfo_class) != NULL);
5972         tp->remote_class = mono_remote_class (domain, class_name, klass);
5973
5974         res->vtable = mono_remote_class_vtable (domain, tp->remote_class, rp);
5975         return res;
5976 }
5977
5978 ICALL_EXPORT MonoReflectionType *
5979 ves_icall_Remoting_RealProxy_InternalGetProxyType (MonoTransparentProxy *tp)
5980 {
5981         return mono_type_get_object (mono_object_domain (tp), &tp->remote_class->proxy_class->byval_arg);
5982 }
5983 #endif
5984
5985 /* System.Environment */
5986
5987 MonoString*
5988 ves_icall_System_Environment_get_UserName (void)
5989 {
5990         /* using glib is more portable */
5991         return mono_string_new (mono_domain_get (), g_get_user_name ());
5992 }
5993
5994
5995 ICALL_EXPORT MonoString *
5996 ves_icall_System_Environment_get_MachineName (void)
5997 {
5998 #if defined (HOST_WIN32)
5999         gunichar2 *buf;
6000         guint32 len;
6001         MonoString *result;
6002
6003         len = MAX_COMPUTERNAME_LENGTH + 1;
6004         buf = g_new (gunichar2, len);
6005
6006         result = NULL;
6007         if (GetComputerName (buf, (PDWORD) &len))
6008                 result = mono_string_new_utf16 (mono_domain_get (), buf, len);
6009
6010         g_free (buf);
6011         return result;
6012 #elif !defined(DISABLE_SOCKETS)
6013         gchar buf [256];
6014         MonoString *result;
6015
6016         if (gethostname (buf, sizeof (buf)) == 0)
6017                 result = mono_string_new (mono_domain_get (), buf);
6018         else
6019                 result = NULL;
6020         
6021         return result;
6022 #else
6023         return mono_string_new (mono_domain_get (), "mono");
6024 #endif
6025 }
6026
6027 ICALL_EXPORT int
6028 ves_icall_System_Environment_get_Platform (void)
6029 {
6030 #if defined (TARGET_WIN32)
6031         /* Win32NT */
6032         return 2;
6033 #elif defined(__MACH__)
6034         /* OSX */
6035         //
6036         // Notice that the value is hidden from user code, and only exposed
6037         // to mscorlib.   This is due to Mono's Unix/MacOS code predating the
6038         // define and making assumptions based on Unix/128/4 values before there
6039         // was a MacOS define.    Lots of code would assume that not-Unix meant
6040         // Windows, but in this case, it would be OSX. 
6041         //
6042         return 6;
6043 #else
6044         /* Unix */
6045         return 4;
6046 #endif
6047 }
6048
6049 ICALL_EXPORT MonoString *
6050 ves_icall_System_Environment_get_NewLine (void)
6051 {
6052 #if defined (HOST_WIN32)
6053         return mono_string_new (mono_domain_get (), "\r\n");
6054 #else
6055         return mono_string_new (mono_domain_get (), "\n");
6056 #endif
6057 }
6058
6059 ICALL_EXPORT MonoString *
6060 ves_icall_System_Environment_GetEnvironmentVariable (MonoString *name)
6061 {
6062         const gchar *value;
6063         gchar *utf8_name;
6064
6065         if (name == NULL)
6066                 return NULL;
6067
6068         utf8_name = mono_string_to_utf8 (name); /* FIXME: this should be ascii */
6069         value = g_getenv (utf8_name);
6070
6071         g_free (utf8_name);
6072
6073         if (value == 0)
6074                 return NULL;
6075         
6076         return mono_string_new (mono_domain_get (), value);
6077 }
6078
6079 /*
6080  * There is no standard way to get at environ.
6081  */
6082 #ifndef _MSC_VER
6083 #ifndef __MINGW32_VERSION
6084 #if defined(__APPLE__) && !defined (__arm__) && !defined (__aarch64__)
6085 /* Apple defines this in crt_externs.h but doesn't provide that header for 
6086  * arm-apple-darwin9.  We'll manually define the symbol on Apple as it does
6087  * in fact exist on all implementations (so far) 
6088  */
6089 gchar ***_NSGetEnviron(void);
6090 #define environ (*_NSGetEnviron())
6091 #else
6092 extern
6093 char **environ;
6094 #endif
6095 #endif
6096 #endif
6097
6098 ICALL_EXPORT MonoArray *
6099 ves_icall_System_Environment_GetEnvironmentVariableNames (void)
6100 {
6101 #ifdef HOST_WIN32
6102         MonoArray *names;
6103         MonoDomain *domain;
6104         MonoString *str;
6105         WCHAR* env_strings;
6106         WCHAR* env_string;
6107         WCHAR* equal_str;
6108         int n = 0;
6109
6110         env_strings = GetEnvironmentStrings();
6111
6112         if (env_strings) {
6113                 env_string = env_strings;
6114                 while (*env_string != '\0') {
6115                 /* weird case that MS seems to skip */
6116                         if (*env_string != '=')
6117                                 n++;
6118                         while (*env_string != '\0')
6119                                 env_string++;
6120                         env_string++;
6121                 }
6122         }
6123
6124         domain = mono_domain_get ();
6125         names = mono_array_new (domain, mono_defaults.string_class, n);
6126
6127         if (env_strings) {
6128                 n = 0;
6129                 env_string = env_strings;
6130                 while (*env_string != '\0') {
6131                         /* weird case that MS seems to skip */
6132                         if (*env_string != '=') {
6133                                 equal_str = wcschr(env_string, '=');
6134                                 g_assert(equal_str);
6135                                 str = mono_string_new_utf16 (domain, env_string, equal_str-env_string);
6136                                 mono_array_setref (names, n, str);
6137                                 n++;
6138                         }
6139                         while (*env_string != '\0')
6140                                 env_string++;
6141                         env_string++;
6142                 }
6143
6144                 FreeEnvironmentStrings (env_strings);
6145         }
6146
6147         return names;
6148
6149 #else
6150         MonoArray *names;
6151         MonoDomain *domain;
6152         MonoString *str;
6153         gchar **e, **parts;
6154         int n;
6155
6156         n = 0;
6157         for (e = environ; *e != 0; ++ e)
6158                 ++ n;
6159
6160         domain = mono_domain_get ();
6161         names = mono_array_new (domain, mono_defaults.string_class, n);
6162
6163         n = 0;
6164         for (e = environ; *e != 0; ++ e) {
6165                 parts = g_strsplit (*e, "=", 2);
6166                 if (*parts != 0) {
6167                         str = mono_string_new (domain, *parts);
6168                         mono_array_setref (names, n, str);
6169                 }
6170
6171                 g_strfreev (parts);
6172
6173                 ++ n;
6174         }
6175
6176         return names;
6177 #endif
6178 }
6179
6180 /*
6181  * If your platform lacks setenv/unsetenv, you must upgrade your glib.
6182  */
6183 #if !GLIB_CHECK_VERSION(2,4,0)
6184 #define g_setenv(a,b,c)   setenv(a,b,c)
6185 #define g_unsetenv(a) unsetenv(a)
6186 #endif
6187
6188 ICALL_EXPORT void
6189 ves_icall_System_Environment_InternalSetEnvironmentVariable (MonoString *name, MonoString *value)
6190 {
6191 #ifdef HOST_WIN32
6192         gunichar2 *utf16_name, *utf16_value;
6193 #else
6194         gchar *utf8_name, *utf8_value;
6195         MonoError error;
6196 #endif
6197
6198 #ifdef HOST_WIN32
6199         utf16_name = mono_string_to_utf16 (name);
6200         if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
6201                 SetEnvironmentVariable (utf16_name, NULL);
6202                 g_free (utf16_name);
6203                 return;
6204         }
6205
6206         utf16_value = mono_string_to_utf16 (value);
6207
6208         SetEnvironmentVariable (utf16_name, utf16_value);
6209
6210         g_free (utf16_name);
6211         g_free (utf16_value);
6212 #else
6213         utf8_name = mono_string_to_utf8 (name); /* FIXME: this should be ascii */
6214
6215         if ((value == NULL) || (mono_string_length (value) == 0) || (mono_string_chars (value)[0] == 0)) {
6216                 g_unsetenv (utf8_name);
6217                 g_free (utf8_name);
6218                 return;
6219         }
6220
6221         utf8_value = mono_string_to_utf8_checked (value, &error);
6222         if (!mono_error_ok (&error)) {
6223                 g_free (utf8_name);
6224                 mono_error_raise_exception (&error);
6225         }
6226         g_setenv (utf8_name, utf8_value, TRUE);
6227
6228         g_free (utf8_name);
6229         g_free (utf8_value);
6230 #endif
6231 }
6232
6233 ICALL_EXPORT void
6234 ves_icall_System_Environment_Exit (int result)
6235 {
6236         mono_environment_exitcode_set (result);
6237
6238 /* FIXME: There are some cleanup hangs that should be worked out, but
6239  * if the program is going to exit, everything will be cleaned up when
6240  * NaCl exits anyway.
6241  */
6242 #ifndef __native_client__
6243         if (!mono_runtime_try_shutdown ())
6244                 mono_thread_exit ();
6245
6246         /* Suspend all managed threads since the runtime is going away */
6247         mono_thread_suspend_all_other_threads ();
6248
6249         mono_runtime_quit ();
6250 #endif
6251
6252         /* we may need to do some cleanup here... */
6253         exit (result);
6254 }
6255
6256 ICALL_EXPORT MonoString*
6257 ves_icall_System_Environment_GetGacPath (void)
6258 {
6259         return mono_string_new (mono_domain_get (), mono_assembly_getrootdir ());
6260 }
6261
6262 ICALL_EXPORT MonoString*
6263 ves_icall_System_Environment_GetWindowsFolderPath (int folder)
6264 {
6265 #if defined (HOST_WIN32)
6266         #ifndef CSIDL_FLAG_CREATE
6267                 #define CSIDL_FLAG_CREATE       0x8000
6268         #endif
6269
6270         WCHAR path [MAX_PATH];
6271         /* Create directory if no existing */
6272         if (SUCCEEDED (SHGetFolderPathW (NULL, folder | CSIDL_FLAG_CREATE, NULL, 0, path))) {
6273                 int len = 0;
6274                 while (path [len])
6275                         ++ len;
6276                 return mono_string_new_utf16 (mono_domain_get (), path, len);
6277         }
6278 #else
6279         g_warning ("ves_icall_System_Environment_GetWindowsFolderPath should only be called on Windows!");
6280 #endif
6281         return mono_string_new (mono_domain_get (), "");
6282 }
6283
6284 ICALL_EXPORT MonoArray *
6285 ves_icall_System_Environment_GetLogicalDrives (void)
6286 {
6287         gunichar2 buf [256], *ptr, *dname;
6288         gunichar2 *u16;
6289         guint initial_size = 127, size = 128;
6290         gint ndrives;
6291         MonoArray *result;
6292         MonoString *drivestr;
6293         MonoDomain *domain = mono_domain_get ();
6294         gint len;
6295
6296         buf [0] = '\0';
6297         ptr = buf;
6298
6299         while (size > initial_size) {
6300                 size = (guint) GetLogicalDriveStrings (initial_size, ptr);
6301                 if (size > initial_size) {
6302                         if (ptr != buf)
6303                                 g_free (ptr);
6304                         ptr = g_malloc0 ((size + 1) * sizeof (gunichar2));
6305                         initial_size = size;
6306                         size++;
6307                 }
6308         }
6309
6310         /* Count strings */
6311         dname = ptr;
6312         ndrives = 0;
6313         do {
6314                 while (*dname++);
6315                 ndrives++;
6316         } while (*dname);
6317
6318         dname = ptr;
6319         result = mono_array_new (domain, mono_defaults.string_class, ndrives);
6320         ndrives = 0;
6321         do {
6322                 len = 0;
6323                 u16 = dname;
6324                 while (*u16) { u16++; len ++; }
6325                 drivestr = mono_string_new_utf16 (domain, dname, len);
6326                 mono_array_setref (result, ndrives++, drivestr);
6327                 while (*dname++);
6328         } while (*dname);
6329
6330         if (ptr != buf)
6331                 g_free (ptr);
6332
6333         return result;
6334 }
6335
6336 ICALL_EXPORT MonoString *
6337 ves_icall_System_IO_DriveInfo_GetDriveFormat (MonoString *path)
6338 {
6339         gunichar2 volume_name [MAX_PATH + 1];
6340         
6341         if (GetVolumeInformation (mono_string_chars (path), NULL, 0, NULL, NULL, NULL, volume_name, MAX_PATH + 1) == FALSE)
6342                 return NULL;
6343         return mono_string_from_utf16 (volume_name);
6344 }
6345
6346 ICALL_EXPORT MonoString *
6347 ves_icall_System_Environment_InternalGetHome (void)
6348 {
6349         return mono_string_new (mono_domain_get (), g_get_home_dir ());
6350 }
6351
6352 static const char *encodings [] = {
6353         (char *) 1,
6354                 "ascii", "us_ascii", "us", "ansi_x3.4_1968",
6355                 "ansi_x3.4_1986", "cp367", "csascii", "ibm367",
6356                 "iso_ir_6", "iso646_us", "iso_646.irv:1991",
6357         (char *) 2,
6358                 "utf_7", "csunicode11utf7", "unicode_1_1_utf_7",
6359                 "unicode_2_0_utf_7", "x_unicode_1_1_utf_7",
6360                 "x_unicode_2_0_utf_7",
6361         (char *) 3,
6362                 "utf_8", "unicode_1_1_utf_8", "unicode_2_0_utf_8",
6363                 "x_unicode_1_1_utf_8", "x_unicode_2_0_utf_8",
6364         (char *) 4,
6365                 "utf_16", "UTF_16LE", "ucs_2", "unicode",
6366                 "iso_10646_ucs2",
6367         (char *) 5,
6368                 "unicodefffe", "utf_16be",
6369         (char *) 6,
6370                 "iso_8859_1",
6371         (char *) 0
6372 };
6373
6374 /*
6375  * Returns the internal codepage, if the value of "int_code_page" is
6376  * 1 at entry, and we can not compute a suitable code page number,
6377  * returns the code page as a string
6378  */
6379 ICALL_EXPORT MonoString*
6380 ves_icall_System_Text_EncodingHelper_InternalCodePage (gint32 *int_code_page) 
6381 {
6382         const char *cset;
6383         const char *p;
6384         char *c;
6385         char *codepage = NULL;
6386         int code;
6387         int want_name = *int_code_page;
6388         int i;
6389         
6390         *int_code_page = -1;
6391
6392         g_get_charset (&cset);
6393         c = codepage = strdup (cset);
6394         for (c = codepage; *c; c++){
6395                 if (isascii (*c) && isalpha (*c))
6396                         *c = tolower (*c);
6397                 if (*c == '-')
6398                         *c = '_';
6399         }
6400         /* g_print ("charset: %s\n", cset); */
6401         
6402         /* handle some common aliases */
6403         p = encodings [0];
6404         code = 0;
6405         for (i = 0; p != 0; ){
6406                 if ((gssize) p < 7){
6407                         code = (gssize) p;
6408                         p = encodings [++i];
6409                         continue;
6410                 }
6411                 if (strcmp (p, codepage) == 0){
6412                         *int_code_page = code;
6413                         break;
6414                 }
6415                 p = encodings [++i];
6416         }
6417         
6418         if (strstr (codepage, "utf_8") != NULL)
6419                 *int_code_page |= 0x10000000;
6420         free (codepage);
6421         
6422         if (want_name && *int_code_page == -1)
6423                 return mono_string_new (mono_domain_get (), cset);
6424         else
6425                 return NULL;
6426 }
6427
6428 ICALL_EXPORT MonoBoolean
6429 ves_icall_System_Environment_get_HasShutdownStarted (void)
6430 {
6431         if (mono_runtime_is_shutting_down ())
6432                 return TRUE;
6433
6434         if (mono_domain_is_unloading (mono_domain_get ()))
6435                 return TRUE;
6436
6437         return FALSE;
6438 }
6439
6440 ICALL_EXPORT void
6441 ves_icall_System_Environment_BroadcastSettingChange (void)
6442 {
6443 #ifdef HOST_WIN32
6444         SendMessageTimeout (HWND_BROADCAST, WM_SETTINGCHANGE, (WPARAM)NULL, (LPARAM)L"Environment", SMTO_ABORTIFHUNG, 2000, 0);
6445 #endif
6446 }
6447
6448 ICALL_EXPORT void
6449 ves_icall_MonoMethodMessage_InitMessage (MonoMethodMessage *this, 
6450                                          MonoReflectionMethod *method,
6451                                          MonoArray *out_args)
6452 {
6453         mono_message_init (mono_object_domain (this), this, method, out_args);
6454 }
6455
6456 #ifndef DISABLE_REMOTING
6457 ICALL_EXPORT MonoBoolean
6458 ves_icall_IsTransparentProxy (MonoObject *proxy)
6459 {
6460         if (!proxy)
6461                 return 0;
6462
6463         if (proxy->vtable->klass == mono_defaults.transparent_proxy_class)
6464                 return 1;
6465
6466         return 0;
6467 }
6468
6469 ICALL_EXPORT MonoReflectionMethod *
6470 ves_icall_Remoting_RemotingServices_GetVirtualMethod (
6471         MonoReflectionType *rtype, MonoReflectionMethod *rmethod)
6472 {
6473         MonoClass *klass;
6474         MonoMethod *method;
6475         MonoMethod **vtable;
6476         MonoMethod *res = NULL;
6477
6478         MONO_CHECK_ARG_NULL (rtype, NULL);
6479         MONO_CHECK_ARG_NULL (rmethod, NULL);
6480
6481         method = rmethod->method;
6482         klass = mono_class_from_mono_type (rtype->type);
6483         mono_class_init_or_throw (klass);
6484
6485         if (MONO_CLASS_IS_INTERFACE (klass))
6486                 return NULL;
6487
6488         if (method->flags & METHOD_ATTRIBUTE_STATIC)
6489                 return NULL;
6490
6491         if ((method->flags & METHOD_ATTRIBUTE_FINAL) || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6492                 if (klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE))
6493                         return rmethod;
6494                 else
6495                         return NULL;
6496         }
6497
6498         mono_class_setup_vtable (klass);
6499         vtable = klass->vtable;
6500
6501         if (method->klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6502                 gboolean variance_used = FALSE;
6503                 /*MS fails with variant interfaces but it's the right thing to do anyway.*/
6504                 int offs = mono_class_interface_offset_with_variance (klass, method->klass, &variance_used);
6505                 if (offs >= 0)
6506                         res = vtable [offs + method->slot];
6507         } else {
6508                 if (!(klass == method->klass || mono_class_is_subclass_of (klass, method->klass, FALSE)))
6509                         return NULL;
6510
6511                 if (method->slot != -1)
6512                         res = vtable [method->slot];
6513         }
6514
6515         if (!res)
6516                 return NULL;
6517
6518         return mono_method_get_object (mono_domain_get (), res, NULL);
6519 }
6520
6521 ICALL_EXPORT void
6522 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionType *type, MonoBoolean enable)
6523 {
6524         MonoClass *klass;
6525         MonoVTable* vtable;
6526
6527         klass = mono_class_from_mono_type (type->type);
6528         vtable = mono_class_vtable_full (mono_domain_get (), klass, TRUE);
6529
6530         mono_vtable_set_is_remote (vtable, enable);
6531 }
6532
6533 #else /* DISABLE_REMOTING */
6534
6535 ICALL_EXPORT void
6536 ves_icall_System_Runtime_Activation_ActivationServices_EnableProxyActivation (MonoReflectionType *type, MonoBoolean enable)
6537 {
6538         g_assert_not_reached ();
6539 }
6540
6541 #endif
6542
6543 ICALL_EXPORT MonoObject *
6544 ves_icall_System_Runtime_Activation_ActivationServices_AllocateUninitializedClassInstance (MonoReflectionType *type)
6545 {
6546         MonoClass *klass;
6547         MonoDomain *domain;
6548         
6549         domain = mono_object_domain (type);
6550         klass = mono_class_from_mono_type (type->type);
6551         mono_class_init_or_throw (klass);
6552
6553         if (MONO_CLASS_IS_INTERFACE (klass) || (klass->flags & TYPE_ATTRIBUTE_ABSTRACT)) {
6554                 mono_set_pending_exception (mono_get_exception_argument ("type", "Type cannot be instantiated"));
6555                 return NULL;
6556         }
6557
6558         if (klass->rank >= 1) {
6559                 g_assert (klass->rank == 1);
6560                 return (MonoObject *) mono_array_new (domain, klass->element_class, 0);
6561         } else {
6562                 /* Bypass remoting object creation check */
6563                 return mono_object_new_alloc_specific (mono_class_vtable_full (domain, klass, TRUE));
6564         }
6565 }
6566
6567 ICALL_EXPORT MonoString *
6568 ves_icall_System_IO_get_temp_path (void)
6569 {
6570         return mono_string_new (mono_domain_get (), g_get_tmp_dir ());
6571 }
6572
6573 #ifndef PLATFORM_NO_DRIVEINFO
6574 ICALL_EXPORT MonoBoolean
6575 ves_icall_System_IO_DriveInfo_GetDiskFreeSpace (MonoString *path_name, guint64 *free_bytes_avail,
6576                                                 guint64 *total_number_of_bytes, guint64 *total_number_of_free_bytes,
6577                                                 gint32 *error)
6578 {
6579         gboolean result;
6580         ULARGE_INTEGER wapi_free_bytes_avail;
6581         ULARGE_INTEGER wapi_total_number_of_bytes;
6582         ULARGE_INTEGER wapi_total_number_of_free_bytes;
6583
6584         *error = ERROR_SUCCESS;
6585         result = GetDiskFreeSpaceEx (mono_string_chars (path_name), &wapi_free_bytes_avail, &wapi_total_number_of_bytes,
6586                                      &wapi_total_number_of_free_bytes);
6587
6588         if (result) {
6589                 *free_bytes_avail = wapi_free_bytes_avail.QuadPart;
6590                 *total_number_of_bytes = wapi_total_number_of_bytes.QuadPart;
6591                 *total_number_of_free_bytes = wapi_total_number_of_free_bytes.QuadPart;
6592         } else {
6593                 *free_bytes_avail = 0;
6594                 *total_number_of_bytes = 0;
6595                 *total_number_of_free_bytes = 0;
6596                 *error = GetLastError ();
6597         }
6598
6599         return result;
6600 }
6601
6602 ICALL_EXPORT guint32
6603 ves_icall_System_IO_DriveInfo_GetDriveType (MonoString *root_path_name)
6604 {
6605         return GetDriveType (mono_string_chars (root_path_name));
6606 }
6607 #endif
6608
6609 ICALL_EXPORT gpointer
6610 ves_icall_RuntimeMethod_GetFunctionPointer (MonoMethod *method)
6611 {
6612         return mono_compile_method (method);
6613 }
6614
6615 ICALL_EXPORT MonoString *
6616 ves_icall_System_Configuration_DefaultConfig_get_machine_config_path (void)
6617 {
6618         MonoString *mcpath;
6619         gchar *path;
6620
6621         path = g_build_path (G_DIR_SEPARATOR_S, mono_get_config_dir (), "mono", mono_get_runtime_info ()->framework_version, "machine.config", NULL);
6622
6623 #if defined (HOST_WIN32)
6624         /* Avoid mixing '/' and '\\' */
6625         {
6626                 gint i;
6627                 for (i = strlen (path) - 1; i >= 0; i--)
6628                         if (path [i] == '/')
6629                                 path [i] = '\\';
6630         }
6631 #endif
6632         mcpath = mono_string_new (mono_domain_get (), path);
6633         g_free (path);
6634
6635         return mcpath;
6636 }
6637
6638 static MonoString *
6639 get_bundled_app_config (void)
6640 {
6641         const gchar *app_config;
6642         MonoDomain *domain;
6643         MonoString *file;
6644         gchar *config_file_name, *config_file_path;
6645         gsize len;
6646         gchar *module;
6647
6648         domain = mono_domain_get ();
6649         file = domain->setup->configuration_file;
6650         if (!file)
6651                 return NULL;
6652
6653         // Retrieve config file and remove the extension
6654         config_file_name = mono_string_to_utf8 (file);
6655         config_file_path = mono_portability_find_file (config_file_name, TRUE);
6656         if (!config_file_path)
6657                 config_file_path = config_file_name;
6658         len = strlen (config_file_path) - strlen (".config");
6659         module = g_malloc0 (len + 1);
6660         memcpy (module, config_file_path, len);
6661         // Get the config file from the module name
6662         app_config = mono_config_string_for_assembly_file (module);
6663         // Clean-up
6664         g_free (module);
6665         if (config_file_name != config_file_path)
6666                 g_free (config_file_name);
6667         g_free (config_file_path);
6668
6669         if (!app_config)
6670                 return NULL;
6671
6672         return mono_string_new (mono_domain_get (), app_config);
6673 }
6674
6675 static MonoString *
6676 get_bundled_machine_config (void)
6677 {
6678         const gchar *machine_config;
6679
6680         machine_config = mono_get_machine_config ();
6681
6682         if (!machine_config)
6683                 return NULL;
6684
6685         return mono_string_new (mono_domain_get (), machine_config);
6686 }
6687
6688 ICALL_EXPORT MonoString *
6689 ves_icall_System_Web_Util_ICalls_get_machine_install_dir (void)
6690 {
6691         MonoString *ipath;
6692         gchar *path;
6693
6694         path = g_path_get_dirname (mono_get_config_dir ());
6695
6696 #if defined (HOST_WIN32)
6697         /* Avoid mixing '/' and '\\' */
6698         {
6699                 gint i;
6700                 for (i = strlen (path) - 1; i >= 0; i--)
6701                         if (path [i] == '/')
6702                                 path [i] = '\\';
6703         }
6704 #endif
6705         ipath = mono_string_new (mono_domain_get (), path);
6706         g_free (path);
6707
6708         return ipath;
6709 }
6710
6711 ICALL_EXPORT gboolean
6712 ves_icall_get_resources_ptr (MonoReflectionAssembly *assembly, gpointer *result, gint32 *size)
6713 {
6714         MonoPEResourceDataEntry *entry;
6715         MonoImage *image;
6716
6717         if (!assembly || !result || !size)
6718                 return FALSE;
6719
6720         *result = NULL;
6721         *size = 0;
6722         image = assembly->assembly->image;
6723         entry = mono_image_lookup_resource (image, MONO_PE_RESOURCE_ID_ASPNET_STRING, 0, NULL);
6724         if (!entry)
6725                 return FALSE;
6726
6727         *result = mono_image_rva_map (image, entry->rde_data_offset);
6728         if (!(*result)) {
6729                 g_free (entry);
6730                 return FALSE;
6731         }
6732         *size = entry->rde_size;
6733         g_free (entry);
6734         return TRUE;
6735 }
6736
6737 ICALL_EXPORT MonoBoolean
6738 ves_icall_System_Diagnostics_Debugger_IsAttached_internal (void)
6739 {
6740         return mono_is_debugger_attached ();
6741 }
6742
6743 ICALL_EXPORT MonoBoolean
6744 ves_icall_System_Diagnostics_Debugger_IsLogging (void)
6745 {
6746         if (mono_get_runtime_callbacks ()->debug_log_is_enabled)
6747                 return mono_get_runtime_callbacks ()->debug_log_is_enabled ();
6748         else
6749                 return FALSE;
6750 }
6751
6752 ICALL_EXPORT void
6753 ves_icall_System_Diagnostics_Debugger_Log (int level, MonoString *category, MonoString *message)
6754 {
6755         if (mono_get_runtime_callbacks ()->debug_log)
6756                 mono_get_runtime_callbacks ()->debug_log (level, category, message);
6757 }
6758
6759 ICALL_EXPORT void
6760 ves_icall_System_Diagnostics_DefaultTraceListener_WriteWindowsDebugString (MonoString *message)
6761 {
6762 #if defined (HOST_WIN32)
6763         OutputDebugString (mono_string_chars (message));
6764 #else
6765         g_warning ("WriteWindowsDebugString called and HOST_WIN32 not defined!\n");
6766 #endif
6767 }
6768
6769 /* Only used for value types */
6770 ICALL_EXPORT MonoObject *
6771 ves_icall_System_Activator_CreateInstanceInternal (MonoReflectionType *type)
6772 {
6773         MonoClass *klass;
6774         MonoDomain *domain;
6775         
6776         domain = mono_object_domain (type);
6777         klass = mono_class_from_mono_type (type->type);
6778         mono_class_init_or_throw (klass);
6779
6780         if (mono_class_is_nullable (klass))
6781                 /* No arguments -> null */
6782                 return NULL;
6783
6784         return mono_object_new (domain, klass);
6785 }
6786
6787 ICALL_EXPORT MonoReflectionMethod *
6788 ves_icall_MonoMethod_get_base_method (MonoReflectionMethod *m, gboolean definition)
6789 {
6790         MonoClass *klass, *parent;
6791         MonoMethod *method = m->method;
6792         MonoMethod *result = NULL;
6793         int slot;
6794
6795         if (method->klass == NULL)
6796                 return m;
6797
6798         if (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
6799             MONO_CLASS_IS_INTERFACE (method->klass) ||
6800             method->flags & METHOD_ATTRIBUTE_NEW_SLOT)
6801                 return m;
6802
6803         slot = mono_method_get_vtable_slot (method);
6804         if (slot == -1)
6805                 return m;
6806
6807         klass = method->klass;
6808         if (klass->generic_class)
6809                 klass = klass->generic_class->container_class;
6810
6811         if (definition) {
6812                 /* At the end of the loop, klass points to the eldest class that has this virtual function slot. */
6813                 for (parent = klass->parent; parent != NULL; parent = parent->parent) {
6814                         mono_class_setup_vtable (parent);
6815                         if (parent->vtable_size <= slot)
6816                                 break;
6817                         klass = parent;
6818                 }
6819         } else {
6820                 klass = klass->parent;
6821                 if (!klass)
6822                         return m;
6823         }
6824
6825         if (klass == method->klass)
6826                 return m;
6827
6828         /*This is possible if definition == FALSE.
6829          * Do it here to be really sure we don't read invalid memory.
6830          */
6831         if (slot >= klass->vtable_size)
6832                 return m;
6833
6834         mono_class_setup_vtable (klass);
6835
6836         result = klass->vtable [slot];
6837         if (result == NULL) {
6838                 /* It is an abstract method */
6839                 gpointer iter = NULL;
6840                 while ((result = mono_class_get_methods (klass, &iter)))
6841                         if (result->slot == slot)
6842                                 break;
6843         }
6844
6845         if (result == NULL)
6846                 return m;
6847
6848         return mono_method_get_object (mono_domain_get (), result, NULL);
6849 }
6850
6851 ICALL_EXPORT MonoString*
6852 ves_icall_MonoMethod_get_name (MonoReflectionMethod *m)
6853 {
6854         MonoMethod *method = m->method;
6855
6856         MONO_OBJECT_SETREF (m, name, mono_string_new (mono_object_domain (m), method->name));
6857         return m->name;
6858 }
6859
6860 ICALL_EXPORT void
6861 mono_ArgIterator_Setup (MonoArgIterator *iter, char* argsp, char* start)
6862 {
6863         iter->sig = *(MonoMethodSignature**)argsp;
6864         
6865         g_assert (iter->sig->sentinelpos <= iter->sig->param_count);
6866         g_assert (iter->sig->call_convention == MONO_CALL_VARARG);
6867
6868         iter->next_arg = 0;
6869         /* FIXME: it's not documented what start is exactly... */
6870         if (start) {
6871                 iter->args = start;
6872         } else {
6873                 iter->args = argsp + sizeof (gpointer);
6874         }
6875         iter->num_args = iter->sig->param_count - iter->sig->sentinelpos;
6876
6877         /* g_print ("sig %p, param_count: %d, sent: %d\n", iter->sig, iter->sig->param_count, iter->sig->sentinelpos); */
6878 }
6879
6880 ICALL_EXPORT MonoTypedRef
6881 mono_ArgIterator_IntGetNextArg (MonoArgIterator *iter)
6882 {
6883         guint32 i, arg_size;
6884         gint32 align;
6885         MonoTypedRef res;
6886
6887         i = iter->sig->sentinelpos + iter->next_arg;
6888
6889         g_assert (i < iter->sig->param_count);
6890
6891         res.type = iter->sig->params [i];
6892         res.klass = mono_class_from_mono_type (res.type);
6893         arg_size = mono_type_stack_size (res.type, &align);
6894 #if defined(__arm__) || defined(__mips__)
6895         iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
6896 #endif
6897         res.value = iter->args;
6898 #if defined(__native_client__) && SIZEOF_REGISTER == 8
6899         /* Values are stored as 8 byte register sized objects, but 'value'
6900          * is dereferenced as a pointer in other routines.
6901          */
6902         res.value = (char*)res.value + 4;
6903 #endif
6904 #if G_BYTE_ORDER != G_LITTLE_ENDIAN
6905         if (arg_size <= sizeof (gpointer)) {
6906                 int dummy;
6907                 int padding = arg_size - mono_type_size (res.type, &dummy);
6908                 res.value = (guint8*)res.value + padding;
6909         }
6910 #endif
6911         iter->args = (char*)iter->args + arg_size;
6912         iter->next_arg++;
6913
6914         /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
6915
6916         return res;
6917 }
6918
6919 ICALL_EXPORT MonoTypedRef
6920 mono_ArgIterator_IntGetNextArgT (MonoArgIterator *iter, MonoType *type)
6921 {
6922         guint32 i, arg_size;
6923         gint32 align;
6924         MonoTypedRef res;
6925
6926         i = iter->sig->sentinelpos + iter->next_arg;
6927
6928         g_assert (i < iter->sig->param_count);
6929
6930         while (i < iter->sig->param_count) {
6931                 if (!mono_metadata_type_equal (type, iter->sig->params [i]))
6932                         continue;
6933                 res.type = iter->sig->params [i];
6934                 res.klass = mono_class_from_mono_type (res.type);
6935                 /* FIXME: endianess issue... */
6936                 arg_size = mono_type_stack_size (res.type, &align);
6937 #if defined(__arm__) || defined(__mips__)
6938                 iter->args = (guint8*)(((gsize)iter->args + (align) - 1) & ~(align - 1));
6939 #endif
6940                 res.value = iter->args;
6941                 iter->args = (char*)iter->args + arg_size;
6942                 iter->next_arg++;
6943                 /* g_print ("returning arg %d, type 0x%02x of size %d at %p\n", i, res.type->type, arg_size, res.value); */
6944                 return res;
6945         }
6946         /* g_print ("arg type 0x%02x not found\n", res.type->type); */
6947
6948         res.type = NULL;
6949         res.value = NULL;
6950         res.klass = NULL;
6951         return res;
6952 }
6953
6954 ICALL_EXPORT MonoType*
6955 mono_ArgIterator_IntGetNextArgType (MonoArgIterator *iter)
6956 {
6957         gint i;
6958         
6959         i = iter->sig->sentinelpos + iter->next_arg;
6960
6961         g_assert (i < iter->sig->param_count);
6962
6963         return iter->sig->params [i];
6964 }
6965
6966 ICALL_EXPORT MonoObject*
6967 mono_TypedReference_ToObject (MonoTypedRef tref)
6968 {
6969         if (MONO_TYPE_IS_REFERENCE (tref.type)) {
6970                 MonoObject** objp = tref.value;
6971                 return *objp;
6972         }
6973
6974         return mono_value_box (mono_domain_get (), tref.klass, tref.value);
6975 }
6976
6977 ICALL_EXPORT MonoObject*
6978 mono_TypedReference_ToObjectInternal (MonoType *type, gpointer value, MonoClass *klass)
6979 {
6980         if (MONO_TYPE_IS_REFERENCE (type)) {
6981                 MonoObject** objp = value;
6982                 return *objp;
6983         }
6984
6985         return mono_value_box (mono_domain_get (), klass, value);
6986 }
6987
6988 static void
6989 prelink_method (MonoMethod *method)
6990 {
6991         const char *exc_class, *exc_arg;
6992         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
6993                 return;
6994         mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
6995         if (exc_class) {
6996                 mono_raise_exception( 
6997                         mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg ) );
6998         }
6999         /* create the wrapper, too? */
7000 }
7001
7002 ICALL_EXPORT void
7003 ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethod *method)
7004 {
7005         prelink_method (method->method);
7006 }
7007
7008 ICALL_EXPORT void
7009 ves_icall_System_Runtime_InteropServices_Marshal_PrelinkAll (MonoReflectionType *type)
7010 {
7011         MonoClass *klass = mono_class_from_mono_type (type->type);
7012         MonoMethod* m;
7013         gpointer iter = NULL;
7014
7015         mono_class_init_or_throw (klass);
7016
7017         while ((m = mono_class_get_methods (klass, &iter)))
7018                 prelink_method (m);
7019 }
7020
7021 /* These parameters are "readonly" in corlib/System/NumberFormatter.cs */
7022 ICALL_EXPORT void
7023 ves_icall_System_NumberFormatter_GetFormatterTables (guint64 const **mantissas,
7024                                             gint32 const **exponents,
7025                                             gunichar2 const **digitLowerTable,
7026                                             gunichar2 const **digitUpperTable,
7027                                             gint64 const **tenPowersList,
7028                                             gint32 const **decHexDigits)
7029 {
7030         *mantissas = Formatter_MantissaBitsTable;
7031         *exponents = Formatter_TensExponentTable;
7032         *digitLowerTable = Formatter_DigitLowerTable;
7033         *digitUpperTable = Formatter_DigitUpperTable;
7034         *tenPowersList = Formatter_TenPowersList;
7035         *decHexDigits = Formatter_DecHexDigits;
7036 }
7037
7038 /* These parameters are "readonly" in corlib/System/Globalization/TextInfo.cs */
7039 ICALL_EXPORT void
7040 ves_icall_System_Globalization_TextInfo_GetDataTablePointersLite (
7041                                             guint16 const **to_lower_data_low,
7042                                             guint16 const **to_lower_data_high,
7043                                             guint16 const **to_upper_data_low,
7044                                             guint16 const **to_upper_data_high)
7045 {
7046         *to_lower_data_low = ToLowerDataLow;
7047         *to_lower_data_high = ToLowerDataHigh;
7048         *to_upper_data_low = ToUpperDataLow;
7049         *to_upper_data_high = ToUpperDataHigh;
7050 }
7051
7052 /*
7053  * We return NULL for no modifiers so the corlib code can return Type.EmptyTypes
7054  * and avoid useless allocations.
7055  * 
7056  * MAY THROW
7057  */
7058 static MonoArray*
7059 type_array_from_modifiers (MonoImage *image, MonoType *type, int optional)
7060 {
7061         MonoArray *res;
7062         int i, count = 0;
7063         for (i = 0; i < type->num_mods; ++i) {
7064                 if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required))
7065                         count++;
7066         }
7067         if (!count)
7068                 return NULL;
7069         res = mono_array_new (mono_domain_get (), mono_defaults.systemtype_class, count);
7070         count = 0;
7071         for (i = 0; i < type->num_mods; ++i) {
7072                 if ((optional && !type->modifiers [i].required) || (!optional && type->modifiers [i].required)) {
7073                         MonoError error;
7074                         MonoClass *klass = mono_class_get_checked (image, type->modifiers [i].token, &error);
7075                         mono_error_raise_exception (&error); /* this is safe, no cleanup needed on callers */ 
7076                         mono_array_setref (res, count, mono_type_get_object (mono_domain_get (), &klass->byval_arg));
7077                         count++;
7078                 }
7079         }
7080         return res;
7081 }
7082
7083 ICALL_EXPORT MonoArray*
7084 param_info_get_type_modifiers (MonoReflectionParameter *param, MonoBoolean optional)
7085 {
7086         MonoType *type = param->ClassImpl->type;
7087         MonoClass *member_class = mono_object_class (param->MemberImpl);
7088         MonoMethod *method = NULL;
7089         MonoImage *image;
7090         int pos;
7091         MonoMethodSignature *sig;
7092
7093         if (mono_class_is_reflection_method_or_constructor (member_class)) {
7094                 MonoReflectionMethod *rmethod = (MonoReflectionMethod*)param->MemberImpl;
7095                 method = rmethod->method;
7096         } else if (member_class->image == mono_defaults.corlib && !strcmp ("MonoProperty", member_class->name)) {
7097                 MonoReflectionProperty *prop = (MonoReflectionProperty *)param->MemberImpl;
7098                 if (!(method = prop->property->get))
7099                         method = prop->property->set;
7100                 g_assert (method);      
7101         } else {
7102                 char *type_name = mono_type_get_full_name (member_class);
7103                 char *msg = g_strdup_printf ("Custom modifiers on a ParamInfo with member %s are not supported", type_name);
7104                 MonoException *ex = mono_get_exception_not_supported  (msg);
7105                 g_free (type_name);
7106                 g_free (msg);
7107                 mono_set_pending_exception (ex);
7108                 return NULL;
7109         }
7110
7111         image = method->klass->image;
7112         pos = param->PositionImpl;
7113         sig = mono_method_signature (method);
7114         if (pos == -1)
7115                 type = sig->ret;
7116         else
7117                 type = sig->params [pos];
7118
7119         return type_array_from_modifiers (image, type, optional);
7120 }
7121
7122 static MonoType*
7123 get_property_type (MonoProperty *prop)
7124 {
7125         MonoMethodSignature *sig;
7126         if (prop->get) {
7127                 sig = mono_method_signature (prop->get);
7128                 return sig->ret;
7129         } else if (prop->set) {
7130                 sig = mono_method_signature (prop->set);
7131                 return sig->params [sig->param_count - 1];
7132         }
7133         return NULL;
7134 }
7135
7136 ICALL_EXPORT MonoArray*
7137 property_info_get_type_modifiers (MonoReflectionProperty *property, MonoBoolean optional)
7138 {
7139         MonoType *type = get_property_type (property->property);
7140         MonoImage *image = property->klass->image;
7141
7142         if (!type)
7143                 return NULL;
7144         return type_array_from_modifiers (image, type, optional);
7145 }
7146
7147 /*
7148  *Construct a MonoType suited to be used to decode a constant blob object.
7149  *
7150  * @type is the target type which will be constructed
7151  * @blob_type is the blob type, for example, that comes from the constant table
7152  * @real_type is the expected constructed type.
7153  */
7154 static void
7155 mono_type_from_blob_type (MonoType *type, MonoTypeEnum blob_type, MonoType *real_type)
7156 {
7157         type->type = blob_type;
7158         type->data.klass = NULL;
7159         if (blob_type == MONO_TYPE_CLASS)
7160                 type->data.klass = mono_defaults.object_class;
7161         else if (real_type->type == MONO_TYPE_VALUETYPE && real_type->data.klass->enumtype) {
7162                 /* For enums, we need to use the base type */
7163                 type->type = MONO_TYPE_VALUETYPE;
7164                 type->data.klass = mono_class_from_mono_type (real_type);
7165         } else
7166                 type->data.klass = mono_class_from_mono_type (real_type);
7167 }
7168
7169 ICALL_EXPORT MonoObject*
7170 property_info_get_default_value (MonoReflectionProperty *property)
7171 {
7172         MonoType blob_type;
7173         MonoProperty *prop = property->property;
7174         MonoType *type = get_property_type (prop);
7175         MonoDomain *domain = mono_object_domain (property); 
7176         MonoTypeEnum def_type;
7177         const char *def_value;
7178         MonoObject *o;
7179
7180         mono_class_init (prop->parent);
7181
7182         if (!(prop->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT)) {
7183                 mono_set_pending_exception (mono_get_exception_invalid_operation (NULL));
7184                 return NULL;
7185         }
7186
7187         def_value = mono_class_get_property_default_value (prop, &def_type);
7188
7189         mono_type_from_blob_type (&blob_type, def_type, type);
7190         o = mono_get_object_from_blob (domain, &blob_type, def_value);
7191
7192         return o;
7193 }
7194
7195 ICALL_EXPORT MonoBoolean
7196 custom_attrs_defined_internal (MonoObject *obj, MonoReflectionType *attr_type)
7197 {
7198         MonoClass *attr_class = mono_class_from_mono_type (attr_type->type);
7199         MonoCustomAttrInfo *cinfo;
7200         gboolean found;
7201
7202         mono_class_init_or_throw (attr_class);
7203
7204         cinfo = mono_reflection_get_custom_attrs_info (obj);
7205         if (!cinfo)
7206                 return FALSE;
7207         found = mono_custom_attrs_has_attr (cinfo, attr_class);
7208         if (!cinfo->cached)
7209                 mono_custom_attrs_free (cinfo);
7210         return found;
7211 }
7212
7213 ICALL_EXPORT MonoArray*
7214 custom_attrs_get_by_type (MonoObject *obj, MonoReflectionType *attr_type)
7215 {
7216         MonoClass *attr_class = attr_type ? mono_class_from_mono_type (attr_type->type) : NULL;
7217         MonoArray *res;
7218         MonoError error;
7219
7220         if (attr_class)
7221                 mono_class_init_or_throw (attr_class);
7222
7223         res = mono_reflection_get_custom_attrs_by_type (obj, attr_class, &error);
7224         mono_error_raise_exception (&error);
7225
7226         if (mono_loader_get_last_error ()) {
7227                 mono_set_pending_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
7228                 return NULL;
7229         } else {
7230                 return res;
7231         }
7232 }
7233
7234 ICALL_EXPORT MonoString*
7235 ves_icall_Mono_Runtime_GetDisplayName (void)
7236 {
7237         char *info;
7238         MonoString *display_name;
7239
7240         info = mono_get_runtime_callbacks ()->get_runtime_build_info ();
7241         display_name = mono_string_new (mono_domain_get (), info);
7242         g_free (info);
7243         return display_name;
7244 }
7245
7246 ICALL_EXPORT MonoString*
7247 ves_icall_System_ComponentModel_Win32Exception_W32ErrorMessage (guint32 code)
7248 {
7249         MonoString *message;
7250         guint32 ret;
7251         gunichar2 buf[256];
7252         
7253         ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
7254                              FORMAT_MESSAGE_IGNORE_INSERTS, NULL, code, 0,
7255                              buf, 255, NULL);
7256         if (ret == 0) {
7257                 message = mono_string_new (mono_domain_get (), "Error looking up error string");
7258         } else {
7259                 message = mono_string_new_utf16 (mono_domain_get (), buf, ret);
7260         }
7261         
7262         return message;
7263 }
7264
7265 ICALL_EXPORT int
7266 ves_icall_System_StackFrame_GetILOffsetFromFile (MonoString *path, int methodToken, int nativeOffset)
7267 {
7268         guint32 il_offset;
7269         char *path_str = mono_string_to_utf8 (path);
7270
7271         if (!seq_point_data_get_il_offset (path_str, methodToken, nativeOffset, &il_offset))
7272                 il_offset = -1;
7273
7274         g_free (path_str);
7275
7276         return il_offset;
7277 }
7278
7279 #ifndef DISABLE_ICALL_TABLES
7280
7281 #define ICALL_TYPE(id,name,first)
7282 #define ICALL(id,name,func) Icall_ ## id,
7283
7284 enum {
7285 #include "metadata/icall-def.h"
7286         Icall_last
7287 };
7288
7289 #undef ICALL_TYPE
7290 #undef ICALL
7291 #define ICALL_TYPE(id,name,first) Icall_type_ ## id,
7292 #define ICALL(id,name,func)
7293 enum {
7294 #include "metadata/icall-def.h"
7295         Icall_type_num
7296 };
7297
7298 #undef ICALL_TYPE
7299 #undef ICALL
7300 #define ICALL_TYPE(id,name,firstic) {(Icall_ ## firstic)},
7301 #define ICALL(id,name,func)
7302 typedef struct {
7303         guint16 first_icall;
7304 } IcallTypeDesc;
7305
7306 static const IcallTypeDesc
7307 icall_type_descs [] = {
7308 #include "metadata/icall-def.h"
7309         {Icall_last}
7310 };
7311
7312 #define icall_desc_num_icalls(desc) ((desc) [1].first_icall - (desc) [0].first_icall)
7313
7314 #undef ICALL_TYPE
7315 #define ICALL_TYPE(id,name,first)
7316 #undef ICALL
7317
7318 #ifdef HAVE_ARRAY_ELEM_INIT
7319 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
7320 #define MSGSTRFIELD1(line) str##line
7321
7322 static const struct msgstrtn_t {
7323 #define ICALL(id,name,func)
7324 #undef ICALL_TYPE
7325 #define ICALL_TYPE(id,name,first) char MSGSTRFIELD(__LINE__) [sizeof (name)];
7326 #include "metadata/icall-def.h"
7327 #undef ICALL_TYPE
7328 } icall_type_names_str = {
7329 #define ICALL_TYPE(id,name,first) (name),
7330 #include "metadata/icall-def.h"
7331 #undef ICALL_TYPE
7332 };
7333 static const guint16 icall_type_names_idx [] = {
7334 #define ICALL_TYPE(id,name,first) [Icall_type_ ## id] = offsetof (struct msgstrtn_t, MSGSTRFIELD(__LINE__)),
7335 #include "metadata/icall-def.h"
7336 #undef ICALL_TYPE
7337 };
7338 #define icall_type_name_get(id) ((const char*)&icall_type_names_str + icall_type_names_idx [(id)])
7339
7340 static const struct msgstr_t {
7341 #undef ICALL
7342 #define ICALL_TYPE(id,name,first)
7343 #define ICALL(id,name,func) char MSGSTRFIELD(__LINE__) [sizeof (name)];
7344 #include "metadata/icall-def.h"
7345 #undef ICALL
7346 } icall_names_str = {
7347 #define ICALL(id,name,func) (name),
7348 #include "metadata/icall-def.h"
7349 #undef ICALL
7350 };
7351 static const guint16 icall_names_idx [] = {
7352 #define ICALL(id,name,func) [Icall_ ## id] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
7353 #include "metadata/icall-def.h"
7354 #undef ICALL
7355 };
7356 #define icall_name_get(id) ((const char*)&icall_names_str + icall_names_idx [(id)])
7357
7358 #else
7359
7360 #undef ICALL_TYPE
7361 #undef ICALL
7362 #define ICALL_TYPE(id,name,first) name,
7363 #define ICALL(id,name,func)
7364 static const char* const
7365 icall_type_names [] = {
7366 #include "metadata/icall-def.h"
7367         NULL
7368 };
7369
7370 #define icall_type_name_get(id) (icall_type_names [(id)])
7371
7372 #undef ICALL_TYPE
7373 #undef ICALL
7374 #define ICALL_TYPE(id,name,first)
7375 #define ICALL(id,name,func) name,
7376 static const char* const
7377 icall_names [] = {
7378 #include "metadata/icall-def.h"
7379         NULL
7380 };
7381 #define icall_name_get(id) icall_names [(id)]
7382
7383 #endif /* !HAVE_ARRAY_ELEM_INIT */
7384
7385 #undef ICALL_TYPE
7386 #undef ICALL
7387 #define ICALL_TYPE(id,name,first)
7388 #define ICALL(id,name,func) func,
7389 static const gconstpointer
7390 icall_functions [] = {
7391 #include "metadata/icall-def.h"
7392         NULL
7393 };
7394
7395 #ifdef ENABLE_ICALL_SYMBOL_MAP
7396 #undef ICALL_TYPE
7397 #undef ICALL
7398 #define ICALL_TYPE(id,name,first)
7399 #define ICALL(id,name,func) #func,
7400 static const gconstpointer
7401 icall_symbols [] = {
7402 #include "metadata/icall-def.h"
7403         NULL
7404 };
7405 #endif
7406
7407 #endif /* DISABLE_ICALL_TABLES */
7408
7409 static mono_mutex_t icall_mutex;
7410 static GHashTable *icall_hash = NULL;
7411 static GHashTable *jit_icall_hash_name = NULL;
7412 static GHashTable *jit_icall_hash_addr = NULL;
7413
7414 void
7415 mono_icall_init (void)
7416 {
7417 #ifndef DISABLE_ICALL_TABLES
7418         int i = 0;
7419
7420         /* check that tables are sorted: disable in release */
7421         if (TRUE) {
7422                 int j;
7423                 const char *prev_class = NULL;
7424                 const char *prev_method;
7425                 
7426                 for (i = 0; i < Icall_type_num; ++i) {
7427                         const IcallTypeDesc *desc;
7428                         int num_icalls;
7429                         prev_method = NULL;
7430                         if (prev_class && strcmp (prev_class, icall_type_name_get (i)) >= 0)
7431                                 g_print ("class %s should come before class %s\n", icall_type_name_get (i), prev_class);
7432                         prev_class = icall_type_name_get (i);
7433                         desc = &icall_type_descs [i];
7434                         num_icalls = icall_desc_num_icalls (desc);
7435                         /*g_print ("class %s has %d icalls starting at %d\n", prev_class, num_icalls, desc->first_icall);*/
7436                         for (j = 0; j < num_icalls; ++j) {
7437                                 const char *methodn = icall_name_get (desc->first_icall + j);
7438                                 if (prev_method && strcmp (prev_method, methodn) >= 0)
7439                                         g_print ("method %s should come before method %s\n", methodn, prev_method);
7440                                 prev_method = methodn;
7441                         }
7442                 }
7443         }
7444 #endif
7445
7446         icall_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7447         mono_mutex_init (&icall_mutex);
7448 }
7449
7450 static void
7451 mono_icall_lock (void)
7452 {
7453         mono_locks_mutex_acquire (&icall_mutex, IcallLock);
7454 }
7455
7456 static void
7457 mono_icall_unlock (void)
7458 {
7459         mono_locks_mutex_release (&icall_mutex, IcallLock);
7460 }
7461
7462 void
7463 mono_icall_cleanup (void)
7464 {
7465         g_hash_table_destroy (icall_hash);
7466         g_hash_table_destroy (jit_icall_hash_name);
7467         g_hash_table_destroy (jit_icall_hash_addr);
7468         mono_mutex_destroy (&icall_mutex);
7469 }
7470
7471 void
7472 mono_add_internal_call (const char *name, gconstpointer method)
7473 {
7474         mono_icall_lock ();
7475
7476         g_hash_table_insert (icall_hash, g_strdup (name), (gpointer) method);
7477
7478         mono_icall_unlock ();
7479 }
7480
7481 #ifndef DISABLE_ICALL_TABLES
7482
7483 #ifdef HAVE_ARRAY_ELEM_INIT
7484 static int
7485 compare_method_imap (const void *key, const void *elem)
7486 {
7487         const char* method_name = (const char*)&icall_names_str + (*(guint16*)elem);
7488         return strcmp (key, method_name);
7489 }
7490
7491 static gpointer
7492 find_method_icall (const IcallTypeDesc *imap, const char *name)
7493 {
7494         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);
7495         if (!nameslot)
7496                 return NULL;
7497         return (gpointer)icall_functions [(nameslot - &icall_names_idx [0])];
7498 }
7499
7500 static int
7501 compare_class_imap (const void *key, const void *elem)
7502 {
7503         const char* class_name = (const char*)&icall_type_names_str + (*(guint16*)elem);
7504         return strcmp (key, class_name);
7505 }
7506
7507 static const IcallTypeDesc*
7508 find_class_icalls (const char *name)
7509 {
7510         const guint16 *nameslot = mono_binary_search (name, icall_type_names_idx, Icall_type_num, sizeof (icall_type_names_idx [0]), compare_class_imap);
7511         if (!nameslot)
7512                 return NULL;
7513         return &icall_type_descs [nameslot - &icall_type_names_idx [0]];
7514 }
7515
7516 #else /* HAVE_ARRAY_ELEM_INIT */
7517
7518 static int
7519 compare_method_imap (const void *key, const void *elem)
7520 {
7521         const char** method_name = (const char**)elem;
7522         return strcmp (key, *method_name);
7523 }
7524
7525 static gpointer
7526 find_method_icall (const IcallTypeDesc *imap, const char *name)
7527 {
7528         const char **nameslot = mono_binary_search (name, icall_names + imap->first_icall, icall_desc_num_icalls (imap), sizeof (icall_names [0]), compare_method_imap);
7529         if (!nameslot)
7530                 return NULL;
7531         return (gpointer)icall_functions [(nameslot - icall_names)];
7532 }
7533
7534 static int
7535 compare_class_imap (const void *key, const void *elem)
7536 {
7537         const char** class_name = (const char**)elem;
7538         return strcmp (key, *class_name);
7539 }
7540
7541 static const IcallTypeDesc*
7542 find_class_icalls (const char *name)
7543 {
7544         const char **nameslot = mono_binary_search (name, icall_type_names, Icall_type_num, sizeof (icall_type_names [0]), compare_class_imap);
7545         if (!nameslot)
7546                 return NULL;
7547         return &icall_type_descs [nameslot - icall_type_names];
7548 }
7549
7550 #endif /* HAVE_ARRAY_ELEM_INIT */
7551
7552 #endif /* DISABLE_ICALL_TABLES */
7553
7554 /* 
7555  * we should probably export this as an helper (handle nested types).
7556  * Returns the number of chars written in buf.
7557  */
7558 static int
7559 concat_class_name (char *buf, int bufsize, MonoClass *klass)
7560 {
7561         int nspacelen, cnamelen;
7562         nspacelen = strlen (klass->name_space);
7563         cnamelen = strlen (klass->name);
7564         if (nspacelen + cnamelen + 2 > bufsize)
7565                 return 0;
7566         if (nspacelen) {
7567                 memcpy (buf, klass->name_space, nspacelen);
7568                 buf [nspacelen ++] = '.';
7569         }
7570         memcpy (buf + nspacelen, klass->name, cnamelen);
7571         buf [nspacelen + cnamelen] = 0;
7572         return nspacelen + cnamelen;
7573 }
7574
7575 #ifdef DISABLE_ICALL_TABLES
7576 static void
7577 no_icall_table (void)
7578 {
7579         g_assert_not_reached ();
7580 }
7581 #endif
7582
7583 gpointer
7584 mono_lookup_internal_call (MonoMethod *method)
7585 {
7586         char *sigstart;
7587         char *tmpsig;
7588         char mname [2048];
7589         int typelen = 0, mlen, siglen;
7590         gpointer res;
7591 #ifndef DISABLE_ICALL_TABLES
7592         const IcallTypeDesc *imap = NULL;
7593 #endif
7594
7595         g_assert (method != NULL);
7596
7597         if (method->is_inflated)
7598                 method = ((MonoMethodInflated *) method)->declaring;
7599
7600         if (method->klass->nested_in) {
7601                 int pos = concat_class_name (mname, sizeof (mname)-2, method->klass->nested_in);
7602                 if (!pos)
7603                         return NULL;
7604
7605                 mname [pos++] = '/';
7606                 mname [pos] = 0;
7607
7608                 typelen = concat_class_name (mname+pos, sizeof (mname)-pos-1, method->klass);
7609                 if (!typelen)
7610                         return NULL;
7611
7612                 typelen += pos;
7613         } else {
7614                 typelen = concat_class_name (mname, sizeof (mname), method->klass);
7615                 if (!typelen)
7616                         return NULL;
7617         }
7618
7619 #ifndef DISABLE_ICALL_TABLES
7620         imap = find_class_icalls (mname);
7621 #endif
7622
7623         mname [typelen] = ':';
7624         mname [typelen + 1] = ':';
7625
7626         mlen = strlen (method->name);
7627         memcpy (mname + typelen + 2, method->name, mlen);
7628         sigstart = mname + typelen + 2 + mlen;
7629         *sigstart = 0;
7630
7631         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
7632         siglen = strlen (tmpsig);
7633         if (typelen + mlen + siglen + 6 > sizeof (mname))
7634                 return NULL;
7635         sigstart [0] = '(';
7636         memcpy (sigstart + 1, tmpsig, siglen);
7637         sigstart [siglen + 1] = ')';
7638         sigstart [siglen + 2] = 0;
7639         g_free (tmpsig);
7640         
7641         mono_icall_lock ();
7642
7643         res = g_hash_table_lookup (icall_hash, mname);
7644         if (res) {
7645                 mono_icall_unlock ();;
7646                 return res;
7647         }
7648         /* try without signature */
7649         *sigstart = 0;
7650         res = g_hash_table_lookup (icall_hash, mname);
7651         if (res) {
7652                 mono_icall_unlock ();
7653                 return res;
7654         }
7655
7656 #ifdef DISABLE_ICALL_TABLES
7657         mono_icall_unlock ();
7658         /* Fail only when the result is actually used */
7659         /* mono_marshal_get_native_wrapper () depends on this */
7660         if (method->klass == mono_defaults.string_class && !strcmp (method->name, ".ctor"))
7661                 return ves_icall_System_String_ctor_RedirectToCreateString;
7662         else
7663                 return no_icall_table;
7664 #else
7665         /* it wasn't found in the static call tables */
7666         if (!imap) {
7667                 mono_icall_unlock ();
7668                 return NULL;
7669         }
7670         res = find_method_icall (imap, sigstart - mlen);
7671         if (res) {
7672                 mono_icall_unlock ();
7673                 return res;
7674         }
7675         /* try _with_ signature */
7676         *sigstart = '(';
7677         res = find_method_icall (imap, sigstart - mlen);
7678         if (res) {
7679                 mono_icall_unlock ();
7680                 return res;
7681         }
7682
7683         g_warning ("cant resolve internal call to \"%s\" (tested without signature also)", mname);
7684         g_print ("\nYour mono runtime and class libraries are out of sync.\n");
7685         g_print ("The out of sync library is: %s\n", method->klass->image->name);
7686         g_print ("\nWhen you update one from git you need to update, compile and install\nthe other too.\n");
7687         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");
7688         g_print ("If you see other errors or faults after this message they are probably related\n");
7689         g_print ("and you need to fix your mono install first.\n");
7690
7691         mono_icall_unlock ();
7692
7693         return NULL;
7694 #endif
7695 }
7696
7697 #ifdef ENABLE_ICALL_SYMBOL_MAP
7698 static int
7699 func_cmp (gconstpointer key, gconstpointer p)
7700 {
7701         return (gsize)key - (gsize)*(gsize*)p;
7702 }
7703 #endif
7704
7705 /*
7706  * mono_lookup_icall_symbol:
7707  *
7708  *   Given the icall METHOD, returns its C symbol.
7709  */
7710 const char*
7711 mono_lookup_icall_symbol (MonoMethod *m)
7712 {
7713 #ifdef DISABLE_ICALL_TABLES
7714         g_assert_not_reached ();
7715         return NULL;
7716 #else
7717 #ifdef ENABLE_ICALL_SYMBOL_MAP
7718         gpointer func;
7719         int i;
7720         gpointer slot;
7721         static gconstpointer *functions_sorted;
7722         static const char**symbols_sorted;
7723         static gboolean inited;
7724
7725         if (!inited) {
7726                 gboolean changed;
7727
7728                 functions_sorted = g_malloc (G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7729                 memcpy (functions_sorted, icall_functions, G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7730                 symbols_sorted = g_malloc (G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7731                 memcpy (symbols_sorted, icall_symbols, G_N_ELEMENTS (icall_functions) * sizeof (gpointer));
7732                 /* Bubble sort the two arrays */
7733                 changed = TRUE;
7734                 while (changed) {
7735                         changed = FALSE;
7736                         for (i = 0; i < G_N_ELEMENTS (icall_functions) - 1; ++i) {
7737                                 if (functions_sorted [i] > functions_sorted [i + 1]) {
7738                                         gconstpointer tmp;
7739
7740                                         tmp = functions_sorted [i];
7741                                         functions_sorted [i] = functions_sorted [i + 1];
7742                                         functions_sorted [i + 1] = tmp;
7743                                         tmp = symbols_sorted [i];
7744                                         symbols_sorted [i] = symbols_sorted [i + 1];
7745                                         symbols_sorted [i + 1] = tmp;
7746                                         changed = TRUE;
7747                                 }
7748                         }
7749                 }
7750         }
7751
7752         func = mono_lookup_internal_call (m);
7753         if (!func)
7754                 return NULL;
7755         slot = mono_binary_search (func, functions_sorted, G_N_ELEMENTS (icall_functions), sizeof (gpointer), func_cmp);
7756         if (!slot)
7757                 return NULL;
7758         g_assert (slot);
7759         return symbols_sorted [(gpointer*)slot - (gpointer*)functions_sorted];
7760 #else
7761         fprintf (stderr, "icall symbol maps not enabled, pass --enable-icall-symbol-map to configure.\n");
7762         g_assert_not_reached ();
7763         return 0;
7764 #endif
7765 #endif
7766 }
7767
7768 static MonoType*
7769 type_from_typename (char *typename)
7770 {
7771         MonoClass *klass = NULL;        /* assignment to shut GCC warning up */
7772
7773         if (!strcmp (typename, "int"))
7774                 klass = mono_defaults.int_class;
7775         else if (!strcmp (typename, "ptr"))
7776                 klass = mono_defaults.int_class;
7777         else if (!strcmp (typename, "void"))
7778                 klass = mono_defaults.void_class;
7779         else if (!strcmp (typename, "int32"))
7780                 klass = mono_defaults.int32_class;
7781         else if (!strcmp (typename, "uint32"))
7782                 klass = mono_defaults.uint32_class;
7783         else if (!strcmp (typename, "int8"))
7784                 klass = mono_defaults.sbyte_class;
7785         else if (!strcmp (typename, "uint8"))
7786                 klass = mono_defaults.byte_class;
7787         else if (!strcmp (typename, "int16"))
7788                 klass = mono_defaults.int16_class;
7789         else if (!strcmp (typename, "uint16"))
7790                 klass = mono_defaults.uint16_class;
7791         else if (!strcmp (typename, "long"))
7792                 klass = mono_defaults.int64_class;
7793         else if (!strcmp (typename, "ulong"))
7794                 klass = mono_defaults.uint64_class;
7795         else if (!strcmp (typename, "float"))
7796                 klass = mono_defaults.single_class;
7797         else if (!strcmp (typename, "double"))
7798                 klass = mono_defaults.double_class;
7799         else if (!strcmp (typename, "object"))
7800                 klass = mono_defaults.object_class;
7801         else if (!strcmp (typename, "obj"))
7802                 klass = mono_defaults.object_class;
7803         else if (!strcmp (typename, "string"))
7804                 klass = mono_defaults.string_class;
7805         else if (!strcmp (typename, "bool"))
7806                 klass = mono_defaults.boolean_class;
7807         else if (!strcmp (typename, "boolean"))
7808                 klass = mono_defaults.boolean_class;
7809         else {
7810                 g_error ("%s", typename);
7811                 g_assert_not_reached ();
7812         }
7813         return &klass->byval_arg;
7814 }
7815
7816 /**
7817  * LOCKING: Take the corlib image lock.
7818  */
7819 MonoMethodSignature*
7820 mono_create_icall_signature (const char *sigstr)
7821 {
7822         gchar **parts;
7823         int i, len;
7824         gchar **tmp;
7825         MonoMethodSignature *res, *res2;
7826         MonoImage *corlib = mono_defaults.corlib;
7827
7828         mono_image_lock (corlib);
7829         res = g_hash_table_lookup (corlib->helper_signatures, sigstr);
7830         mono_image_unlock (corlib);
7831
7832         if (res)
7833                 return res;
7834
7835         parts = g_strsplit (sigstr, " ", 256);
7836
7837         tmp = parts;
7838         len = 0;
7839         while (*tmp) {
7840                 len ++;
7841                 tmp ++;
7842         }
7843
7844         res = mono_metadata_signature_alloc (corlib, len - 1);
7845         res->pinvoke = 1;
7846
7847 #ifdef HOST_WIN32
7848         /* 
7849          * Under windows, the default pinvoke calling convention is STDCALL but
7850          * we need CDECL.
7851          */
7852         res->call_convention = MONO_CALL_C;
7853 #endif
7854
7855         res->ret = type_from_typename (parts [0]);
7856         for (i = 1; i < len; ++i) {
7857                 res->params [i - 1] = type_from_typename (parts [i]);
7858         }
7859
7860         g_strfreev (parts);
7861
7862         mono_image_lock (corlib);
7863         res2 = g_hash_table_lookup (corlib->helper_signatures, sigstr);
7864         if (res2)
7865                 res = res2; /*Value is allocated in the image pool*/
7866         else
7867                 g_hash_table_insert (corlib->helper_signatures, (gpointer)sigstr, res);
7868         mono_image_unlock (corlib);
7869
7870         return res;
7871 }
7872
7873 MonoJitICallInfo *
7874 mono_find_jit_icall_by_name (const char *name)
7875 {
7876         MonoJitICallInfo *info;
7877         g_assert (jit_icall_hash_name);
7878
7879         mono_icall_lock ();
7880         info = g_hash_table_lookup (jit_icall_hash_name, name);
7881         mono_icall_unlock ();
7882         return info;
7883 }
7884
7885 MonoJitICallInfo *
7886 mono_find_jit_icall_by_addr (gconstpointer addr)
7887 {
7888         MonoJitICallInfo *info;
7889         g_assert (jit_icall_hash_addr);
7890
7891         mono_icall_lock ();
7892         info = g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
7893         mono_icall_unlock ();
7894
7895         return info;
7896 }
7897
7898 /*
7899  * mono_get_jit_icall_info:
7900  *
7901  *   Return the hashtable mapping JIT icall names to MonoJitICallInfo structures. The
7902  * caller should access it while holding the icall lock.
7903  */
7904 GHashTable*
7905 mono_get_jit_icall_info (void)
7906 {
7907         return jit_icall_hash_name;
7908 }
7909
7910 /*
7911  * mono_lookup_jit_icall_symbol:
7912  *
7913  *   Given the jit icall NAME, returns its C symbol if possible, or NULL.
7914  */
7915 const char*
7916 mono_lookup_jit_icall_symbol (const char *name)
7917 {
7918         MonoJitICallInfo *info;
7919         const char *res = NULL;
7920
7921         mono_icall_lock ();
7922         info = g_hash_table_lookup (jit_icall_hash_name, name);
7923         if (info)
7924                 res = info->c_symbol;
7925         mono_icall_unlock ();
7926         return res;
7927 }
7928
7929 void
7930 mono_register_jit_icall_wrapper (MonoJitICallInfo *info, gconstpointer wrapper)
7931 {
7932         mono_icall_lock ();
7933         g_hash_table_insert (jit_icall_hash_addr, (gpointer)wrapper, info);
7934         mono_icall_unlock ();
7935 }
7936
7937 /*
7938  * 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
7939  * icalls without wrappers in some cases.
7940  */
7941 MonoJitICallInfo *
7942 mono_register_jit_icall_full (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save, gboolean no_raise, const char *c_symbol)
7943 {
7944         MonoJitICallInfo *info;
7945         
7946         g_assert (func);
7947         g_assert (name);
7948
7949         mono_icall_lock ();
7950
7951         if (!jit_icall_hash_name) {
7952                 jit_icall_hash_name = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free);
7953                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
7954         }
7955
7956         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
7957                 g_warning ("jit icall already defined \"%s\"\n", name);
7958                 g_assert_not_reached ();
7959         }
7960
7961         info = g_new0 (MonoJitICallInfo, 1);
7962         
7963         info->name = name;
7964         info->func = func;
7965         info->sig = sig;
7966         info->c_symbol = c_symbol;
7967         info->no_raise = no_raise;
7968
7969         if (is_save) {
7970                 info->wrapper = func;
7971         } else {
7972                 info->wrapper = NULL;
7973         }
7974
7975         g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
7976         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
7977
7978         mono_icall_unlock ();
7979         return info;
7980 }
7981
7982 MonoJitICallInfo *
7983 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
7984 {
7985         return mono_register_jit_icall_full (func, name, sig, is_save, FALSE, NULL);
7986 }
7987