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