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