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