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