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