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