Merge pull request #1991 from esdrubal/seq_test_fix
[mono.git] / mono / metadata / marshal.c
1 /*
2  * marshal.c: Routines for marshaling complex types in P/Invoke methods.
3  * 
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *
7  * Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
8  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
9  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
10  *
11  */
12
13 #include "config.h"
14 #ifdef HAVE_ALLOCA_H
15 #include <alloca.h>
16 #endif
17
18 #include "object.h"
19 #include "loader.h"
20 #include "cil-coff.h"
21 #include "metadata/marshal.h"
22 #include "metadata/method-builder.h"
23 #include "metadata/tabledefs.h"
24 #include "metadata/exception.h"
25 #include "metadata/appdomain.h"
26 #include "mono/metadata/abi-details.h"
27 #include "mono/metadata/debug-helpers.h"
28 #include "mono/metadata/threads.h"
29 #include "mono/metadata/monitor.h"
30 #include "mono/metadata/class-internals.h"
31 #include "mono/metadata/metadata-internals.h"
32 #include "mono/metadata/domain-internals.h"
33 #include "mono/metadata/gc-internal.h"
34 #include "mono/metadata/threads-types.h"
35 #include "mono/metadata/string-icalls.h"
36 #include "mono/metadata/attrdefs.h"
37 #include "mono/metadata/gc-internal.h"
38 #include "mono/metadata/cominterop.h"
39 #include "mono/metadata/remoting.h"
40 #include "mono/metadata/reflection-internals.h"
41 #include "mono/metadata/threadpool-ms.h"
42 #include "mono/utils/mono-counters.h"
43 #include "mono/utils/mono-tls.h"
44 #include "mono/utils/mono-memory-model.h"
45 #include "mono/utils/atomic.h"
46 #include <mono/utils/mono-threads.h>
47
48 #include <string.h>
49 #include <errno.h>
50
51 /* #define DEBUG_RUNTIME_CODE */
52
53 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
54         a = i,
55
56 enum {
57 #include "mono/cil/opcode.def"
58         LAST = 0xff
59 };
60 #undef OPDEF
61
62 /* 
63  * This mutex protects the various marshalling related caches in MonoImage
64  * and a few other data structures static to this file.
65  *
66  * The marshal lock is a non-recursive complex lock that sits below the domain lock in the
67  * runtime locking latice. Which means it can take simple locks suck as the image lock.
68  */
69 #define mono_marshal_lock() mono_locks_acquire (&marshal_mutex, MarshalLock)
70 #define mono_marshal_unlock() mono_locks_release (&marshal_mutex, MarshalLock)
71 static mono_mutex_t marshal_mutex;
72 static gboolean marshal_mutex_initialized;
73
74 static MonoNativeTlsKey last_error_tls_id;
75
76 static MonoNativeTlsKey load_type_info_tls_id;
77
78 static gboolean use_aot_wrappers;
79
80 static void
81 delegate_hash_table_add (MonoDelegate *d);
82
83 static void
84 emit_struct_conv (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object);
85
86 static void
87 emit_struct_conv_full (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object, MonoMarshalNative string_encoding);
88
89 static void 
90 mono_struct_delete_old (MonoClass *klass, char *ptr);
91
92 MONO_API void *
93 mono_marshal_string_to_utf16 (MonoString *s);
94
95 static void *
96 mono_marshal_string_to_utf16_copy (MonoString *s);
97
98 static gpointer
99 mono_string_to_lpstr (MonoString *string_obj);
100
101 static MonoStringBuilder *
102 mono_string_utf8_to_builder2 (char *text);
103
104 static MonoStringBuilder *
105 mono_string_utf16_to_builder2 (gunichar2 *text);
106
107 static MonoString*
108 mono_string_new_len_wrapper (const char *text, guint length);
109
110 static MonoString *
111 mono_string_from_byvalstr (const char *data, int len);
112
113 static MonoString *
114 mono_string_from_byvalwstr (gunichar2 *data, int len);
115
116 static void
117 mono_byvalarray_to_array (MonoArray *arr, gpointer native_arr, MonoClass *eltype, guint32 elnum);
118
119 static void
120 mono_byvalarray_to_byte_array (MonoArray *arr, gpointer native_arr, guint32 elnum);
121
122 static void
123 mono_array_to_byvalarray (gpointer native_arr, MonoArray *arr, MonoClass *eltype, guint32 elnum);
124
125 static void
126 mono_array_to_byte_byvalarray (gpointer native_arr, MonoArray *arr, guint32 elnum);
127
128 static MonoAsyncResult *
129 mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params);
130
131 static MonoObject *
132 mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params);
133
134 static void
135 mono_marshal_set_last_error_windows (int error);
136
137 static MonoObject *
138 mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *cache);
139
140 static void init_safe_handle (void);
141
142 /* MonoMethod pointers to SafeHandle::DangerousAddRef and ::DangerousRelease */
143 static MonoMethod *sh_dangerous_add_ref;
144 static MonoMethod *sh_dangerous_release;
145
146
147 static void
148 init_safe_handle ()
149 {
150         sh_dangerous_add_ref = mono_class_get_method_from_name (
151                 mono_defaults.safehandle_class, "DangerousAddRef", 1);
152         sh_dangerous_release = mono_class_get_method_from_name (
153                 mono_defaults.safehandle_class, "DangerousRelease", 0);
154 }
155
156 static void
157 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
158 {
159         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
160
161         mono_register_jit_icall (func, name, sig, save);
162 }
163
164 MonoMethodSignature*
165 mono_signature_no_pinvoke (MonoMethod *method)
166 {
167         MonoMethodSignature *sig = mono_method_signature (method);
168         if (sig->pinvoke) {
169                 sig = mono_metadata_signature_dup_full (method->klass->image, sig);
170                 sig->pinvoke = FALSE;
171         }
172         
173         return sig;
174 }
175
176 void
177 mono_marshal_init_tls (void)
178 {
179         mono_native_tls_alloc (&last_error_tls_id, NULL);
180         mono_native_tls_alloc (&load_type_info_tls_id, NULL);
181 }
182
183 void
184 mono_marshal_init (void)
185 {
186         static gboolean module_initialized = FALSE;
187
188         if (!module_initialized) {
189                 module_initialized = TRUE;
190                 mono_mutex_init_recursive (&marshal_mutex);
191                 marshal_mutex_initialized = TRUE;
192
193                 register_icall (ves_icall_System_Threading_Thread_ResetAbort, "ves_icall_System_Threading_Thread_ResetAbort", "void", TRUE);
194                 register_icall (mono_marshal_string_to_utf16, "mono_marshal_string_to_utf16", "ptr obj", FALSE);
195                 register_icall (mono_marshal_string_to_utf16_copy, "mono_marshal_string_to_utf16_copy", "ptr obj", FALSE);
196                 register_icall (mono_string_to_utf16, "mono_string_to_utf16", "ptr obj", FALSE);
197                 register_icall (mono_string_from_utf16, "mono_string_from_utf16", "obj ptr", FALSE);
198                 register_icall (mono_string_from_byvalstr, "mono_string_from_byvalstr", "obj ptr int", FALSE);
199                 register_icall (mono_string_from_byvalwstr, "mono_string_from_byvalwstr", "obj ptr int", FALSE);
200                 register_icall (mono_string_new_wrapper, "mono_string_new_wrapper", "obj ptr", FALSE);
201                 register_icall (mono_string_new_len_wrapper, "mono_string_new_len_wrapper", "obj ptr int", FALSE);
202                 register_icall (mono_string_to_utf8, "mono_string_to_utf8", "ptr obj", FALSE);
203                 register_icall (mono_string_to_lpstr, "mono_string_to_lpstr", "ptr obj", FALSE);
204                 register_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", "ptr object", FALSE);
205                 register_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", "ptr object", FALSE);
206                 register_icall (mono_string_builder_to_utf16, "mono_string_builder_to_utf16", "ptr object", FALSE);
207                 register_icall (mono_array_to_savearray, "mono_array_to_savearray", "ptr object", FALSE);
208                 register_icall (mono_array_to_lparray, "mono_array_to_lparray", "ptr object", FALSE);
209                 register_icall (mono_free_lparray, "mono_free_lparray", "void object ptr", FALSE);
210                 register_icall (mono_byvalarray_to_array, "mono_byvalarray_to_array", "void object ptr ptr int32", FALSE);
211                 register_icall (mono_byvalarray_to_byte_array, "mono_byvalarray_to_byte_array", "void object ptr int32", FALSE);
212                 register_icall (mono_array_to_byvalarray, "mono_array_to_byvalarray", "void ptr object ptr int32", FALSE);
213                 register_icall (mono_array_to_byte_byvalarray, "mono_array_to_byte_byvalarray", "void ptr object int32", FALSE);
214                 register_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", "ptr object", FALSE);
215                 register_icall (mono_ftnptr_to_delegate, "mono_ftnptr_to_delegate", "object ptr ptr", FALSE);
216                 register_icall (mono_marshal_asany, "mono_marshal_asany", "ptr object int32 int32", FALSE);
217                 register_icall (mono_marshal_free_asany, "mono_marshal_free_asany", "void object ptr int32 int32", FALSE);
218                 register_icall (mono_marshal_alloc, "mono_marshal_alloc", "ptr int32", FALSE);
219                 register_icall (mono_marshal_free, "mono_marshal_free", "void ptr", FALSE);
220                 register_icall (mono_marshal_set_last_error, "mono_marshal_set_last_error", "void", FALSE);
221                 register_icall (mono_marshal_set_last_error_windows, "mono_marshal_set_last_error_windows", "void int32", FALSE);
222                 register_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", "void ptr ptr", FALSE);
223                 register_icall (mono_string_utf8_to_builder2, "mono_string_utf8_to_builder2", "object ptr", FALSE);
224                 register_icall (mono_string_utf16_to_builder, "mono_string_utf16_to_builder", "void ptr ptr", FALSE);
225                 register_icall (mono_string_utf16_to_builder2, "mono_string_utf16_to_builder2", "object ptr", FALSE);
226                 register_icall (mono_marshal_free_array, "mono_marshal_free_array", "void ptr int32", FALSE);
227                 register_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", "void ptr ptr int32", FALSE);
228                 register_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", "void ptr ptr int32", FALSE);
229                 register_icall (g_free, "g_free", "void ptr", FALSE);
230                 register_icall (mono_object_isinst, "mono_object_isinst", "object object ptr", FALSE);
231                 register_icall (mono_struct_delete_old, "mono_struct_delete_old", "void ptr ptr", FALSE);
232                 register_icall (mono_delegate_begin_invoke, "mono_delegate_begin_invoke", "object object ptr", FALSE);
233                 register_icall (mono_delegate_end_invoke, "mono_delegate_end_invoke", "object object ptr", FALSE);
234                 register_icall (mono_compile_method, "mono_compile_method", "ptr ptr", FALSE);
235                 register_icall (mono_context_get, "mono_context_get", "object", FALSE);
236                 register_icall (mono_context_set, "mono_context_set", "void object", FALSE);
237                 register_icall (mono_gc_wbarrier_generic_nostore, "wb_generic", "void ptr", FALSE);
238                 register_icall (mono_gchandle_get_target, "mono_gchandle_get_target", "object int32", TRUE);
239                 register_icall (mono_marshal_isinst_with_cache, "mono_marshal_isinst_with_cache", "object object ptr ptr", FALSE);
240
241                 mono_cominterop_init ();
242                 mono_remoting_init ();
243
244 #ifdef USE_COOP_GC
245                 register_icall (mono_threads_prepare_blocking, "mono_threads_prepare_blocking", "int", FALSE);
246                 register_icall (mono_threads_finish_blocking, "mono_threads_finish_blocking", "void int", FALSE);
247                 register_icall (mono_threads_reset_blocking_start, "mono_threads_reset_blocking_start","int", TRUE);
248                 register_icall (mono_threads_reset_blocking_end, "mono_threads_reset_blocking_end","void int", TRUE);
249 #endif
250         }
251 }
252
253 void
254 mono_marshal_cleanup (void)
255 {
256         mono_cominterop_cleanup ();
257
258         mono_native_tls_free (load_type_info_tls_id);
259         mono_native_tls_free (last_error_tls_id);
260         mono_mutex_destroy (&marshal_mutex);
261         marshal_mutex_initialized = FALSE;
262 }
263
264 void
265 mono_marshal_lock_internal (void)
266 {
267         mono_marshal_lock ();
268 }
269
270 void
271 mono_marshal_unlock_internal (void)
272 {
273         mono_marshal_unlock ();
274 }
275
276 gpointer
277 mono_delegate_to_ftnptr (MonoDelegate *delegate)
278 {
279         MonoMethod *method, *wrapper;
280         MonoClass *klass;
281         uint32_t target_handle = 0;
282
283         if (!delegate)
284                 return NULL;
285
286         if (delegate->delegate_trampoline)
287                 return delegate->delegate_trampoline;
288
289         klass = ((MonoObject *)delegate)->vtable->klass;
290         g_assert (klass->delegate);
291
292         method = delegate->method;
293
294         if (mono_method_signature (method)->pinvoke) {
295                 const char *exc_class, *exc_arg;
296                 gpointer ftnptr;
297
298                 ftnptr = mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
299                 if (!ftnptr) {
300                         g_assert (exc_class);
301                         mono_raise_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System", exc_class, exc_arg));
302                 }
303                 return ftnptr;
304         }
305
306         if (delegate->target) {
307                 /* Produce a location which can be embedded in JITted code */
308                 target_handle = mono_gchandle_new_weakref (delegate->target, FALSE);
309         }
310
311         wrapper = mono_marshal_get_managed_wrapper (method, klass, target_handle);
312
313         delegate->delegate_trampoline = mono_compile_method (wrapper);
314
315         // Add the delegate to the delegate hash table
316         delegate_hash_table_add (delegate);
317
318         /* when the object is collected, collect the dynamic method, too */
319         mono_object_register_finalizer ((MonoObject*)delegate);
320
321         return delegate->delegate_trampoline;
322 }
323
324 /* 
325  * this hash table maps from a delegate trampoline object to a weak reference
326  * of the delegate. As an optimizations with a non-moving GC we store the
327  * object pointer itself, otherwise we use a GC handle.
328  */
329 static GHashTable *delegate_hash_table;
330
331 static GHashTable *
332 delegate_hash_table_new (void) {
333         return g_hash_table_new (NULL, NULL);
334 }
335
336 static void 
337 delegate_hash_table_remove (MonoDelegate *d)
338 {
339         guint32 gchandle = 0;
340
341         mono_marshal_lock ();
342         if (delegate_hash_table == NULL)
343                 delegate_hash_table = delegate_hash_table_new ();
344         if (mono_gc_is_moving ())
345                 gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, d->delegate_trampoline));
346         g_hash_table_remove (delegate_hash_table, d->delegate_trampoline);
347         mono_marshal_unlock ();
348         if (mono_gc_is_moving ())
349                 mono_gchandle_free (gchandle);
350 }
351
352 static void
353 delegate_hash_table_add (MonoDelegate *d)
354 {
355         guint32 gchandle;
356         guint32 old_gchandle;
357
358         mono_marshal_lock ();
359         if (delegate_hash_table == NULL)
360                 delegate_hash_table = delegate_hash_table_new ();
361         if (mono_gc_is_moving ()) {
362                 gchandle = mono_gchandle_new_weakref ((MonoObject*)d, FALSE);
363                 old_gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, d->delegate_trampoline));
364                 g_hash_table_insert (delegate_hash_table, d->delegate_trampoline, GUINT_TO_POINTER (gchandle));
365                 if (old_gchandle)
366                         mono_gchandle_free (old_gchandle);
367         } else {
368                 g_hash_table_insert (delegate_hash_table, d->delegate_trampoline, d);
369         }
370         mono_marshal_unlock ();
371 }
372
373 /*
374  * mono_marshal_use_aot_wrappers:
375  *
376  *   Instructs this module to use AOT compatible wrappers.
377  */
378 void
379 mono_marshal_use_aot_wrappers (gboolean use)
380 {
381         use_aot_wrappers = use;
382 }
383
384 static void
385 parse_unmanaged_function_pointer_attr (MonoClass *klass, MonoMethodPInvoke *piinfo)
386 {
387         static MonoClass *UnmanagedFunctionPointerAttribute;
388         MonoCustomAttrInfo *cinfo;
389         MonoReflectionUnmanagedFunctionPointerAttribute *attr;
390
391         if (!UnmanagedFunctionPointerAttribute)
392                 UnmanagedFunctionPointerAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
393
394         /* The attribute is only available in Net 2.0 */
395         if (UnmanagedFunctionPointerAttribute) {
396                 /* 
397                  * The pinvoke attributes are stored in a real custom attribute so we have to
398                  * construct it.
399                  */
400                 cinfo = mono_custom_attrs_from_class (klass);
401                 if (cinfo && !mono_runtime_get_no_exec ()) {
402                         MonoError error;
403                         attr = (MonoReflectionUnmanagedFunctionPointerAttribute*)mono_custom_attrs_get_attr_checked (cinfo, UnmanagedFunctionPointerAttribute, &error);
404                         if (attr) {
405                                 piinfo->piflags = (attr->call_conv << 8) | (attr->charset ? (attr->charset - 1) * 2 : 1) | attr->set_last_error;
406                         } else {
407                                 if (!mono_error_ok (&error)) {
408                                         g_warning ("Could not load UnmanagedFunctionPointerAttribute due to %s", mono_error_get_message (&error));
409                                         mono_error_cleanup (&error);
410                                 }
411                         }
412                         if (!cinfo->cached)
413                                 mono_custom_attrs_free (cinfo);
414                 }
415         }
416 }
417
418 MonoDelegate*
419 mono_ftnptr_to_delegate (MonoClass *klass, gpointer ftn)
420 {
421         guint32 gchandle;
422         MonoDelegate *d;
423
424         if (ftn == NULL)
425                 return NULL;
426
427         mono_marshal_lock ();
428         if (delegate_hash_table == NULL)
429                 delegate_hash_table = delegate_hash_table_new ();
430
431         if (mono_gc_is_moving ()) {
432                 gchandle = GPOINTER_TO_UINT (g_hash_table_lookup (delegate_hash_table, ftn));
433                 mono_marshal_unlock ();
434                 if (gchandle)
435                         d = (MonoDelegate*)mono_gchandle_get_target (gchandle);
436                 else
437                         d = NULL;
438         } else {
439                 d = g_hash_table_lookup (delegate_hash_table, ftn);
440                 mono_marshal_unlock ();
441         }
442         if (d == NULL) {
443                 /* This is a native function, so construct a delegate for it */
444                 MonoMethodSignature *sig;
445                 MonoMethod *wrapper;
446                 MonoMarshalSpec **mspecs;
447                 MonoMethod *invoke = mono_get_delegate_invoke (klass);
448                 MonoMethodPInvoke piinfo;
449                 MonoObject *this_obj;
450                 int i;
451
452                 if (use_aot_wrappers) {
453                         wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
454                         this_obj = mono_value_box (mono_domain_get (), mono_defaults.int_class, &ftn);
455                 } else {
456                         memset (&piinfo, 0, sizeof (piinfo));
457                         parse_unmanaged_function_pointer_attr (klass, &piinfo);
458
459                         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
460                         mono_method_get_marshal_info (invoke, mspecs);
461                         /* Freed below so don't alloc from mempool */
462                         sig = mono_metadata_signature_dup (mono_method_signature (invoke));
463                         sig->hasthis = 0;
464
465                         wrapper = mono_marshal_get_native_func_wrapper (klass->image, sig, &piinfo, mspecs, ftn);
466                         this_obj = NULL;
467
468                         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
469                                 if (mspecs [i])
470                                         mono_metadata_free_marshal_spec (mspecs [i]);
471                         g_free (mspecs);
472                         g_free (sig);
473                 }
474
475                 d = (MonoDelegate*)mono_object_new (mono_domain_get (), klass);
476                 mono_delegate_ctor_with_method ((MonoObject*)d, this_obj, mono_compile_method (wrapper), wrapper);
477         }
478
479         if (d->object.vtable->domain != mono_domain_get ())
480                 mono_raise_exception (mono_get_exception_not_supported ("Delegates cannot be marshalled from native code into a domain other than their home domain"));
481
482         return d;
483 }
484
485 void
486 mono_delegate_free_ftnptr (MonoDelegate *delegate)
487 {
488         MonoJitInfo *ji;
489         void *ptr;
490
491         delegate_hash_table_remove (delegate);
492
493         ptr = (gpointer)InterlockedExchangePointer (&delegate->delegate_trampoline, NULL);
494
495         if (!delegate->target) {
496                 /* The wrapper method is shared between delegates -> no need to free it */
497                 return;
498         }
499
500         if (ptr) {
501                 uint32_t gchandle;
502                 void **method_data;
503                 MonoMethod *method;
504
505                 ji = mono_jit_info_table_find (mono_domain_get (), mono_get_addr_from_ftnptr (ptr));
506                 g_assert (ji);
507
508                 method = mono_jit_info_get_method (ji);
509                 method_data = ((MonoMethodWrapper*)method)->method_data;
510
511                 /*the target gchandle is the first entry after size and the wrapper itself.*/
512                 gchandle = GPOINTER_TO_UINT (method_data [2]);
513
514                 if (gchandle)
515                         mono_gchandle_free (gchandle);
516
517                 mono_runtime_free_method (mono_object_domain (delegate), method);
518         }
519 }
520
521 static MonoString *
522 mono_string_from_byvalstr (const char *data, int max_len)
523 {
524         MonoDomain *domain = mono_domain_get ();
525         int len = 0;
526
527         if (!data)
528                 return NULL;
529
530         while (len < max_len - 1 && data [len])
531                 len++;
532
533         return mono_string_new_len (domain, data, len);
534 }
535
536 static MonoString *
537 mono_string_from_byvalwstr (gunichar2 *data, int max_len)
538 {
539         MonoDomain *domain = mono_domain_get ();
540         int len = 0;
541
542         if (!data)
543                 return NULL;
544
545         while (data [len]) len++;
546
547         return mono_string_new_utf16 (domain, data, MIN (len, max_len));
548 }
549
550 gpointer
551 mono_array_to_savearray (MonoArray *array)
552 {
553         if (!array)
554                 return NULL;
555
556         g_assert_not_reached ();
557         return NULL;
558 }
559
560 gpointer
561 mono_array_to_lparray (MonoArray *array)
562 {
563 #ifndef DISABLE_COM
564         gpointer *nativeArray = NULL;
565         int nativeArraySize = 0;
566
567         int i = 0;
568         MonoClass *klass;
569 #endif
570
571         if (!array)
572                 return NULL;
573 #ifndef DISABLE_COM
574
575         klass = array->obj.vtable->klass;
576
577         switch (klass->element_class->byval_arg.type) {
578         case MONO_TYPE_VOID:
579                 g_assert_not_reached ();
580                 break;
581         case MONO_TYPE_CLASS:
582                 nativeArraySize = array->max_length;
583                 nativeArray = malloc(sizeof(gpointer) * nativeArraySize);
584                 for(i = 0; i < nativeArraySize; ++i)    
585                         nativeArray[i] = ves_icall_System_Runtime_InteropServices_Marshal_GetIUnknownForObjectInternal(((gpointer*)array->vector)[i]);
586                 return nativeArray;
587         case MONO_TYPE_U1:
588         case MONO_TYPE_BOOLEAN:
589         case MONO_TYPE_I1:
590         case MONO_TYPE_U2:
591         case MONO_TYPE_CHAR:
592         case MONO_TYPE_I2:
593         case MONO_TYPE_I:
594         case MONO_TYPE_U:
595         case MONO_TYPE_I4:
596         case MONO_TYPE_U4:
597         case MONO_TYPE_U8:
598         case MONO_TYPE_I8:
599         case MONO_TYPE_R4:
600         case MONO_TYPE_R8:
601         case MONO_TYPE_VALUETYPE:
602         case MONO_TYPE_PTR:
603                 /* nothing to do */
604                 break;
605         case MONO_TYPE_GENERICINST:
606         case MONO_TYPE_OBJECT:
607         case MONO_TYPE_ARRAY: 
608         case MONO_TYPE_SZARRAY:
609         case MONO_TYPE_STRING:
610         default:
611                 g_warning ("type 0x%x not handled", klass->element_class->byval_arg.type);
612                 g_assert_not_reached ();
613         }
614 #endif
615         return array->vector;
616 }
617
618 void
619 mono_free_lparray (MonoArray *array, gpointer* nativeArray)
620 {
621 #ifndef DISABLE_COM
622         MonoClass *klass;
623         int i = 0;
624
625         if (!array)
626                 return;
627
628         if (!nativeArray)
629                 return;
630         klass = array->obj.vtable->klass;
631
632         if (klass->element_class->byval_arg.type == MONO_TYPE_CLASS) {
633                 for(i = 0; i < array->max_length; ++i)
634                         mono_marshal_free_ccw (mono_array_get (array, MonoObject*, i));
635                 free(nativeArray);
636         }
637 #endif
638 }
639
640 static void
641 mono_byvalarray_to_array (MonoArray *arr, gpointer native_arr, MonoClass *elclass, guint32 elnum)
642 {
643         g_assert (arr->obj.vtable->klass->element_class == mono_defaults.char_class);
644
645         if (elclass == mono_defaults.byte_class) {
646                 GError *error = NULL;
647                 guint16 *ut;
648                 glong items_written;
649
650                 ut = g_utf8_to_utf16 (native_arr, elnum, NULL, &items_written, &error);
651
652                 if (!error) {
653                         memcpy (mono_array_addr (arr, guint16, 0), ut, items_written * sizeof (guint16));
654                         g_free (ut);
655                 }
656                 else
657                         g_error_free (error);
658         }
659         else
660                 g_assert_not_reached ();
661 }
662
663 static void
664 mono_byvalarray_to_byte_array (MonoArray *arr, gpointer native_arr, guint32 elnum)
665 {
666         mono_byvalarray_to_array (arr, native_arr, mono_defaults.byte_class, elnum);
667 }
668
669 static void
670 mono_array_to_byvalarray (gpointer native_arr, MonoArray *arr, MonoClass *elclass, guint32 elnum)
671 {
672         g_assert (arr->obj.vtable->klass->element_class == mono_defaults.char_class);
673
674         if (elclass == mono_defaults.byte_class) {
675                 char *as;
676                 GError *error = NULL;
677
678                 as = g_utf16_to_utf8 (mono_array_addr (arr, gunichar2, 0), mono_array_length (arr), NULL, NULL, &error);
679                 if (error) {
680                         MonoException *exc = mono_get_exception_argument ("string", error->message);
681                         g_error_free (error);
682                         mono_raise_exception (exc);
683                 }
684
685                 memcpy (native_arr, as, MIN (strlen (as), elnum));
686                 g_free (as);
687         } else {
688                 g_assert_not_reached ();
689         }
690 }
691
692 static void
693 mono_array_to_byte_byvalarray (gpointer native_arr, MonoArray *arr, guint32 elnum)
694 {
695         mono_array_to_byvalarray (native_arr, arr, mono_defaults.byte_class, elnum);
696 }
697
698 static MonoStringBuilder *
699 mono_string_builder_new (int starting_string_length)
700 {
701         static MonoClass *string_builder_class;
702         static MonoMethod *sb_ctor;
703         static void *args [1];
704         int initial_len = starting_string_length;
705
706         if (initial_len < 0)
707                 initial_len = 0;
708
709         if (!sb_ctor) {
710                 MonoMethodDesc *desc;
711                 MonoMethod *m;
712
713                 string_builder_class = mono_class_from_name (mono_defaults.corlib, "System.Text", "StringBuilder");
714                 g_assert (string_builder_class);
715                 desc = mono_method_desc_new (":.ctor(int)", FALSE);
716                 m = mono_method_desc_search_in_class (desc, string_builder_class);
717                 g_assert (m);
718                 mono_method_desc_free (desc);
719                 mono_memory_barrier ();
720                 sb_ctor = m;
721         }
722
723         // We make a new array in the _to_builder function, so this
724         // array will always be garbage collected.
725         args [0] = &initial_len;
726
727         MonoStringBuilder *sb = (MonoStringBuilder*)mono_object_new (mono_domain_get (), string_builder_class);
728         MonoObject *exc;
729         g_assert (sb);
730
731         mono_runtime_invoke (sb_ctor, sb, args, &exc);
732         g_assert (!exc);
733
734         g_assert (sb->chunkChars->max_length >= initial_len);
735
736         return sb;
737 }
738
739 static void
740 mono_string_utf16_to_builder_copy (MonoStringBuilder *sb, gunichar2 *text, size_t string_len)
741 {
742         gunichar2 *charDst = (gunichar2 *)sb->chunkChars->vector;
743         gunichar2 *charSrc = (gunichar2 *)text;
744         memcpy (charDst, charSrc, sizeof (gunichar2) * string_len);
745
746         sb->chunkLength = string_len;
747
748         return;
749 }
750
751 MonoStringBuilder *
752 mono_string_utf16_to_builder2 (gunichar2 *text)
753 {
754         if (!text)
755                 return NULL;
756
757         int len;
758         for (len = 0; text [len] != 0; ++len);
759
760         MonoStringBuilder *sb = mono_string_builder_new (len);
761         mono_string_utf16_to_builder (sb, text);
762
763         return sb;
764 }
765
766 void
767 mono_string_utf8_to_builder (MonoStringBuilder *sb, char *text)
768 {
769         if (!sb || !text)
770                 return;
771
772         int len = strlen (text);
773         if (len > mono_string_builder_capacity (sb))
774                 len = mono_string_builder_capacity (sb);
775
776         GError *error = NULL;
777         glong copied;
778         gunichar2* ut = g_utf8_to_utf16 (text, len, NULL, &copied, &error);
779
780         if (!error) {
781                 MONO_OBJECT_SETREF (sb, chunkPrevious, NULL);
782                 mono_string_utf16_to_builder_copy (sb, ut, copied);
783         } else
784                 g_error_free (error);
785
786         g_free (ut);
787 }
788
789 MonoStringBuilder *
790 mono_string_utf8_to_builder2 (char *text)
791 {
792         if (!text)
793                 return NULL;
794
795         int len = strlen (text);
796         MonoStringBuilder *sb = mono_string_builder_new (len);
797         mono_string_utf8_to_builder (sb, text);
798
799         return sb;
800 }
801
802
803 void
804 mono_string_utf16_to_builder (MonoStringBuilder *sb, gunichar2 *text)
805 {
806         if (!sb || !text)
807                 return;
808
809         guint32 len;
810         for (len = 0; text [len] != 0; ++len);
811         
812         if (len > mono_string_builder_capacity (sb))
813                 len = mono_string_builder_capacity (sb);
814
815         mono_string_utf16_to_builder_copy (sb, text, len);
816 }
817
818 /**
819  * mono_string_builder_to_utf8:
820  * @sb: the string builder
821  *
822  * Converts to utf8 the contents of the MonoStringBuilder.
823  *
824  * Returns: a utf8 string with the contents of the StringBuilder.
825  *
826  * The return value must be released with g_free.
827  */
828 gchar*
829 mono_string_builder_to_utf8 (MonoStringBuilder *sb)
830 {
831         GError *error = NULL;
832
833         if (!sb)
834                 return NULL;
835
836
837         gunichar2 *str_utf16 = mono_string_builder_to_utf16 (sb);
838
839         guint str_len = mono_string_builder_string_length (sb);
840
841         gchar *tmp = g_utf16_to_utf8 (str_utf16, str_len, NULL, NULL, &error);
842
843         if (error) {
844                 g_error_free (error);
845                 g_free (str_utf16);
846                 mono_raise_exception (mono_get_exception_execution_engine ("Failed to convert StringBuilder from utf16 to utf8"));
847                 return NULL;
848         } else {
849                 guint len = mono_string_builder_capacity (sb) + 1;
850                 gchar *res = mono_marshal_alloc (len * sizeof (gchar));
851                 g_assert (str_len < len);
852                 memcpy (res, tmp, str_len * sizeof (gchar));
853                 res[str_len] = '\0';
854
855
856                 g_free (str_utf16);
857                 g_free (tmp);
858                 return res;
859         }
860 }
861
862 /**
863  * mono_string_builder_to_utf16:
864  * @sb: the string builder
865  *
866  * Converts to utf16 the contents of the MonoStringBuilder.
867  *
868  * Returns: a utf16 string with the contents of the StringBuilder.
869  *
870  * The return value must not be freed.
871  */
872 gunichar2*
873 mono_string_builder_to_utf16 (MonoStringBuilder *sb)
874 {
875         if (!sb)
876                 return NULL;
877
878         g_assert (sb->chunkChars);
879
880         guint len = mono_string_builder_capacity (sb);
881
882         if (len == 0)
883                 len = 1;
884
885         gunichar2 *str = mono_marshal_alloc ((len + 1) * sizeof (gunichar2));
886         str[len] = '\0';
887
888         if (len == 0)
889                 return str;
890
891         MonoStringBuilder* chunk = sb;
892         do {
893                 if (chunk->chunkLength > 0) {
894                         // Check that we will not overrun our boundaries.
895                         gunichar2 *source = (gunichar2 *)chunk->chunkChars->vector;
896
897                         if (chunk->chunkLength <= len) {
898                                 memcpy (str + chunk->chunkOffset, source, chunk->chunkLength * sizeof(gunichar2));
899                         } else {
900                                 g_error ("A chunk in the StringBuilder had a length longer than expected from the offset.");
901                         }
902
903                         len -= chunk->chunkLength;
904                 }
905                 chunk = chunk->chunkPrevious;
906         } while (chunk != NULL);
907
908         return str;
909 }
910
911 static gpointer
912 mono_string_to_lpstr (MonoString *s)
913 {
914 #ifdef TARGET_WIN32
915         char *as, *tmp;
916         glong len;
917         GError *error = NULL;
918
919         if (s == NULL)
920                 return NULL;
921
922         if (!s->length) {
923                 as = CoTaskMemAlloc (1);
924                 as [0] = '\0';
925                 return as;
926         }
927
928         tmp = g_utf16_to_utf8 (mono_string_chars (s), s->length, NULL, &len, &error);
929         if (error) {
930                 MonoException *exc = mono_get_exception_argument ("string", error->message);
931                 g_error_free (error);
932                 mono_raise_exception(exc);
933                 return NULL;
934         } else {
935                 as = CoTaskMemAlloc (len + 1);
936                 memcpy (as, tmp, len + 1);
937                 g_free (tmp);
938                 return as;
939         }
940 #else
941         return mono_string_to_utf8 (s);
942 #endif
943 }       
944
945 gpointer
946 mono_string_to_ansibstr (MonoString *string_obj)
947 {
948         g_error ("UnmanagedMarshal.BStr is not implemented.");
949         return NULL;
950 }
951
952 /**
953  * mono_string_to_byvalstr:
954  * @dst: Where to store the null-terminated utf8 decoded string.
955  * @src: the MonoString to copy.
956  * @size: the maximum number of bytes to copy.
957  *
958  * Copies the MonoString pointed to by @src as a utf8 string
959  * into @dst, it copies at most @size bytes into the destination.
960  */
961 void
962 mono_string_to_byvalstr (gpointer dst, MonoString *src, int size)
963 {
964         char *s;
965         int len;
966
967         g_assert (dst != NULL);
968         g_assert (size > 0);
969
970         memset (dst, 0, size);
971         if (!src)
972                 return;
973
974         s = mono_string_to_utf8 (src);
975         len = MIN (size, strlen (s));
976         if (len >= size)
977                 len--;
978         memcpy (dst, s, len);
979         g_free (s);
980 }
981
982 /**
983  * mono_string_to_byvalwstr:
984  * @dst: Where to store the null-terminated utf16 decoded string.
985  * @src: the MonoString to copy.
986  * @size: the maximum number of bytes to copy.
987  *
988  * Copies the MonoString pointed to by @src as a utf16 string into
989  * @dst, it copies at most @size bytes into the destination (including
990  * a terminating 16-bit zero terminator).
991  */
992 void
993 mono_string_to_byvalwstr (gpointer dst, MonoString *src, int size)
994 {
995         int len;
996
997         g_assert (dst != NULL);
998         g_assert (size > 1);
999
1000         if (!src) {
1001                 memset (dst, 0, size * 2);
1002                 return;
1003         }
1004
1005         len = MIN (size, (mono_string_length (src)));
1006         memcpy (dst, mono_string_chars (src), size * 2);
1007         if (size <= mono_string_length (src))
1008                 len--;
1009         *((gunichar2 *) dst + len) = 0;
1010 }
1011
1012 static MonoString*
1013 mono_string_new_len_wrapper (const char *text, guint length)
1014 {
1015         return mono_string_new_len (mono_domain_get (), text, length);
1016 }
1017
1018 #ifndef DISABLE_JIT
1019
1020 /*
1021  * mono_mb_emit_exception_marshal_directive:
1022  *
1023  *   This function assumes ownership of MSG, which should be malloc-ed.
1024  */
1025 static void
1026 mono_mb_emit_exception_marshal_directive (MonoMethodBuilder *mb, char *msg)
1027 {
1028         char *s;
1029
1030         if (!mb->dynamic) {
1031                 s = mono_image_strdup (mb->method->klass->image, msg);
1032                 g_free (msg);
1033         } else {
1034                 s = g_strdup (msg);
1035         }
1036         mono_mb_emit_exception_full (mb, "System.Runtime.InteropServices", "MarshalDirectiveException", s);
1037 }
1038
1039 #endif /* !DISABLE_JIT */
1040
1041 guint
1042 mono_type_to_ldind (MonoType *type)
1043 {
1044         if (type->byref)
1045                 return CEE_LDIND_I;
1046
1047 handle_enum:
1048         switch (type->type) {
1049         case MONO_TYPE_I1:
1050                 return CEE_LDIND_I1;
1051         case MONO_TYPE_U1:
1052         case MONO_TYPE_BOOLEAN:
1053                 return CEE_LDIND_U1;
1054         case MONO_TYPE_I2:
1055                 return CEE_LDIND_I2;
1056         case MONO_TYPE_U2:
1057         case MONO_TYPE_CHAR:
1058                 return CEE_LDIND_U2;
1059         case MONO_TYPE_I4:
1060                 return CEE_LDIND_I4;
1061         case MONO_TYPE_U4:
1062                 return CEE_LDIND_U4;
1063         case MONO_TYPE_I:
1064         case MONO_TYPE_U:
1065         case MONO_TYPE_PTR:
1066         case MONO_TYPE_FNPTR:
1067                 return CEE_LDIND_I;
1068         case MONO_TYPE_CLASS:
1069         case MONO_TYPE_STRING:
1070         case MONO_TYPE_OBJECT:
1071         case MONO_TYPE_SZARRAY:
1072         case MONO_TYPE_ARRAY:    
1073                 return CEE_LDIND_REF;
1074         case MONO_TYPE_I8:
1075         case MONO_TYPE_U8:
1076                 return CEE_LDIND_I8;
1077         case MONO_TYPE_R4:
1078                 return CEE_LDIND_R4;
1079         case MONO_TYPE_R8:
1080                 return CEE_LDIND_R8;
1081         case MONO_TYPE_VALUETYPE:
1082                 if (type->data.klass->enumtype) {
1083                         type = mono_class_enum_basetype (type->data.klass);
1084                         goto handle_enum;
1085                 }
1086                 return CEE_LDOBJ;
1087         case MONO_TYPE_TYPEDBYREF:
1088                 return CEE_LDOBJ;
1089         case MONO_TYPE_GENERICINST:
1090                 type = &type->data.generic_class->container_class->byval_arg;
1091                 goto handle_enum;
1092         default:
1093                 g_error ("unknown type 0x%02x in type_to_ldind", type->type);
1094         }
1095         return -1;
1096 }
1097
1098 guint
1099 mono_type_to_stind (MonoType *type)
1100 {
1101         if (type->byref)
1102                 return CEE_STIND_I;
1103
1104 handle_enum:
1105         switch (type->type) {
1106         case MONO_TYPE_I1:
1107         case MONO_TYPE_U1:
1108         case MONO_TYPE_BOOLEAN:
1109                 return CEE_STIND_I1;
1110         case MONO_TYPE_I2:
1111         case MONO_TYPE_U2:
1112         case MONO_TYPE_CHAR:
1113                 return CEE_STIND_I2;
1114         case MONO_TYPE_I4:
1115         case MONO_TYPE_U4:
1116                 return CEE_STIND_I4;
1117         case MONO_TYPE_I:
1118         case MONO_TYPE_U:
1119         case MONO_TYPE_PTR:
1120         case MONO_TYPE_FNPTR:
1121                 return CEE_STIND_I;
1122         case MONO_TYPE_CLASS:
1123         case MONO_TYPE_STRING:
1124         case MONO_TYPE_OBJECT:
1125         case MONO_TYPE_SZARRAY:
1126         case MONO_TYPE_ARRAY:    
1127                 return CEE_STIND_REF;
1128         case MONO_TYPE_I8:
1129         case MONO_TYPE_U8:
1130                 return CEE_STIND_I8;
1131         case MONO_TYPE_R4:
1132                 return CEE_STIND_R4;
1133         case MONO_TYPE_R8:
1134                 return CEE_STIND_R8;
1135         case MONO_TYPE_VALUETYPE:
1136                 if (type->data.klass->enumtype) {
1137                         type = mono_class_enum_basetype (type->data.klass);
1138                         goto handle_enum;
1139                 }
1140                 return CEE_STOBJ;
1141         case MONO_TYPE_TYPEDBYREF:
1142                 return CEE_STOBJ;
1143         case MONO_TYPE_GENERICINST:
1144                 type = &type->data.generic_class->container_class->byval_arg;
1145                 goto handle_enum;
1146         default:
1147                 g_error ("unknown type 0x%02x in type_to_stind", type->type);
1148         }
1149         return -1;
1150 }
1151
1152 #ifndef DISABLE_JIT
1153
1154 static void
1155 emit_ptr_to_object_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv conv, MonoMarshalSpec *mspec)
1156 {
1157         switch (conv) {
1158         case MONO_MARSHAL_CONV_BOOL_I4:
1159                 mono_mb_emit_ldloc (mb, 1);
1160                 mono_mb_emit_ldloc (mb, 0);
1161                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
1162                 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
1163                 mono_mb_emit_byte (mb, 3);
1164                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1165                 mono_mb_emit_byte (mb, CEE_BR_S);
1166                 mono_mb_emit_byte (mb, 1);
1167                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1168                 mono_mb_emit_byte (mb, CEE_STIND_I1);
1169                 break;
1170         case MONO_MARSHAL_CONV_BOOL_VARIANTBOOL:
1171                 mono_mb_emit_ldloc (mb, 1);
1172                 mono_mb_emit_ldloc (mb, 0);
1173                 mono_mb_emit_byte (mb, CEE_LDIND_I2);
1174                 mono_mb_emit_byte (mb, CEE_BRFALSE_S);
1175                 mono_mb_emit_byte (mb, 3);
1176                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1177                 mono_mb_emit_byte (mb, CEE_BR_S);
1178                 mono_mb_emit_byte (mb, 1);
1179                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1180                 mono_mb_emit_byte (mb, CEE_STIND_I1);
1181                 break;
1182         case MONO_MARSHAL_CONV_ARRAY_BYVALARRAY: {
1183                 MonoClass *eklass = NULL;
1184                 int esize;
1185
1186                 if (type->type == MONO_TYPE_SZARRAY) {
1187                         eklass = type->data.klass;
1188                 } else {
1189                         g_assert_not_reached ();
1190                 }
1191
1192                 esize = mono_class_native_size (eklass, NULL);
1193
1194                 /* create a new array */
1195                 mono_mb_emit_ldloc (mb, 1);
1196                 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1197                 mono_mb_emit_op (mb, CEE_NEWARR, eklass);       
1198                 mono_mb_emit_byte (mb, CEE_STIND_I);
1199
1200                 if (eklass->blittable) {
1201                         /* copy the elements */
1202                         mono_mb_emit_ldloc (mb, 1);
1203                         mono_mb_emit_byte (mb, CEE_LDIND_I);
1204                         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
1205                         mono_mb_emit_byte (mb, CEE_ADD);
1206                         mono_mb_emit_ldloc (mb, 0);
1207                         mono_mb_emit_icon (mb, mspec->data.array_data.num_elem * esize);
1208                         mono_mb_emit_byte (mb, CEE_PREFIX1);
1209                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
1210                 }
1211                 else {
1212                         int array_var, src_var, dst_var, index_var;
1213                         guint32 label2, label3;
1214
1215                         array_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
1216                         src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1217                         dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1218
1219                         /* set array_var */
1220                         mono_mb_emit_ldloc (mb, 1);
1221                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
1222                         mono_mb_emit_stloc (mb, array_var);
1223                 
1224                         /* save the old src pointer */
1225                         mono_mb_emit_ldloc (mb, 0);
1226                         mono_mb_emit_stloc (mb, src_var);
1227                         /* save the old dst pointer */
1228                         mono_mb_emit_ldloc (mb, 1);
1229                         mono_mb_emit_stloc (mb, dst_var);
1230
1231                         /* Emit marshalling loop */
1232                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1233                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1234                         mono_mb_emit_stloc (mb, index_var);
1235
1236                         /* Loop header */
1237                         label2 = mono_mb_get_label (mb);
1238                         mono_mb_emit_ldloc (mb, index_var);
1239                         mono_mb_emit_ldloc (mb, array_var);
1240                         mono_mb_emit_byte (mb, CEE_LDLEN);
1241                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
1242
1243                         /* src is already set */
1244
1245                         /* Set dst */
1246                         mono_mb_emit_ldloc (mb, array_var);
1247                         mono_mb_emit_ldloc (mb, index_var);
1248                         mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
1249                         mono_mb_emit_stloc (mb, 1);
1250
1251                         /* Do the conversion */
1252                         emit_struct_conv (mb, eklass, TRUE);
1253
1254                         /* Loop footer */
1255                         mono_mb_emit_add_to_local (mb, index_var, 1);
1256
1257                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
1258
1259                         mono_mb_patch_branch (mb, label3);
1260                 
1261                         /* restore the old src pointer */
1262                         mono_mb_emit_ldloc (mb, src_var);
1263                         mono_mb_emit_stloc (mb, 0);
1264                         /* restore the old dst pointer */
1265                         mono_mb_emit_ldloc (mb, dst_var);
1266                         mono_mb_emit_stloc (mb, 1);
1267                 }
1268                 break;
1269         }
1270         case MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY: {
1271                 MonoClass *eclass = mono_defaults.char_class;
1272
1273                 /* create a new array */
1274                 mono_mb_emit_ldloc (mb, 1);
1275                 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1276                 mono_mb_emit_op (mb, CEE_NEWARR, eclass);       
1277                 mono_mb_emit_byte (mb, CEE_STIND_REF);
1278
1279                 mono_mb_emit_ldloc (mb, 1);
1280                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1281                 mono_mb_emit_ldloc (mb, 0);
1282                 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1283                 mono_mb_emit_icall (mb, mono_byvalarray_to_byte_array);
1284                 break;
1285         }
1286         case MONO_MARSHAL_CONV_STR_BYVALSTR: 
1287                 if (mspec && mspec->native == MONO_NATIVE_BYVALTSTR && mspec->data.array_data.num_elem) {
1288                         mono_mb_emit_ldloc (mb, 1);
1289                         mono_mb_emit_ldloc (mb, 0);
1290                         mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1291                         mono_mb_emit_icall (mb, mono_string_from_byvalstr);
1292                 } else {
1293                         mono_mb_emit_ldloc (mb, 1);
1294                         mono_mb_emit_ldloc (mb, 0);
1295                         mono_mb_emit_icall (mb, mono_string_new_wrapper);
1296                 }
1297                 mono_mb_emit_byte (mb, CEE_STIND_REF);          
1298                 break;
1299         case MONO_MARSHAL_CONV_STR_BYVALWSTR:
1300                 if (mspec && mspec->native == MONO_NATIVE_BYVALTSTR && mspec->data.array_data.num_elem) {
1301                         mono_mb_emit_ldloc (mb, 1);
1302                         mono_mb_emit_ldloc (mb, 0);
1303                         mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1304                         mono_mb_emit_icall (mb, mono_string_from_byvalwstr);
1305                 } else {
1306                         mono_mb_emit_ldloc (mb, 1);
1307                         mono_mb_emit_ldloc (mb, 0);
1308                         mono_mb_emit_icall (mb, mono_string_from_utf16);
1309                 }
1310                 mono_mb_emit_byte (mb, CEE_STIND_REF);          
1311                 break;          
1312         case MONO_MARSHAL_CONV_STR_LPTSTR:
1313                 mono_mb_emit_ldloc (mb, 1);
1314                 mono_mb_emit_ldloc (mb, 0);
1315                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1316 #ifdef TARGET_WIN32
1317                 mono_mb_emit_icall (mb, mono_string_from_utf16);
1318 #else
1319                 mono_mb_emit_icall (mb, mono_string_new_wrapper);
1320 #endif
1321                 mono_mb_emit_byte (mb, CEE_STIND_REF);  
1322                 break;
1323         case MONO_MARSHAL_CONV_STR_LPSTR:
1324                 mono_mb_emit_ldloc (mb, 1);
1325                 mono_mb_emit_ldloc (mb, 0);
1326                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1327                 mono_mb_emit_icall (mb, mono_string_new_wrapper);
1328                 mono_mb_emit_byte (mb, CEE_STIND_REF);          
1329                 break;
1330         case MONO_MARSHAL_CONV_STR_LPWSTR:
1331                 mono_mb_emit_ldloc (mb, 1);
1332                 mono_mb_emit_ldloc (mb, 0);
1333                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1334                 mono_mb_emit_icall (mb, mono_string_from_utf16);
1335                 mono_mb_emit_byte (mb, CEE_STIND_REF);
1336                 break;
1337         case MONO_MARSHAL_CONV_OBJECT_STRUCT: {
1338                 MonoClass *klass = mono_class_from_mono_type (type);
1339                 int src_var, dst_var;
1340
1341                 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1342                 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1343                 
1344                 /* *dst = new object */
1345                 mono_mb_emit_ldloc (mb, 1);
1346                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1347                 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);   
1348                 mono_mb_emit_byte (mb, CEE_STIND_REF);
1349         
1350                 /* save the old src pointer */
1351                 mono_mb_emit_ldloc (mb, 0);
1352                 mono_mb_emit_stloc (mb, src_var);
1353                 /* save the old dst pointer */
1354                 mono_mb_emit_ldloc (mb, 1);
1355                 mono_mb_emit_stloc (mb, dst_var);
1356
1357                 /* dst = pointer to newly created object data */
1358                 mono_mb_emit_ldloc (mb, 1);
1359                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1360                 mono_mb_emit_icon (mb, sizeof (MonoObject));
1361                 mono_mb_emit_byte (mb, CEE_ADD);
1362                 mono_mb_emit_stloc (mb, 1); 
1363
1364                 emit_struct_conv (mb, klass, TRUE);
1365                 
1366                 /* restore the old src pointer */
1367                 mono_mb_emit_ldloc (mb, src_var);
1368                 mono_mb_emit_stloc (mb, 0);
1369                 /* restore the old dst pointer */
1370                 mono_mb_emit_ldloc (mb, dst_var);
1371                 mono_mb_emit_stloc (mb, 1);
1372                 break;
1373         }
1374         case MONO_MARSHAL_CONV_DEL_FTN: {
1375                 MonoClass *klass = mono_class_from_mono_type (type);
1376
1377                 mono_mb_emit_ldloc (mb, 1);
1378                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1379                 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
1380                 mono_mb_emit_ldloc (mb, 0);
1381                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1382                 mono_mb_emit_icall (mb, mono_ftnptr_to_delegate);
1383                 mono_mb_emit_byte (mb, CEE_STIND_REF);
1384                 break;
1385         }
1386         case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1387                 g_error ("Structure field of type %s can't be marshalled as LPArray", mono_class_from_mono_type (type)->name);
1388                 break;
1389
1390 #ifndef DISABLE_COM
1391         case MONO_MARSHAL_CONV_OBJECT_INTERFACE:
1392         case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN:
1393         case MONO_MARSHAL_CONV_OBJECT_IDISPATCH:
1394                 mono_cominterop_emit_ptr_to_object_conv (mb, type, conv, mspec);
1395                 break;
1396 #endif /* DISABLE_COM */
1397
1398         case MONO_MARSHAL_CONV_SAFEHANDLE: {
1399                 /*
1400                  * Passing SafeHandles as ref does not allow the unmanaged code
1401                  * to change the SafeHandle value.   If the value is changed,
1402                  * we should issue a diagnostic exception (NotSupportedException)
1403                  * that informs the user that changes to handles in unmanaged code
1404                  * is not supported. 
1405                  *
1406                  * Since we currently have no access to the original
1407                  * SafeHandle that was used during the marshalling,
1408                  * for now we just ignore this, and ignore/discard any
1409                  * changes that might have happened to the handle.
1410                  */
1411                 break;
1412         }
1413                 
1414         case MONO_MARSHAL_CONV_HANDLEREF: {
1415                 /*
1416                  * Passing HandleRefs in a struct that is ref()ed does not 
1417                  * copy the values back to the HandleRef
1418                  */
1419                 break;
1420         }
1421                 
1422         case MONO_MARSHAL_CONV_STR_BSTR:
1423         case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1424         case MONO_MARSHAL_CONV_STR_TBSTR:
1425         case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1426         default: {
1427                 char *msg = g_strdup_printf ("marshaling conversion %d not implemented", conv);
1428
1429                 mono_mb_emit_exception_marshal_directive (mb, msg);
1430                 break;
1431         }
1432         }
1433 }
1434
1435 static gpointer
1436 conv_to_icall (MonoMarshalConv conv)
1437 {
1438         switch (conv) {
1439         case MONO_MARSHAL_CONV_STR_LPWSTR:
1440                 return mono_marshal_string_to_utf16;            
1441         case MONO_MARSHAL_CONV_LPWSTR_STR:
1442                 return mono_string_from_utf16;
1443         case MONO_MARSHAL_CONV_LPTSTR_STR:
1444                 return mono_string_new_wrapper;
1445         case MONO_MARSHAL_CONV_LPSTR_STR:
1446                 return mono_string_new_wrapper;
1447         case MONO_MARSHAL_CONV_STR_LPTSTR:
1448 #ifdef TARGET_WIN32
1449                 return mono_marshal_string_to_utf16;
1450 #else
1451                 return mono_string_to_lpstr;
1452 #endif
1453         case MONO_MARSHAL_CONV_STR_LPSTR:
1454                 return mono_string_to_lpstr;
1455         case MONO_MARSHAL_CONV_STR_BSTR:
1456                 return mono_string_to_bstr;
1457         case MONO_MARSHAL_CONV_BSTR_STR:
1458                 return mono_string_from_bstr;
1459         case MONO_MARSHAL_CONV_STR_TBSTR:
1460         case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1461                 return mono_string_to_ansibstr;
1462         case MONO_MARSHAL_CONV_SB_LPSTR:
1463                 return mono_string_builder_to_utf8;
1464         case MONO_MARSHAL_CONV_SB_LPTSTR:
1465 #ifdef TARGET_WIN32
1466                 return mono_string_builder_to_utf16;
1467 #else
1468                 return mono_string_builder_to_utf8;
1469 #endif
1470         case MONO_MARSHAL_CONV_SB_LPWSTR:
1471                 return mono_string_builder_to_utf16;
1472         case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1473                 return mono_array_to_savearray;
1474         case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1475                 return mono_array_to_lparray;
1476         case MONO_MARSHAL_FREE_LPARRAY:
1477                 return mono_free_lparray;
1478         case MONO_MARSHAL_CONV_DEL_FTN:
1479                 return mono_delegate_to_ftnptr;
1480         case MONO_MARSHAL_CONV_FTN_DEL:
1481                 return mono_ftnptr_to_delegate;
1482         case MONO_MARSHAL_CONV_LPSTR_SB:
1483                 return mono_string_utf8_to_builder;
1484         case MONO_MARSHAL_CONV_LPTSTR_SB:
1485 #ifdef TARGET_WIN32
1486                 return mono_string_utf16_to_builder;
1487 #else
1488                 return mono_string_utf8_to_builder;
1489 #endif
1490         case MONO_MARSHAL_CONV_LPWSTR_SB:
1491                 return mono_string_utf16_to_builder;
1492         case MONO_MARSHAL_FREE_ARRAY:
1493                 return mono_marshal_free_array;
1494         case MONO_MARSHAL_CONV_STR_BYVALSTR:
1495                 return mono_string_to_byvalstr;
1496         case MONO_MARSHAL_CONV_STR_BYVALWSTR:
1497                 return mono_string_to_byvalwstr;
1498         default:
1499                 g_assert_not_reached ();
1500         }
1501
1502         return NULL;
1503 }
1504
1505 static void
1506 emit_object_to_ptr_conv (MonoMethodBuilder *mb, MonoType *type, MonoMarshalConv conv, MonoMarshalSpec *mspec)
1507 {
1508         int pos;
1509
1510         switch (conv) {
1511         case MONO_MARSHAL_CONV_BOOL_I4:
1512                 mono_mb_emit_ldloc (mb, 1);
1513                 mono_mb_emit_ldloc (mb, 0);
1514                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
1515                 mono_mb_emit_byte (mb, CEE_STIND_I4);
1516                 break;
1517         case MONO_MARSHAL_CONV_BOOL_VARIANTBOOL:
1518                 mono_mb_emit_ldloc (mb, 1);
1519                 mono_mb_emit_ldloc (mb, 0);
1520                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
1521                 mono_mb_emit_byte (mb, CEE_NEG);
1522                 mono_mb_emit_byte (mb, CEE_STIND_I2);
1523                 break;
1524         case MONO_MARSHAL_CONV_STR_LPWSTR:
1525         case MONO_MARSHAL_CONV_STR_LPSTR:
1526         case MONO_MARSHAL_CONV_STR_LPTSTR:
1527         case MONO_MARSHAL_CONV_STR_BSTR:
1528         case MONO_MARSHAL_CONV_STR_ANSIBSTR:
1529         case MONO_MARSHAL_CONV_STR_TBSTR: {
1530                 int pos;
1531
1532                 /* free space if free == true */
1533                 mono_mb_emit_ldloc (mb, 2);
1534                 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
1535                 mono_mb_emit_ldloc (mb, 1);
1536                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1537                 mono_mb_emit_icall (mb, g_free);
1538                 mono_mb_patch_short_branch (mb, pos);
1539
1540                 mono_mb_emit_ldloc (mb, 1);
1541                 mono_mb_emit_ldloc (mb, 0);
1542                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1543                 mono_mb_emit_icall (mb, conv_to_icall (conv));
1544                 mono_mb_emit_byte (mb, CEE_STIND_I);    
1545                 break;
1546         }
1547         case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
1548         case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
1549         case MONO_MARSHAL_CONV_DEL_FTN:
1550                 mono_mb_emit_ldloc (mb, 1);
1551                 mono_mb_emit_ldloc (mb, 0);
1552                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1553                 mono_mb_emit_icall (mb, conv_to_icall (conv));
1554                 mono_mb_emit_byte (mb, CEE_STIND_I);    
1555                 break;
1556         case MONO_MARSHAL_CONV_STR_BYVALSTR: 
1557         case MONO_MARSHAL_CONV_STR_BYVALWSTR: {
1558                 g_assert (mspec);
1559
1560                 mono_mb_emit_ldloc (mb, 1); /* dst */
1561                 mono_mb_emit_ldloc (mb, 0);     
1562                 mono_mb_emit_byte (mb, CEE_LDIND_REF); /* src String */
1563                 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1564                 mono_mb_emit_icall (mb, conv_to_icall (conv));
1565                 break;
1566         }
1567         case MONO_MARSHAL_CONV_ARRAY_BYVALARRAY: {
1568                 MonoClass *eklass = NULL;
1569                 int esize;
1570
1571                 if (type->type == MONO_TYPE_SZARRAY) {
1572                         eklass = type->data.klass;
1573                 } else {
1574                         g_assert_not_reached ();
1575                 }
1576
1577                 if (eklass->valuetype)
1578                         esize = mono_class_native_size (eklass, NULL);
1579                 else
1580                         esize = sizeof (gpointer);
1581
1582                 mono_mb_emit_ldloc (mb, 0);
1583                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1584                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
1585
1586                 if (eklass->blittable) {
1587                         mono_mb_emit_ldloc (mb, 1);
1588                         mono_mb_emit_ldloc (mb, 0);     
1589                         mono_mb_emit_byte (mb, CEE_LDIND_REF);  
1590                         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
1591                         mono_mb_emit_icon (mb, mspec->data.array_data.num_elem * esize);
1592                         mono_mb_emit_byte (mb, CEE_PREFIX1);
1593                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
1594                 } else {
1595                         int array_var, src_var, dst_var, index_var;
1596                         guint32 label2, label3;
1597
1598                         array_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
1599                         src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1600                         dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1601
1602                         /* set array_var */
1603                         mono_mb_emit_ldloc (mb, 0);     
1604                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
1605                         mono_mb_emit_stloc (mb, array_var);
1606
1607                         /* save the old src pointer */
1608                         mono_mb_emit_ldloc (mb, 0);
1609                         mono_mb_emit_stloc (mb, src_var);
1610                         /* save the old dst pointer */
1611                         mono_mb_emit_ldloc (mb, 1);
1612                         mono_mb_emit_stloc (mb, dst_var);
1613
1614                         /* Emit marshalling loop */
1615                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1616                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1617                         mono_mb_emit_stloc (mb, index_var);
1618
1619                         /* Loop header */
1620                         label2 = mono_mb_get_label (mb);
1621                         mono_mb_emit_ldloc (mb, index_var);
1622                         mono_mb_emit_ldloc (mb, array_var);
1623                         mono_mb_emit_byte (mb, CEE_LDLEN);
1624                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
1625
1626                         /* Set src */
1627                         mono_mb_emit_ldloc (mb, array_var);
1628                         mono_mb_emit_ldloc (mb, index_var);
1629                         mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
1630                         mono_mb_emit_stloc (mb, 0);
1631
1632                         /* dst is already set */
1633
1634                         /* Do the conversion */
1635                         emit_struct_conv (mb, eklass, FALSE);
1636
1637                         /* Loop footer */
1638                         mono_mb_emit_add_to_local (mb, index_var, 1);
1639
1640                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
1641
1642                         mono_mb_patch_branch (mb, label3);
1643                 
1644                         /* restore the old src pointer */
1645                         mono_mb_emit_ldloc (mb, src_var);
1646                         mono_mb_emit_stloc (mb, 0);
1647                         /* restore the old dst pointer */
1648                         mono_mb_emit_ldloc (mb, dst_var);
1649                         mono_mb_emit_stloc (mb, 1);
1650                 }
1651
1652                 mono_mb_patch_branch (mb, pos);
1653                 break;
1654         }
1655         case MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY: {
1656                 mono_mb_emit_ldloc (mb, 0);
1657                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1658                 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
1659
1660                 mono_mb_emit_ldloc (mb, 1);
1661                 mono_mb_emit_ldloc (mb, 0);     
1662                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1663                 mono_mb_emit_icon (mb, mspec->data.array_data.num_elem);
1664                 mono_mb_emit_icall (mb, mono_array_to_byte_byvalarray);
1665                 mono_mb_patch_short_branch (mb, pos);
1666                 break;
1667         }
1668         case MONO_MARSHAL_CONV_OBJECT_STRUCT: {
1669                 int src_var, dst_var;
1670
1671                 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1672                 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1673                 
1674                 mono_mb_emit_ldloc (mb, 0);
1675                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1676                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
1677                 
1678                 /* save the old src pointer */
1679                 mono_mb_emit_ldloc (mb, 0);
1680                 mono_mb_emit_stloc (mb, src_var);
1681                 /* save the old dst pointer */
1682                 mono_mb_emit_ldloc (mb, 1);
1683                 mono_mb_emit_stloc (mb, dst_var);
1684
1685                 /* src = pointer to object data */
1686                 mono_mb_emit_ldloc (mb, 0);
1687                 mono_mb_emit_byte (mb, CEE_LDIND_I);            
1688                 mono_mb_emit_icon (mb, sizeof (MonoObject));
1689                 mono_mb_emit_byte (mb, CEE_ADD);
1690                 mono_mb_emit_stloc (mb, 0); 
1691
1692                 emit_struct_conv (mb, mono_class_from_mono_type (type), FALSE);
1693                 
1694                 /* restore the old src pointer */
1695                 mono_mb_emit_ldloc (mb, src_var);
1696                 mono_mb_emit_stloc (mb, 0);
1697                 /* restore the old dst pointer */
1698                 mono_mb_emit_ldloc (mb, dst_var);
1699                 mono_mb_emit_stloc (mb, 1);
1700
1701                 mono_mb_patch_branch (mb, pos);
1702                 break;
1703         }
1704
1705 #ifndef DISABLE_COM
1706         case MONO_MARSHAL_CONV_OBJECT_INTERFACE:
1707         case MONO_MARSHAL_CONV_OBJECT_IDISPATCH:
1708         case MONO_MARSHAL_CONV_OBJECT_IUNKNOWN:
1709                 mono_cominterop_emit_object_to_ptr_conv (mb, type, conv, mspec);
1710                 break;
1711 #endif /* DISABLE_COM */
1712
1713         case MONO_MARSHAL_CONV_SAFEHANDLE: {
1714                 int pos;
1715                 
1716                 mono_mb_emit_ldloc (mb, 0);
1717                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1718                 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
1719                 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
1720                 mono_mb_patch_branch (mb, pos);
1721                 
1722                 /* Pull the handle field from SafeHandle */
1723                 mono_mb_emit_ldloc (mb, 1);
1724                 mono_mb_emit_ldloc (mb, 0);
1725                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1726                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
1727                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1728                 mono_mb_emit_byte (mb, CEE_STIND_I);
1729                 break;
1730         }
1731
1732         case MONO_MARSHAL_CONV_HANDLEREF: {
1733                 mono_mb_emit_ldloc (mb, 1);
1734                 mono_mb_emit_ldloc (mb, 0);
1735                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoHandleRef, handle));
1736                 mono_mb_emit_byte (mb, CEE_ADD);
1737                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1738                 mono_mb_emit_byte (mb, CEE_STIND_I);
1739                 break;
1740         }
1741                 
1742         default: {
1743                 char *msg = g_strdup_printf ("marshalling conversion %d not implemented", conv);
1744                 MonoException *exc = mono_get_exception_not_implemented (msg);
1745                 g_warning ("%s", msg);
1746                 g_free (msg);
1747                 mono_raise_exception (exc);
1748         }
1749         }
1750 }
1751
1752 static void
1753 emit_struct_conv_full (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object,
1754                                            MonoMarshalNative string_encoding)
1755 {
1756         MonoMarshalType *info;
1757         int i;
1758
1759         if (klass->parent)
1760                 emit_struct_conv(mb, klass->parent, to_object);
1761
1762         info = mono_marshal_load_type_info (klass);
1763
1764         if (info->native_size == 0)
1765                 return;
1766
1767         if (klass->blittable) {
1768                 int msize = mono_class_value_size (klass, NULL);
1769                 g_assert (msize == info->native_size);
1770                 mono_mb_emit_ldloc (mb, 1);
1771                 mono_mb_emit_ldloc (mb, 0);
1772                 mono_mb_emit_icon (mb, msize);
1773                 mono_mb_emit_byte (mb, CEE_PREFIX1);
1774                 mono_mb_emit_byte (mb, CEE_CPBLK);
1775
1776                 mono_mb_emit_add_to_local (mb, 0, msize);
1777                 mono_mb_emit_add_to_local (mb, 1, msize);
1778                 return;
1779         }
1780
1781         if (klass != mono_defaults.safehandle_class) {
1782                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
1783                         char *msg = g_strdup_printf ("Type %s which is passed to unmanaged code must have a StructLayout attribute.",
1784                                                                                  mono_type_full_name (&klass->byval_arg));
1785                         mono_mb_emit_exception_marshal_directive (mb, msg);
1786                         return;
1787                 }
1788         }
1789
1790         for (i = 0; i < info->num_fields; i++) {
1791                 MonoMarshalNative ntype;
1792                 MonoMarshalConv conv;
1793                 MonoType *ftype = info->fields [i].field->type;
1794                 int msize = 0;
1795                 int usize = 0;
1796                 gboolean last_field = i < (info->num_fields -1) ? 0 : 1;
1797
1798                 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
1799                         continue;
1800
1801                 ntype = mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, klass->unicode, &conv);
1802
1803                 if (last_field) {
1804                         msize = klass->instance_size - info->fields [i].field->offset;
1805                         usize = info->native_size - info->fields [i].offset;
1806                 } else {
1807                         msize = info->fields [i + 1].field->offset - info->fields [i].field->offset;
1808                         usize = info->fields [i + 1].offset - info->fields [i].offset;
1809                 }
1810
1811                 if (klass != mono_defaults.safehandle_class){
1812                         /* 
1813                          * FIXME: Should really check for usize==0 and msize>0, but we apply 
1814                          * the layout to the managed structure as well.
1815                          */
1816                         
1817                         if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) && (usize == 0)) {
1818                                 if (MONO_TYPE_IS_REFERENCE (info->fields [i].field->type) ||
1819                                     ((!last_field && MONO_TYPE_IS_REFERENCE (info->fields [i + 1].field->type))))
1820                                         g_error ("Type %s which has an [ExplicitLayout] attribute cannot have a "
1821                                                  "reference field at the same offset as another field.",
1822                                                  mono_type_full_name (&klass->byval_arg));
1823                         }
1824                 }
1825                 
1826                 switch (conv) {
1827                 case MONO_MARSHAL_CONV_NONE: {
1828                         int t;
1829
1830                         if (ftype->byref || ftype->type == MONO_TYPE_I ||
1831                             ftype->type == MONO_TYPE_U) {
1832                                 mono_mb_emit_ldloc (mb, 1);
1833                                 mono_mb_emit_ldloc (mb, 0);
1834                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
1835                                 mono_mb_emit_byte (mb, CEE_STIND_I);
1836                                 break;
1837                         }
1838
1839                 handle_enum:
1840                         t = ftype->type;
1841                         switch (t) {
1842                         case MONO_TYPE_I4:
1843                         case MONO_TYPE_U4:
1844                         case MONO_TYPE_I1:
1845                         case MONO_TYPE_U1:
1846                         case MONO_TYPE_BOOLEAN:
1847                         case MONO_TYPE_I2:
1848                         case MONO_TYPE_U2:
1849                         case MONO_TYPE_CHAR:
1850                         case MONO_TYPE_I8:
1851                         case MONO_TYPE_U8:
1852                         case MONO_TYPE_PTR:
1853                         case MONO_TYPE_R4:
1854                         case MONO_TYPE_R8:
1855                                 mono_mb_emit_ldloc (mb, 1);
1856                                 mono_mb_emit_ldloc (mb, 0);
1857                                 if (t == MONO_TYPE_CHAR && ntype == MONO_NATIVE_U1 && string_encoding != MONO_NATIVE_LPWSTR) {
1858                                         if (to_object) {
1859                                                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
1860                                                 mono_mb_emit_byte (mb, CEE_STIND_I2);
1861                                         } else {
1862                                                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
1863                                                 mono_mb_emit_byte (mb, CEE_STIND_I1);
1864                                         }
1865                                 } else {
1866                                         mono_mb_emit_byte (mb, mono_type_to_ldind (ftype));
1867                                         mono_mb_emit_byte (mb, mono_type_to_stind (ftype));
1868                                 }
1869                                 break;
1870                         case MONO_TYPE_VALUETYPE: {
1871                                 int src_var, dst_var;
1872
1873                                 if (ftype->data.klass->enumtype) {
1874                                         ftype = mono_class_enum_basetype (ftype->data.klass);
1875                                         goto handle_enum;
1876                                 }
1877
1878                                 src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1879                                 dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1880         
1881                                 /* save the old src pointer */
1882                                 mono_mb_emit_ldloc (mb, 0);
1883                                 mono_mb_emit_stloc (mb, src_var);
1884                                 /* save the old dst pointer */
1885                                 mono_mb_emit_ldloc (mb, 1);
1886                                 mono_mb_emit_stloc (mb, dst_var);
1887
1888                                 emit_struct_conv (mb, ftype->data.klass, to_object);
1889
1890                                 /* restore the old src pointer */
1891                                 mono_mb_emit_ldloc (mb, src_var);
1892                                 mono_mb_emit_stloc (mb, 0);
1893                                 /* restore the old dst pointer */
1894                                 mono_mb_emit_ldloc (mb, dst_var);
1895                                 mono_mb_emit_stloc (mb, 1);
1896                                 break;
1897                         }
1898                         case MONO_TYPE_OBJECT: {
1899 #ifndef DISABLE_COM
1900                                 if (to_object) {
1901                                         static MonoMethod *variant_clear = NULL;
1902                                         static MonoMethod *get_object_for_native_variant = NULL;
1903
1904                                         if (!variant_clear)
1905                                                 variant_clear = mono_class_get_method_from_name (mono_class_get_variant_class (), "Clear", 0);
1906                                         if (!get_object_for_native_variant)
1907                                                 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
1908                                         mono_mb_emit_ldloc (mb, 1);
1909                                         mono_mb_emit_ldloc (mb, 0);
1910                                         mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
1911                                         mono_mb_emit_byte (mb, CEE_STIND_REF);
1912
1913                                         mono_mb_emit_ldloc (mb, 0);
1914                                         mono_mb_emit_managed_call (mb, variant_clear, NULL);
1915                                 }
1916                                 else {
1917                                         static MonoMethod *get_native_variant_for_object = NULL;
1918
1919                                         if (!get_native_variant_for_object)
1920                                                 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
1921
1922                                         mono_mb_emit_ldloc (mb, 0);
1923                                         mono_mb_emit_byte(mb, CEE_LDIND_REF);
1924                                         mono_mb_emit_ldloc (mb, 1);
1925                                         mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
1926                                 }
1927 #else
1928                                 char *msg = g_strdup_printf ("COM support was disabled at compilation time.");
1929                                 mono_mb_emit_exception_marshal_directive (mb, msg);
1930 #endif
1931                                 break;
1932                         }
1933
1934                         default: 
1935                                 g_warning ("marshaling type %02x not implemented", ftype->type);
1936                                 g_assert_not_reached ();
1937                         }
1938                         break;
1939                 }
1940                 default: {
1941                         int src_var, dst_var;
1942
1943                         src_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1944                         dst_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1945
1946                         /* save the old src pointer */
1947                         mono_mb_emit_ldloc (mb, 0);
1948                         mono_mb_emit_stloc (mb, src_var);
1949                         /* save the old dst pointer */
1950                         mono_mb_emit_ldloc (mb, 1);
1951                         mono_mb_emit_stloc (mb, dst_var);
1952
1953                         if (to_object) 
1954                                 emit_ptr_to_object_conv (mb, ftype, conv, info->fields [i].mspec);
1955                         else
1956                                 emit_object_to_ptr_conv (mb, ftype, conv, info->fields [i].mspec);
1957
1958                         /* restore the old src pointer */
1959                         mono_mb_emit_ldloc (mb, src_var);
1960                         mono_mb_emit_stloc (mb, 0);
1961                         /* restore the old dst pointer */
1962                         mono_mb_emit_ldloc (mb, dst_var);
1963                         mono_mb_emit_stloc (mb, 1);
1964                 }
1965                 }
1966
1967                 if (to_object) {
1968                         mono_mb_emit_add_to_local (mb, 0, usize);
1969                         mono_mb_emit_add_to_local (mb, 1, msize);
1970                 } else {
1971                         mono_mb_emit_add_to_local (mb, 0, msize);
1972                         mono_mb_emit_add_to_local (mb, 1, usize);
1973                 }                               
1974         }
1975 }
1976
1977 static void
1978 emit_struct_conv (MonoMethodBuilder *mb, MonoClass *klass, gboolean to_object)
1979 {
1980         emit_struct_conv_full (mb, klass, to_object, -1);
1981 }
1982
1983 static void
1984 emit_struct_free (MonoMethodBuilder *mb, MonoClass *klass, int struct_var)
1985 {
1986         /* Call DestroyStructure */
1987         /* FIXME: Only do this if needed */
1988         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1989         mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
1990         mono_mb_emit_ldloc (mb, struct_var);
1991         mono_mb_emit_icall (mb, mono_struct_delete_old);
1992 }
1993
1994 static void
1995 emit_thread_interrupt_checkpoint_call (MonoMethodBuilder *mb, gpointer checkpoint_func)
1996 {
1997         int pos_noabort, pos_noex;
1998
1999         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
2000         mono_mb_emit_byte (mb, CEE_MONO_LDPTR_INT_REQ_FLAG);
2001         mono_mb_emit_byte (mb, CEE_LDIND_U4);
2002         pos_noabort = mono_mb_emit_branch (mb, CEE_BRFALSE);
2003
2004         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
2005         mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
2006
2007         mono_mb_emit_icall (mb, checkpoint_func);
2008         /* Throw the exception returned by the checkpoint function, if any */
2009         mono_mb_emit_byte (mb, CEE_DUP);
2010         pos_noex = mono_mb_emit_branch (mb, CEE_BRFALSE);
2011         mono_mb_emit_byte (mb, CEE_THROW);
2012         mono_mb_patch_branch (mb, pos_noex);
2013         mono_mb_emit_byte (mb, CEE_POP);
2014         
2015         mono_mb_patch_branch (mb, pos_noabort);
2016 }
2017
2018 static void
2019 emit_thread_interrupt_checkpoint (MonoMethodBuilder *mb)
2020 {
2021         if (strstr (mb->name, "mono_thread_interruption_checkpoint"))
2022                 return;
2023         
2024         emit_thread_interrupt_checkpoint_call (mb, mono_thread_interruption_checkpoint);
2025 }
2026
2027 static void
2028 emit_thread_force_interrupt_checkpoint (MonoMethodBuilder *mb)
2029 {
2030         emit_thread_interrupt_checkpoint_call (mb, mono_thread_force_interruption_checkpoint_noraise);
2031 }
2032
2033 void
2034 mono_marshal_emit_thread_interrupt_checkpoint (MonoMethodBuilder *mb)
2035 {
2036         emit_thread_interrupt_checkpoint (mb);
2037 }
2038
2039 void
2040 mono_marshal_emit_thread_force_interrupt_checkpoint (MonoMethodBuilder *mb)
2041 {
2042         emit_thread_force_interrupt_checkpoint (mb);
2043 }
2044
2045 #endif /* DISABLE_JIT */
2046
2047 static MonoAsyncResult *
2048 mono_delegate_begin_invoke (MonoDelegate *delegate, gpointer *params)
2049 {
2050         MonoMulticastDelegate *mcast_delegate;
2051         MonoClass *klass;
2052         MonoMethod *method;
2053
2054         g_assert (delegate);
2055         mcast_delegate = (MonoMulticastDelegate *) delegate;
2056         if (mcast_delegate->delegates != NULL)
2057                 mono_raise_exception (mono_get_exception_argument (NULL, "The delegate must have only one target"));
2058
2059 #ifndef DISABLE_REMOTING
2060         if (delegate->target && mono_object_class (delegate->target) == mono_defaults.transparent_proxy_class) {
2061
2062                 MonoTransparentProxy* tp = (MonoTransparentProxy *)delegate->target;
2063                 if (!mono_class_is_contextbound (tp->remote_class->proxy_class) || tp->rp->context != (MonoObject *) mono_context_get ()) {
2064
2065                         /* If the target is a proxy, make a direct call. Is proxy's work
2066                         // to make the call asynchronous.
2067                         */
2068                         MonoMethodMessage *msg;
2069                         MonoDelegate *async_callback;
2070                         MonoObject *state;
2071                         MonoAsyncResult *ares;
2072                         MonoObject *exc;
2073                         MonoArray *out_args;
2074                         method = delegate->method;
2075
2076                         msg = mono_method_call_message_new (mono_marshal_method_from_wrapper (method), params, NULL, &async_callback, &state);
2077                         ares = mono_async_result_new (mono_domain_get (), NULL, state, NULL, NULL);
2078                         MONO_OBJECT_SETREF (ares, async_delegate, (MonoObject *)delegate);
2079                         MONO_OBJECT_SETREF (ares, async_callback, (MonoObject *)async_callback);
2080                         MONO_OBJECT_SETREF (msg, async_result, ares);
2081                         msg->call_type = CallType_BeginInvoke;
2082
2083                         exc = NULL;
2084                         mono_remoting_invoke ((MonoObject *)tp->rp, msg, &exc, &out_args);
2085                         if (exc)
2086                                 mono_raise_exception ((MonoException *) exc);
2087                         return ares;
2088                 }
2089         }
2090 #endif
2091
2092         klass = delegate->object.vtable->klass;
2093
2094         method = mono_class_get_method_from_name (klass, "BeginInvoke", -1);
2095         if (!method)
2096                 method = mono_get_delegate_invoke (klass);
2097         g_assert (method);
2098
2099         return mono_threadpool_ms_begin_invoke (mono_domain_get (), (MonoObject*) delegate, method, params);
2100 }
2101
2102 #ifndef DISABLE_JIT
2103
2104 int
2105 mono_mb_emit_save_args (MonoMethodBuilder *mb, MonoMethodSignature *sig, gboolean save_this)
2106 {
2107         int i, params_var, tmp_var;
2108
2109         /* allocate local (pointer) *params[] */
2110         params_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2111         /* allocate local (pointer) tmp */
2112         tmp_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
2113
2114         /* alloate space on stack to store an array of pointers to the arguments */
2115         mono_mb_emit_icon (mb, sizeof (gpointer) * (sig->param_count + 1));
2116         mono_mb_emit_byte (mb, CEE_PREFIX1);
2117         mono_mb_emit_byte (mb, CEE_LOCALLOC);
2118         mono_mb_emit_stloc (mb, params_var);
2119
2120         /* tmp = params */
2121         mono_mb_emit_ldloc (mb, params_var);
2122         mono_mb_emit_stloc (mb, tmp_var);
2123
2124         if (save_this && sig->hasthis) {
2125                 mono_mb_emit_ldloc (mb, tmp_var);
2126                 mono_mb_emit_ldarg_addr (mb, 0);
2127                 mono_mb_emit_byte (mb, CEE_STIND_I);
2128                 /* tmp = tmp + sizeof (gpointer) */
2129                 if (sig->param_count)
2130                         mono_mb_emit_add_to_local (mb, tmp_var, sizeof (gpointer));
2131
2132         }
2133
2134         for (i = 0; i < sig->param_count; i++) {
2135                 mono_mb_emit_ldloc (mb, tmp_var);
2136                 mono_mb_emit_ldarg_addr (mb, i + sig->hasthis);
2137                 mono_mb_emit_byte (mb, CEE_STIND_I);
2138                 /* tmp = tmp + sizeof (gpointer) */
2139                 if (i < (sig->param_count - 1))
2140                         mono_mb_emit_add_to_local (mb, tmp_var, sizeof (gpointer));
2141         }
2142
2143         return params_var;
2144 }
2145
2146 #endif /* DISABLE_JIT */
2147
2148 static char*
2149 mono_signature_to_name (MonoMethodSignature *sig, const char *prefix)
2150 {
2151         int i;
2152         char *result;
2153         GString *res = g_string_new ("");
2154
2155         if (prefix) {
2156                 g_string_append (res, prefix);
2157                 g_string_append_c (res, '_');
2158         }
2159
2160         mono_type_get_desc (res, sig->ret, FALSE);
2161
2162         if (sig->hasthis)
2163                 g_string_append (res, "__this__");
2164
2165         for (i = 0; i < sig->param_count; ++i) {
2166                 g_string_append_c (res, '_');
2167                 mono_type_get_desc (res, sig->params [i], FALSE);
2168         }
2169         result = res->str;
2170         g_string_free (res, FALSE);
2171         return result;
2172 }
2173
2174 /**
2175  * mono_marshal_get_string_encoding:
2176  *
2177  *  Return the string encoding which should be used for a given parameter.
2178  */
2179 static MonoMarshalNative
2180 mono_marshal_get_string_encoding (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2181 {
2182         /* First try the parameter marshal info */
2183         if (spec) {
2184                 if (spec->native == MONO_NATIVE_LPARRAY) {
2185                         if ((spec->data.array_data.elem_type != 0) && (spec->data.array_data.elem_type != MONO_NATIVE_MAX))
2186                                 return spec->data.array_data.elem_type;
2187                 }
2188                 else
2189                         return spec->native;
2190         }
2191
2192         if (!piinfo)
2193                 return MONO_NATIVE_LPSTR;
2194
2195         /* Then try the method level marshal info */
2196         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
2197         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
2198                 return MONO_NATIVE_LPSTR;
2199         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
2200                 return MONO_NATIVE_LPWSTR;
2201         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
2202 #ifdef TARGET_WIN32
2203                 return MONO_NATIVE_LPWSTR;
2204 #else
2205                 return MONO_NATIVE_LPSTR;
2206 #endif
2207         default:
2208                 return MONO_NATIVE_LPSTR;
2209         }
2210 }
2211
2212 static MonoMarshalConv
2213 mono_marshal_get_string_to_ptr_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2214 {
2215         MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2216
2217         switch (encoding) {
2218         case MONO_NATIVE_LPWSTR:
2219                 return MONO_MARSHAL_CONV_STR_LPWSTR;
2220         case MONO_NATIVE_LPSTR:
2221         case MONO_NATIVE_VBBYREFSTR:
2222                 return MONO_MARSHAL_CONV_STR_LPSTR;
2223         case MONO_NATIVE_LPTSTR:
2224                 return MONO_MARSHAL_CONV_STR_LPTSTR;
2225         case MONO_NATIVE_BSTR:
2226                 return MONO_MARSHAL_CONV_STR_BSTR;
2227         default:
2228                 return -1;
2229         }
2230 }
2231
2232 static MonoMarshalConv
2233 mono_marshal_get_stringbuilder_to_ptr_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2234 {
2235         MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2236
2237         switch (encoding) {
2238         case MONO_NATIVE_LPWSTR:
2239                 return MONO_MARSHAL_CONV_SB_LPWSTR;
2240                 break;
2241         case MONO_NATIVE_LPSTR:
2242                 return MONO_MARSHAL_CONV_SB_LPSTR;
2243                 break;
2244         case MONO_NATIVE_LPTSTR:
2245                 return MONO_MARSHAL_CONV_SB_LPTSTR;
2246                 break;
2247         default:
2248                 return -1;
2249         }
2250 }
2251
2252 static MonoMarshalConv
2253 mono_marshal_get_ptr_to_string_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec, gboolean *need_free)
2254 {
2255         MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2256
2257         *need_free = TRUE;
2258
2259         switch (encoding) {
2260         case MONO_NATIVE_LPWSTR:
2261                 *need_free = FALSE;
2262                 return MONO_MARSHAL_CONV_LPWSTR_STR;
2263         case MONO_NATIVE_LPSTR:
2264         case MONO_NATIVE_VBBYREFSTR:
2265                 return MONO_MARSHAL_CONV_LPSTR_STR;
2266         case MONO_NATIVE_LPTSTR:
2267                 return MONO_MARSHAL_CONV_LPTSTR_STR;
2268         case MONO_NATIVE_BSTR:
2269                 return MONO_MARSHAL_CONV_BSTR_STR;
2270         default:
2271                 return -1;
2272         }
2273 }
2274
2275 static MonoMarshalConv
2276 mono_marshal_get_ptr_to_stringbuilder_conv (MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec, gboolean *need_free)
2277 {
2278         MonoMarshalNative encoding = mono_marshal_get_string_encoding (piinfo, spec);
2279
2280         *need_free = TRUE;
2281
2282         switch (encoding) {
2283         case MONO_NATIVE_LPWSTR:
2284                 /* 
2285                  * mono_string_builder_to_utf16 does not allocate a 
2286                  * new buffer, so no need to free it.
2287                  */
2288                 *need_free = FALSE;
2289                 return MONO_MARSHAL_CONV_LPWSTR_SB;
2290         case MONO_NATIVE_LPSTR:
2291                 return MONO_MARSHAL_CONV_LPSTR_SB;
2292                 break;
2293         case MONO_NATIVE_LPTSTR:
2294                 return MONO_MARSHAL_CONV_LPTSTR_SB;
2295                 break;
2296         default:
2297                 return -1;
2298         }
2299 }
2300
2301 /*
2302  * Return whenever a field of a native structure or an array member needs to 
2303  * be freed.
2304  */
2305 static gboolean
2306 mono_marshal_need_free (MonoType *t, MonoMethodPInvoke *piinfo, MonoMarshalSpec *spec)
2307 {
2308         MonoMarshalNative encoding;
2309
2310         switch (t->type) {
2311         case MONO_TYPE_VALUETYPE:
2312                 /* FIXME: Optimize this */
2313                 return TRUE;
2314         case MONO_TYPE_OBJECT:
2315         case MONO_TYPE_CLASS:
2316                 if (t->data.klass == mono_defaults.stringbuilder_class) {
2317                         gboolean need_free;
2318                         mono_marshal_get_ptr_to_stringbuilder_conv (piinfo, spec, &need_free);
2319                         return need_free;
2320                 }
2321                 return FALSE;
2322         case MONO_TYPE_STRING:
2323                 encoding = mono_marshal_get_string_encoding (piinfo, spec);
2324                 return (encoding == MONO_NATIVE_LPWSTR) ? FALSE : TRUE;
2325         default:
2326                 return FALSE;
2327         }
2328 }
2329
2330 /*
2331  * Return the hash table pointed to by VAR, lazily creating it if neccesary.
2332  */
2333 static GHashTable*
2334 get_cache (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func)
2335 {
2336         if (!(*var)) {
2337                 mono_marshal_lock ();
2338                 if (!(*var)) {
2339                         GHashTable *cache = 
2340                                 g_hash_table_new (hash_func, equal_func);
2341                         mono_memory_barrier ();
2342                         *var = cache;
2343                 }
2344                 mono_marshal_unlock ();
2345         }
2346         return *var;
2347 }
2348
2349 GHashTable*
2350 mono_marshal_get_cache (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func)
2351 {
2352         return get_cache (var, hash_func, equal_func);
2353 }
2354
2355 MonoMethod*
2356 mono_marshal_find_in_cache (GHashTable *cache, gpointer key)
2357 {
2358         MonoMethod *res;
2359
2360         mono_marshal_lock ();
2361         res = g_hash_table_lookup (cache, key);
2362         mono_marshal_unlock ();
2363         return res;
2364 }
2365
2366 /*
2367  * mono_mb_create:
2368  *
2369  *   Create a MonoMethod from MB, set INFO as wrapper info.
2370  */
2371 MonoMethod*
2372 mono_mb_create (MonoMethodBuilder *mb, MonoMethodSignature *sig,
2373                                 int max_stack, WrapperInfo *info)
2374 {
2375         MonoMethod *res;
2376
2377         res = mono_mb_create_method (mb, sig, max_stack);
2378         if (info)
2379                 mono_marshal_set_wrapper_info (res, info);
2380         return res;
2381 }
2382
2383 /* Create the method from the builder and place it in the cache */
2384 MonoMethod*
2385 mono_mb_create_and_cache_full (GHashTable *cache, gpointer key,
2386                                                            MonoMethodBuilder *mb, MonoMethodSignature *sig,
2387                                                            int max_stack, WrapperInfo *info, gboolean *out_found)
2388 {
2389         MonoMethod *res;
2390
2391         if (out_found)
2392                 *out_found = FALSE;
2393
2394         mono_marshal_lock ();
2395         res = g_hash_table_lookup (cache, key);
2396         mono_marshal_unlock ();
2397         if (!res) {
2398                 MonoMethod *newm;
2399                 newm = mono_mb_create_method (mb, sig, max_stack);
2400                 mono_marshal_lock ();
2401                 res = g_hash_table_lookup (cache, key);
2402                 if (!res) {
2403                         res = newm;
2404                         g_hash_table_insert (cache, key, res);
2405                         if (info)
2406                                 mono_marshal_set_wrapper_info (res, info);
2407                         else
2408                                 mono_marshal_set_wrapper_info (res, key);
2409                         mono_marshal_unlock ();
2410                 } else {
2411                         if (out_found)
2412                                 *out_found = TRUE;
2413                         mono_marshal_unlock ();
2414                         mono_free_method (newm);
2415                 }
2416         }
2417
2418         return res;
2419 }               
2420
2421 MonoMethod*
2422 mono_mb_create_and_cache (GHashTable *cache, gpointer key,
2423                                                            MonoMethodBuilder *mb, MonoMethodSignature *sig,
2424                                                            int max_stack)
2425 {
2426         return mono_mb_create_and_cache_full (cache, key, mb, sig, max_stack, NULL, NULL);
2427 }
2428
2429 MonoMethod *
2430 mono_marshal_method_from_wrapper (MonoMethod *wrapper)
2431 {
2432         gpointer res;
2433         int wrapper_type = wrapper->wrapper_type;
2434         WrapperInfo *info;
2435
2436         if (wrapper_type == MONO_WRAPPER_NONE || wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
2437                 return wrapper;
2438
2439         switch (wrapper_type) {
2440         case MONO_WRAPPER_REMOTING_INVOKE:
2441         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2442         case MONO_WRAPPER_XDOMAIN_INVOKE:
2443         case MONO_WRAPPER_SYNCHRONIZED:
2444         case MONO_WRAPPER_UNBOX:
2445                 res = mono_marshal_get_wrapper_info (wrapper);
2446                 if (res == NULL)
2447                         return wrapper;
2448                 if (wrapper->is_inflated) {
2449                         MonoError error;
2450                         MonoMethod *result;
2451                         /*
2452                          * A method cannot be inflated and a wrapper at the same time, so the wrapper info
2453                          * contains an uninflated method.
2454                          */
2455                         result = mono_class_inflate_generic_method_checked (res, mono_method_get_context (wrapper), &error);
2456                         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2457                         return result;
2458                 }
2459                 return res;
2460         case MONO_WRAPPER_MANAGED_TO_NATIVE:
2461                 info = mono_marshal_get_wrapper_info (wrapper);
2462                 if (info && (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT || info->subtype == WRAPPER_SUBTYPE_PINVOKE))
2463                         return info->d.managed_to_native.method;
2464                 else
2465                         return NULL;
2466         case MONO_WRAPPER_RUNTIME_INVOKE:
2467                 info = mono_marshal_get_wrapper_info (wrapper);
2468                 if (info && (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL))
2469                         return info->d.runtime_invoke.method;
2470                 else
2471                         return NULL;
2472         default:
2473                 return NULL;
2474         }
2475 }
2476
2477 /*
2478  * mono_marshal_get_wrapper_info:
2479  *
2480  *   Retrieve the pointer stored by mono_marshal_set_wrapper_info. The type of data
2481  * returned depends on the wrapper type. It is usually a method, a class, or a
2482  * WrapperInfo structure.
2483  */
2484 gpointer
2485 mono_marshal_get_wrapper_info (MonoMethod *wrapper)
2486 {
2487         g_assert (wrapper->wrapper_type);
2488
2489         return mono_method_get_wrapper_data (wrapper, 1);
2490 }
2491
2492 /*
2493  * mono_marshal_set_wrapper_info:
2494  *
2495  *   Store an arbitrary pointer inside the wrapper which is retrievable by 
2496  * mono_marshal_get_wrapper_info. The format of the data depends on the type of the
2497  * wrapper (method->wrapper_type).
2498  */
2499 void
2500 mono_marshal_set_wrapper_info (MonoMethod *method, gpointer data)
2501 {
2502         void **datav;
2503         /* assert */
2504         if (method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
2505                 return;
2506
2507         datav = ((MonoMethodWrapper *)method)->method_data;
2508         datav [1] = data;
2509 }
2510
2511 WrapperInfo*
2512 mono_wrapper_info_create (MonoMethodBuilder *mb, WrapperSubtype subtype)
2513 {
2514         WrapperInfo *info;
2515
2516         info = mono_image_alloc0 (mb->method->klass->image, sizeof (WrapperInfo));
2517         info->subtype = subtype;
2518         return info;
2519 }
2520
2521 /*
2522  * get_wrapper_target_class:
2523  *
2524  *   Return the class where a wrapper method should be placed.
2525  */
2526 static MonoClass*
2527 get_wrapper_target_class (MonoImage *image)
2528 {
2529         MonoError error;
2530         MonoClass *klass;
2531
2532         /*
2533          * Notes:
2534          * - can't put all wrappers into an mscorlib class, because they reference
2535          *   metadata (signature) so they should be put into the same image as the 
2536          *   method they wrap, so they are unloaded together.
2537          * - putting them into a class with a type initalizer could cause the 
2538          *   initializer to be executed which can be a problem if the wrappers are 
2539          *   shared.
2540          * - putting them into an inflated class can cause problems if the the 
2541          *   class is deleted because it references an image which is unloaded.
2542          * To avoid these problems, we put the wrappers into the <Module> class of 
2543          * the image.
2544          */
2545         if (image_is_dynamic (image)) {
2546                 klass = ((MonoDynamicImage*)image)->wrappers_type;
2547         } else {
2548                 klass = mono_class_get_checked (image, mono_metadata_make_token (MONO_TABLE_TYPEDEF, 1), &error);
2549                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2550         }
2551         g_assert (klass);
2552
2553         return klass;
2554 }
2555
2556 /*
2557  * Wrappers for generic methods should be instances of generic wrapper methods, i.e .the wrapper for Sort<int> should be
2558  * an instance of the wrapper for Sort<T>. This is required for full-aot to work.
2559  */
2560
2561 /*
2562  * check_generic_wrapper_cache:
2563  *
2564  *   Check CACHE for the wrapper of the generic instance ORIG_METHOD, and return it if it is found.
2565  * KEY should be the key for ORIG_METHOD in the cache, while DEF_KEY should be the key of its
2566  * generic method definition.
2567  */
2568 static MonoMethod*
2569 check_generic_wrapper_cache (GHashTable *cache, MonoMethod *orig_method, gpointer key, gpointer def_key)
2570 {
2571         MonoMethod *res;
2572         MonoMethod *inst, *def;
2573         MonoGenericContext *ctx;
2574
2575         g_assert (orig_method->is_inflated);
2576         ctx = mono_method_get_context (orig_method);
2577
2578         /*
2579          * Look for the instance
2580          */
2581         res = mono_marshal_find_in_cache (cache, key);
2582         if (res)
2583                 return res;
2584
2585         /*
2586          * Look for the definition
2587          */
2588         def = mono_marshal_find_in_cache (cache, def_key);
2589         if (def) {
2590                 MonoError error;
2591                 inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
2592                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2593                 /* Cache it */
2594                 mono_memory_barrier ();
2595                 mono_marshal_lock ();
2596                 res = g_hash_table_lookup (cache, key);
2597                 if (!res) {
2598                         g_hash_table_insert (cache, key, inst);
2599                         res = inst;
2600                 }
2601                 mono_marshal_unlock ();
2602                 return res;
2603         }
2604         return NULL;
2605 }
2606
2607 static MonoMethod*
2608 cache_generic_wrapper (GHashTable *cache, MonoMethod *orig_method, MonoMethod *def, MonoGenericContext *ctx, gpointer key)
2609 {
2610         MonoError error;
2611         MonoMethod *inst, *res;
2612
2613         /*
2614          * We use the same cache for the generic definition and the instances.
2615          */
2616         inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
2617         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2618         mono_memory_barrier ();
2619         mono_marshal_lock ();
2620         res = g_hash_table_lookup (cache, key);
2621         if (!res) {
2622                 g_hash_table_insert (cache, key, inst);
2623                 res = inst;
2624         }
2625         mono_marshal_unlock ();
2626         return res;
2627 }
2628
2629 static MonoMethod*
2630 check_generic_delegate_wrapper_cache (GHashTable *cache, MonoMethod *orig_method, MonoMethod *def_method, MonoGenericContext *ctx)
2631 {
2632         MonoError error;
2633         MonoMethod *res;
2634         MonoMethod *inst, *def;
2635
2636         /*
2637          * Look for the instance
2638          */
2639         res = mono_marshal_find_in_cache (cache, orig_method->klass);
2640         if (res)
2641                 return res;
2642
2643         /*
2644          * Look for the definition
2645          */
2646         def = mono_marshal_find_in_cache (cache, def_method->klass);
2647         if (def) {
2648                 inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
2649                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2650
2651                 /* Cache it */
2652                 mono_memory_barrier ();
2653                 mono_marshal_lock ();
2654                 res = g_hash_table_lookup (cache, orig_method->klass);
2655                 if (!res) {
2656                         g_hash_table_insert (cache, orig_method->klass, inst);
2657                         res = inst;
2658                 }
2659                 mono_marshal_unlock ();
2660                 return res;
2661         }
2662         return NULL;
2663 }
2664
2665 static MonoMethod*
2666 cache_generic_delegate_wrapper (GHashTable *cache, MonoMethod *orig_method, MonoMethod *def, MonoGenericContext *ctx)
2667 {
2668         MonoError error;
2669         MonoMethod *inst, *res;
2670
2671         /*
2672          * We use the same cache for the generic definition and the instances.
2673          */
2674         inst = mono_class_inflate_generic_method_checked (def, ctx, &error);
2675         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
2676
2677         mono_memory_barrier ();
2678         mono_marshal_lock ();
2679         res = g_hash_table_lookup (cache, orig_method->klass);
2680         if (!res) {
2681                 g_hash_table_insert (cache, orig_method->klass, inst);
2682                 res = inst;
2683         }
2684         mono_marshal_unlock ();
2685         return res;
2686 }
2687
2688 MonoMethod *
2689 mono_marshal_get_delegate_begin_invoke (MonoMethod *method)
2690 {
2691         MonoMethodSignature *sig;
2692         MonoMethodBuilder *mb;
2693         MonoMethod *res;
2694         GHashTable *cache;
2695         int params_var;
2696         char *name;
2697         MonoGenericContext *ctx = NULL;
2698         MonoMethod *orig_method = NULL;
2699
2700         g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
2701                   !strcmp (method->name, "BeginInvoke"));
2702
2703         /*
2704          * For generic delegates, create a generic wrapper, and returns an instance to help AOT.
2705          */
2706         if (method->is_inflated) {
2707                 orig_method = method;
2708                 ctx = &((MonoMethodInflated*)method)->context;
2709                 method = ((MonoMethodInflated*)method)->declaring;
2710         }
2711
2712         sig = mono_signature_no_pinvoke (method);
2713
2714         /*
2715          * Check cache
2716          */
2717         if (ctx) {
2718                 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.delegate_begin_invoke_cache, mono_aligned_addr_hash, NULL);
2719                 res = check_generic_delegate_wrapper_cache (cache, orig_method, method, ctx);
2720                 if (res)
2721                         return res;
2722         } else {
2723                 cache = get_cache (&method->klass->image->wrapper_caches.delegate_begin_invoke_cache,
2724                                                    (GHashFunc)mono_signature_hash, 
2725                                                    (GCompareFunc)mono_metadata_signature_equal);
2726                 if ((res = mono_marshal_find_in_cache (cache, sig)))
2727                         return res;
2728         }
2729
2730         g_assert (sig->hasthis);
2731
2732         name = mono_signature_to_name (sig, "begin_invoke");
2733         if (ctx)
2734                 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_BEGIN_INVOKE);
2735         else
2736                 mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_BEGIN_INVOKE);
2737         g_free (name);
2738
2739 #ifndef DISABLE_JIT
2740         params_var = mono_mb_emit_save_args (mb, sig, FALSE);
2741
2742         mono_mb_emit_ldarg (mb, 0);
2743         mono_mb_emit_ldloc (mb, params_var);
2744         mono_mb_emit_icall (mb, mono_delegate_begin_invoke);
2745         mono_mb_emit_byte (mb, CEE_RET);
2746 #endif
2747
2748         if (ctx) {
2749                 MonoMethod *def;
2750                 def = mono_mb_create_and_cache (cache, method->klass, mb, sig, sig->param_count + 16);
2751                 res = cache_generic_delegate_wrapper (cache, orig_method, def, ctx);
2752         } else {
2753                 res = mono_mb_create_and_cache (cache, sig, mb, sig, sig->param_count + 16);
2754         }
2755
2756         mono_mb_free (mb);
2757         return res;
2758 }
2759
2760 static MonoObject *
2761 mono_delegate_end_invoke (MonoDelegate *delegate, gpointer *params)
2762 {
2763         MonoDomain *domain = mono_domain_get ();
2764         MonoAsyncResult *ares;
2765         MonoMethod *method = NULL;
2766         MonoMethodSignature *sig;
2767         MonoMethodMessage *msg;
2768         MonoObject *res, *exc;
2769         MonoArray *out_args;
2770         MonoClass *klass;
2771
2772         g_assert (delegate);
2773
2774         if (!delegate->method_info) {
2775                 g_assert (delegate->method);
2776                 MONO_OBJECT_SETREF (delegate, method_info, mono_method_get_object (domain, delegate->method, NULL));
2777         }
2778
2779         if (!delegate->method_info || !delegate->method_info->method)
2780                 g_assert_not_reached ();
2781
2782         klass = delegate->object.vtable->klass;
2783
2784         method = mono_class_get_method_from_name (klass, "EndInvoke", -1);
2785         g_assert (method != NULL);
2786
2787         sig = mono_signature_no_pinvoke (method);
2788
2789         msg = mono_method_call_message_new (method, params, NULL, NULL, NULL);
2790
2791         ares = mono_array_get (msg->args, gpointer, sig->param_count - 1);
2792         if (ares == NULL) {
2793                 mono_raise_exception (mono_exception_from_name_msg (mono_defaults.corlib, "System.Runtime.Remoting", "RemotingException", "The async result object is null or of an unexpected type."));
2794                 return NULL;
2795         }
2796
2797         if (ares->async_delegate != (MonoObject*)delegate) {
2798                 mono_raise_exception (mono_get_exception_invalid_operation (
2799                         "The IAsyncResult object provided does not match this delegate."));
2800                 return NULL;
2801         }
2802
2803 #ifndef DISABLE_REMOTING
2804         if (delegate->target && mono_object_is_transparent_proxy (delegate->target)) {
2805                 MonoTransparentProxy* tp = (MonoTransparentProxy *)delegate->target;
2806                 msg = (MonoMethodMessage *)mono_object_new (domain, mono_defaults.mono_method_message_class);
2807                 mono_message_init (domain, msg, delegate->method_info, NULL);
2808                 msg->call_type = CallType_EndInvoke;
2809                 MONO_OBJECT_SETREF (msg, async_result, ares);
2810                 res = mono_remoting_invoke ((MonoObject *)tp->rp, msg, &exc, &out_args);
2811         } else
2812 #endif
2813         {
2814                 res = mono_threadpool_ms_end_invoke (ares, &out_args, &exc);
2815         }
2816
2817         if (exc) {
2818                 if (((MonoException*)exc)->stack_trace) {
2819                         char *strace = mono_string_to_utf8 (((MonoException*)exc)->stack_trace);
2820                         char  *tmp;
2821                         tmp = g_strdup_printf ("%s\nException Rethrown at:\n", strace);
2822                         g_free (strace);        
2823                         MONO_OBJECT_SETREF (((MonoException*)exc), stack_trace, mono_string_new (domain, tmp));
2824                         g_free (tmp);
2825                 }
2826                 mono_raise_exception ((MonoException*)exc);
2827         }
2828
2829         mono_method_return_message_restore (method, params, out_args);
2830         return res;
2831 }
2832
2833 #ifndef DISABLE_JIT
2834
2835 void
2836 mono_mb_emit_restore_result (MonoMethodBuilder *mb, MonoType *return_type)
2837 {
2838         MonoType *t = mono_type_get_underlying_type (return_type);
2839
2840         if (return_type->byref)
2841                 return_type = &mono_defaults.int_class->byval_arg;
2842
2843         switch (t->type) {
2844         case MONO_TYPE_VOID:
2845                 g_assert_not_reached ();
2846                 break;
2847         case MONO_TYPE_PTR:
2848         case MONO_TYPE_STRING:
2849         case MONO_TYPE_CLASS: 
2850         case MONO_TYPE_OBJECT: 
2851         case MONO_TYPE_ARRAY: 
2852         case MONO_TYPE_SZARRAY: 
2853                 /* nothing to do */
2854                 break;
2855         case MONO_TYPE_U1:
2856         case MONO_TYPE_BOOLEAN:
2857         case MONO_TYPE_I1:
2858         case MONO_TYPE_U2:
2859         case MONO_TYPE_CHAR:
2860         case MONO_TYPE_I2:
2861         case MONO_TYPE_I:
2862         case MONO_TYPE_U:
2863         case MONO_TYPE_I4:
2864         case MONO_TYPE_U4:
2865         case MONO_TYPE_U8:
2866         case MONO_TYPE_I8:
2867         case MONO_TYPE_R4:
2868         case MONO_TYPE_R8:
2869                 mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (return_type));
2870                 mono_mb_emit_byte (mb, mono_type_to_ldind (return_type));
2871                 break;
2872         case MONO_TYPE_GENERICINST:
2873                 if (!mono_type_generic_inst_is_valuetype (t))
2874                         break;
2875                 /* fall through */
2876         case MONO_TYPE_VALUETYPE: {
2877                 MonoClass *klass = mono_class_from_mono_type (return_type);
2878                 mono_mb_emit_op (mb, CEE_UNBOX, klass);
2879                 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
2880                 break;
2881         }
2882         case MONO_TYPE_VAR:
2883         case MONO_TYPE_MVAR: {
2884                 MonoClass *klass = mono_class_from_mono_type (return_type);
2885                 mono_mb_emit_op (mb, CEE_UNBOX_ANY, klass);
2886                 break;
2887         }
2888         default:
2889                 g_warning ("type 0x%x not handled", return_type->type);
2890                 g_assert_not_reached ();
2891         }
2892
2893         mono_mb_emit_byte (mb, CEE_RET);
2894 }
2895
2896 #endif /* DISABLE_JIT */
2897
2898 MonoMethod *
2899 mono_marshal_get_delegate_end_invoke (MonoMethod *method)
2900 {
2901         MonoMethodSignature *sig;
2902         MonoMethodBuilder *mb;
2903         MonoMethod *res;
2904         GHashTable *cache;
2905         int params_var;
2906         char *name;
2907         MonoGenericContext *ctx = NULL;
2908         MonoMethod *orig_method = NULL;
2909
2910         g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
2911                   !strcmp (method->name, "EndInvoke"));
2912
2913         /*
2914          * For generic delegates, create a generic wrapper, and returns an instance to help AOT.
2915          */
2916         if (method->is_inflated) {
2917                 orig_method = method;
2918                 ctx = &((MonoMethodInflated*)method)->context;
2919                 method = ((MonoMethodInflated*)method)->declaring;
2920         }
2921
2922         sig = mono_signature_no_pinvoke (method);
2923
2924         /*
2925          * Check cache
2926          */
2927         if (ctx) {
2928                 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.delegate_end_invoke_cache, mono_aligned_addr_hash, NULL);
2929                 res = check_generic_delegate_wrapper_cache (cache, orig_method, method, ctx);
2930                 if (res)
2931                         return res;
2932         } else {
2933                 cache = get_cache (&method->klass->image->wrapper_caches.delegate_end_invoke_cache,
2934                                                    (GHashFunc)mono_signature_hash, 
2935                                                    (GCompareFunc)mono_metadata_signature_equal);
2936                 if ((res = mono_marshal_find_in_cache (cache, sig)))
2937                         return res;
2938         }
2939
2940         g_assert (sig->hasthis);
2941
2942         name = mono_signature_to_name (sig, "end_invoke");
2943         if (ctx)
2944                 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_END_INVOKE);
2945         else
2946                 mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_END_INVOKE);
2947         g_free (name);
2948
2949 #ifndef DISABLE_JIT
2950         params_var = mono_mb_emit_save_args (mb, sig, FALSE);
2951
2952         mono_mb_emit_ldarg (mb, 0);
2953         mono_mb_emit_ldloc (mb, params_var);
2954         mono_mb_emit_icall (mb, mono_delegate_end_invoke);
2955
2956         if (sig->ret->type == MONO_TYPE_VOID) {
2957                 mono_mb_emit_byte (mb, CEE_POP);
2958                 mono_mb_emit_byte (mb, CEE_RET);
2959         } else
2960                 mono_mb_emit_restore_result (mb, sig->ret);
2961 #endif
2962
2963         if (ctx) {
2964                 MonoMethod *def;
2965                 def = mono_mb_create_and_cache (cache, method->klass, mb, sig, sig->param_count + 16);
2966                 res = cache_generic_delegate_wrapper (cache, orig_method, def, ctx);
2967         } else {
2968                 res = mono_mb_create_and_cache (cache, sig,
2969                                                                                 mb, sig, sig->param_count + 16);
2970         }
2971         mono_mb_free (mb);
2972
2973         return res;
2974 }
2975
2976 typedef struct
2977 {
2978         MonoMethodSignature *sig;
2979         gpointer pointer;
2980 } SignaturePointerPair;
2981
2982 static guint
2983 signature_pointer_pair_hash (gconstpointer data)
2984 {
2985         SignaturePointerPair *pair = (SignaturePointerPair*)data;
2986
2987         return mono_signature_hash (pair->sig) ^ mono_aligned_addr_hash (pair->pointer);
2988 }
2989
2990 static gboolean
2991 signature_pointer_pair_equal (gconstpointer data1, gconstpointer data2)
2992 {
2993         SignaturePointerPair *pair1 = (SignaturePointerPair*) data1, *pair2 = (SignaturePointerPair*) data2;
2994         return mono_metadata_signature_equal (pair1->sig, pair2->sig) && (pair1->pointer == pair2->pointer);
2995 }
2996
2997 static gboolean
2998 signature_pointer_pair_matches_pointer (gpointer key, gpointer value, gpointer user_data)
2999 {
3000         SignaturePointerPair *pair = (SignaturePointerPair*)key;
3001
3002         return pair->pointer == user_data;
3003 }
3004
3005 static void
3006 free_signature_pointer_pair (SignaturePointerPair *pair)
3007 {
3008         g_free (pair);
3009 }
3010
3011 MonoMethod *
3012 mono_marshal_get_delegate_invoke_internal (MonoMethod *method, gboolean callvirt, gboolean static_method_with_first_arg_bound, MonoMethod *target_method)
3013 {
3014         MonoMethodSignature *sig, *static_sig, *invoke_sig;
3015         int i;
3016         MonoMethodBuilder *mb;
3017         MonoMethod *res;
3018         GHashTable *cache;
3019         gpointer cache_key = NULL;
3020         SignaturePointerPair key;
3021         SignaturePointerPair *new_key;
3022         int local_i, local_len, local_delegates, local_d, local_target, local_res;
3023         int pos0, pos1, pos2;
3024         char *name;
3025         MonoClass *target_class = NULL;
3026         gboolean closed_over_null = FALSE;
3027         MonoGenericContext *ctx = NULL;
3028         MonoGenericContainer *container = NULL;
3029         MonoMethod *orig_method = NULL;
3030         WrapperInfo *info;
3031         WrapperSubtype subtype = WRAPPER_SUBTYPE_NONE;
3032         gboolean found;
3033         gboolean void_ret;
3034
3035         g_assert (method && method->klass->parent == mono_defaults.multicastdelegate_class &&
3036                   !strcmp (method->name, "Invoke"));
3037
3038         invoke_sig = sig = mono_signature_no_pinvoke (method);
3039
3040         /*
3041          * If the delegate target is null, and the target method is not static, a virtual 
3042          * call is made to that method with the first delegate argument as this. This is 
3043          * a non-documented .NET feature.
3044          */
3045         if (callvirt) {
3046                 subtype = WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL;
3047                 if (target_method->is_inflated) {
3048                         MonoType *target_type;
3049
3050                         g_assert (method->signature->hasthis);
3051                         target_type = mono_class_inflate_generic_type (method->signature->params [0],
3052                                 mono_method_get_context (method));
3053                         target_class = mono_class_from_mono_type (target_type);
3054                 } else {
3055                         target_class = target_method->klass;
3056                 }
3057
3058                 closed_over_null = sig->param_count == mono_method_signature (target_method)->param_count;
3059         }
3060
3061         if (static_method_with_first_arg_bound) {
3062                 subtype = WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND;
3063                 g_assert (!callvirt);
3064                 invoke_sig = mono_method_signature (target_method);
3065         }
3066
3067         /*
3068          * For generic delegates, create a generic wrapper, and return an instance to help AOT.
3069          */
3070         if (method->is_inflated && subtype == WRAPPER_SUBTYPE_NONE) {
3071                 orig_method = method;
3072                 ctx = &((MonoMethodInflated*)method)->context;
3073                 method = ((MonoMethodInflated*)method)->declaring;
3074
3075                 container = mono_method_get_generic_container (method);
3076                 if (!container)
3077                         container = method->klass->generic_container;
3078                 g_assert (container);
3079
3080                 invoke_sig = sig = mono_signature_no_pinvoke (method);
3081         }
3082
3083         /*
3084          * Check cache
3085          */
3086         if (ctx) {
3087                 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.delegate_invoke_cache, mono_aligned_addr_hash, NULL);
3088                 res = check_generic_delegate_wrapper_cache (cache, orig_method, method, ctx);
3089                 if (res)
3090                         return res;
3091                 cache_key = method->klass;
3092         } else if (static_method_with_first_arg_bound) {
3093                 cache = get_cache (&method->klass->image->delegate_bound_static_invoke_cache,
3094                                                    (GHashFunc)mono_signature_hash, 
3095                                                    (GCompareFunc)mono_metadata_signature_equal);
3096                 /*
3097                  * The wrapper is based on sig+invoke_sig, but sig can be derived from invoke_sig.
3098                  */
3099                 res = mono_marshal_find_in_cache (cache, invoke_sig);
3100                 if (res)
3101                         return res;
3102                 cache_key = invoke_sig;
3103         } else if (callvirt) {
3104                 GHashTable **cache_ptr;
3105
3106                 cache_ptr = &mono_method_get_wrapper_cache (method)->delegate_abstract_invoke_cache;
3107
3108                 /* We need to cache the signature+method pair */
3109                 mono_marshal_lock ();
3110                 if (!*cache_ptr)
3111                         *cache_ptr = g_hash_table_new_full (signature_pointer_pair_hash, (GEqualFunc)signature_pointer_pair_equal, (GDestroyNotify)free_signature_pointer_pair, NULL);
3112                 cache = *cache_ptr;
3113                 key.sig = invoke_sig;
3114                 key.pointer = target_method;
3115                 res = g_hash_table_lookup (cache, &key);
3116                 mono_marshal_unlock ();
3117                 if (res)
3118                         return res;
3119         } else {
3120                 // Inflated methods should not be in this cache because it's not stored on the imageset.
3121                 g_assert (!method->is_inflated);
3122                 cache = get_cache (&method->klass->image->wrapper_caches.delegate_invoke_cache,
3123                                                    (GHashFunc)mono_signature_hash, 
3124                                                    (GCompareFunc)mono_metadata_signature_equal);
3125                 res = mono_marshal_find_in_cache (cache, sig);
3126                 if (res)
3127                         return res;
3128                 cache_key = sig;
3129         }
3130
3131         static_sig = mono_metadata_signature_dup_full (method->klass->image, sig);
3132         static_sig->hasthis = 0;
3133         if (!static_method_with_first_arg_bound)
3134                 invoke_sig = static_sig;
3135
3136         if (static_method_with_first_arg_bound)
3137                 name = mono_signature_to_name (invoke_sig, "invoke_bound");
3138         else if (closed_over_null)
3139                 name = mono_signature_to_name (invoke_sig, "invoke_closed_over_null");
3140         else if (callvirt)
3141                 name = mono_signature_to_name (invoke_sig, "invoke_callvirt");
3142         else
3143                 name = mono_signature_to_name (invoke_sig, "invoke");
3144         if (ctx)
3145                 mb = mono_mb_new (method->klass, name, MONO_WRAPPER_DELEGATE_INVOKE);
3146         else
3147                 mb = mono_mb_new (get_wrapper_target_class (method->klass->image), name, MONO_WRAPPER_DELEGATE_INVOKE);
3148         g_free (name);
3149
3150 #ifndef DISABLE_JIT
3151         void_ret = sig->ret->type == MONO_TYPE_VOID && !method->string_ctor;
3152
3153         /* allocate local 0 (object) */
3154         local_i = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
3155         local_len = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
3156         local_delegates = mono_mb_add_local (mb, &mono_defaults.array_class->byval_arg);
3157         local_d = mono_mb_add_local (mb, &mono_defaults.multicastdelegate_class->byval_arg);
3158         local_target = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3159
3160         if (!void_ret)
3161                 local_res = mono_mb_add_local (mb, &mono_class_from_mono_type (sig->ret)->byval_arg);
3162
3163         g_assert (sig->hasthis);
3164
3165         /*
3166          * {type: sig->ret} res;
3167          * if (delegates == null) {
3168          *     return this.<target> ( args .. );
3169          * } else {
3170          *     int i = 0, len = this.delegates.Length;
3171          *     do {
3172          *         res = this.delegates [i].Invoke ( args .. );
3173          *     } while (++i < len);
3174          *     return res;
3175          * }
3176          */
3177
3178         /* this wrapper can be used in unmanaged-managed transitions */
3179         emit_thread_interrupt_checkpoint (mb);
3180
3181         /* delegates = this.delegates */
3182         mono_mb_emit_ldarg (mb, 0);
3183         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoMulticastDelegate, delegates));
3184         mono_mb_emit_byte (mb, CEE_LDIND_REF);
3185         mono_mb_emit_stloc (mb, local_delegates);
3186
3187
3188         /* if (delegates == null) */
3189         mono_mb_emit_ldloc (mb, local_delegates);
3190         pos2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
3191
3192         /* return target.<target_method|method_ptr> ( args .. ); */
3193
3194         /* target = d.target; */
3195         mono_mb_emit_ldarg (mb, 0);
3196         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, target));
3197         mono_mb_emit_byte (mb, CEE_LDIND_REF);
3198         mono_mb_emit_stloc (mb, local_target);
3199
3200         /*static methods with bound first arg can have null target and still be bound*/
3201         if (!static_method_with_first_arg_bound) {
3202                 /* if target != null */
3203                 mono_mb_emit_ldloc (mb, local_target);
3204                 pos0 = mono_mb_emit_branch (mb, CEE_BRFALSE);
3205
3206                 /* then call this->method_ptr nonstatic */
3207                 if (callvirt) {
3208                         // FIXME:
3209                         mono_mb_emit_exception_full (mb, "System", "NotImplementedException", "");
3210                 } else {
3211                         mono_mb_emit_ldloc (mb, local_target);
3212                         for (i = 0; i < sig->param_count; ++i)
3213                                 mono_mb_emit_ldarg (mb, i + 1);
3214                         mono_mb_emit_ldarg (mb, 0);
3215                         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr));
3216                         mono_mb_emit_byte (mb, CEE_LDIND_I );
3217                         mono_mb_emit_op (mb, CEE_CALLI, sig);
3218
3219                         mono_mb_emit_byte (mb, CEE_RET);
3220                 }
3221         
3222                 /* else [target == null] call this->method_ptr static */
3223                 mono_mb_patch_branch (mb, pos0);
3224         }
3225
3226         if (callvirt) {
3227                 if (!closed_over_null) {
3228                         if (target_class->valuetype) {
3229                                 mono_mb_emit_ldarg (mb, 1);
3230                                 for (i = 1; i < sig->param_count; ++i)
3231                                         mono_mb_emit_ldarg (mb, i + 1);
3232                                 mono_mb_emit_op (mb, CEE_CALL, target_method);
3233                         } else {
3234                                 mono_mb_emit_ldarg (mb, 1);
3235                                 mono_mb_emit_op (mb, CEE_CASTCLASS, target_class);
3236                                 for (i = 1; i < sig->param_count; ++i)
3237                                         mono_mb_emit_ldarg (mb, i + 1);
3238                                 mono_mb_emit_op (mb, CEE_CALLVIRT, target_method);
3239                         }
3240                 } else {
3241                         mono_mb_emit_byte (mb, CEE_LDNULL);
3242                         for (i = 0; i < sig->param_count; ++i)
3243                                 mono_mb_emit_ldarg (mb, i + 1);
3244                         mono_mb_emit_op (mb, CEE_CALL, target_method);
3245                 }
3246         } else {
3247                 if (static_method_with_first_arg_bound) {
3248                         mono_mb_emit_ldloc (mb, local_target);
3249                         if (!MONO_TYPE_IS_REFERENCE (invoke_sig->params[0]))
3250                                 mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (invoke_sig->params[0]));
3251                 }
3252                 for (i = 0; i < sig->param_count; ++i)
3253                         mono_mb_emit_ldarg (mb, i + 1);
3254                 mono_mb_emit_ldarg (mb, 0);
3255                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr));
3256                 mono_mb_emit_byte (mb, CEE_LDIND_I );
3257                 mono_mb_emit_op (mb, CEE_CALLI, invoke_sig);
3258         }
3259
3260         mono_mb_emit_byte (mb, CEE_RET);
3261
3262         /* else [delegates != null] */
3263         mono_mb_patch_branch (mb, pos2);
3264
3265         /* len = delegates.Length; */
3266         mono_mb_emit_ldloc (mb, local_delegates);
3267         mono_mb_emit_byte (mb, CEE_LDLEN);
3268         mono_mb_emit_byte (mb, CEE_CONV_I4);
3269         mono_mb_emit_stloc (mb, local_len);
3270
3271         /* i = 0; */
3272         mono_mb_emit_icon (mb, 0);
3273         mono_mb_emit_stloc (mb, local_i);
3274
3275         pos1 = mono_mb_get_label (mb);
3276
3277         /* d = delegates [i]; */
3278         mono_mb_emit_ldloc (mb, local_delegates);
3279         mono_mb_emit_ldloc (mb, local_i);
3280         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
3281         mono_mb_emit_stloc (mb, local_d);
3282
3283         /* res = d.Invoke ( args .. ); */
3284         mono_mb_emit_ldloc (mb, local_d);
3285         for (i = 0; i < sig->param_count; i++)
3286                 mono_mb_emit_ldarg (mb, i + 1);
3287         if (!ctx) {
3288                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
3289         } else {
3290                 MonoError error;
3291                 mono_mb_emit_op (mb, CEE_CALLVIRT, mono_class_inflate_generic_method_checked (method, &container->context, &error));
3292                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3293         }
3294         if (!void_ret)
3295                 mono_mb_emit_stloc (mb, local_res);
3296
3297         /* i += 1 */
3298         mono_mb_emit_add_to_local (mb, local_i, 1);
3299
3300         /* i < l */
3301         mono_mb_emit_ldloc (mb, local_i);
3302         mono_mb_emit_ldloc (mb, local_len);
3303         mono_mb_emit_branch_label (mb, CEE_BLT, pos1);
3304
3305         /* return res */
3306         if (!void_ret)
3307                 mono_mb_emit_ldloc (mb, local_res);
3308         mono_mb_emit_byte (mb, CEE_RET);
3309
3310         mb->skip_visibility = 1;
3311 #endif /* DISABLE_JIT */
3312
3313         if (ctx) {
3314                 MonoMethod *def;
3315
3316                 def = mono_mb_create_and_cache (cache, cache_key, mb, sig, sig->param_count + 16);
3317                 res = cache_generic_delegate_wrapper (cache, orig_method, def, ctx);
3318         } else if (callvirt) {
3319                 new_key = g_new0 (SignaturePointerPair, 1);
3320                 *new_key = key;
3321
3322                 info = mono_wrapper_info_create (mb, subtype);
3323
3324                 res = mono_mb_create_and_cache_full (cache, new_key, mb, sig, sig->param_count + 16, info, &found);
3325                 if (found)
3326                         g_free (new_key);
3327         } else {
3328                 info = mono_wrapper_info_create (mb, subtype);
3329
3330                 res = mono_mb_create_and_cache_full (cache, cache_key, mb, sig, sig->param_count + 16, info, NULL);
3331         }
3332         mono_mb_free (mb);
3333
3334         /* mono_method_print_code (res); */
3335
3336         return res;     
3337 }
3338
3339 /*
3340  * the returned method invokes all methods in a multicast delegate.
3341  */
3342 MonoMethod *
3343 mono_marshal_get_delegate_invoke (MonoMethod *method, MonoDelegate *del)
3344 {
3345         gboolean callvirt = FALSE;
3346         gboolean static_method_with_first_arg_bound = FALSE;
3347         MonoMethod *target_method = NULL;
3348         MonoMethodSignature *sig;
3349
3350         sig = mono_signature_no_pinvoke (method);
3351
3352         if (del && !del->target && del->method && mono_method_signature (del->method)->hasthis) {
3353                 callvirt = TRUE;
3354                 target_method = del->method;
3355         }
3356
3357         if (del && del->method && mono_method_signature (del->method)->param_count == sig->param_count + 1 && (del->method->flags & METHOD_ATTRIBUTE_STATIC)) {
3358                 static_method_with_first_arg_bound = TRUE;
3359                 target_method = del->method;
3360         }
3361
3362         return mono_marshal_get_delegate_invoke_internal (method, callvirt, static_method_with_first_arg_bound, target_method);
3363 }
3364
3365 typedef struct {
3366         MonoMethodSignature *ctor_sig;
3367         MonoMethodSignature *sig;
3368 } CtorSigPair;
3369
3370 /* protected by the marshal lock, contains CtorSigPair pointers */
3371 static GSList *strsig_list = NULL;
3372
3373 static MonoMethodSignature *
3374 lookup_string_ctor_signature (MonoMethodSignature *sig)
3375 {
3376         MonoMethodSignature *callsig;
3377         CtorSigPair *cs;
3378         GSList *item;
3379
3380         mono_marshal_lock ();
3381         callsig = NULL;
3382         for (item = strsig_list; item; item = item->next) {
3383                 cs = item->data;
3384                 /* mono_metadata_signature_equal () is safe to call with the marshal lock
3385                  * because it is lock-free.
3386                  */
3387                 if (mono_metadata_signature_equal (sig, cs->ctor_sig)) {
3388                         callsig = cs->sig;
3389                         break;
3390                 }
3391         }
3392         mono_marshal_unlock ();
3393         return callsig;
3394 }
3395
3396 static MonoMethodSignature *
3397 add_string_ctor_signature (MonoMethod *method)
3398 {
3399         MonoMethodSignature *callsig;
3400         CtorSigPair *cs;
3401
3402         callsig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
3403         callsig->ret = &mono_defaults.string_class->byval_arg;
3404         cs = g_new (CtorSigPair, 1);
3405         cs->sig = callsig;
3406         cs->ctor_sig = mono_method_signature (method);
3407
3408         mono_marshal_lock ();
3409         strsig_list = g_slist_prepend (strsig_list, cs);
3410         mono_marshal_unlock ();
3411         return callsig;
3412 }
3413
3414 /*
3415  * mono_marshal_get_string_ctor_signature:
3416  *
3417  *   Return the modified signature used by string ctors (they return the newly created
3418  * string).
3419  */
3420 MonoMethodSignature*
3421 mono_marshal_get_string_ctor_signature (MonoMethod *method)
3422 {
3423         MonoMethodSignature *sig = lookup_string_ctor_signature (mono_method_signature (method));
3424         if (!sig)
3425                 sig = add_string_ctor_signature (method);
3426
3427         return sig;
3428 }
3429
3430 static MonoType*
3431 get_runtime_invoke_type (MonoType *t, gboolean ret)
3432 {
3433         if (t->byref) {
3434                 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t)))
3435                         return t;
3436                 /* Can't share this with 'I' as that needs another indirection */
3437                 return &mono_defaults.int_class->this_arg;
3438         }
3439
3440         if (MONO_TYPE_IS_REFERENCE (t))
3441                 return &mono_defaults.object_class->byval_arg;
3442
3443         if (ret)
3444                 /* The result needs to be boxed */
3445                 return t;
3446
3447 handle_enum:
3448         switch (t->type) {
3449                 /* Can't share these as the argument needs to be loaded using sign/zero extension */
3450                 /*
3451         case MONO_TYPE_U1:
3452                 return &mono_defaults.sbyte_class->byval_arg;
3453         case MONO_TYPE_U2:
3454                 return &mono_defaults.int16_class->byval_arg;
3455         case MONO_TYPE_U4:
3456                 return &mono_defaults.int32_class->byval_arg;
3457                 */
3458         case MONO_TYPE_U8:
3459                 return &mono_defaults.int64_class->byval_arg;
3460         case MONO_TYPE_BOOLEAN:
3461                 return &mono_defaults.byte_class->byval_arg;
3462         case MONO_TYPE_CHAR:
3463                 return &mono_defaults.uint16_class->byval_arg;
3464         case MONO_TYPE_U:
3465         case MONO_TYPE_PTR:
3466                 return &mono_defaults.int_class->byval_arg;
3467         case MONO_TYPE_VALUETYPE:
3468                 if (t->data.klass->enumtype) {
3469                         t = mono_class_enum_basetype (t->data.klass);
3470                         goto handle_enum;
3471                 }
3472                 return t;
3473         default:
3474                 return t;
3475         }
3476 }
3477
3478 /*
3479  * mono_marshal_get_runtime_invoke_sig:
3480  *
3481  *   Return a common signature used for sharing runtime invoke wrappers.
3482  */
3483 static MonoMethodSignature*
3484 mono_marshal_get_runtime_invoke_sig (MonoMethodSignature *sig)
3485 {
3486         MonoMethodSignature *res = mono_metadata_signature_dup (sig);
3487         int i;
3488
3489         res->generic_param_count = 0;
3490         res->ret = get_runtime_invoke_type (sig->ret, TRUE);
3491         for (i = 0; i < res->param_count; ++i)
3492                 res->params [i] = get_runtime_invoke_type (sig->params [i], FALSE);
3493
3494         return res;
3495 }
3496
3497 static gboolean
3498 runtime_invoke_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
3499 {
3500         /* Can't share wrappers which return a vtype since it needs to be boxed */
3501         if (sig1->ret != sig2->ret && !(MONO_TYPE_IS_REFERENCE (sig1->ret) && MONO_TYPE_IS_REFERENCE (sig2->ret)) && !mono_metadata_type_equal (sig1->ret, sig2->ret))
3502                 return FALSE;
3503         else
3504                 return mono_metadata_signature_equal (sig1, sig2);
3505 }
3506
3507 #ifndef DISABLE_JIT
3508
3509 /*
3510  * emit_invoke_call:
3511  *
3512  *   Emit the call to the wrapper method from a runtime invoke wrapper.
3513  */
3514 static void
3515 emit_invoke_call (MonoMethodBuilder *mb, MonoMethod *method,
3516                                   MonoMethodSignature *sig, MonoMethodSignature *callsig,
3517                                   int loc_res,
3518                                   gboolean virtual, gboolean need_direct_wrapper)
3519 {
3520         static MonoString *string_dummy = NULL;
3521         int i;
3522         int *tmp_nullable_locals;
3523         gboolean void_ret = FALSE;
3524
3525         /* to make it work with our special string constructors */
3526         if (!string_dummy) {
3527                 MONO_GC_REGISTER_ROOT_SINGLE (string_dummy);
3528                 string_dummy = mono_string_new_wrapper ("dummy");
3529         }
3530
3531         if (virtual) {
3532                 g_assert (sig->hasthis);
3533                 g_assert (method->flags & METHOD_ATTRIBUTE_VIRTUAL);
3534         }
3535
3536         if (sig->hasthis) {
3537                 if (method->string_ctor) {
3538                         if (mono_gc_is_moving ()) {
3539                                 mono_mb_emit_ptr (mb, &string_dummy);
3540                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3541                         } else {
3542                                 mono_mb_emit_ptr (mb, string_dummy);
3543                         }
3544                 } else {
3545                         mono_mb_emit_ldarg (mb, 0);
3546                 }
3547         }
3548
3549         tmp_nullable_locals = g_new0 (int, sig->param_count);
3550
3551         for (i = 0; i < sig->param_count; i++) {
3552                 MonoType *t = sig->params [i];
3553                 int type;
3554
3555                 mono_mb_emit_ldarg (mb, 1);
3556                 if (i) {
3557                         mono_mb_emit_icon (mb, sizeof (gpointer) * i);
3558                         mono_mb_emit_byte (mb, CEE_ADD);
3559                 }
3560
3561                 if (t->byref) {
3562                         mono_mb_emit_byte (mb, CEE_LDIND_I);
3563                         /* A Nullable<T> type don't have a boxed form, it's either null or a boxed T.
3564                          * So to make this work we unbox it to a local variablee and push a reference to that.
3565                          */
3566                         if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
3567                                 tmp_nullable_locals [i] = mono_mb_add_local (mb, &mono_class_from_mono_type (t)->byval_arg);
3568
3569                                 mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (t));
3570                                 mono_mb_emit_stloc (mb, tmp_nullable_locals [i]);
3571                                 mono_mb_emit_ldloc_addr (mb, tmp_nullable_locals [i]);
3572                         }
3573                         continue;
3574                 }
3575
3576                 /*FIXME 'this doesn't handle generic enums. Shouldn't we?*/
3577                 type = sig->params [i]->type;
3578 handle_enum:
3579                 switch (type) {
3580                 case MONO_TYPE_I1:
3581                 case MONO_TYPE_BOOLEAN:
3582                 case MONO_TYPE_U1:
3583                 case MONO_TYPE_I2:
3584                 case MONO_TYPE_U2:
3585                 case MONO_TYPE_CHAR:
3586                 case MONO_TYPE_I:
3587                 case MONO_TYPE_U:
3588                 case MONO_TYPE_I4:
3589                 case MONO_TYPE_U4:
3590                 case MONO_TYPE_R4:
3591                 case MONO_TYPE_R8:
3592                 case MONO_TYPE_I8:
3593                 case MONO_TYPE_U8:
3594                         mono_mb_emit_byte (mb, CEE_LDIND_I);
3595                         mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
3596                         break;
3597                 case MONO_TYPE_STRING:
3598                 case MONO_TYPE_CLASS:  
3599                 case MONO_TYPE_ARRAY:
3600                 case MONO_TYPE_PTR:
3601                 case MONO_TYPE_SZARRAY:
3602                 case MONO_TYPE_OBJECT:
3603                         mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
3604                         break;
3605                 case MONO_TYPE_GENERICINST:
3606                         if (!mono_type_generic_inst_is_valuetype (sig->params [i])) {
3607                                 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
3608                                 break;
3609                         }
3610
3611                         /* fall through */
3612                 case MONO_TYPE_VALUETYPE:
3613                         if (type == MONO_TYPE_VALUETYPE && t->data.klass->enumtype) {
3614                                 type = mono_class_enum_basetype (t->data.klass)->type;
3615                                 goto handle_enum;
3616                         }
3617                         mono_mb_emit_byte (mb, CEE_LDIND_I);
3618                         if (mono_class_is_nullable (mono_class_from_mono_type (sig->params [i]))) {
3619                                 /* Need to convert a boxed vtype to an mp to a Nullable struct */
3620                                 mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (sig->params [i]));
3621                                 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
3622                         } else {
3623                                 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
3624                         }
3625                         break;
3626                 default:
3627                         g_assert_not_reached ();
3628                 }
3629         }
3630         
3631         if (virtual) {
3632                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
3633         } else if (need_direct_wrapper) {
3634                 mono_mb_emit_op (mb, CEE_CALL, method);
3635         } else {
3636                 mono_mb_emit_ldarg (mb, 3);
3637                 mono_mb_emit_calli (mb, callsig);
3638         }
3639
3640         if (sig->ret->byref) {
3641                 /* fixme: */
3642                 g_assert_not_reached ();
3643         }
3644
3645         switch (sig->ret->type) {
3646         case MONO_TYPE_VOID:
3647                 if (!method->string_ctor)
3648                         void_ret = TRUE;
3649                 break;
3650         case MONO_TYPE_BOOLEAN:
3651         case MONO_TYPE_CHAR:
3652         case MONO_TYPE_I1:
3653         case MONO_TYPE_U1:
3654         case MONO_TYPE_I2:
3655         case MONO_TYPE_U2:
3656         case MONO_TYPE_I4:
3657         case MONO_TYPE_U4:
3658         case MONO_TYPE_I:
3659         case MONO_TYPE_U:
3660         case MONO_TYPE_R4:
3661         case MONO_TYPE_R8:
3662         case MONO_TYPE_I8:
3663         case MONO_TYPE_U8:
3664         case MONO_TYPE_VALUETYPE:
3665         case MONO_TYPE_TYPEDBYREF:
3666         case MONO_TYPE_GENERICINST:
3667                 /* box value types */
3668                 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
3669                 break;
3670         case MONO_TYPE_STRING:
3671         case MONO_TYPE_CLASS:  
3672         case MONO_TYPE_ARRAY:
3673         case MONO_TYPE_SZARRAY:
3674         case MONO_TYPE_OBJECT:
3675                 /* nothing to do */
3676                 break;
3677         case MONO_TYPE_PTR:
3678                 /* The result is an IntPtr */
3679                 mono_mb_emit_op (mb, CEE_BOX, mono_defaults.int_class);
3680                 break;
3681         default:
3682                 g_assert_not_reached ();
3683         }
3684
3685         if (!void_ret)
3686                 mono_mb_emit_stloc (mb, loc_res);
3687
3688         /* Convert back nullable-byref arguments */
3689         for (i = 0; i < sig->param_count; i++) {
3690                 MonoType *t = sig->params [i];
3691
3692                 /* 
3693                  * Box the result and put it back into the array, the caller will have
3694                  * to obtain it from there.
3695                  */
3696                 if (t->byref && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
3697                         mono_mb_emit_ldarg (mb, 1);                     
3698                         mono_mb_emit_icon (mb, sizeof (gpointer) * i);
3699                         mono_mb_emit_byte (mb, CEE_ADD);
3700
3701                         mono_mb_emit_ldloc (mb, tmp_nullable_locals [i]);
3702                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
3703
3704                         mono_mb_emit_byte (mb, CEE_STIND_REF);
3705                 }
3706         }
3707
3708         g_free (tmp_nullable_locals);
3709 }
3710
3711 static void
3712 emit_runtime_invoke_body (MonoMethodBuilder *mb, MonoClass *target_klass, MonoMethod *method,
3713                                                   MonoMethodSignature *sig, MonoMethodSignature *callsig,
3714                                                   gboolean virtual, gboolean need_direct_wrapper)
3715 {
3716         gint32 labels [16];
3717         MonoExceptionClause *clause;
3718         int loc_res, loc_exc;
3719
3720         /* The wrapper looks like this:
3721          *
3722          * <interrupt check>
3723          * if (exc) {
3724          *       try {
3725          *         return <call>
3726          *       } catch (Exception e) {
3727          *     *exc = e;
3728          *   }
3729          * } else {
3730          *     return <call>
3731          * }
3732          */
3733
3734         /* allocate local 0 (object) tmp */
3735         loc_res = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3736         /* allocate local 1 (object) exc */
3737         loc_exc = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3738
3739         /* *exc is assumed to be initialized to NULL by the caller */
3740
3741         mono_mb_emit_byte (mb, CEE_LDARG_2);
3742         labels [0] = mono_mb_emit_branch (mb, CEE_BRFALSE);
3743
3744         /*
3745          * if (exc) case
3746          */
3747         labels [1] = mono_mb_get_label (mb);
3748         emit_thread_force_interrupt_checkpoint (mb);
3749         emit_invoke_call (mb, method, sig, callsig, loc_res, virtual, need_direct_wrapper);
3750
3751         labels [2] = mono_mb_emit_branch (mb, CEE_LEAVE);
3752
3753         /* Add a try clause around the call */
3754         clause = mono_image_alloc0 (target_klass->image, sizeof (MonoExceptionClause));
3755         clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
3756         clause->data.catch_class = mono_defaults.exception_class;
3757         clause->try_offset = labels [1];
3758         clause->try_len = mono_mb_get_label (mb) - labels [1];
3759
3760         clause->handler_offset = mono_mb_get_label (mb);
3761
3762         /* handler code */
3763         mono_mb_emit_stloc (mb, loc_exc);       
3764         mono_mb_emit_byte (mb, CEE_LDARG_2);
3765         mono_mb_emit_ldloc (mb, loc_exc);
3766         mono_mb_emit_byte (mb, CEE_STIND_REF);
3767
3768         mono_mb_emit_branch (mb, CEE_LEAVE);
3769
3770         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
3771
3772         mono_mb_set_clauses (mb, 1, clause);
3773
3774         mono_mb_patch_branch (mb, labels [2]);
3775         mono_mb_emit_ldloc (mb, loc_res);
3776         mono_mb_emit_byte (mb, CEE_RET);
3777
3778         /*
3779          * if (!exc) case
3780          */
3781         mono_mb_patch_branch (mb, labels [0]);
3782         emit_thread_force_interrupt_checkpoint (mb);
3783         emit_invoke_call (mb, method, sig, callsig, loc_res, virtual, need_direct_wrapper);
3784
3785         mono_mb_emit_ldloc (mb, 0);
3786         mono_mb_emit_byte (mb, CEE_RET);
3787 }
3788 #endif
3789
3790 /*
3791  * generates IL code for the runtime invoke function 
3792  * MonoObject *runtime_invoke (MonoObject *this, void **params, MonoObject **exc, void* method)
3793  *
3794  * we also catch exceptions if exc != null
3795  * If VIRTUAL is TRUE, then METHOD is invoked virtually on THIS. This is useful since
3796  * it means that the compiled code for METHOD does not have to be looked up 
3797  * before calling the runtime invoke wrapper. In this case, the wrapper ignores
3798  * its METHOD argument.
3799  */
3800 MonoMethod *
3801 mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual)
3802 {
3803         MonoMethodSignature *sig, *csig, *callsig;
3804         MonoMethodBuilder *mb;
3805         GHashTable *cache = NULL;
3806         MonoClass *target_klass;
3807         MonoMethod *res = NULL;
3808         static MonoMethodSignature *cctor_signature = NULL;
3809         static MonoMethodSignature *finalize_signature = NULL;
3810         char *name;
3811         const char *param_names [16];
3812         gboolean need_direct_wrapper = FALSE;
3813         WrapperInfo *info;
3814
3815         g_assert (method);
3816
3817         if (!cctor_signature) {
3818                 cctor_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3819                 cctor_signature->ret = &mono_defaults.void_class->byval_arg;
3820         }
3821         if (!finalize_signature) {
3822                 finalize_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3823                 finalize_signature->ret = &mono_defaults.void_class->byval_arg;
3824                 finalize_signature->hasthis = 1;
3825         }
3826
3827         if (virtual)
3828                 need_direct_wrapper = TRUE;
3829
3830         /* 
3831          * Use a separate cache indexed by methods to speed things up and to avoid the
3832          * boundless mempool growth caused by the signature_dup stuff below.
3833          */
3834         if (virtual)
3835                 cache = get_cache (&method->klass->image->runtime_invoke_vcall_cache, mono_aligned_addr_hash, NULL);
3836         else
3837                 cache = get_cache (&mono_method_get_wrapper_cache (method)->runtime_invoke_direct_cache, mono_aligned_addr_hash, NULL);
3838
3839         res = mono_marshal_find_in_cache (cache, method);
3840         if (res)
3841                 return res;
3842                 
3843         if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
3844                 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
3845                 /* 
3846                  * Array Get/Set/Address methods. The JIT implements them using inline code
3847                  * so we need to create an invoke wrapper which calls the method directly.
3848                  */
3849                 need_direct_wrapper = TRUE;
3850         }
3851                 
3852         if (method->string_ctor) {
3853                 callsig = lookup_string_ctor_signature (mono_method_signature (method));
3854                 if (!callsig)
3855                         callsig = add_string_ctor_signature (method);
3856                 /* Can't share this as we push a string as this */
3857                 need_direct_wrapper = TRUE;
3858         } else {
3859                 if (method_is_dynamic (method))
3860                         callsig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
3861                 else
3862                         callsig = mono_method_signature (method);
3863         }
3864
3865         target_klass = get_wrapper_target_class (method->klass->image);
3866
3867         /* Try to share wrappers for non-corlib methods with simple signatures */
3868         if (mono_metadata_signature_equal (callsig, cctor_signature)) {
3869                 callsig = cctor_signature;
3870                 target_klass = mono_defaults.object_class;
3871         } else if (mono_metadata_signature_equal (callsig, finalize_signature)) {
3872                 callsig = finalize_signature;
3873                 target_klass = mono_defaults.object_class;
3874         }
3875
3876         if (need_direct_wrapper) {
3877                 /* Already searched at the start */
3878         } else {
3879                 MonoMethodSignature *tmp_sig;
3880
3881                 callsig = mono_marshal_get_runtime_invoke_sig (callsig);
3882                 GHashTable **cache_table = NULL;
3883
3884                 if (method->klass->valuetype && mono_method_signature (method)->hasthis)
3885                         cache_table = &mono_method_get_wrapper_cache (method)->runtime_invoke_vtype_cache;
3886                 else
3887                         cache_table = &mono_method_get_wrapper_cache (method)->runtime_invoke_cache;
3888
3889                 cache = get_cache (cache_table, (GHashFunc)mono_signature_hash,
3890                                                            (GCompareFunc)runtime_invoke_signature_equal);
3891
3892                 /* from mono_marshal_find_in_cache */
3893                 mono_marshal_lock ();
3894                 res = g_hash_table_lookup (cache, callsig);
3895                 mono_marshal_unlock ();
3896
3897                 if (res) {
3898                         g_free (callsig);
3899                         return res;
3900                 }
3901
3902                 /* Make a copy of the signature from the image mempool */
3903                 tmp_sig = callsig;
3904                 callsig = mono_metadata_signature_dup_full (target_klass->image, callsig);
3905                 g_free (tmp_sig);
3906         }
3907         
3908         sig = mono_method_signature (method);
3909
3910         csig = mono_metadata_signature_alloc (target_klass->image, 4);
3911
3912         csig->ret = &mono_defaults.object_class->byval_arg;
3913         if (method->klass->valuetype && mono_method_signature (method)->hasthis)
3914                 csig->params [0] = get_runtime_invoke_type (&method->klass->this_arg, FALSE);
3915         else
3916                 csig->params [0] = &mono_defaults.object_class->byval_arg;
3917         csig->params [1] = &mono_defaults.int_class->byval_arg;
3918         csig->params [2] = &mono_defaults.int_class->byval_arg;
3919         csig->params [3] = &mono_defaults.int_class->byval_arg;
3920         csig->pinvoke = 1;
3921 #if TARGET_WIN32
3922         /* This is called from runtime code so it has to be cdecl */
3923         csig->call_convention = MONO_CALL_C;
3924 #endif
3925
3926         name = mono_signature_to_name (callsig, virtual ? "runtime_invoke_virtual" : "runtime_invoke");
3927         mb = mono_mb_new (target_klass, name,  MONO_WRAPPER_RUNTIME_INVOKE);
3928         g_free (name);
3929
3930 #ifndef DISABLE_JIT
3931         param_names [0] = "this";
3932         param_names [1] = "params";
3933         param_names [2] = "exc";
3934         param_names [3] = "method";
3935         mono_mb_set_param_names (mb, param_names);
3936
3937         emit_runtime_invoke_body (mb, target_klass, method, sig, callsig, virtual, need_direct_wrapper);
3938 #endif
3939
3940         if (need_direct_wrapper) {
3941 #ifndef DISABLE_JIT
3942                 mb->skip_visibility = 1;
3943 #endif
3944                 info = mono_wrapper_info_create (mb, virtual ? WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL : WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT);
3945                 info->d.runtime_invoke.method = method;
3946                 res = mono_mb_create_and_cache_full (cache, method, mb, csig, sig->param_count + 16, info, NULL);
3947         } else {
3948                 /* taken from mono_mb_create_and_cache */
3949                 mono_marshal_lock ();
3950                 res = g_hash_table_lookup (cache, callsig);
3951                 mono_marshal_unlock ();
3952
3953                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL);
3954                 info->d.runtime_invoke.sig = callsig;
3955
3956                 /* Somebody may have created it before us */
3957                 if (!res) {
3958                         MonoMethod *newm;
3959                         newm = mono_mb_create (mb, csig, sig->param_count + 16, info);
3960
3961                         mono_marshal_lock ();
3962                         res = g_hash_table_lookup (cache, callsig);
3963                         if (!res) {
3964                                 GHashTable *direct_cache;
3965                                 res = newm;
3966                                 g_hash_table_insert (cache, callsig, res);
3967                                 /* Can't insert it into wrapper_hash since the key is a signature */
3968                                 direct_cache = mono_method_get_wrapper_cache (method)->runtime_invoke_direct_cache;
3969
3970                                 g_hash_table_insert (direct_cache, method, res);
3971                         } else {
3972                                 mono_free_method (newm);
3973                         }
3974                         mono_marshal_unlock ();
3975                 }
3976
3977                 /* end mono_mb_create_and_cache */
3978         }
3979
3980         mono_mb_free (mb);
3981
3982         return res;     
3983 }
3984
3985 /*
3986  * mono_marshal_get_runtime_invoke_dynamic:
3987  *
3988  *   Return a method which can be used to invoke managed methods from native code
3989  * dynamically.
3990  * The signature of the returned method is given by RuntimeInvokeDynamicFunction:
3991  * void runtime_invoke (void *args, MonoObject **exc, void *compiled_method)
3992  * ARGS should point to an architecture specific structure containing 
3993  * the arguments and space for the return value.
3994  * The other arguments are the same as for runtime_invoke (), except that
3995  * ARGS should contain the this argument too.
3996  * This wrapper serves the same purpose as the runtime-invoke wrappers, but there
3997  * is only one copy of it, which is useful in full-aot.
3998  * The wrapper info for the wrapper is a WrapperInfo structure.
3999  */
4000 MonoMethod*
4001 mono_marshal_get_runtime_invoke_dynamic (void)
4002 {
4003         static MonoMethod *method;
4004         MonoMethodSignature *csig;
4005         MonoExceptionClause *clause;
4006         MonoMethodBuilder *mb;
4007         int pos, posna;
4008         char *name;
4009         WrapperInfo *info;
4010
4011         if (method)
4012                 return method;
4013
4014         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
4015
4016         csig->ret = &mono_defaults.void_class->byval_arg;
4017         csig->params [0] = &mono_defaults.int_class->byval_arg;
4018         csig->params [1] = &mono_defaults.int_class->byval_arg;
4019         csig->params [2] = &mono_defaults.int_class->byval_arg;
4020         csig->params [3] = &mono_defaults.int_class->byval_arg;
4021
4022         name = g_strdup ("runtime_invoke_dynamic");
4023         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_RUNTIME_INVOKE);
4024         g_free (name);
4025
4026 #ifndef DISABLE_JIT
4027         /* allocate local 0 (object) tmp */
4028         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4029         /* allocate local 1 (object) exc */
4030         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4031
4032         /* cond set *exc to null */
4033         mono_mb_emit_byte (mb, CEE_LDARG_1);
4034         mono_mb_emit_byte (mb, CEE_BRFALSE_S);
4035         mono_mb_emit_byte (mb, 3);      
4036         mono_mb_emit_byte (mb, CEE_LDARG_1);
4037         mono_mb_emit_byte (mb, CEE_LDNULL);
4038         mono_mb_emit_byte (mb, CEE_STIND_REF);
4039
4040         emit_thread_force_interrupt_checkpoint (mb);
4041
4042         mono_mb_emit_byte (mb, CEE_LDARG_0);
4043         mono_mb_emit_byte (mb, CEE_LDARG_2);
4044         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4045         mono_mb_emit_byte (mb, CEE_MONO_DYN_CALL);
4046
4047         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
4048
4049         clause = mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
4050         clause->flags = MONO_EXCEPTION_CLAUSE_FILTER;
4051         clause->try_len = mono_mb_get_label (mb);
4052
4053         /* filter code */
4054         clause->data.filter_offset = mono_mb_get_label (mb);
4055         
4056         mono_mb_emit_byte (mb, CEE_POP);
4057         mono_mb_emit_byte (mb, CEE_LDARG_1);
4058         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
4059         mono_mb_emit_byte (mb, CEE_PREFIX1);
4060         mono_mb_emit_byte (mb, CEE_CGT_UN);
4061         mono_mb_emit_byte (mb, CEE_PREFIX1);
4062         mono_mb_emit_byte (mb, CEE_ENDFILTER);
4063
4064         clause->handler_offset = mono_mb_get_label (mb);
4065
4066         /* handler code */
4067         /* store exception */
4068         mono_mb_emit_stloc (mb, 1);
4069         
4070         mono_mb_emit_byte (mb, CEE_LDARG_1);
4071         mono_mb_emit_ldloc (mb, 1);
4072         mono_mb_emit_byte (mb, CEE_STIND_REF);
4073
4074         mono_mb_emit_byte (mb, CEE_LDNULL);
4075         mono_mb_emit_stloc (mb, 0);
4076
4077         /* Check for the abort exception */
4078         mono_mb_emit_ldloc (mb, 1);
4079         mono_mb_emit_op (mb, CEE_ISINST, mono_defaults.threadabortexception_class);
4080         posna = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
4081
4082         /* Delay the abort exception */
4083         mono_mb_emit_icall (mb, ves_icall_System_Threading_Thread_ResetAbort);
4084
4085         mono_mb_patch_short_branch (mb, posna);
4086         mono_mb_emit_branch (mb, CEE_LEAVE);
4087
4088         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
4089
4090         mono_mb_set_clauses (mb, 1, clause);
4091
4092         /* return result */
4093         mono_mb_patch_branch (mb, pos);
4094         //mono_mb_emit_ldloc (mb, 0);
4095         mono_mb_emit_byte (mb, CEE_RET);
4096 #endif /* DISABLE_JIT */
4097
4098         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC);
4099
4100         mono_marshal_lock ();
4101         /* double-checked locking */
4102         if (!method)
4103                 method = mono_mb_create (mb, csig, 16, info);
4104
4105         mono_marshal_unlock ();
4106
4107         mono_mb_free (mb);
4108
4109         return method;
4110 }
4111
4112 #ifndef DISABLE_JIT
4113 static void
4114 mono_mb_emit_auto_layout_exception (MonoMethodBuilder *mb, MonoClass *klass)
4115 {
4116         char *msg = g_strdup_printf ("The type `%s.%s' layout needs to be Sequential or Explicit",
4117                                      klass->name_space, klass->name);
4118
4119         mono_mb_emit_exception_marshal_directive (mb, msg);
4120 }
4121 #endif
4122
4123 /*
4124  * generates IL code for the icall wrapper (the generated method
4125  * calls the unmanaged code in func)
4126  * The wrapper info for the wrapper is a WrapperInfo structure.
4127  */
4128 MonoMethod *
4129 mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gconstpointer func, gboolean check_exceptions)
4130 {
4131         MonoMethodSignature *csig, *csig2;
4132         MonoMethodBuilder *mb;
4133         MonoMethod *res;
4134         int i;
4135         WrapperInfo *info;
4136         
4137         g_assert (sig->pinvoke);
4138
4139         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
4140
4141         mb->method->save_lmf = 1;
4142
4143         /* Add an explicit this argument */
4144         if (sig->hasthis)
4145                 csig2 = mono_metadata_signature_dup_add_this (mono_defaults.corlib, sig, mono_defaults.object_class);
4146         else
4147                 csig2 = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
4148
4149 #ifndef DISABLE_JIT
4150         if (sig->hasthis)
4151                 mono_mb_emit_byte (mb, CEE_LDARG_0);
4152
4153         for (i = 0; i < sig->param_count; i++)
4154                 mono_mb_emit_ldarg (mb, i + sig->hasthis);
4155
4156         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4157         mono_mb_emit_op (mb, CEE_MONO_JIT_ICALL_ADDR, (gpointer)func);
4158         mono_mb_emit_calli (mb, csig2);
4159         if (check_exceptions)
4160                 emit_thread_interrupt_checkpoint (mb);
4161         mono_mb_emit_byte (mb, CEE_RET);
4162 #endif
4163
4164         csig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
4165         csig->pinvoke = 0;
4166         if (csig->call_convention == MONO_CALL_VARARG)
4167                 csig->call_convention = 0;
4168
4169         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ICALL_WRAPPER);
4170         info->d.icall.func = (gpointer)func;
4171         res = mono_mb_create (mb, csig, csig->param_count + 16, info);
4172         mono_mb_free (mb);
4173
4174         return res;
4175 }
4176
4177 static int
4178 emit_marshal_custom (EmitMarshalContext *m, int argnum, MonoType *t,
4179                                          MonoMarshalSpec *spec, 
4180                                          int conv_arg, MonoType **conv_arg_type, 
4181                                          MarshalAction action)
4182 {
4183 #ifdef DISABLE_JIT
4184         if (action == MARSHAL_ACTION_CONV_IN && t->type == MONO_TYPE_VALUETYPE)
4185                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4186         return conv_arg;
4187 #else
4188         MonoType *mtype;
4189         MonoClass *mklass;
4190         static MonoClass *ICustomMarshaler = NULL;
4191         static MonoMethod *cleanup_native, *cleanup_managed;
4192         static MonoMethod *marshal_managed_to_native, *marshal_native_to_managed;
4193         MonoMethod *get_instance = NULL;
4194         MonoMethodBuilder *mb = m->mb;
4195         char *exception_msg = NULL;
4196         guint32 loc1;
4197         int pos2;
4198
4199         if (!ICustomMarshaler) {
4200                 MonoClass *klass = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "ICustomMarshaler");
4201                 if (!klass) {
4202                         exception_msg = g_strdup ("Current profile doesn't support ICustomMarshaler");
4203                         goto handle_exception;
4204                 }
4205
4206                 cleanup_native = mono_class_get_method_from_name (klass, "CleanUpNativeData", 1);
4207                 g_assert (cleanup_native);
4208                 cleanup_managed = mono_class_get_method_from_name (klass, "CleanUpManagedData", 1);
4209                 g_assert (cleanup_managed);
4210                 marshal_managed_to_native = mono_class_get_method_from_name (klass, "MarshalManagedToNative", 1);
4211                 g_assert (marshal_managed_to_native);
4212                 marshal_native_to_managed = mono_class_get_method_from_name (klass, "MarshalNativeToManaged", 1);
4213                 g_assert (marshal_native_to_managed);
4214
4215                 mono_memory_barrier ();
4216                 ICustomMarshaler = klass;
4217         }
4218
4219         if (spec->data.custom_data.image)
4220                 mtype = mono_reflection_type_from_name (spec->data.custom_data.custom_name, spec->data.custom_data.image);
4221         else
4222                 mtype = mono_reflection_type_from_name (spec->data.custom_data.custom_name, m->image);
4223         g_assert (mtype != NULL);
4224         mklass = mono_class_from_mono_type (mtype);
4225         g_assert (mklass != NULL);
4226
4227         if (!mono_class_is_assignable_from (ICustomMarshaler, mklass))
4228                 exception_msg = g_strdup_printf ("Custom marshaler '%s' does not implement the ICustomMarshaler interface.", mklass->name);
4229
4230         get_instance = mono_class_get_method_from_name_flags (mklass, "GetInstance", 1, METHOD_ATTRIBUTE_STATIC);
4231         if (get_instance) {
4232                 MonoMethodSignature *get_sig = mono_method_signature (get_instance);
4233                 if ((get_sig->ret->type != MONO_TYPE_CLASS) ||
4234                         (mono_class_from_mono_type (get_sig->ret) != ICustomMarshaler) ||
4235                         (get_sig->params [0]->type != MONO_TYPE_STRING))
4236                         get_instance = NULL;
4237         }
4238
4239         if (!get_instance)
4240                 exception_msg = g_strdup_printf ("Custom marshaler '%s' does not implement a static GetInstance method that takes a single string parameter and returns an ICustomMarshaler.", mklass->name);
4241
4242 handle_exception:
4243         /* Throw exception and emit compensation code if neccesary */
4244         if (exception_msg) {
4245                 switch (action) {
4246                 case MARSHAL_ACTION_CONV_IN:
4247                 case MARSHAL_ACTION_CONV_RESULT:
4248                 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4249                         if ((action == MARSHAL_ACTION_CONV_RESULT) || (action == MARSHAL_ACTION_MANAGED_CONV_RESULT))
4250                                 mono_mb_emit_byte (mb, CEE_POP);
4251
4252                         mono_mb_emit_exception_full (mb, "System", "ApplicationException", exception_msg);
4253                         g_free (exception_msg);
4254
4255                         break;
4256                 case MARSHAL_ACTION_PUSH:
4257                         mono_mb_emit_byte (mb, CEE_LDNULL);
4258                         break;
4259                 default:
4260                         break;
4261                 }
4262                 return 0;
4263         }
4264
4265         /* FIXME: MS.NET seems to create one instance for each klass + cookie pair */
4266         /* FIXME: MS.NET throws an exception if GetInstance returns null */
4267
4268         switch (action) {
4269         case MARSHAL_ACTION_CONV_IN:
4270                 switch (t->type) {
4271                 case MONO_TYPE_CLASS:
4272                 case MONO_TYPE_OBJECT:
4273                 case MONO_TYPE_STRING:
4274                 case MONO_TYPE_ARRAY:
4275                 case MONO_TYPE_SZARRAY:
4276                 case MONO_TYPE_VALUETYPE:
4277                         break;
4278
4279                 default:
4280                         g_warning ("custom marshalling of type %x is currently not supported", t->type);
4281                         g_assert_not_reached ();
4282                         break;
4283                 }
4284
4285                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4286
4287                 mono_mb_emit_byte (mb, CEE_LDNULL);
4288                 mono_mb_emit_stloc (mb, conv_arg);
4289
4290                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT))
4291                         break;
4292
4293                 /* Minic MS.NET behavior */
4294                 if (!t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT) && !(t->attrs & PARAM_ATTRIBUTE_IN))
4295                         break;
4296
4297                 /* Check for null */
4298                 mono_mb_emit_ldarg (mb, argnum);
4299                 if (t->byref)
4300                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4301                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4302
4303                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4304
4305                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4306                                 
4307                 mono_mb_emit_ldarg (mb, argnum);
4308                 if (t->byref)
4309                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
4310
4311                 if (t->type == MONO_TYPE_VALUETYPE) {
4312                         /*
4313                          * Since we can't determine the type of the argument, we
4314                          * will assume the unmanaged function takes a pointer.
4315                          */
4316                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
4317
4318                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
4319                 }
4320
4321                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4322                 mono_mb_emit_stloc (mb, conv_arg);
4323
4324                 mono_mb_patch_branch (mb, pos2);
4325                 break;
4326
4327         case MARSHAL_ACTION_CONV_OUT:
4328                 /* Check for null */
4329                 mono_mb_emit_ldloc (mb, conv_arg);
4330                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4331
4332                 if (t->byref) {
4333                         mono_mb_emit_ldarg (mb, argnum);
4334
4335                         mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4336
4337                         mono_mb_emit_op (mb, CEE_CALL, get_instance);
4338
4339                         mono_mb_emit_ldloc (mb, conv_arg);
4340                         mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4341                         mono_mb_emit_byte (mb, CEE_STIND_REF);
4342                 } else if (t->attrs & PARAM_ATTRIBUTE_OUT) {
4343                         mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4344
4345                         mono_mb_emit_op (mb, CEE_CALL, get_instance);
4346
4347                         mono_mb_emit_ldloc (mb, conv_arg);
4348                         mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4349
4350                         /* We have nowhere to store the result */
4351                         mono_mb_emit_byte (mb, CEE_POP);
4352                 }
4353
4354                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4355
4356                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4357
4358                 mono_mb_emit_ldloc (mb, conv_arg);
4359
4360                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4361
4362                 mono_mb_patch_branch (mb, pos2);
4363                 break;
4364
4365         case MARSHAL_ACTION_PUSH:
4366                 if (t->byref)
4367                         mono_mb_emit_ldloc_addr (mb, conv_arg);
4368                 else
4369                         mono_mb_emit_ldloc (mb, conv_arg);
4370                 break;
4371
4372         case MARSHAL_ACTION_CONV_RESULT:
4373                 loc1 = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4374                         
4375                 mono_mb_emit_stloc (mb, 3);
4376
4377                 mono_mb_emit_ldloc (mb, 3);
4378                 mono_mb_emit_stloc (mb, loc1);
4379
4380                 /* Check for null */
4381                 mono_mb_emit_ldloc (mb, 3);
4382                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4383
4384                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4385
4386                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4387                 mono_mb_emit_byte (mb, CEE_DUP);
4388
4389                 mono_mb_emit_ldloc (mb, 3);
4390                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4391                 mono_mb_emit_stloc (mb, 3);
4392
4393                 mono_mb_emit_ldloc (mb, loc1);
4394                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4395
4396                 mono_mb_patch_branch (mb, pos2);
4397                 break;
4398
4399         case MARSHAL_ACTION_MANAGED_CONV_IN:
4400                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4401
4402                 mono_mb_emit_byte (mb, CEE_LDNULL);
4403                 mono_mb_emit_stloc (mb, conv_arg);
4404
4405                 if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
4406                         break;
4407
4408                 /* Check for null */
4409                 mono_mb_emit_ldarg (mb, argnum);
4410                 if (t->byref)
4411                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4412                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4413
4414                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4415                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4416                                 
4417                 mono_mb_emit_ldarg (mb, argnum);
4418                 if (t->byref)
4419                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4420                                 
4421                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4422                 mono_mb_emit_stloc (mb, conv_arg);
4423
4424                 mono_mb_patch_branch (mb, pos2);
4425                 break;
4426
4427         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4428                 g_assert (!t->byref);
4429
4430                 loc1 = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4431                         
4432                 mono_mb_emit_stloc (mb, 3);
4433                         
4434                 mono_mb_emit_ldloc (mb, 3);
4435                 mono_mb_emit_stloc (mb, loc1);
4436
4437                 /* Check for null */
4438                 mono_mb_emit_ldloc (mb, 3);
4439                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4440
4441                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4442                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4443                 mono_mb_emit_byte (mb, CEE_DUP);
4444
4445                 mono_mb_emit_ldloc (mb, 3);
4446                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4447                 mono_mb_emit_stloc (mb, 3);
4448
4449                 mono_mb_emit_ldloc (mb, loc1);
4450                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
4451
4452                 mono_mb_patch_branch (mb, pos2);
4453                 break;
4454
4455         case MARSHAL_ACTION_MANAGED_CONV_OUT:
4456
4457                 /* Check for null */
4458                 mono_mb_emit_ldloc (mb, conv_arg);
4459                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4460
4461                 if (t->byref) {
4462                         mono_mb_emit_ldarg (mb, argnum);
4463
4464                         mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4465
4466                         mono_mb_emit_op (mb, CEE_CALL, get_instance);
4467
4468                         mono_mb_emit_ldloc (mb, conv_arg);
4469                         mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4470                         mono_mb_emit_byte (mb, CEE_STIND_I);
4471                 }
4472
4473                 /* Call CleanUpManagedData */
4474                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4475
4476                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4477                                 
4478                 mono_mb_emit_ldloc (mb, conv_arg);
4479                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
4480
4481                 mono_mb_patch_branch (mb, pos2);
4482                 break;
4483
4484         default:
4485                 g_assert_not_reached ();
4486         }
4487         return conv_arg;
4488 #endif
4489
4490 }
4491
4492 static int
4493 emit_marshal_asany (EmitMarshalContext *m, int argnum, MonoType *t,
4494                                         MonoMarshalSpec *spec, 
4495                                         int conv_arg, MonoType **conv_arg_type, 
4496                                         MarshalAction action)
4497 {
4498 #ifndef DISABLE_JIT
4499         MonoMethodBuilder *mb = m->mb;
4500
4501         switch (action) {
4502         case MARSHAL_ACTION_CONV_IN: {
4503                 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
4504
4505                 g_assert (t->type == MONO_TYPE_OBJECT);
4506                 g_assert (!t->byref);
4507
4508                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4509                 mono_mb_emit_ldarg (mb, argnum);
4510                 mono_mb_emit_icon (mb, encoding);
4511                 mono_mb_emit_icon (mb, t->attrs);
4512                 mono_mb_emit_icall (mb, mono_marshal_asany);
4513                 mono_mb_emit_stloc (mb, conv_arg);
4514                 break;
4515         }
4516
4517         case MARSHAL_ACTION_PUSH:
4518                 mono_mb_emit_ldloc (mb, conv_arg);
4519                 break;
4520
4521         case MARSHAL_ACTION_CONV_OUT: {
4522                 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
4523
4524                 mono_mb_emit_ldarg (mb, argnum);
4525                 mono_mb_emit_ldloc (mb, conv_arg);
4526                 mono_mb_emit_icon (mb, encoding);
4527                 mono_mb_emit_icon (mb, t->attrs);
4528                 mono_mb_emit_icall (mb, mono_marshal_free_asany);
4529                 break;
4530         }
4531
4532         default:
4533                 g_assert_not_reached ();
4534         }
4535 #endif
4536         return conv_arg;
4537 }
4538
4539 static int
4540 emit_marshal_vtype (EmitMarshalContext *m, int argnum, MonoType *t,
4541                                         MonoMarshalSpec *spec, 
4542                                         int conv_arg, MonoType **conv_arg_type, 
4543                                         MarshalAction action)
4544 {
4545 #ifndef DISABLE_JIT
4546         MonoMethodBuilder *mb = m->mb;
4547         MonoClass *klass, *date_time_class;
4548         int pos = 0, pos2;
4549
4550         klass = mono_class_from_mono_type (t);
4551
4552         date_time_class = mono_class_from_name_cached (mono_defaults.corlib, "System", "DateTime");
4553
4554         switch (action) {
4555         case MARSHAL_ACTION_CONV_IN:
4556                 if (klass == date_time_class) {
4557                         /* Convert it to an OLE DATE type */
4558                         static MonoMethod *to_oadate;
4559
4560                         if (!to_oadate)
4561                                 to_oadate = mono_class_get_method_from_name (date_time_class, "ToOADate", 0);
4562                         g_assert (to_oadate);
4563
4564                         conv_arg = mono_mb_add_local (mb, &mono_defaults.double_class->byval_arg);
4565
4566                         if (t->byref) {
4567                                 mono_mb_emit_ldarg (mb, argnum);
4568                                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
4569                         }
4570
4571                         if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
4572                                 if (!t->byref)
4573                                         m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.double_class->byval_arg;
4574
4575                                 mono_mb_emit_ldarg_addr (mb, argnum);
4576                                 mono_mb_emit_managed_call (mb, to_oadate, NULL);
4577                                 mono_mb_emit_stloc (mb, conv_arg);
4578                         }
4579
4580                         if (t->byref)
4581                                 mono_mb_patch_branch (mb, pos);
4582                         break;
4583                 }
4584
4585                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4586                         klass->blittable || klass->enumtype)
4587                         break;
4588
4589                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4590                         
4591                 /* store the address of the source into local variable 0 */
4592                 if (t->byref)
4593                         mono_mb_emit_ldarg (mb, argnum);
4594                 else
4595                         mono_mb_emit_ldarg_addr (mb, argnum);
4596                 
4597                 mono_mb_emit_stloc (mb, 0);
4598                         
4599                 /* allocate space for the native struct and
4600                  * store the address into local variable 1 (dest) */
4601                 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
4602                 mono_mb_emit_byte (mb, CEE_PREFIX1);
4603                 mono_mb_emit_byte (mb, CEE_LOCALLOC);
4604                 mono_mb_emit_stloc (mb, conv_arg);
4605
4606                 if (t->byref) {
4607                         mono_mb_emit_ldloc (mb, 0);
4608                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
4609                 }
4610
4611                 if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
4612                         /* set dst_ptr */
4613                         mono_mb_emit_ldloc (mb, conv_arg);
4614                         mono_mb_emit_stloc (mb, 1);
4615
4616                         /* emit valuetype conversion code */
4617                         emit_struct_conv (mb, klass, FALSE);
4618                 }
4619
4620                 if (t->byref)
4621                         mono_mb_patch_branch (mb, pos);
4622                 break;
4623
4624         case MARSHAL_ACTION_PUSH:
4625                 if (spec && spec->native == MONO_NATIVE_LPSTRUCT) {
4626                         /* FIXME: */
4627                         g_assert (!t->byref);
4628
4629                         /* Have to change the signature since the vtype is passed byref */
4630                         m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.int_class->byval_arg;
4631
4632                         if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4633                                 klass->blittable || klass->enumtype)
4634                                 mono_mb_emit_ldarg_addr (mb, argnum);
4635                         else
4636                                 mono_mb_emit_ldloc (mb, conv_arg);
4637                         break;
4638                 }
4639
4640                 if (klass == date_time_class) {
4641                         if (t->byref)
4642                                 mono_mb_emit_ldloc_addr (mb, conv_arg);
4643                         else
4644                                 mono_mb_emit_ldloc (mb, conv_arg);
4645                         break;
4646                 }
4647
4648                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4649                         klass->blittable || klass->enumtype) {
4650                         mono_mb_emit_ldarg (mb, argnum);
4651                         break;
4652                 }                       
4653                 mono_mb_emit_ldloc (mb, conv_arg);
4654                 if (!t->byref) {
4655                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4656                         mono_mb_emit_op (mb, CEE_MONO_LDNATIVEOBJ, klass);
4657                 }
4658                 break;
4659
4660         case MARSHAL_ACTION_CONV_OUT:
4661                 if (klass == date_time_class) {
4662                         /* Convert from an OLE DATE type */
4663                         static MonoMethod *from_oadate;
4664
4665                         if (!t->byref)
4666                                 break;
4667
4668                         if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
4669                                 if (!from_oadate)
4670                                         from_oadate = mono_class_get_method_from_name (date_time_class, "FromOADate", 1);
4671                                 g_assert (from_oadate);
4672
4673                                 mono_mb_emit_ldarg (mb, argnum);
4674                                 mono_mb_emit_ldloc (mb, conv_arg);
4675                                 mono_mb_emit_managed_call (mb, from_oadate, NULL);
4676                                 mono_mb_emit_op (mb, CEE_STOBJ, date_time_class);
4677                         }
4678                         break;
4679                 }
4680
4681                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4682                         klass->blittable || klass->enumtype)
4683                         break;
4684
4685                 if (t->byref) {
4686                         /* dst = argument */
4687                         mono_mb_emit_ldarg (mb, argnum);
4688                         mono_mb_emit_stloc (mb, 1);
4689
4690                         mono_mb_emit_ldloc (mb, 1);
4691                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
4692
4693                         if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
4694                                 /* src = tmp_locals [i] */
4695                                 mono_mb_emit_ldloc (mb, conv_arg);
4696                                 mono_mb_emit_stloc (mb, 0);
4697
4698                                 /* emit valuetype conversion code */
4699                                 emit_struct_conv (mb, klass, TRUE);
4700                         }
4701                 }
4702
4703                 emit_struct_free (mb, klass, conv_arg);
4704                 
4705                 if (t->byref)
4706                         mono_mb_patch_branch (mb, pos);
4707                 break;
4708
4709         case MARSHAL_ACTION_CONV_RESULT:
4710                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4711                         klass->blittable) {
4712                         mono_mb_emit_stloc (mb, 3);
4713                         break;
4714                 }
4715
4716                 /* load pointer to returned value type */
4717                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4718                 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
4719                 /* store the address of the source into local variable 0 */
4720                 mono_mb_emit_stloc (mb, 0);
4721                 /* set dst_ptr */
4722                 mono_mb_emit_ldloc_addr (mb, 3);
4723                 mono_mb_emit_stloc (mb, 1);
4724                                 
4725                 /* emit valuetype conversion code */
4726                 emit_struct_conv (mb, klass, TRUE);
4727                 break;
4728
4729         case MARSHAL_ACTION_MANAGED_CONV_IN:
4730                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4731                         klass->blittable || klass->enumtype) {
4732                         conv_arg = 0;
4733                         break;
4734                 }
4735
4736                 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
4737
4738                 if (t->attrs & PARAM_ATTRIBUTE_OUT)
4739                         break;
4740
4741                 if (t->byref) 
4742                         mono_mb_emit_ldarg (mb, argnum);
4743                 else
4744                         mono_mb_emit_ldarg_addr (mb, argnum);
4745                 mono_mb_emit_stloc (mb, 0);
4746
4747                 if (t->byref) {
4748                         mono_mb_emit_ldloc (mb, 0);
4749                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
4750                 }                       
4751
4752                 mono_mb_emit_ldloc_addr (mb, conv_arg);
4753                 mono_mb_emit_stloc (mb, 1);
4754
4755                 /* emit valuetype conversion code */
4756                 emit_struct_conv (mb, klass, TRUE);
4757
4758                 if (t->byref)
4759                         mono_mb_patch_branch (mb, pos);
4760                 break;
4761
4762         case MARSHAL_ACTION_MANAGED_CONV_OUT:
4763                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4764                         klass->blittable || klass->enumtype) {
4765                         break;
4766                 }
4767
4768                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))
4769                         break;
4770
4771                 /* Check for null */
4772                 mono_mb_emit_ldarg (mb, argnum);
4773                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4774
4775                 /* Set src */
4776                 mono_mb_emit_ldloc_addr (mb, conv_arg);
4777                 mono_mb_emit_stloc (mb, 0);
4778
4779                 /* Set dest */
4780                 mono_mb_emit_ldarg (mb, argnum);
4781                 mono_mb_emit_stloc (mb, 1);
4782
4783                 /* emit valuetype conversion code */
4784                 emit_struct_conv (mb, klass, FALSE);
4785
4786                 mono_mb_patch_branch (mb, pos2);
4787                 break;
4788
4789         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4790                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4791                         klass->blittable || klass->enumtype) {
4792                         mono_mb_emit_stloc (mb, 3);
4793                         m->retobj_var = 0;
4794                         break;
4795                 }
4796                         
4797                 /* load pointer to returned value type */
4798                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4799                 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
4800                         
4801                 /* store the address of the source into local variable 0 */
4802                 mono_mb_emit_stloc (mb, 0);
4803                 /* allocate space for the native struct and
4804                  * store the address into dst_ptr */
4805                 m->retobj_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4806                 m->retobj_class = klass;
4807                 g_assert (m->retobj_var);
4808                 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
4809                 mono_mb_emit_byte (mb, CEE_CONV_I);
4810                 mono_mb_emit_icall (mb, mono_marshal_alloc);
4811                 mono_mb_emit_stloc (mb, 1);
4812                 mono_mb_emit_ldloc (mb, 1);
4813                 mono_mb_emit_stloc (mb, m->retobj_var);
4814
4815                 /* emit valuetype conversion code */
4816                 emit_struct_conv (mb, klass, FALSE);
4817                 break;
4818
4819         default:
4820                 g_assert_not_reached ();
4821         }
4822 #endif
4823         return conv_arg;
4824 }
4825
4826 static int
4827 emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
4828                                          MonoMarshalSpec *spec, 
4829                                          int conv_arg, MonoType **conv_arg_type, 
4830                                          MarshalAction action)
4831 {
4832 #ifdef DISABLE_JIT
4833         switch (action) {
4834         case MARSHAL_ACTION_CONV_IN:
4835                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4836                 break;
4837         case MARSHAL_ACTION_MANAGED_CONV_IN:
4838                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4839                 break;
4840         }
4841 #else
4842         MonoMethodBuilder *mb = m->mb;
4843         MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
4844         MonoMarshalConv conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
4845         gboolean need_free;
4846
4847         switch (action) {
4848         case MARSHAL_ACTION_CONV_IN:
4849                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4850                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4851
4852                 if (t->byref) {
4853                         if (t->attrs & PARAM_ATTRIBUTE_OUT)
4854                                 break;
4855
4856                         mono_mb_emit_ldarg (mb, argnum);
4857                         mono_mb_emit_byte (mb, CEE_LDIND_I);                            
4858                 } else {
4859                         mono_mb_emit_ldarg (mb, argnum);
4860                 }
4861
4862                 if (conv == -1) {
4863                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
4864                         mono_mb_emit_exception_marshal_directive (mb, msg);
4865                 } else {
4866                         mono_mb_emit_icall (mb, conv_to_icall (conv));
4867
4868                         mono_mb_emit_stloc (mb, conv_arg);
4869                 }
4870                 break;
4871
4872         case MARSHAL_ACTION_CONV_OUT:
4873                 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
4874                 if (conv == -1) {
4875                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
4876                         mono_mb_emit_exception_marshal_directive (mb, msg);
4877                         break;
4878                 }
4879
4880                 if (encoding == MONO_NATIVE_VBBYREFSTR) {
4881                         static MonoMethod *m;
4882
4883                         if (!m) {
4884                                 m = mono_class_get_method_from_name_flags (mono_defaults.string_class, "get_Length", -1, 0);
4885                                 g_assert (m);
4886                         }
4887
4888                         if (!t->byref) {
4889                                 char *msg = g_strdup_printf ("VBByRefStr marshalling requires a ref parameter.", encoding);
4890                                 mono_mb_emit_exception_marshal_directive (mb, msg);
4891                                 break;
4892                         }
4893
4894                         /* 
4895                          * Have to allocate a new string with the same length as the original, and
4896                          * copy the contents of the buffer pointed to by CONV_ARG into it.
4897                          */
4898                         g_assert (t->byref);
4899                         mono_mb_emit_ldarg (mb, argnum);
4900                         mono_mb_emit_ldloc (mb, conv_arg);
4901                         mono_mb_emit_ldarg (mb, argnum);
4902                         mono_mb_emit_byte (mb, CEE_LDIND_I);                            
4903                         mono_mb_emit_managed_call (mb, m, NULL);
4904                         mono_mb_emit_icall (mb, mono_string_new_len_wrapper);
4905                         mono_mb_emit_byte (mb, CEE_STIND_REF);
4906                 } else if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
4907                         mono_mb_emit_ldarg (mb, argnum);
4908                         mono_mb_emit_ldloc (mb, conv_arg);
4909                         mono_mb_emit_icall (mb, conv_to_icall (conv));
4910                         mono_mb_emit_byte (mb, CEE_STIND_REF);
4911                         need_free = TRUE;
4912                 }
4913
4914                 if (need_free) {
4915                         mono_mb_emit_ldloc (mb, conv_arg);
4916                         if (conv == MONO_MARSHAL_CONV_BSTR_STR)
4917                                 mono_mb_emit_icall (mb, mono_free_bstr);
4918                         else
4919                                 mono_mb_emit_icall (mb, mono_marshal_free);
4920                 }
4921                 break;
4922
4923         case MARSHAL_ACTION_PUSH:
4924                 if (t->byref && encoding != MONO_NATIVE_VBBYREFSTR)
4925                         mono_mb_emit_ldloc_addr (mb, conv_arg);
4926                 else
4927                         mono_mb_emit_ldloc (mb, conv_arg);
4928                 break;
4929
4930         case MARSHAL_ACTION_CONV_RESULT:
4931                 mono_mb_emit_stloc (mb, 0);
4932                                 
4933                 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
4934                 if (conv == -1) {
4935                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
4936                         mono_mb_emit_exception_marshal_directive (mb, msg);
4937                         break;
4938                 }
4939
4940                 mono_mb_emit_ldloc (mb, 0);
4941                 mono_mb_emit_icall (mb, conv_to_icall (conv));
4942                 mono_mb_emit_stloc (mb, 3);
4943
4944                 /* free the string */
4945                 mono_mb_emit_ldloc (mb, 0);
4946                 if (conv == MONO_MARSHAL_CONV_BSTR_STR)
4947                         mono_mb_emit_icall (mb, mono_free_bstr);
4948                 else
4949                         mono_mb_emit_icall (mb, mono_marshal_free);
4950                 break;
4951
4952         case MARSHAL_ACTION_MANAGED_CONV_IN:
4953                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4954
4955                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4956
4957                 if (t->byref) {
4958                         if (t->attrs & PARAM_ATTRIBUTE_OUT)
4959                                 break;
4960                 }
4961
4962                 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
4963                 if (conv == -1) {
4964                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
4965                         mono_mb_emit_exception_marshal_directive (mb, msg);
4966                         break;
4967                 }
4968
4969                 mono_mb_emit_ldarg (mb, argnum);
4970                 if (t->byref)
4971                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4972                 mono_mb_emit_icall (mb, conv_to_icall (conv));
4973                 mono_mb_emit_stloc (mb, conv_arg);
4974                 break;
4975
4976         case MARSHAL_ACTION_MANAGED_CONV_OUT:
4977                 if (t->byref) {
4978                         if (conv_arg) {
4979                                 mono_mb_emit_ldarg (mb, argnum);
4980                                 mono_mb_emit_ldloc (mb, conv_arg);
4981                                 mono_mb_emit_icall (mb, conv_to_icall (conv));
4982                                 mono_mb_emit_byte (mb, CEE_STIND_I);
4983                         }
4984                 }
4985                 break;
4986
4987         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4988                 if (conv_to_icall (conv) == mono_marshal_string_to_utf16)
4989                         /* We need to make a copy so the caller is able to free it */
4990                         mono_mb_emit_icall (mb, mono_marshal_string_to_utf16_copy);
4991                 else
4992                         mono_mb_emit_icall (mb, conv_to_icall (conv));
4993                 mono_mb_emit_stloc (mb, 3);
4994                 break;
4995
4996         default:
4997                 g_assert_not_reached ();
4998         }
4999 #endif
5000         return conv_arg;
5001 }
5002
5003
5004 static int
5005 emit_marshal_safehandle (EmitMarshalContext *m, int argnum, MonoType *t, 
5006                          MonoMarshalSpec *spec, int conv_arg, 
5007                          MonoType **conv_arg_type, MarshalAction action)
5008 {
5009 #ifdef DISABLE_JIT
5010         if (action == MARSHAL_ACTION_CONV_IN)
5011                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5012 #else
5013         MonoMethodBuilder *mb = m->mb;
5014
5015         switch (action){
5016         case MARSHAL_ACTION_CONV_IN: {
5017                 MonoType *intptr_type;
5018                 int dar_release_slot, pos;
5019
5020                 intptr_type = &mono_defaults.int_class->byval_arg;
5021                 conv_arg = mono_mb_add_local (mb, intptr_type);
5022                 *conv_arg_type = intptr_type;
5023
5024                 if (!sh_dangerous_add_ref)
5025                         init_safe_handle ();
5026
5027                 mono_mb_emit_ldarg (mb, argnum);
5028                 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
5029                 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
5030                 
5031                 mono_mb_patch_branch (mb, pos);
5032                 if (t->byref){
5033                         /*
5034                          * My tests in show that ref SafeHandles are not really
5035                          * passed as ref objects.  Instead a NULL is passed as the
5036                          * value of the ref
5037                          */
5038                         mono_mb_emit_icon (mb, 0);
5039                         mono_mb_emit_stloc (mb, conv_arg);
5040                         break;
5041                 } 
5042
5043                 /* Create local to hold the ref parameter to DangerousAddRef */
5044                 dar_release_slot = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
5045
5046                 /* set release = false; */
5047                 mono_mb_emit_icon (mb, 0);
5048                 mono_mb_emit_stloc (mb, dar_release_slot);
5049
5050                 /* safehandle.DangerousAddRef (ref release) */
5051                 mono_mb_emit_ldarg (mb, argnum);
5052                 mono_mb_emit_ldloc_addr (mb, dar_release_slot);
5053                 mono_mb_emit_managed_call (mb, sh_dangerous_add_ref, NULL);
5054
5055                 /* Pull the handle field from SafeHandle */
5056                 mono_mb_emit_ldarg (mb, argnum);
5057                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5058                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5059                 mono_mb_emit_stloc (mb, conv_arg);
5060
5061                 break;
5062         }
5063
5064         case MARSHAL_ACTION_PUSH:
5065                 if (t->byref)
5066                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5067                 else 
5068                         mono_mb_emit_ldloc (mb, conv_arg);
5069                 break;
5070
5071         case MARSHAL_ACTION_CONV_OUT: {
5072                 /* The slot for the boolean is the next temporary created after conv_arg, see the CONV_IN code */
5073                 int dar_release_slot = conv_arg + 1;
5074                 int label_next;
5075
5076                 if (!sh_dangerous_release)
5077                         init_safe_handle ();
5078
5079                 if (t->byref){
5080                         MonoMethod *ctor;
5081                         
5082                         /*
5083                          * My tests indicate that ref SafeHandles parameters are not actually
5084                          * passed by ref, but instead a new Handle is created regardless of
5085                          * whether a change happens in the unmanaged side.
5086                          *
5087                          * Also, the Handle is created before calling into unmanaged code,
5088                          * but we do not support that mechanism (getting to the original
5089                          * handle) and it makes no difference where we create this
5090                          */
5091                         ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5092                         if (ctor == NULL){
5093                                 mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5094                                 break;
5095                         }
5096                         /* refval = new SafeHandleDerived ()*/
5097                         mono_mb_emit_ldarg (mb, argnum);
5098                         mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5099                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5100
5101                         /* refval.handle = returned_handle */
5102                         mono_mb_emit_ldarg (mb, argnum);
5103                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
5104                         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5105                         mono_mb_emit_ldloc (mb, conv_arg);
5106                         mono_mb_emit_byte (mb, CEE_STIND_I);
5107                 } else {
5108                         mono_mb_emit_ldloc (mb, dar_release_slot);
5109                         label_next = mono_mb_emit_branch (mb, CEE_BRFALSE);
5110                         mono_mb_emit_ldarg (mb, argnum);
5111                         mono_mb_emit_managed_call (mb, sh_dangerous_release, NULL);
5112                         mono_mb_patch_branch (mb, label_next);
5113                 }
5114                 break;
5115         }
5116                 
5117         case MARSHAL_ACTION_CONV_RESULT: {
5118                 MonoMethod *ctor = NULL;
5119                 int intptr_handle_slot;
5120                 
5121                 if (t->data.klass->flags & TYPE_ATTRIBUTE_ABSTRACT){
5122                         mono_mb_emit_byte (mb, CEE_POP);
5123                         mono_mb_emit_exception_marshal_directive (mb, g_strdup ("Returned SafeHandles should not be abstract"));
5124                         break;
5125                 }
5126
5127                 ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5128                 if (ctor == NULL){
5129                         mono_mb_emit_byte (mb, CEE_POP);
5130                         mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5131                         break;
5132                 }
5133                 /* Store the IntPtr results into a local */
5134                 intptr_handle_slot = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5135                 mono_mb_emit_stloc (mb, intptr_handle_slot);
5136
5137                 /* Create return value */
5138                 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5139                 mono_mb_emit_stloc (mb, 3);
5140
5141                 /* Set the return.handle to the value, am using ldflda, not sure if thats a good idea */
5142                 mono_mb_emit_ldloc (mb, 3);
5143                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5144                 mono_mb_emit_ldloc (mb, intptr_handle_slot);
5145                 mono_mb_emit_byte (mb, CEE_STIND_I);
5146                 break;
5147         }
5148                 
5149         case MARSHAL_ACTION_MANAGED_CONV_IN:
5150                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5151                 break;
5152                 
5153         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5154                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5155                 break;
5156
5157         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5158                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5159                 break;
5160         default:
5161                 printf ("Unhandled case for MarshalAction: %d\n", action);
5162         }
5163 #endif
5164         return conv_arg;
5165 }
5166
5167
5168 static int
5169 emit_marshal_handleref (EmitMarshalContext *m, int argnum, MonoType *t, 
5170                         MonoMarshalSpec *spec, int conv_arg, 
5171                         MonoType **conv_arg_type, MarshalAction action)
5172 {
5173 #ifdef DISABLE_JIT
5174         if (action == MARSHAL_ACTION_CONV_IN)
5175                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5176 #else
5177         MonoMethodBuilder *mb = m->mb;
5178
5179         switch (action){
5180         case MARSHAL_ACTION_CONV_IN: {
5181                 MonoType *intptr_type;
5182
5183                 intptr_type = &mono_defaults.int_class->byval_arg;
5184                 conv_arg = mono_mb_add_local (mb, intptr_type);
5185                 *conv_arg_type = intptr_type;
5186
5187                 if (t->byref){
5188                         char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5189                         mono_mb_emit_exception_marshal_directive (mb, msg);
5190                         break;
5191                 } 
5192                 mono_mb_emit_ldarg_addr (mb, argnum);
5193                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoHandleRef, handle));
5194                 mono_mb_emit_byte (mb, CEE_ADD);
5195                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5196                 mono_mb_emit_stloc (mb, conv_arg);
5197                 break;
5198         }
5199
5200         case MARSHAL_ACTION_PUSH:
5201                 mono_mb_emit_ldloc (mb, conv_arg);
5202                 break;
5203
5204         case MARSHAL_ACTION_CONV_OUT: {
5205                 /* no resource release required */
5206                 break;
5207         }
5208                 
5209         case MARSHAL_ACTION_CONV_RESULT: {
5210                 char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5211                 mono_mb_emit_exception_marshal_directive (mb, msg);
5212                 break;
5213         }
5214                 
5215         case MARSHAL_ACTION_MANAGED_CONV_IN:
5216                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5217                 break;
5218                 
5219         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5220                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5221                 break;
5222
5223         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5224                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5225                 break;
5226         default:
5227                 fprintf (stderr, "Unhandled case for MarshalAction: %d\n", action);
5228         }
5229 #endif
5230         return conv_arg;
5231 }
5232
5233
5234 static int
5235 emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
5236                      MonoMarshalSpec *spec, 
5237                      int conv_arg, MonoType **conv_arg_type, 
5238                      MarshalAction action)
5239 {
5240 #ifdef DISABLE_JIT
5241         if (action == MARSHAL_ACTION_CONV_IN)
5242                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5243 #else
5244         MonoMethodBuilder *mb = m->mb;
5245         MonoClass *klass = mono_class_from_mono_type (t);
5246         int pos, pos2, loc;
5247
5248         switch (action) {
5249         case MARSHAL_ACTION_CONV_IN:
5250                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5251                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5252
5253                 m->orig_conv_args [argnum] = 0;
5254
5255                 if (mono_class_from_mono_type (t) == mono_defaults.object_class) {
5256                         char *msg = g_strdup_printf ("Marshalling of type object is not implemented");
5257                         mono_mb_emit_exception_marshal_directive (mb, msg);
5258                         break;
5259                 }
5260
5261                 if (klass->delegate) {
5262                         if (t->byref) {
5263                                 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5264                                         char *msg = g_strdup_printf ("Byref marshalling of delegates is not implemented.");
5265                                         mono_mb_emit_exception_marshal_directive (mb, msg);
5266                                 }
5267                                 mono_mb_emit_byte (mb, CEE_LDNULL);
5268                                 mono_mb_emit_stloc (mb, conv_arg);
5269                         } else {
5270                                 mono_mb_emit_ldarg (mb, argnum);
5271                                 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN));
5272                                 mono_mb_emit_stloc (mb, conv_arg);
5273                         }
5274                 } else if (klass == mono_defaults.stringbuilder_class) {
5275                         MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5276                         MonoMarshalConv conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
5277
5278 #if 0                   
5279                         if (t->byref) {
5280                                 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5281                                         char *msg = g_strdup_printf ("Byref marshalling of stringbuilders is not implemented.");
5282                                         mono_mb_emit_exception_marshal_directive (mb, msg);
5283                                 }
5284                                 break;
5285                         }
5286 #endif
5287
5288                         if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))
5289                                 break;
5290
5291                         if (conv == -1) {
5292                                 char *msg = g_strdup_printf ("stringbuilder marshalling conversion %d not implemented", encoding);
5293                                 mono_mb_emit_exception_marshal_directive (mb, msg);
5294                                 break;
5295                         }
5296
5297                         mono_mb_emit_ldarg (mb, argnum);
5298                         if (t->byref)
5299                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5300
5301                         mono_mb_emit_icall (mb, conv_to_icall (conv));
5302                         mono_mb_emit_stloc (mb, conv_arg);
5303                 } else if (klass->blittable) {
5304                         mono_mb_emit_byte (mb, CEE_LDNULL);
5305                         mono_mb_emit_stloc (mb, conv_arg);
5306
5307                         mono_mb_emit_ldarg (mb, argnum);
5308                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5309
5310                         mono_mb_emit_ldarg (mb, argnum);
5311                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5312                         mono_mb_emit_stloc (mb, conv_arg);
5313
5314                         mono_mb_patch_branch (mb, pos);
5315                         break;
5316                 } else {
5317                         mono_mb_emit_byte (mb, CEE_LDNULL);
5318                         mono_mb_emit_stloc (mb, conv_arg);
5319
5320                         if (t->byref) {
5321                                 /* we dont need any conversions for out parameters */
5322                                 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5323                                         break;
5324
5325                                 mono_mb_emit_ldarg (mb, argnum);                                
5326                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5327
5328                         } else {
5329                                 mono_mb_emit_ldarg (mb, argnum);
5330                                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5331                                 mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
5332                         }
5333                                 
5334                         /* store the address of the source into local variable 0 */
5335                         mono_mb_emit_stloc (mb, 0);
5336                         mono_mb_emit_ldloc (mb, 0);
5337                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5338
5339                         /* allocate space for the native struct and store the address */
5340                         mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5341                         mono_mb_emit_byte (mb, CEE_PREFIX1);
5342                         mono_mb_emit_byte (mb, CEE_LOCALLOC);
5343                         mono_mb_emit_stloc (mb, conv_arg);
5344
5345                         if (t->byref) {
5346                                 /* Need to store the original buffer so we can free it later */
5347                                 m->orig_conv_args [argnum] = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5348                                 mono_mb_emit_ldloc (mb, conv_arg);
5349                                 mono_mb_emit_stloc (mb, m->orig_conv_args [argnum]);
5350                         }
5351
5352                         /* set the src_ptr */
5353                         mono_mb_emit_ldloc (mb, 0);
5354                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5355                         mono_mb_emit_stloc (mb, 0);
5356
5357                         /* set dst_ptr */
5358                         mono_mb_emit_ldloc (mb, conv_arg);
5359                         mono_mb_emit_stloc (mb, 1);
5360
5361                         /* emit valuetype conversion code */
5362                         emit_struct_conv (mb, klass, FALSE);
5363
5364                         mono_mb_patch_branch (mb, pos);
5365                 }
5366                 break;
5367
5368         case MARSHAL_ACTION_CONV_OUT:
5369                 if (klass == mono_defaults.stringbuilder_class) {
5370                         gboolean need_free;
5371                         MonoMarshalNative encoding;
5372                         MonoMarshalConv conv;
5373
5374                         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5375                         conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
5376
5377                         g_assert (encoding != -1);
5378
5379                         if (t->byref) {
5380                                 //g_assert (!(t->attrs & PARAM_ATTRIBUTE_OUT));
5381
5382                                 need_free = TRUE;
5383
5384                                 mono_mb_emit_ldarg (mb, argnum);
5385                                 mono_mb_emit_ldloc (mb, conv_arg);
5386
5387                                 switch (encoding) {
5388                                 case MONO_NATIVE_LPWSTR:
5389                                         mono_mb_emit_icall (mb, mono_string_utf16_to_builder2);
5390                                         break;
5391                                 case MONO_NATIVE_LPSTR:
5392                                         mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5393                                         break;
5394                                 default:
5395                                         g_assert_not_reached ();
5396                                 }
5397
5398                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
5399                         } else {
5400                                 mono_mb_emit_ldarg (mb, argnum);
5401                                 mono_mb_emit_ldloc (mb, conv_arg);
5402
5403                                 mono_mb_emit_icall (mb, conv_to_icall (conv));
5404                         }
5405
5406                         if (need_free) {
5407                                 mono_mb_emit_ldloc (mb, conv_arg);
5408                                 mono_mb_emit_icall (mb, mono_marshal_free);
5409                         }
5410                         break;
5411                 }
5412
5413                 if (klass->delegate) {
5414                         if (t->byref) {
5415                                 mono_mb_emit_ldarg (mb, argnum);
5416                                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5417                                 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5418                                 mono_mb_emit_ldloc (mb, conv_arg);
5419                                 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
5420                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
5421                         }
5422                         break;
5423                 }
5424
5425                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT)) {
5426                         /* allocate a new object */
5427                         mono_mb_emit_ldarg (mb, argnum);
5428                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5429                         mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
5430                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5431                 }
5432
5433                 /* dst = *argument */
5434                 mono_mb_emit_ldarg (mb, argnum);
5435
5436                 if (t->byref)
5437                         mono_mb_emit_byte (mb, CEE_LDIND_I);
5438
5439                 mono_mb_emit_stloc (mb, 1);
5440
5441                 mono_mb_emit_ldloc (mb, 1);
5442                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5443
5444                 if (t->byref || (t->attrs & PARAM_ATTRIBUTE_OUT)) {
5445                         mono_mb_emit_ldloc (mb, 1);
5446                         mono_mb_emit_icon (mb, sizeof (MonoObject));
5447                         mono_mb_emit_byte (mb, CEE_ADD);
5448                         mono_mb_emit_stloc (mb, 1);
5449                         
5450                         /* src = tmp_locals [i] */
5451                         mono_mb_emit_ldloc (mb, conv_arg);
5452                         mono_mb_emit_stloc (mb, 0);
5453
5454                         /* emit valuetype conversion code */
5455                         emit_struct_conv (mb, klass, TRUE);
5456
5457                         /* Free the structure returned by the native code */
5458                         emit_struct_free (mb, klass, conv_arg);
5459
5460                         if (m->orig_conv_args [argnum]) {
5461                                 /* 
5462                                  * If the native function changed the pointer, then free
5463                                  * the original structure plus the new pointer.
5464                                  */
5465                                 mono_mb_emit_ldloc (mb, m->orig_conv_args [argnum]);
5466                                 mono_mb_emit_ldloc (mb, conv_arg);
5467                                 pos2 = mono_mb_emit_branch (mb, CEE_BEQ);
5468
5469                                 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5470                                         g_assert (m->orig_conv_args [argnum]);
5471
5472                                         emit_struct_free (mb, klass, m->orig_conv_args [argnum]);
5473                                 }
5474
5475                                 mono_mb_emit_ldloc (mb, conv_arg);
5476                                 mono_mb_emit_icall (mb, mono_marshal_free);
5477
5478                                 mono_mb_patch_branch (mb, pos2);
5479                         }
5480                 }
5481                 else
5482                         /* Free the original structure passed to native code */
5483                         emit_struct_free (mb, klass, conv_arg);
5484
5485                 mono_mb_patch_branch (mb, pos);
5486                 break;
5487
5488         case MARSHAL_ACTION_PUSH:
5489                 if (t->byref)
5490                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5491                 else
5492                         mono_mb_emit_ldloc (mb, conv_arg);
5493                 break;
5494
5495         case MARSHAL_ACTION_CONV_RESULT:
5496                 if (klass->delegate) {
5497                         g_assert (!t->byref);
5498                         mono_mb_emit_stloc (mb, 0);
5499                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5500                         mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5501                         mono_mb_emit_ldloc (mb, 0);
5502                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
5503                         mono_mb_emit_stloc (mb, 3);
5504                 } else {
5505                         /* set src */
5506                         mono_mb_emit_stloc (mb, 0);
5507         
5508                         /* Make a copy since emit_conv modifies local 0 */
5509                         loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5510                         mono_mb_emit_ldloc (mb, 0);
5511                         mono_mb_emit_stloc (mb, loc);
5512         
5513                         mono_mb_emit_byte (mb, CEE_LDNULL);
5514                         mono_mb_emit_stloc (mb, 3);
5515         
5516                         mono_mb_emit_ldloc (mb, 0);
5517                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5518         
5519                         /* allocate result object */
5520         
5521                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5522                         mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);   
5523                         mono_mb_emit_stloc (mb, 3);
5524                                         
5525                         /* set dst  */
5526         
5527                         mono_mb_emit_ldloc (mb, 3);
5528                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5529                         mono_mb_emit_stloc (mb, 1);
5530                                                                 
5531                         /* emit conversion code */
5532                         emit_struct_conv (mb, klass, TRUE);
5533         
5534                         emit_struct_free (mb, klass, loc);
5535         
5536                         /* Free the pointer allocated by unmanaged code */
5537                         mono_mb_emit_ldloc (mb, loc);
5538                         mono_mb_emit_icall (mb, mono_marshal_free);
5539                         mono_mb_patch_branch (mb, pos);
5540                 }
5541                 break;
5542
5543         case MARSHAL_ACTION_MANAGED_CONV_IN:
5544                 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
5545
5546                 if (klass->delegate) {
5547                         g_assert (!t->byref);
5548                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5549                         mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5550                         mono_mb_emit_ldarg (mb, argnum);
5551                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL));
5552                         mono_mb_emit_stloc (mb, conv_arg);
5553                         break;
5554                 }
5555
5556                 if (klass == mono_defaults.stringbuilder_class) {
5557                         MonoMarshalNative encoding;
5558
5559                         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5560
5561                         // FIXME:
5562                         g_assert (encoding == MONO_NATIVE_LPSTR);
5563
5564                         g_assert (!t->byref);
5565                         g_assert (encoding != -1);
5566
5567                         mono_mb_emit_ldarg (mb, argnum);
5568                         mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5569                         mono_mb_emit_stloc (mb, conv_arg);
5570                         break;
5571                 }
5572
5573                 /* The class can not have an automatic layout */
5574                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
5575                         mono_mb_emit_auto_layout_exception (mb, klass);
5576                         break;
5577                 }
5578
5579                 if (t->attrs & PARAM_ATTRIBUTE_OUT) {
5580                         mono_mb_emit_byte (mb, CEE_LDNULL);
5581                         mono_mb_emit_stloc (mb, conv_arg);
5582                         break;
5583                 }
5584
5585                 /* Set src */
5586                 mono_mb_emit_ldarg (mb, argnum);
5587                 if (t->byref) {
5588                         int pos2;
5589
5590                         /* Check for NULL and raise an exception */
5591                         pos2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
5592
5593                         mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
5594
5595                         mono_mb_patch_branch (mb, pos2);
5596                         mono_mb_emit_ldarg (mb, argnum);
5597                         mono_mb_emit_byte (mb, CEE_LDIND_I);
5598                 }                               
5599
5600                 mono_mb_emit_stloc (mb, 0);
5601
5602                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
5603                 mono_mb_emit_stloc (mb, conv_arg);
5604
5605                 mono_mb_emit_ldloc (mb, 0);
5606                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5607
5608                 /* Create and set dst */
5609                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5610                 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);   
5611                 mono_mb_emit_stloc (mb, conv_arg);
5612                 mono_mb_emit_ldloc (mb, conv_arg);
5613                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5614                 mono_mb_emit_stloc (mb, 1); 
5615
5616                 /* emit valuetype conversion code */
5617                 emit_struct_conv (mb, klass, TRUE);
5618
5619                 mono_mb_patch_branch (mb, pos);
5620                 break;
5621
5622         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5623                 if (t->byref) {
5624                         /* Check for null */
5625                         mono_mb_emit_ldloc (mb, conv_arg);
5626                         pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
5627                         mono_mb_emit_ldarg (mb, argnum);
5628                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
5629                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5630                         pos2 = mono_mb_emit_branch (mb, CEE_BR);
5631
5632                         mono_mb_patch_branch (mb, pos);                 
5633                         
5634                         /* Set src */
5635                         mono_mb_emit_ldloc (mb, conv_arg);
5636                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5637                         mono_mb_emit_stloc (mb, 0);
5638
5639                         /* Allocate and set dest */
5640                         mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5641                         mono_mb_emit_byte (mb, CEE_CONV_I);
5642                         mono_mb_emit_icall (mb, mono_marshal_alloc);
5643                         mono_mb_emit_stloc (mb, 1);
5644                         
5645                         /* Update argument pointer */
5646                         mono_mb_emit_ldarg (mb, argnum);
5647                         mono_mb_emit_ldloc (mb, 1);
5648                         mono_mb_emit_byte (mb, CEE_STIND_I);
5649                 
5650                         /* emit valuetype conversion code */
5651                         emit_struct_conv (mb, klass, FALSE);
5652
5653                         mono_mb_patch_branch (mb, pos2);
5654                 } else if (klass == mono_defaults.stringbuilder_class) {
5655                         // FIXME: What to do here ?
5656                 } else {
5657                         /* byval [Out] marshalling */
5658
5659                         /* FIXME: Handle null */
5660
5661                         /* Set src */
5662                         mono_mb_emit_ldloc (mb, conv_arg);
5663                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5664                         mono_mb_emit_stloc (mb, 0);
5665
5666                         /* Set dest */
5667                         mono_mb_emit_ldarg (mb, argnum);
5668                         mono_mb_emit_stloc (mb, 1);
5669                         
5670                         /* emit valuetype conversion code */
5671                         emit_struct_conv (mb, klass, FALSE);
5672                 }                       
5673                 break;
5674
5675         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5676                 if (klass->delegate) {
5677                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN));
5678                         mono_mb_emit_stloc (mb, 3);
5679                         break;
5680                 }
5681
5682                 /* The class can not have an automatic layout */
5683                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
5684                         mono_mb_emit_auto_layout_exception (mb, klass);
5685                         break;
5686                 }
5687
5688                 mono_mb_emit_stloc (mb, 0);
5689                 /* Check for null */
5690                 mono_mb_emit_ldloc (mb, 0);
5691                 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
5692                 mono_mb_emit_byte (mb, CEE_LDNULL);
5693                 mono_mb_emit_stloc (mb, 3);
5694                 pos2 = mono_mb_emit_branch (mb, CEE_BR);
5695
5696                 mono_mb_patch_branch (mb, pos);
5697
5698                 /* Set src */
5699                 mono_mb_emit_ldloc (mb, 0);
5700                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5701                 mono_mb_emit_stloc (mb, 0);
5702
5703                 /* Allocate and set dest */
5704                 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5705                 mono_mb_emit_byte (mb, CEE_CONV_I);
5706                 mono_mb_emit_icall (mb, mono_marshal_alloc);
5707                 mono_mb_emit_byte (mb, CEE_DUP);
5708                 mono_mb_emit_stloc (mb, 1);
5709                 mono_mb_emit_stloc (mb, 3);
5710
5711                 emit_struct_conv (mb, klass, FALSE);
5712
5713                 mono_mb_patch_branch (mb, pos2);
5714                 break;
5715
5716         default:
5717                 g_assert_not_reached ();
5718         }
5719 #endif
5720         return conv_arg;
5721 }
5722
5723 #ifndef DISABLE_JIT
5724
5725 #ifndef DISABLE_COM
5726
5727 static int
5728 emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
5729                      MonoMarshalSpec *spec, 
5730                      int conv_arg, MonoType **conv_arg_type, 
5731                      MarshalAction action)
5732 {
5733         MonoMethodBuilder *mb = m->mb;
5734         static MonoMethod *get_object_for_native_variant = NULL;
5735         static MonoMethod *get_native_variant_for_object = NULL;
5736
5737         if (!get_object_for_native_variant)
5738                 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
5739         g_assert (get_object_for_native_variant);
5740
5741         if (!get_native_variant_for_object)
5742                 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
5743         g_assert (get_native_variant_for_object);
5744
5745         switch (action) {
5746         case MARSHAL_ACTION_CONV_IN: {
5747                 conv_arg = mono_mb_add_local (mb, &mono_class_get_variant_class ()->byval_arg);
5748                 
5749                 if (t->byref)
5750                         *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
5751                 else
5752                         *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
5753
5754                 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
5755                         break;
5756
5757                 mono_mb_emit_ldarg (mb, argnum);
5758                 if (t->byref)
5759                         mono_mb_emit_byte(mb, CEE_LDIND_REF);
5760                 mono_mb_emit_ldloc_addr (mb, conv_arg);
5761                 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
5762                 break;
5763         }
5764
5765         case MARSHAL_ACTION_CONV_OUT: {
5766                 static MonoMethod *variant_clear = NULL;
5767
5768                 if (!variant_clear)
5769                         variant_clear = mono_class_get_method_from_name (mono_class_get_variant_class (), "Clear", 0);
5770                 g_assert (variant_clear);
5771
5772
5773                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
5774                         mono_mb_emit_ldarg (mb, argnum);
5775                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5776                         mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
5777                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5778                 }
5779
5780                 mono_mb_emit_ldloc_addr (mb, conv_arg);
5781                 mono_mb_emit_managed_call (mb, variant_clear, NULL);
5782                 break;
5783         }
5784
5785         case MARSHAL_ACTION_PUSH:
5786                 if (t->byref)
5787                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5788                 else
5789                         mono_mb_emit_ldloc (mb, conv_arg);
5790                 break;
5791
5792         case MARSHAL_ACTION_CONV_RESULT: {
5793                 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
5794                 mono_mb_emit_exception_marshal_directive (mb, msg);
5795                 break;
5796         }
5797
5798         case MARSHAL_ACTION_MANAGED_CONV_IN: {
5799                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5800
5801                 if (t->byref)
5802                         *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
5803                 else
5804                         *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
5805
5806                 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
5807                         break;
5808
5809                 if (t->byref)
5810                         mono_mb_emit_ldarg (mb, argnum);
5811                 else
5812                         mono_mb_emit_ldarg_addr (mb, argnum);
5813                 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
5814                 mono_mb_emit_stloc (mb, conv_arg);
5815                 break;
5816         }
5817
5818         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
5819                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
5820                         mono_mb_emit_ldloc (mb, conv_arg);
5821                         mono_mb_emit_ldarg (mb, argnum);
5822                         mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
5823                 }
5824                 break;
5825         }
5826
5827         case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
5828                 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
5829                 mono_mb_emit_exception_marshal_directive (mb, msg);
5830                 break;
5831         }
5832
5833         default:
5834                 g_assert_not_reached ();
5835         }
5836
5837         return conv_arg;
5838 }
5839
5840 #endif /* DISABLE_COM */
5841 #endif /* DISABLE_JIT */
5842
5843 static gboolean
5844 mono_pinvoke_is_unicode (MonoMethodPInvoke *piinfo)
5845 {
5846         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
5847         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
5848                 return FALSE;
5849         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
5850                 return TRUE;
5851         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
5852         default:
5853 #ifdef TARGET_WIN32
5854                 return TRUE;
5855 #else
5856                 return FALSE;
5857 #endif
5858         }
5859 }
5860
5861
5862 static int
5863 emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
5864                                         MonoMarshalSpec *spec, 
5865                                         int conv_arg, MonoType **conv_arg_type, 
5866                                         MarshalAction action)
5867 {
5868 #ifdef DISABLE_JIT
5869         switch (action) {
5870         case MARSHAL_ACTION_CONV_IN:
5871                 *conv_arg_type = &mono_defaults.object_class->byval_arg;
5872                 break;
5873         case MARSHAL_ACTION_MANAGED_CONV_IN:
5874                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5875                 break;
5876         }
5877 #else
5878         MonoMethodBuilder *mb = m->mb;
5879         MonoClass *klass = mono_class_from_mono_type (t);
5880         gboolean need_convert, need_free;
5881         MonoMarshalNative encoding;
5882
5883         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5884
5885         switch (action) {
5886         case MARSHAL_ACTION_CONV_IN:
5887                 *conv_arg_type = &mono_defaults.object_class->byval_arg;
5888                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5889
5890                 if (klass->element_class->blittable) {
5891                         mono_mb_emit_ldarg (mb, argnum);
5892                         if (t->byref)
5893                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5894                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_ARRAY_LPARRAY));
5895                         mono_mb_emit_stloc (mb, conv_arg);
5896                 } else {
5897                         MonoClass *eklass;
5898                         guint32 label1, label2, label3;
5899                         int index_var, src_var, dest_ptr, esize;
5900                         MonoMarshalConv conv;
5901                         gboolean is_string = FALSE;
5902
5903                         dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5904
5905                         eklass = klass->element_class;
5906
5907                         if (eklass == mono_defaults.string_class) {
5908                                 is_string = TRUE;
5909                                 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
5910                         }
5911                         else if (eklass == mono_defaults.stringbuilder_class) {
5912                                 is_string = TRUE;
5913                                 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
5914                         }
5915                         else
5916                                 conv = -1;
5917
5918                         if (is_string && conv == -1) {
5919                                 char *msg = g_strdup_printf ("string/stringbuilder marshalling conversion %d not implemented", encoding);
5920                                 mono_mb_emit_exception_marshal_directive (mb, msg);
5921                                 break;
5922                         }
5923
5924                         src_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5925                         mono_mb_emit_ldarg (mb, argnum);
5926                         if (t->byref)
5927                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5928                         mono_mb_emit_stloc (mb, src_var);
5929
5930                         /* Check null */
5931                         mono_mb_emit_ldloc (mb, src_var);
5932                         mono_mb_emit_stloc (mb, conv_arg);
5933                         mono_mb_emit_ldloc (mb, src_var);
5934                         label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5935
5936                         if (is_string)
5937                                 esize = sizeof (gpointer);
5938                         else if (eklass == mono_defaults.char_class) /*can't call mono_marshal_type_size since it causes all sorts of asserts*/
5939                                 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
5940                         else
5941                                 esize = mono_class_native_size (eklass, NULL);
5942
5943                         /* allocate space for the native struct and store the address */
5944                         mono_mb_emit_icon (mb, esize);
5945                         mono_mb_emit_ldloc (mb, src_var);
5946                         mono_mb_emit_byte (mb, CEE_LDLEN);
5947
5948                         if (eklass == mono_defaults.string_class) {
5949                                 /* Make the array bigger for the terminating null */
5950                                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
5951                                 mono_mb_emit_byte (mb, CEE_ADD);
5952                         }
5953                         mono_mb_emit_byte (mb, CEE_MUL);
5954                         mono_mb_emit_byte (mb, CEE_PREFIX1);
5955                         mono_mb_emit_byte (mb, CEE_LOCALLOC);
5956                         mono_mb_emit_stloc (mb, conv_arg);
5957
5958                         mono_mb_emit_ldloc (mb, conv_arg);
5959                         mono_mb_emit_stloc (mb, dest_ptr);
5960
5961                         /* Emit marshalling loop */
5962                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
5963                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
5964                         mono_mb_emit_stloc (mb, index_var);
5965                         label2 = mono_mb_get_label (mb);
5966                         mono_mb_emit_ldloc (mb, index_var);
5967                         mono_mb_emit_ldloc (mb, src_var);
5968                         mono_mb_emit_byte (mb, CEE_LDLEN);
5969                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
5970
5971                         /* Emit marshalling code */
5972
5973                         if (is_string) {
5974                                 mono_mb_emit_ldloc (mb, dest_ptr);
5975                                 mono_mb_emit_ldloc (mb, src_var);
5976                                 mono_mb_emit_ldloc (mb, index_var);
5977                                 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
5978                                 mono_mb_emit_icall (mb, conv_to_icall (conv));
5979                                 mono_mb_emit_byte (mb, CEE_STIND_I);
5980                         } else {
5981                                 /* set the src_ptr */
5982                                 mono_mb_emit_ldloc (mb, src_var);
5983                                 mono_mb_emit_ldloc (mb, index_var);
5984                                 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
5985                                 mono_mb_emit_stloc (mb, 0);
5986
5987                                 /* set dst_ptr */
5988                                 mono_mb_emit_ldloc (mb, dest_ptr);
5989                                 mono_mb_emit_stloc (mb, 1);
5990
5991                                 /* emit valuetype conversion code */
5992                                 emit_struct_conv_full (mb, eklass, FALSE, eklass == mono_defaults.char_class ? encoding : -1);
5993                         }
5994
5995                         mono_mb_emit_add_to_local (mb, index_var, 1);
5996                         mono_mb_emit_add_to_local (mb, dest_ptr, esize);
5997                         
5998                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
5999
6000                         mono_mb_patch_branch (mb, label3);
6001
6002                         if (eklass == mono_defaults.string_class) {
6003                                 /* Null terminate */
6004                                 mono_mb_emit_ldloc (mb, dest_ptr);
6005                                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6006                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
6007                         }
6008
6009                         mono_mb_patch_branch (mb, label1);
6010                 }
6011
6012                 break;
6013
6014         case MARSHAL_ACTION_CONV_OUT:
6015                 /* Unicode character arrays are implicitly marshalled as [Out] under MS.NET */
6016                 need_convert = ((klass->element_class == mono_defaults.char_class) && (encoding == MONO_NATIVE_LPWSTR)) || (klass->element_class == mono_defaults.stringbuilder_class) || (t->attrs & PARAM_ATTRIBUTE_OUT);
6017                 need_free = mono_marshal_need_free (&klass->element_class->byval_arg, 
6018                                                                                         m->piinfo, spec);
6019
6020                 if ((t->attrs & PARAM_ATTRIBUTE_OUT) && spec && spec->native == MONO_NATIVE_LPARRAY && spec->data.array_data.param_num != -1) {
6021                         int param_num = spec->data.array_data.param_num;
6022                         MonoType *param_type;
6023
6024                         param_type = m->sig->params [param_num];
6025
6026                         if (param_type->byref && param_type->type != MONO_TYPE_I4) {
6027                                 char *msg = g_strdup ("Not implemented.");
6028                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6029                                 break;
6030                         }
6031
6032                         mono_mb_emit_ldarg (mb, argnum);
6033
6034                         /* Create the managed array */
6035                         mono_mb_emit_ldarg (mb, param_num);
6036                         if (m->sig->params [param_num]->byref)
6037                                 // FIXME: Support other types
6038                                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
6039                         mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6040                         mono_mb_emit_op (mb, CEE_NEWARR, klass->element_class);
6041                         /* Store into argument */
6042                         mono_mb_emit_byte (mb, CEE_STIND_I);
6043                 }
6044
6045                 if (need_convert || need_free) {
6046                         /* FIXME: Optimize blittable case */
6047                         MonoClass *eklass;
6048                         guint32 label1, label2, label3;
6049                         int index_var, src_ptr, loc, esize;
6050
6051                         eklass = klass->element_class;
6052                         if ((eklass == mono_defaults.stringbuilder_class) || (eklass == mono_defaults.string_class))
6053                                 esize = sizeof (gpointer);
6054                         else if (eklass == mono_defaults.char_class)
6055                                 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6056                         else
6057                                 esize = mono_class_native_size (eklass, NULL);
6058                         src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6059                         loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6060
6061                         /* Check null */
6062                         mono_mb_emit_ldarg (mb, argnum);
6063                         if (t->byref)
6064                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6065                         label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6066
6067                         mono_mb_emit_ldloc (mb, conv_arg);
6068                         mono_mb_emit_stloc (mb, src_ptr);
6069
6070                         /* Emit marshalling loop */
6071                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
6072                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6073                         mono_mb_emit_stloc (mb, index_var);
6074                         label2 = mono_mb_get_label (mb);
6075                         mono_mb_emit_ldloc (mb, index_var);
6076                         mono_mb_emit_ldarg (mb, argnum);
6077                         if (t->byref)
6078                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6079                         mono_mb_emit_byte (mb, CEE_LDLEN);
6080                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
6081
6082                         /* Emit marshalling code */
6083
6084                         if (eklass == mono_defaults.stringbuilder_class) {
6085                                 gboolean need_free2;
6086                                 MonoMarshalConv conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free2);
6087
6088                                 g_assert (conv != -1);
6089
6090                                 /* dest */
6091                                 mono_mb_emit_ldarg (mb, argnum);
6092                                 if (t->byref)
6093                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6094                                 mono_mb_emit_ldloc (mb, index_var);
6095                                 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6096
6097                                 /* src */
6098                                 mono_mb_emit_ldloc (mb, src_ptr);
6099                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6100
6101                                 mono_mb_emit_icall (mb, conv_to_icall (conv));
6102
6103                                 if (need_free) {
6104                                         /* src */
6105                                         mono_mb_emit_ldloc (mb, src_ptr);
6106                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6107
6108                                         mono_mb_emit_icall (mb, mono_marshal_free);
6109                                 }
6110                         }
6111                         else if (eklass == mono_defaults.string_class) {
6112                                 if (need_free) {
6113                                         /* src */
6114                                         mono_mb_emit_ldloc (mb, src_ptr);
6115                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6116
6117                                         mono_mb_emit_icall (mb, mono_marshal_free);
6118                                 }
6119                         }
6120                         else {
6121                                 if (need_convert) {
6122                                         /* set the src_ptr */
6123                                         mono_mb_emit_ldloc (mb, src_ptr);
6124                                         mono_mb_emit_stloc (mb, 0);
6125
6126                                         /* set dst_ptr */
6127                                         mono_mb_emit_ldarg (mb, argnum);
6128                                         if (t->byref)
6129                                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6130                                         mono_mb_emit_ldloc (mb, index_var);
6131                                         mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6132                                         mono_mb_emit_stloc (mb, 1);
6133
6134                                         /* emit valuetype conversion code */
6135                                         emit_struct_conv_full (mb, eklass, TRUE, eklass == mono_defaults.char_class ? encoding : -1);
6136                                 }
6137
6138                                 if (need_free) {
6139                                         mono_mb_emit_ldloc (mb, src_ptr);
6140                                         mono_mb_emit_stloc (mb, loc);
6141                                         mono_mb_emit_ldloc (mb, loc);
6142
6143                                         emit_struct_free (mb, eklass, loc);
6144                                 }
6145                         }
6146
6147                         mono_mb_emit_add_to_local (mb, index_var, 1);
6148                         mono_mb_emit_add_to_local (mb, src_ptr, esize);
6149
6150                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
6151
6152                         mono_mb_patch_branch (mb, label1);
6153                         mono_mb_patch_branch (mb, label3);
6154                 }
6155                 
6156                 if (klass->element_class->blittable) {
6157                         /* free memory allocated (if any) by MONO_MARSHAL_CONV_ARRAY_LPARRAY */
6158
6159                         mono_mb_emit_ldarg (mb, argnum);
6160                         if (t->byref)
6161                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6162                         mono_mb_emit_ldloc (mb, conv_arg);
6163                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_FREE_LPARRAY));
6164                 }
6165
6166                 break;
6167
6168         case MARSHAL_ACTION_PUSH:
6169                 if (t->byref)
6170                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6171                 else
6172                         mono_mb_emit_ldloc (mb, conv_arg);
6173                 break;
6174
6175         case MARSHAL_ACTION_CONV_RESULT:
6176                 /* fixme: we need conversions here */
6177                 mono_mb_emit_stloc (mb, 3);
6178                 break;
6179
6180         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6181                 MonoClass *eklass;
6182                 guint32 label1, label2, label3;
6183                 int index_var, src_ptr, esize, param_num, num_elem;
6184                 MonoMarshalConv conv;
6185                 gboolean is_string = FALSE;
6186                 
6187                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6188                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6189
6190                 if (t->byref) {
6191                         char *msg = g_strdup ("Byref array marshalling to managed code is not implemented.");
6192                         mono_mb_emit_exception_marshal_directive (mb, msg);
6193                         return conv_arg;
6194                 }
6195                 if (!spec) {
6196                         char *msg = g_strdup ("[MarshalAs] attribute required to marshal arrays to managed code.");
6197                         mono_mb_emit_exception_marshal_directive (mb, msg);
6198                         return conv_arg;
6199                 }                       
6200                 if (spec->native != MONO_NATIVE_LPARRAY) {
6201                         char *msg = g_strdup ("Non LPArray marshalling of arrays to managed code is not implemented.");
6202                         mono_mb_emit_exception_marshal_directive (mb, msg);
6203                         return conv_arg;                        
6204                 }
6205
6206                 /* FIXME: t is from the method which is wrapped, not the delegate type */
6207                 /* g_assert (t->attrs & PARAM_ATTRIBUTE_IN); */
6208
6209                 param_num = spec->data.array_data.param_num;
6210                 num_elem = spec->data.array_data.num_elem;
6211                 if (spec->data.array_data.elem_mult == 0)
6212                         /* param_num is not specified */
6213                         param_num = -1;
6214
6215                 if (param_num == -1) {
6216                         if (num_elem <= 0) {
6217                                 char *msg = g_strdup ("Either SizeConst or SizeParamIndex should be specified when marshalling arrays to managed code.");
6218                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6219                                 return conv_arg;
6220                         }
6221                 }
6222
6223                 /* FIXME: Optimize blittable case */
6224
6225                 eklass = klass->element_class;
6226                 if (eklass == mono_defaults.string_class) {
6227                         is_string = TRUE;
6228                         conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
6229                 }
6230                 else if (eklass == mono_defaults.stringbuilder_class) {
6231                         is_string = TRUE;
6232                         conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
6233                 }
6234                 else
6235                         conv = -1;
6236
6237                 mono_marshal_load_type_info (eklass);
6238
6239                 if (is_string)
6240                         esize = sizeof (gpointer);
6241                 else
6242                         esize = mono_class_native_size (eklass, NULL);
6243                 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6244
6245                 mono_mb_emit_byte (mb, CEE_LDNULL);
6246                 mono_mb_emit_stloc (mb, conv_arg);
6247
6248                 /* Check param index */
6249                 if (param_num != -1) {
6250                         if (param_num >= m->sig->param_count) {
6251                                 char *msg = g_strdup ("Array size control parameter index is out of range.");
6252                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6253                                 return conv_arg;
6254                         }
6255                         switch (m->sig->params [param_num]->type) {
6256                         case MONO_TYPE_I1:
6257                         case MONO_TYPE_U1:
6258                         case MONO_TYPE_I2:
6259                         case MONO_TYPE_U2:
6260                         case MONO_TYPE_I4:
6261                         case MONO_TYPE_U4:
6262                         case MONO_TYPE_I:
6263                         case MONO_TYPE_U:
6264                         case MONO_TYPE_I8:
6265                         case MONO_TYPE_U8:
6266                                 break;
6267                         default: {
6268                                 char *msg = g_strdup ("Array size control parameter must be an integral type.");
6269                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6270                                 return conv_arg;
6271                         }
6272                         }
6273                 }
6274
6275                 /* Check null */
6276                 mono_mb_emit_ldarg (mb, argnum);
6277                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6278
6279                 mono_mb_emit_ldarg (mb, argnum);
6280                 mono_mb_emit_stloc (mb, src_ptr);
6281
6282                 /* Create managed array */
6283                 /* 
6284                  * The LPArray marshalling spec says that sometimes param_num starts 
6285                  * from 1, sometimes it starts from 0. But MS seems to allways start
6286                  * from 0.
6287                  */
6288
6289                 if (param_num == -1) {
6290                         mono_mb_emit_icon (mb, num_elem);
6291                 } else {
6292                         mono_mb_emit_ldarg (mb, param_num);
6293                         if (num_elem > 0) {
6294                                 mono_mb_emit_icon (mb, num_elem);
6295                                 mono_mb_emit_byte (mb, CEE_ADD);
6296                         }
6297                         mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6298                 }
6299
6300                 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
6301                 mono_mb_emit_stloc (mb, conv_arg);
6302
6303                 if (eklass->blittable) {
6304                         mono_mb_emit_ldloc (mb, conv_arg);
6305                         mono_mb_emit_byte (mb, CEE_CONV_I);
6306                         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6307                         mono_mb_emit_byte (mb, CEE_ADD);
6308                         mono_mb_emit_ldarg (mb, argnum);
6309                         mono_mb_emit_ldloc (mb, conv_arg);
6310                         mono_mb_emit_byte (mb, CEE_LDLEN);
6311                         mono_mb_emit_icon (mb, esize);
6312                         mono_mb_emit_byte (mb, CEE_MUL);
6313                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6314                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
6315                         break;
6316                 }
6317
6318                 /* Emit marshalling loop */
6319                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6320                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6321                 mono_mb_emit_stloc (mb, index_var);
6322                 label2 = mono_mb_get_label (mb);
6323                 mono_mb_emit_ldloc (mb, index_var);
6324                 mono_mb_emit_ldloc (mb, conv_arg);
6325                 mono_mb_emit_byte (mb, CEE_LDLEN);
6326                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6327
6328                 /* Emit marshalling code */
6329                 if (is_string) {
6330                         g_assert (conv != -1);
6331
6332                         mono_mb_emit_ldloc (mb, conv_arg);
6333                         mono_mb_emit_ldloc (mb, index_var);
6334
6335                         mono_mb_emit_ldloc (mb, src_ptr);
6336                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6337
6338                         mono_mb_emit_icall (mb, conv_to_icall (conv));
6339                         mono_mb_emit_byte (mb, CEE_STELEM_REF);
6340                 }
6341                 else {
6342                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6343                         mono_mb_emit_exception_marshal_directive (mb, msg);
6344                         return conv_arg;
6345                 }
6346
6347                 mono_mb_emit_add_to_local (mb, index_var, 1);
6348                 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6349
6350                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6351
6352                 mono_mb_patch_branch (mb, label1);
6353                 mono_mb_patch_branch (mb, label3);
6354                 
6355                 break;
6356         }
6357         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6358                 MonoClass *eklass;
6359                 guint32 label1, label2, label3;
6360                 int index_var, dest_ptr, esize, param_num, num_elem;
6361                 MonoMarshalConv conv;
6362                 gboolean is_string = FALSE;
6363
6364                 if (!spec)
6365                         /* Already handled in CONV_IN */
6366                         break;
6367                 
6368                 /* These are already checked in CONV_IN */
6369                 g_assert (!t->byref);
6370                 g_assert (spec->native == MONO_NATIVE_LPARRAY);
6371                 g_assert (t->attrs & PARAM_ATTRIBUTE_OUT);
6372
6373                 param_num = spec->data.array_data.param_num;
6374                 num_elem = spec->data.array_data.num_elem;
6375
6376                 if (spec->data.array_data.elem_mult == 0)
6377                         /* param_num is not specified */
6378                         param_num = -1;
6379
6380                 if (param_num == -1) {
6381                         if (num_elem <= 0) {
6382                                 g_assert_not_reached ();
6383                         }
6384                 }
6385
6386                 /* FIXME: Optimize blittable case */
6387
6388                 eklass = klass->element_class;
6389                 if (eklass == mono_defaults.string_class) {
6390                         is_string = TRUE;
6391                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6392                 }
6393                 else if (eklass == mono_defaults.stringbuilder_class) {
6394                         is_string = TRUE;
6395                         conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6396                 }
6397                 else
6398                         conv = -1;
6399
6400                 mono_marshal_load_type_info (eklass);
6401
6402                 if (is_string)
6403                         esize = sizeof (gpointer);
6404                 else
6405                         esize = mono_class_native_size (eklass, NULL);
6406
6407                 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6408
6409                 /* Check null */
6410                 mono_mb_emit_ldloc (mb, conv_arg);
6411                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6412
6413                 mono_mb_emit_ldarg (mb, argnum);
6414                 mono_mb_emit_stloc (mb, dest_ptr);
6415
6416                 if (eklass->blittable) {
6417                         /* dest */
6418                         mono_mb_emit_ldarg (mb, argnum);
6419                         /* src */
6420                         mono_mb_emit_ldloc (mb, conv_arg);
6421                         mono_mb_emit_byte (mb, CEE_CONV_I);
6422                         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6423                         mono_mb_emit_byte (mb, CEE_ADD);
6424                         /* length */
6425                         mono_mb_emit_ldloc (mb, conv_arg);
6426                         mono_mb_emit_byte (mb, CEE_LDLEN);
6427                         mono_mb_emit_icon (mb, esize);
6428                         mono_mb_emit_byte (mb, CEE_MUL);
6429                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6430                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
6431                         break;
6432                 }
6433
6434                 /* Emit marshalling loop */
6435                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6436                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6437                 mono_mb_emit_stloc (mb, index_var);
6438                 label2 = mono_mb_get_label (mb);
6439                 mono_mb_emit_ldloc (mb, index_var);
6440                 mono_mb_emit_ldloc (mb, conv_arg);
6441                 mono_mb_emit_byte (mb, CEE_LDLEN);
6442                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6443
6444                 /* Emit marshalling code */
6445                 if (is_string) {
6446                         g_assert (conv != -1);
6447
6448                         /* dest */
6449                         mono_mb_emit_ldloc (mb, dest_ptr);
6450
6451                         /* src */
6452                         mono_mb_emit_ldloc (mb, conv_arg);
6453                         mono_mb_emit_ldloc (mb, index_var);
6454
6455                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6456
6457                         mono_mb_emit_icall (mb, conv_to_icall (conv));
6458                         mono_mb_emit_byte (mb, CEE_STIND_I);
6459                 }
6460                 else {
6461                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6462                         mono_mb_emit_exception_marshal_directive (mb, msg);
6463                         return conv_arg;
6464                 }
6465
6466                 mono_mb_emit_add_to_local (mb, index_var, 1);
6467                 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6468
6469                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6470
6471                 mono_mb_patch_branch (mb, label1);
6472                 mono_mb_patch_branch (mb, label3);
6473
6474                 break;
6475         }
6476         case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6477                 MonoClass *eklass;
6478                 guint32 label1, label2, label3;
6479                 int index_var, src, dest, esize;
6480                 MonoMarshalConv conv = -1;
6481                 gboolean is_string = FALSE;
6482                 
6483                 g_assert (!t->byref);
6484
6485                 eklass = klass->element_class;
6486
6487                 mono_marshal_load_type_info (eklass);
6488
6489                 if (eklass == mono_defaults.string_class) {
6490                         is_string = TRUE;
6491                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6492                 }
6493                 else {
6494                         g_assert_not_reached ();
6495                 }
6496
6497                 if (is_string)
6498                         esize = sizeof (gpointer);
6499                 else if (eklass == mono_defaults.char_class)
6500                         esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6501                 else
6502                         esize = mono_class_native_size (eklass, NULL);
6503
6504                 src = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6505                 dest = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6506                         
6507                 mono_mb_emit_stloc (mb, src);
6508                 mono_mb_emit_ldloc (mb, src);
6509                 mono_mb_emit_stloc (mb, 3);
6510
6511                 /* Check for null */
6512                 mono_mb_emit_ldloc (mb, src);
6513                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6514
6515                 /* Allocate native array */
6516                 mono_mb_emit_icon (mb, esize);
6517                 mono_mb_emit_ldloc (mb, src);
6518                 mono_mb_emit_byte (mb, CEE_LDLEN);
6519
6520                 if (eklass == mono_defaults.string_class) {
6521                         /* Make the array bigger for the terminating null */
6522                         mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6523                         mono_mb_emit_byte (mb, CEE_ADD);
6524                 }
6525                 mono_mb_emit_byte (mb, CEE_MUL);
6526                 mono_mb_emit_icall (mb, mono_marshal_alloc);
6527                 mono_mb_emit_stloc (mb, dest);
6528                 mono_mb_emit_ldloc (mb, dest);
6529                 mono_mb_emit_stloc (mb, 3);
6530
6531                 /* Emit marshalling loop */
6532                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6533                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6534                 mono_mb_emit_stloc (mb, index_var);
6535                 label2 = mono_mb_get_label (mb);
6536                 mono_mb_emit_ldloc (mb, index_var);
6537                 mono_mb_emit_ldloc (mb, src);
6538                 mono_mb_emit_byte (mb, CEE_LDLEN);
6539                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6540
6541                 /* Emit marshalling code */
6542                 if (is_string) {
6543                         g_assert (conv != -1);
6544
6545                         /* dest */
6546                         mono_mb_emit_ldloc (mb, dest);
6547
6548                         /* src */
6549                         mono_mb_emit_ldloc (mb, src);
6550                         mono_mb_emit_ldloc (mb, index_var);
6551
6552                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6553
6554                         mono_mb_emit_icall (mb, conv_to_icall (conv));
6555                         mono_mb_emit_byte (mb, CEE_STIND_I);
6556                 }
6557                 else {
6558                         char *msg = g_strdup ("Marshalling of non-string arrays to managed code is not implemented.");
6559                         mono_mb_emit_exception_marshal_directive (mb, msg);
6560                         return conv_arg;
6561                 }
6562
6563                 mono_mb_emit_add_to_local (mb, index_var, 1);
6564                 mono_mb_emit_add_to_local (mb, dest, esize);
6565
6566                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6567
6568                 mono_mb_patch_branch (mb, label3);
6569                 mono_mb_patch_branch (mb, label1);
6570                 break;
6571         }
6572         default:
6573                 g_assert_not_reached ();
6574         }
6575 #endif
6576         return conv_arg;
6577 }
6578
6579 static MonoType*
6580 marshal_boolean_conv_in_get_local_type (MonoMarshalSpec *spec, guint8 *ldc_op /*out*/)
6581 {
6582         if (spec == NULL) {
6583                 return &mono_defaults.int32_class->byval_arg;
6584         } else {
6585                 switch (spec->native) {
6586                 case MONO_NATIVE_I1:
6587                 case MONO_NATIVE_U1:
6588                         return &mono_defaults.byte_class->byval_arg;
6589                 case MONO_NATIVE_VARIANTBOOL:
6590                         if (ldc_op) *ldc_op = CEE_LDC_I4_M1;
6591                         return &mono_defaults.int16_class->byval_arg;
6592                 case MONO_NATIVE_BOOLEAN:
6593                         return &mono_defaults.int32_class->byval_arg;
6594                 default:
6595                         g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
6596                         return &mono_defaults.int32_class->byval_arg;
6597                 }
6598         }
6599 }
6600
6601 static MonoClass*
6602 marshal_boolean_managed_conv_in_get_conv_arg_class (MonoMarshalSpec *spec, guint8 *ldop/*out*/)
6603 {
6604         MonoClass* conv_arg_class = mono_defaults.int32_class;
6605         if (spec) {
6606                 switch (spec->native) {
6607                 case MONO_NATIVE_I1:
6608                 case MONO_NATIVE_U1:
6609                         conv_arg_class = mono_defaults.byte_class;
6610                         if (ldop) *ldop = CEE_LDIND_I1;
6611                         break;
6612                 case MONO_NATIVE_VARIANTBOOL:
6613                         conv_arg_class = mono_defaults.int16_class;
6614                         if (ldop) *ldop = CEE_LDIND_I2;
6615                         break;
6616                 case MONO_NATIVE_BOOLEAN:
6617                         break;
6618                 default:
6619                         g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
6620                 }
6621         }
6622         return conv_arg_class;
6623 }
6624
6625 static int
6626 emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
6627                       MonoMarshalSpec *spec, 
6628                       int conv_arg, MonoType **conv_arg_type, 
6629                       MarshalAction action)
6630 {
6631 #ifdef DISABLE_JIT
6632         switch (action) {
6633         case MARSHAL_ACTION_CONV_IN:
6634                 if (t->byref)
6635                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
6636                 else
6637                         *conv_arg_type = marshal_boolean_conv_in_get_local_type (spec, NULL);
6638                 break;
6639
6640         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6641                 MonoClass* conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, NULL);
6642                 if (t->byref)
6643                         *conv_arg_type = &conv_arg_class->this_arg;
6644                 else
6645                         *conv_arg_type = &conv_arg_class->byval_arg;
6646                 break;
6647         }
6648
6649         }
6650 #else
6651         MonoMethodBuilder *mb = m->mb;
6652
6653         switch (action) {
6654         case MARSHAL_ACTION_CONV_IN: {
6655                 MonoType *local_type;
6656                 int label_false;
6657                 guint8 ldc_op = CEE_LDC_I4_1;
6658
6659                 local_type = marshal_boolean_conv_in_get_local_type (spec, &ldc_op);
6660                 if (t->byref)
6661                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
6662                 else
6663                         *conv_arg_type = local_type;
6664                 conv_arg = mono_mb_add_local (mb, local_type);
6665                 
6666                 mono_mb_emit_ldarg (mb, argnum);
6667                 if (t->byref)
6668                         mono_mb_emit_byte (mb, CEE_LDIND_I1);
6669                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
6670                 mono_mb_emit_byte (mb, ldc_op);
6671                 mono_mb_emit_stloc (mb, conv_arg);
6672                 mono_mb_patch_branch (mb, label_false);
6673
6674                 break;
6675         }
6676
6677         case MARSHAL_ACTION_CONV_OUT:
6678         {
6679                 int label_false, label_end;
6680                 if (!t->byref)
6681                         break;
6682
6683                 mono_mb_emit_ldarg (mb, argnum);
6684                 mono_mb_emit_ldloc (mb, conv_arg);
6685                 
6686                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
6687                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6688
6689                 label_end = mono_mb_emit_branch (mb, CEE_BR);
6690                 mono_mb_patch_branch (mb, label_false);
6691                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6692                 mono_mb_patch_branch (mb, label_end);
6693
6694                 mono_mb_emit_byte (mb, CEE_STIND_I1);
6695                 break;
6696         }
6697
6698         case MARSHAL_ACTION_PUSH:
6699                 if (t->byref)
6700                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6701                 else if (conv_arg)
6702                         mono_mb_emit_ldloc (mb, conv_arg);
6703                 else
6704                         mono_mb_emit_ldarg (mb, argnum);
6705                 break;
6706
6707         case MARSHAL_ACTION_CONV_RESULT:
6708                 /* maybe we need to make sure that it fits within 8 bits */
6709                 mono_mb_emit_stloc (mb, 3);
6710                 break;
6711
6712         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6713                 MonoClass* conv_arg_class = mono_defaults.int32_class;
6714                 guint8 ldop = CEE_LDIND_I4;
6715                 int label_null, label_false;
6716
6717                 conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, &ldop);
6718                 conv_arg = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
6719
6720                 if (t->byref)
6721                         *conv_arg_type = &conv_arg_class->this_arg;
6722                 else
6723                         *conv_arg_type = &conv_arg_class->byval_arg;
6724
6725
6726                 mono_mb_emit_ldarg (mb, argnum);
6727                 
6728                 /* Check null */
6729                 if (t->byref) {
6730                         label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
6731                         mono_mb_emit_ldarg (mb, argnum);
6732                         mono_mb_emit_byte (mb, ldop);
6733                 } else
6734                         label_null = 0;
6735
6736                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
6737                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6738                 mono_mb_emit_stloc (mb, conv_arg);
6739                 mono_mb_patch_branch (mb, label_false);
6740
6741                 if (t->byref) 
6742                         mono_mb_patch_branch (mb, label_null);
6743                 break;
6744         }
6745
6746         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6747                 guint8 stop = CEE_STIND_I4;
6748                 guint8 ldc_op = CEE_LDC_I4_1;
6749                 int label_null,label_false, label_end;;
6750
6751                 if (!t->byref)
6752                         break;
6753                 if (spec) {
6754                         switch (spec->native) {
6755                         case MONO_NATIVE_I1:
6756                         case MONO_NATIVE_U1:
6757                                 stop = CEE_STIND_I1;
6758                                 break;
6759                         case MONO_NATIVE_VARIANTBOOL:
6760                                 stop = CEE_STIND_I2;
6761                                 ldc_op = CEE_LDC_I4_M1;
6762                                 break;
6763                         default:
6764                                 break;
6765                         }
6766                 }
6767                 
6768                 /* Check null */
6769                 mono_mb_emit_ldarg (mb, argnum);
6770                 label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
6771
6772                 mono_mb_emit_ldarg (mb, argnum);
6773                 mono_mb_emit_ldloc (mb, conv_arg);
6774
6775                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
6776                 mono_mb_emit_byte (mb, ldc_op);
6777                 label_end = mono_mb_emit_branch (mb, CEE_BR);
6778
6779                 mono_mb_patch_branch (mb, label_false);
6780                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6781                 mono_mb_patch_branch (mb, label_end);
6782
6783                 mono_mb_emit_byte (mb, stop);
6784                 mono_mb_patch_branch (mb, label_null);
6785                 break;
6786         }
6787
6788         default:
6789                 g_assert_not_reached ();
6790         }
6791 #endif
6792         return conv_arg;
6793 }
6794
6795 static int
6796 emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t, 
6797                   MonoMarshalSpec *spec, int conv_arg, 
6798                   MonoType **conv_arg_type, MarshalAction action)
6799 {
6800 #ifndef DISABLE_JIT
6801         MonoMethodBuilder *mb = m->mb;
6802
6803         switch (action) {
6804         case MARSHAL_ACTION_CONV_IN:
6805                 /* MS seems to allow this in some cases, ie. bxc #158 */
6806                 /*
6807                 if (MONO_TYPE_ISSTRUCT (t->data.type) && !mono_class_from_mono_type (t->data.type)->blittable) {
6808                         char *msg = g_strdup_printf ("Can not marshal 'parameter #%d': Pointers can not reference marshaled structures. Use byref instead.", argnum + 1);
6809                         mono_mb_emit_exception_marshal_directive (m->mb, msg);
6810                 }
6811                 */
6812                 break;
6813
6814         case MARSHAL_ACTION_PUSH:
6815                 mono_mb_emit_ldarg (mb, argnum);
6816                 break;
6817
6818         case MARSHAL_ACTION_CONV_RESULT:
6819                 /* no conversions necessary */
6820                 mono_mb_emit_stloc (mb, 3);
6821                 break;
6822
6823         default:
6824                 break;
6825         }
6826 #endif
6827         return conv_arg;
6828 }
6829
6830 static int
6831 emit_marshal_char (EmitMarshalContext *m, int argnum, MonoType *t, 
6832                    MonoMarshalSpec *spec, int conv_arg, 
6833                    MonoType **conv_arg_type, MarshalAction action)
6834 {
6835 #ifndef DISABLE_JIT
6836         MonoMethodBuilder *mb = m->mb;
6837
6838         switch (action) {
6839         case MARSHAL_ACTION_PUSH:
6840                 /* fixme: dont know how to marshal that. We cant simply
6841                  * convert it to a one byte UTF8 character, because an
6842                  * unicode character may need more that one byte in UTF8 */
6843                 mono_mb_emit_ldarg (mb, argnum);
6844                 break;
6845
6846         case MARSHAL_ACTION_CONV_RESULT:
6847                 /* fixme: we need conversions here */
6848                 mono_mb_emit_stloc (mb, 3);
6849                 break;
6850
6851         default:
6852                 break;
6853         }
6854 #endif
6855         return conv_arg;
6856 }
6857
6858 static int
6859 emit_marshal_scalar (EmitMarshalContext *m, int argnum, MonoType *t, 
6860                      MonoMarshalSpec *spec, int conv_arg, 
6861                      MonoType **conv_arg_type, MarshalAction action)
6862 {
6863 #ifndef DISABLE_JIT
6864         MonoMethodBuilder *mb = m->mb;
6865
6866         switch (action) {
6867         case MARSHAL_ACTION_PUSH:
6868                 mono_mb_emit_ldarg (mb, argnum);
6869                 break;
6870
6871         case MARSHAL_ACTION_CONV_RESULT:
6872                 /* no conversions necessary */
6873                 mono_mb_emit_stloc (mb, 3);
6874                 break;
6875
6876         default:
6877                 break;
6878         }
6879 #endif
6880         return conv_arg;
6881 }
6882
6883 static int
6884 emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t, 
6885               MonoMarshalSpec *spec, int conv_arg, 
6886               MonoType **conv_arg_type, MarshalAction action)
6887 {
6888         /* Ensure that we have marshalling info for this param */
6889         mono_marshal_load_type_info (mono_class_from_mono_type (t));
6890
6891         if (spec && spec->native == MONO_NATIVE_CUSTOM)
6892                 return emit_marshal_custom (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6893
6894         if (spec && spec->native == MONO_NATIVE_ASANY)
6895                 return emit_marshal_asany (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6896                         
6897         switch (t->type) {
6898         case MONO_TYPE_VALUETYPE:
6899                 if (t->data.klass == mono_defaults.handleref_class)
6900                         return emit_marshal_handleref (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6901                 
6902                 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6903         case MONO_TYPE_STRING:
6904                 return emit_marshal_string (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6905         case MONO_TYPE_CLASS:
6906         case MONO_TYPE_OBJECT:
6907 #ifndef DISABLE_COM
6908                 if (spec && spec->native == MONO_NATIVE_STRUCT)
6909                         return emit_marshal_variant (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6910
6911                 if (spec && (spec->native == MONO_NATIVE_IUNKNOWN ||
6912                         spec->native == MONO_NATIVE_IDISPATCH ||
6913                         spec->native == MONO_NATIVE_INTERFACE))
6914                         return mono_cominterop_emit_marshal_com_interface (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6915                 if (spec && (spec->native == MONO_NATIVE_SAFEARRAY) && 
6916                         (spec->data.safearray_data.elem_type == MONO_VARIANT_VARIANT) && 
6917                         ((action == MARSHAL_ACTION_CONV_OUT) || (action == MARSHAL_ACTION_CONV_IN) || (action == MARSHAL_ACTION_PUSH)))
6918                         return mono_cominterop_emit_marshal_safearray (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6919 #endif
6920
6921                 if (mono_defaults.safehandle_class != NULL && t->data.klass &&
6922                     mono_class_is_subclass_of (t->data.klass,  mono_defaults.safehandle_class, FALSE))
6923                         return emit_marshal_safehandle (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6924                 
6925                 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6926         case MONO_TYPE_ARRAY:
6927         case MONO_TYPE_SZARRAY:
6928                 return emit_marshal_array (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6929         case MONO_TYPE_BOOLEAN:
6930                 return emit_marshal_boolean (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6931         case MONO_TYPE_PTR:
6932                 return emit_marshal_ptr (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6933         case MONO_TYPE_CHAR:
6934                 return emit_marshal_char (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6935         case MONO_TYPE_I1:
6936         case MONO_TYPE_U1:
6937         case MONO_TYPE_I2:
6938         case MONO_TYPE_U2:
6939         case MONO_TYPE_I4:
6940         case MONO_TYPE_U4:
6941         case MONO_TYPE_I:
6942         case MONO_TYPE_U:
6943         case MONO_TYPE_R4:
6944         case MONO_TYPE_R8:
6945         case MONO_TYPE_I8:
6946         case MONO_TYPE_U8:
6947         case MONO_TYPE_FNPTR:
6948                 return emit_marshal_scalar (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6949         case MONO_TYPE_GENERICINST:
6950                 if (mono_type_generic_inst_is_valuetype (t))
6951                         return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6952                 else
6953                         return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6954         default:
6955                 return conv_arg;
6956         }
6957 }
6958
6959 #ifndef DISABLE_JIT
6960 /**
6961  * mono_marshal_emit_native_wrapper:
6962  * @image: the image to use for looking up custom marshallers
6963  * @sig: The signature of the native function
6964  * @piinfo: Marshalling information
6965  * @mspecs: Marshalling information
6966  * @aot: whenever the created method will be compiled by the AOT compiler
6967  * @method: if non-NULL, the pinvoke method to call
6968  * @check_exceptions: Whenever to check for pending exceptions after the native call
6969  * @func_param: the function to call is passed as a boxed IntPtr as the first parameter
6970  *
6971  * generates IL code for the pinvoke wrapper, the generated code calls @func.
6972  */
6973 void
6974 mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoMethodSignature *sig, MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func, gboolean aot, gboolean check_exceptions, gboolean func_param)
6975 {
6976         EmitMarshalContext m;
6977         MonoMethodSignature *csig;
6978         MonoClass *klass;
6979         int i, argnum, *tmp_locals;
6980         int type, param_shift = 0;
6981         static MonoMethodSignature *get_last_error_sig = NULL;
6982 #ifdef USE_COOP_GC
6983         int coop_gc_var;
6984 #endif
6985
6986         memset (&m, 0, sizeof (m));
6987         m.mb = mb;
6988         m.sig = sig;
6989         m.piinfo = piinfo;
6990
6991         /* we copy the signature, so that we can set pinvoke to 0 */
6992         if (func_param) {
6993                 /* The function address is passed as the first argument */
6994                 g_assert (!sig->hasthis);
6995                 param_shift += 1;
6996         }
6997         csig = mono_metadata_signature_dup_full (mb->method->klass->image, sig);
6998         csig->pinvoke = 1;
6999         m.csig = csig;
7000         m.image = image;
7001
7002         if (sig->hasthis)
7003                 param_shift += 1;
7004
7005         /* we allocate local for use with emit_struct_conv() */
7006         /* allocate local 0 (pointer) src_ptr */
7007         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7008         /* allocate local 1 (pointer) dst_ptr */
7009         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7010         /* allocate local 2 (boolean) delete_old */
7011         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7012
7013         /* delete_old = FALSE */
7014         mono_mb_emit_icon (mb, 0);
7015         mono_mb_emit_stloc (mb, 2);
7016
7017         if (!MONO_TYPE_IS_VOID(sig->ret)) {
7018                 /* allocate local 3 to store the return value */
7019                 mono_mb_add_local (mb, sig->ret);
7020         }
7021
7022 #ifdef USE_COOP_GC
7023         /* local 4, the local to be used when calling the suspend funcs */
7024         coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7025 #endif
7026
7027         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7028                 /* Return type custom marshaling */
7029                 /*
7030                  * Since we can't determine the return type of the unmanaged function,
7031                  * we assume it returns a pointer, and pass that pointer to
7032                  * MarshalNativeToManaged.
7033                  */
7034                 csig->ret = &mono_defaults.int_class->byval_arg;
7035         }
7036
7037         /* we first do all conversions */
7038         tmp_locals = alloca (sizeof (int) * sig->param_count);
7039         m.orig_conv_args = alloca (sizeof (int) * (sig->param_count + 1));
7040
7041         for (i = 0; i < sig->param_count; i ++) {
7042                 tmp_locals [i] = emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_CONV_IN);
7043         }
7044
7045         /* push all arguments */
7046
7047         if (sig->hasthis)
7048                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7049
7050         for (i = 0; i < sig->param_count; i++) {
7051                 emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
7052         }                       
7053
7054 #ifdef USE_COOP_GC
7055         mono_mb_emit_icall (mb, mono_threads_prepare_blocking);
7056         mono_mb_emit_stloc (mb, coop_gc_var);
7057 #endif
7058
7059         /* call the native method */
7060         if (func_param) {
7061                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7062                 mono_mb_emit_op (mb, CEE_UNBOX, mono_defaults.int_class);
7063                 mono_mb_emit_byte (mb, CEE_LDIND_I);
7064                 mono_mb_emit_calli (mb, csig);
7065         } else if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
7066 #ifndef DISABLE_COM
7067                 mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
7068 #else
7069                 g_assert_not_reached ();
7070 #endif
7071         }
7072         else {
7073                 if (aot) {
7074                         /* Reuse the ICALL_ADDR opcode for pinvokes too */
7075                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7076                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7077                         mono_mb_emit_calli (mb, csig);
7078                 } else {                        
7079                         mono_mb_emit_native_call (mb, csig, func);
7080                 }
7081         }
7082
7083         /* Set LastError if needed */
7084         if (piinfo->piflags & PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR) {
7085                 if (!get_last_error_sig) {
7086                         get_last_error_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
7087                         get_last_error_sig->ret = &mono_defaults.int_class->byval_arg;
7088                         get_last_error_sig->pinvoke = 1;
7089                 }
7090
7091 #ifdef TARGET_WIN32
7092                 /* 
7093                  * Have to call GetLastError () early and without a wrapper, since various runtime components could
7094                  * clobber its value.
7095                  */
7096                 mono_mb_emit_native_call (mb, get_last_error_sig, GetLastError);
7097                 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7098 #else
7099                 mono_mb_emit_icall (mb, mono_marshal_set_last_error);
7100 #endif
7101         }               
7102
7103 #ifdef USE_COOP_GC
7104         mono_mb_emit_ldloc (mb, coop_gc_var);
7105         mono_mb_emit_icall (mb, mono_threads_finish_blocking);
7106 #endif
7107
7108         /* convert the result */
7109         if (!sig->ret->byref) {
7110                 MonoMarshalSpec *spec = mspecs [0];
7111                 type = sig->ret->type;
7112
7113                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7114                         emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7115                 } else {
7116
7117                 handle_enum:
7118                         switch (type) {
7119                         case MONO_TYPE_VOID:
7120                                 break;
7121                         case MONO_TYPE_VALUETYPE:
7122                                 klass = sig->ret->data.klass;
7123                                 if (klass->enumtype) {
7124                                         type = mono_class_enum_basetype (sig->ret->data.klass)->type;
7125                                         goto handle_enum;
7126                                 }
7127                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7128                                 break;
7129                         case MONO_TYPE_I1:
7130                         case MONO_TYPE_U1:
7131                         case MONO_TYPE_I2:
7132                         case MONO_TYPE_U2:
7133                         case MONO_TYPE_I4:
7134                         case MONO_TYPE_U4:
7135                         case MONO_TYPE_I:
7136                         case MONO_TYPE_U:
7137                         case MONO_TYPE_R4:
7138                         case MONO_TYPE_R8:
7139                         case MONO_TYPE_I8:
7140                         case MONO_TYPE_U8:
7141                         case MONO_TYPE_FNPTR:
7142                         case MONO_TYPE_STRING:
7143                         case MONO_TYPE_CLASS:
7144                         case MONO_TYPE_OBJECT:
7145                         case MONO_TYPE_BOOLEAN:
7146                         case MONO_TYPE_ARRAY:
7147                         case MONO_TYPE_SZARRAY:
7148                         case MONO_TYPE_CHAR:
7149                         case MONO_TYPE_PTR:
7150                         case MONO_TYPE_GENERICINST:
7151                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7152                                 break;
7153                         case MONO_TYPE_TYPEDBYREF:
7154                         default:
7155                                 g_warning ("return type 0x%02x unknown", sig->ret->type);       
7156                                 g_assert_not_reached ();
7157                         }
7158                 }
7159         } else {
7160                 mono_mb_emit_stloc (mb, 3);
7161         }
7162
7163         /* 
7164          * Need to call this after converting the result since MONO_VTADDR needs 
7165          * to be adjacent to the call instruction.
7166          */
7167         if (check_exceptions)
7168                 emit_thread_interrupt_checkpoint (mb);
7169
7170         /* we need to convert byref arguments back and free string arrays */
7171         for (i = 0; i < sig->param_count; i++) {
7172                 MonoType *t = sig->params [i];
7173                 MonoMarshalSpec *spec = mspecs [i + 1];
7174
7175                 argnum = i + param_shift;
7176
7177                 if (spec && ((spec->native == MONO_NATIVE_CUSTOM) || (spec->native == MONO_NATIVE_ASANY))) {
7178                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7179                         continue;
7180                 }
7181
7182                 switch (t->type) {
7183                 case MONO_TYPE_STRING:
7184                 case MONO_TYPE_VALUETYPE:
7185                 case MONO_TYPE_CLASS:
7186                 case MONO_TYPE_OBJECT:
7187                 case MONO_TYPE_SZARRAY:
7188                 case MONO_TYPE_BOOLEAN:
7189                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7190                         break;
7191                 default:
7192                         break;
7193                 }
7194         }
7195
7196         if (!MONO_TYPE_IS_VOID(sig->ret))
7197                 mono_mb_emit_ldloc (mb, 3);
7198
7199         mono_mb_emit_byte (mb, CEE_RET);
7200 }
7201 #endif /* DISABLE_JIT */
7202
7203 /**
7204  * mono_marshal_get_native_wrapper:
7205  * @method: The MonoMethod to wrap.
7206  * @check_exceptions: Whenever to check for pending exceptions
7207  *
7208  * generates IL code for the pinvoke wrapper (the generated method
7209  * calls the unmanaged code in piinfo->addr)
7210  * The wrapper info for the wrapper is a WrapperInfo structure.
7211  */
7212 MonoMethod *
7213 mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
7214 {
7215         MonoMethodSignature *sig, *csig;
7216         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7217         MonoMethodBuilder *mb;
7218         MonoMarshalSpec **mspecs;
7219         MonoMethod *res;
7220         GHashTable *cache;
7221         gboolean pinvoke = FALSE;
7222         gpointer iter;
7223         int i;
7224         const char *exc_class = "MissingMethodException";
7225         const char *exc_arg = NULL;
7226         WrapperInfo *info;
7227
7228         g_assert (method != NULL);
7229         g_assert (mono_method_signature (method)->pinvoke);
7230
7231         GHashTable **cache_ptr;
7232
7233         if (aot) {
7234                 if (check_exceptions)
7235                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_check_cache;
7236                 else
7237                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_cache;
7238         } else {
7239                 if (check_exceptions)
7240                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_check_cache;
7241                 else
7242                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_cache;
7243         }
7244
7245         cache = get_cache (cache_ptr, mono_aligned_addr_hash, NULL);
7246
7247         if ((res = mono_marshal_find_in_cache (cache, method)))
7248                 return res;
7249
7250         if (MONO_CLASS_IS_IMPORT (method->klass)) {
7251                 /* The COM code is not AOT compatible, it calls mono_custom_attrs_get_attr_checked () */
7252                 if (aot)
7253                         return method;
7254 #ifndef DISABLE_COM
7255                 return mono_cominterop_get_native_wrapper (method);
7256 #else
7257                 g_assert_not_reached ();
7258 #endif
7259         }
7260
7261         sig = mono_method_signature (method);
7262
7263         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
7264             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7265                 pinvoke = TRUE;
7266
7267         if (!piinfo->addr) {
7268                 if (pinvoke) {
7269                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
7270                                 exc_arg = "Method contains unsupported native code";
7271                         else if (!aot)
7272                                 mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7273                 } else {
7274                         piinfo->addr = mono_lookup_internal_call (method);
7275                 }
7276         }
7277
7278         /* hack - redirect certain string constructors to CreateString */
7279         if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
7280                 g_assert (!pinvoke);
7281                 g_assert (method->string_ctor);
7282                 g_assert (sig->hasthis);
7283
7284                 /* CreateString returns a value */
7285                 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7286                 csig->ret = &mono_defaults.string_class->byval_arg;
7287                 csig->pinvoke = 0;
7288
7289                 iter = NULL;
7290                 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
7291                         if (!strcmp ("CreateString", res->name) &&
7292                                 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
7293                                 WrapperInfo *info;
7294
7295                                 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
7296                                 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
7297
7298                                 /* create a wrapper to preserve .ctor in stack trace */
7299                                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
7300
7301 #ifndef DISABLE_JIT
7302                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7303                                 for (i = 1; i <= csig->param_count; i++)
7304                                         mono_mb_emit_ldarg (mb, i);
7305                                 mono_mb_emit_managed_call (mb, res, NULL);
7306                                 mono_mb_emit_byte (mb, CEE_RET);
7307 #endif
7308
7309                                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRING_CTOR);
7310                                 info->d.string_ctor.method = method;
7311
7312                                 /* use native_wrapper_cache because internal calls are looked up there */
7313                                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7314                                                                                                          csig->param_count + 1, info, NULL);
7315                                 mono_mb_free (mb);
7316
7317                                 return res;
7318                         }
7319                 }
7320
7321                 /* exception will be thrown */
7322                 piinfo->addr = NULL;
7323                 g_warning ("cannot find CreateString for .ctor");
7324         }
7325
7326         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7327
7328         mb->method->save_lmf = 1;
7329
7330         /*
7331          * In AOT mode and embedding scenarios, it is possible that the icall is not
7332          * registered in the runtime doing the AOT compilation.
7333          */
7334         if (!piinfo->addr && !aot) {
7335 #ifndef DISABLE_JIT
7336                 mono_mb_emit_exception (mb, exc_class, exc_arg);
7337 #endif
7338                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7339                 info->d.managed_to_native.method = method;
7340
7341                 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7342                 csig->pinvoke = 0;
7343                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7344                                                                                          csig->param_count + 16, info, NULL);
7345                 mono_mb_free (mb);
7346
7347                 return res;
7348         }
7349
7350         /* internal calls: we simply push all arguments and call the method (no conversions) */
7351         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
7352                 if (sig->hasthis)
7353                         csig = mono_metadata_signature_dup_add_this (method->klass->image, sig, method->klass);
7354                 else
7355                         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7356
7357                 /* hack - string constructors returns a value */
7358                 if (method->string_ctor)
7359                         csig->ret = &mono_defaults.string_class->byval_arg;
7360
7361 #ifndef DISABLE_JIT
7362                 if (sig->hasthis) {
7363                         int pos;
7364
7365                         /*
7366                          * Add a null check since public icalls can be called with 'call' which
7367                          * does no such check.
7368                          */
7369                         mono_mb_emit_byte (mb, CEE_LDARG_0);                    
7370                         pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
7371                         mono_mb_emit_exception (mb, "NullReferenceException", NULL);
7372                         mono_mb_patch_branch (mb, pos);
7373
7374                         mono_mb_emit_byte (mb, CEE_LDARG_0);
7375                 }
7376
7377                 for (i = 0; i < sig->param_count; i++)
7378                         mono_mb_emit_ldarg (mb, i + sig->hasthis);
7379
7380                 if (aot) {
7381                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7382                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7383                         mono_mb_emit_calli (mb, csig);
7384                 } else {
7385                         g_assert (piinfo->addr);
7386                         mono_mb_emit_native_call (mb, csig, piinfo->addr);
7387                 }
7388                 if (check_exceptions)
7389                         emit_thread_interrupt_checkpoint (mb);
7390                 mono_mb_emit_byte (mb, CEE_RET);
7391 #endif
7392                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7393                 info->d.managed_to_native.method = method;
7394
7395                 csig = mono_metadata_signature_dup_full (method->klass->image, csig);
7396                 csig->pinvoke = 0;
7397                 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7398                                                                                          info, NULL);
7399
7400                 mono_mb_free (mb);
7401                 return res;
7402         }
7403
7404         g_assert (pinvoke);
7405         if (!aot)
7406                 g_assert (piinfo->addr);
7407
7408 #ifndef DISABLE_JIT
7409         mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
7410         mono_method_get_marshal_info (method, mspecs);
7411
7412         mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr, aot, check_exceptions, FALSE);
7413 #endif
7414         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PINVOKE);
7415         info->d.managed_to_native.method = method;
7416
7417         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7418         csig->pinvoke = 0;
7419         res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7420                                                                                  info, NULL);
7421         mono_mb_free (mb);
7422
7423 #ifndef DISABLE_JIT
7424         for (i = sig->param_count; i >= 0; i--)
7425                 if (mspecs [i])
7426                         mono_metadata_free_marshal_spec (mspecs [i]);
7427         g_free (mspecs);
7428 #endif
7429
7430         /* mono_method_print_code (res); */
7431
7432         return res;
7433 }
7434
7435 /**
7436  * mono_marshal_get_native_func_wrapper:
7437  * @image: The image to use for memory allocation and for looking up custom marshallers.
7438  * @sig: The signature of the function
7439  * @func: The native function to wrap
7440  *
7441  *   Returns a wrapper method around native functions, similar to the pinvoke
7442  * wrapper.
7443  */
7444 MonoMethod *
7445 mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig, 
7446                                                                           MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
7447 {
7448         MonoMethodSignature *csig;
7449
7450         SignaturePointerPair key, *new_key;
7451         MonoMethodBuilder *mb;
7452         MonoMethod *res;
7453         GHashTable *cache;
7454         gboolean found;
7455         char *name;
7456
7457         key.sig = sig;
7458         key.pointer = func;
7459
7460         // Generic types are not safe to place in MonoImage caches.
7461         g_assert (!sig->is_inflated);
7462
7463         cache = get_cache (&image->native_func_wrapper_cache, signature_pointer_pair_hash, signature_pointer_pair_equal);
7464         if ((res = mono_marshal_find_in_cache (cache, &key)))
7465                 return res;
7466
7467         name = g_strdup_printf ("wrapper_native_%p", func);
7468         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7469         mb->method->save_lmf = 1;
7470
7471 #ifndef DISABLE_JIT
7472         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE, FALSE);
7473 #endif
7474
7475         csig = mono_metadata_signature_dup_full (image, sig);
7476         csig->pinvoke = 0;
7477
7478         new_key = g_new (SignaturePointerPair,1);
7479         new_key->sig = csig;
7480         new_key->pointer = func;
7481
7482         res = mono_mb_create_and_cache_full (cache, new_key, mb, csig, csig->param_count + 16, NULL, &found);
7483         if (found)
7484                 g_free (new_key);
7485
7486         mono_mb_free (mb);
7487
7488         mono_marshal_set_wrapper_info (res, NULL);
7489
7490         return res;
7491 }
7492
7493 /*
7494  * The wrapper receives the native function as a boxed IntPtr as its 'this' argument. This is easier to support in
7495  * AOT.
7496  */
7497 MonoMethod*
7498 mono_marshal_get_native_func_wrapper_aot (MonoClass *klass)
7499 {
7500         MonoMethodSignature *sig, *csig;
7501         MonoMethodBuilder *mb;
7502         MonoMethod *res;
7503         GHashTable *cache;
7504         char *name;
7505         WrapperInfo *info;
7506         MonoMethodPInvoke mpiinfo;
7507         MonoMethodPInvoke *piinfo = &mpiinfo;
7508         MonoMarshalSpec **mspecs;
7509         MonoMethod *invoke = mono_get_delegate_invoke (klass);
7510         MonoImage *image = invoke->klass->image;
7511         int i;
7512
7513         // FIXME: include UnmanagedFunctionPointerAttribute info
7514
7515         /*
7516          * The wrapper is associated with the delegate type, to pick up the marshalling info etc.
7517          */
7518         cache = get_cache (&mono_method_get_wrapper_cache (invoke)->native_func_wrapper_aot_cache, mono_aligned_addr_hash, NULL);
7519
7520         if ((res = mono_marshal_find_in_cache (cache, invoke)))
7521                 return res;
7522
7523         memset (&mpiinfo, 0, sizeof (mpiinfo));
7524         parse_unmanaged_function_pointer_attr (klass, &mpiinfo);
7525
7526         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
7527         mono_method_get_marshal_info (invoke, mspecs);
7528         /* Freed below so don't alloc from mempool */
7529         sig = mono_metadata_signature_dup (mono_method_signature (invoke));
7530         sig->hasthis = 0;
7531
7532         name = g_strdup_printf ("wrapper_aot_native");
7533         mb = mono_mb_new (invoke->klass, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7534         mb->method->save_lmf = 1;
7535
7536 #ifndef DISABLE_JIT
7537         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, NULL, FALSE, TRUE, TRUE);
7538 #endif
7539
7540         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NATIVE_FUNC_AOT);
7541         info->d.managed_to_native.method = invoke;
7542
7543         g_assert (!sig->hasthis);
7544         csig = mono_metadata_signature_dup_add_this (image, sig, mono_defaults.object_class);
7545         csig->pinvoke = 0;
7546         res = mono_mb_create_and_cache_full (cache, invoke,
7547                                                                                  mb, csig, csig->param_count + 16,
7548                                                                                  info, NULL);
7549         mono_mb_free (mb);
7550
7551         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
7552                 if (mspecs [i])
7553                         mono_metadata_free_marshal_spec (mspecs [i]);
7554         g_free (mspecs);
7555         g_free (sig);
7556
7557         return res;
7558 }
7559
7560 /*
7561  * mono_marshal_emit_managed_wrapper:
7562  *
7563  *   Emit the body of a native-to-managed wrapper. INVOKE_SIG is the signature of
7564  * the delegate which wraps the managed method to be called. For closed delegates,
7565  * it could have fewer parameters than the method it wraps.
7566  * THIS_LOC is the memory location where the target of the delegate is stored.
7567  */
7568 void
7569 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, uint32_t target_handle)
7570 {
7571 #ifdef DISABLE_JIT
7572         MonoMethodSignature *sig, *csig;
7573         int i;
7574
7575         sig = m->sig;
7576         csig = m->csig;
7577
7578         /* we first do all conversions */
7579         for (i = 0; i < sig->param_count; i ++) {
7580                 MonoType *t = sig->params [i];
7581
7582                 switch (t->type) {
7583                 case MONO_TYPE_OBJECT:
7584                 case MONO_TYPE_CLASS:
7585                 case MONO_TYPE_VALUETYPE:
7586                 case MONO_TYPE_ARRAY:
7587                 case MONO_TYPE_SZARRAY:
7588                 case MONO_TYPE_STRING:
7589                 case MONO_TYPE_BOOLEAN:
7590                         emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
7591                 }
7592         }
7593
7594         if (!sig->ret->byref) {
7595                 switch (sig->ret->type) {
7596                 case MONO_TYPE_STRING:
7597                         csig->ret = &mono_defaults.int_class->byval_arg;
7598                         break;
7599                 default:
7600                         break;
7601                 }
7602         }
7603 #else
7604         MonoMethodSignature *sig, *csig;
7605         int i, *tmp_locals;
7606         gboolean closed = FALSE;
7607 #ifdef USE_COOP_GC
7608         int coop_gc_var;
7609 #endif
7610
7611         sig = m->sig;
7612         csig = m->csig;
7613
7614         /* allocate local 0 (pointer) src_ptr */
7615         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7616         /* allocate local 1 (pointer) dst_ptr */
7617         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7618         /* allocate local 2 (boolean) delete_old */
7619         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7620
7621         if (!sig->hasthis && sig->param_count != invoke_sig->param_count) {
7622                 /* Closed delegate */
7623                 g_assert (sig->param_count == invoke_sig->param_count + 1);
7624                 closed = TRUE;
7625                 /* Use a new signature without the first argument */
7626                 sig = mono_metadata_signature_dup (sig);
7627                 memmove (&sig->params [0], &sig->params [1], (sig->param_count - 1) * sizeof (MonoType*));
7628                 sig->param_count --;
7629         }
7630
7631         if (!MONO_TYPE_IS_VOID(sig->ret)) {
7632                 /* allocate local 3 to store the return value */
7633                 mono_mb_add_local (mb, sig->ret);
7634         }
7635 #ifdef USE_COOP_GC
7636         /* local 4, the local to be used when calling the reset_blocking funcs */
7637         /* tons of code hardcode 3 to be the return var */
7638         coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7639 #endif
7640
7641         mono_mb_emit_icon (mb, 0);
7642         mono_mb_emit_stloc (mb, 2);
7643
7644         /*
7645          * Might need to attach the thread to the JIT or change the
7646          * domain for the callback.
7647          */
7648         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7649         mono_mb_emit_byte (mb, CEE_MONO_JIT_ATTACH);
7650
7651 #ifdef USE_COOP_GC
7652         /* XXX can we merge reset_blocking_start with JIT_ATTACH above and save one call? */
7653         mono_mb_emit_icall (mb, mono_threads_reset_blocking_start);
7654         mono_mb_emit_stloc (mb, coop_gc_var);
7655 #endif
7656
7657         /* we first do all conversions */
7658         tmp_locals = alloca (sizeof (int) * sig->param_count);
7659         for (i = 0; i < sig->param_count; i ++) {
7660                 MonoType *t = sig->params [i];
7661
7662                 switch (t->type) {
7663                 case MONO_TYPE_OBJECT:
7664                 case MONO_TYPE_CLASS:
7665                 case MONO_TYPE_VALUETYPE:
7666                 case MONO_TYPE_ARRAY:
7667                 case MONO_TYPE_SZARRAY:
7668                 case MONO_TYPE_STRING:
7669                 case MONO_TYPE_BOOLEAN:
7670                         tmp_locals [i] = emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
7671
7672                         break;
7673                 default:
7674                         tmp_locals [i] = 0;
7675                         break;
7676                 }
7677         }
7678
7679         emit_thread_interrupt_checkpoint (mb);
7680
7681         if (sig->hasthis) {
7682                 if (target_handle) {
7683                         mono_mb_emit_icon (mb, (gint32)target_handle);
7684                         mono_mb_emit_icall (mb, mono_gchandle_get_target);
7685                 } else {
7686                         /* fixme: */
7687                         g_assert_not_reached ();
7688                 }
7689         } else if (closed) {
7690                 mono_mb_emit_icon (mb, (gint32)target_handle);
7691                 mono_mb_emit_icall (mb, mono_gchandle_get_target);
7692         }
7693
7694         for (i = 0; i < sig->param_count; i++) {
7695                 MonoType *t = sig->params [i];
7696
7697                 if (tmp_locals [i]) {
7698                         if (t->byref)
7699                                 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
7700                         else
7701                                 mono_mb_emit_ldloc (mb, tmp_locals [i]);
7702                 }
7703                 else
7704                         mono_mb_emit_ldarg (mb, i);
7705         }
7706
7707         mono_mb_emit_managed_call (mb, method, NULL);
7708
7709         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7710                 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7711         } else if (!sig->ret->byref) { 
7712                 switch (sig->ret->type) {
7713                 case MONO_TYPE_VOID:
7714                         break;
7715                 case MONO_TYPE_BOOLEAN:
7716                 case MONO_TYPE_I1:
7717                 case MONO_TYPE_U1:
7718                 case MONO_TYPE_CHAR:
7719                 case MONO_TYPE_I2:
7720                 case MONO_TYPE_U2:
7721                 case MONO_TYPE_I4:
7722                 case MONO_TYPE_U4:
7723                 case MONO_TYPE_I:
7724                 case MONO_TYPE_U:
7725                 case MONO_TYPE_PTR:
7726                 case MONO_TYPE_R4:
7727                 case MONO_TYPE_R8:
7728                 case MONO_TYPE_I8:
7729                 case MONO_TYPE_U8:
7730                 case MONO_TYPE_OBJECT:
7731                         mono_mb_emit_stloc (mb, 3);
7732                         break;
7733                 case MONO_TYPE_STRING:
7734                         csig->ret = &mono_defaults.int_class->byval_arg;
7735                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7736                         break;
7737                 case MONO_TYPE_VALUETYPE:
7738                 case MONO_TYPE_CLASS:
7739                 case MONO_TYPE_SZARRAY:
7740                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7741                         break;
7742                 default:
7743                         g_warning ("return type 0x%02x unknown", sig->ret->type);       
7744                         g_assert_not_reached ();
7745                 }
7746         } else {
7747                 mono_mb_emit_stloc (mb, 3);
7748         }
7749
7750         /* Convert byref arguments back */
7751         for (i = 0; i < sig->param_count; i ++) {
7752                 MonoType *t = sig->params [i];
7753                 MonoMarshalSpec *spec = mspecs [i + 1];
7754
7755                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7756                         emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7757                 }
7758                 else if (t->byref) {
7759                         switch (t->type) {
7760                         case MONO_TYPE_CLASS:
7761                         case MONO_TYPE_VALUETYPE:
7762                         case MONO_TYPE_OBJECT:
7763                         case MONO_TYPE_STRING:
7764                         case MONO_TYPE_BOOLEAN:
7765                                 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7766                                 break;
7767                         default:
7768                                 break;
7769                         }
7770                 }
7771                 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
7772                         /* The [Out] information is encoded in the delegate signature */
7773                         switch (t->type) {
7774                         case MONO_TYPE_SZARRAY:
7775                         case MONO_TYPE_CLASS:
7776                         case MONO_TYPE_VALUETYPE:
7777                                 emit_marshal (m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7778                                 break;
7779                         default:
7780                                 g_assert_not_reached ();
7781                         }
7782                 }
7783         }
7784
7785 #ifdef USE_COOP_GC
7786         /* XXX merge reset_blocking_end with detach */
7787         mono_mb_emit_ldloc (mb, coop_gc_var);
7788         mono_mb_emit_icall (mb, mono_threads_reset_blocking_end);
7789 #endif
7790
7791         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7792         mono_mb_emit_byte (mb, CEE_MONO_JIT_DETACH);
7793
7794         if (m->retobj_var) {
7795                 mono_mb_emit_ldloc (mb, m->retobj_var);
7796                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7797                 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m->retobj_class);
7798         }
7799         else {
7800                 if (!MONO_TYPE_IS_VOID(sig->ret))
7801                         mono_mb_emit_ldloc (mb, 3);
7802                 mono_mb_emit_byte (mb, CEE_RET);
7803         }
7804
7805         if (closed)
7806                 g_free (sig);
7807 #endif
7808 }
7809
7810 static void 
7811 mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *csig)
7812 {
7813         MonoMethodSignature *sig;
7814         int i;
7815
7816 #ifdef TARGET_WIN32
7817         /* 
7818          * Under windows, delegates passed to native code must use the STDCALL
7819          * calling convention.
7820          */
7821         csig->call_convention = MONO_CALL_STDCALL;
7822 #endif
7823
7824         sig = mono_method_signature (method);
7825
7826         /* Change default calling convention if needed */
7827         /* Why is this a modopt ? */
7828         if (sig->ret && sig->ret->num_mods) {
7829                 for (i = 0; i < sig->ret->num_mods; ++i) {
7830                         MonoError error;
7831                         MonoClass *cmod_class = mono_class_get_checked (method->klass->image, sig->ret->modifiers [i].token, &error);
7832                         g_assert (mono_error_ok (&error));
7833                         if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
7834                                 if (!strcmp (cmod_class->name, "CallConvCdecl"))
7835                                         csig->call_convention = MONO_CALL_C;
7836                                 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
7837                                         csig->call_convention = MONO_CALL_STDCALL;
7838                                 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
7839                                         csig->call_convention = MONO_CALL_FASTCALL;
7840                                 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
7841                                         csig->call_convention = MONO_CALL_THISCALL;
7842                         }
7843                 }
7844         }
7845 }
7846
7847 /*
7848  * generates IL code to call managed methods from unmanaged code 
7849  * If target_handle==0, the wrapper info will be a WrapperInfo structure.
7850  */
7851 MonoMethod *
7852 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle)
7853 {
7854         static MonoClass *UnmanagedFunctionPointerAttribute;
7855         MonoMethodSignature *sig, *csig, *invoke_sig;
7856         MonoMethodBuilder *mb;
7857         MonoMethod *res, *invoke;
7858         MonoMarshalSpec **mspecs;
7859         MonoMethodPInvoke piinfo;
7860         GHashTable *cache;
7861         int i;
7862         EmitMarshalContext m;
7863
7864         g_assert (method != NULL);
7865         g_assert (!mono_method_signature (method)->pinvoke);
7866
7867         /* 
7868          * FIXME: Should cache the method+delegate type pair, since the same method
7869          * could be called with different delegates, thus different marshalling
7870          * options.
7871          */
7872         cache = get_cache (&mono_method_get_wrapper_cache (method)->managed_wrapper_cache, mono_aligned_addr_hash, NULL);
7873
7874         if (!target_handle && (res = mono_marshal_find_in_cache (cache, method)))
7875                 return res;
7876
7877         invoke = mono_get_delegate_invoke (delegate_klass);
7878         invoke_sig = mono_method_signature (invoke);
7879
7880         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
7881         mono_method_get_marshal_info (invoke, mspecs);
7882
7883         sig = mono_method_signature (method);
7884
7885         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
7886
7887         /*the target gchandle must be the first entry after size and the wrapper itself.*/
7888         mono_mb_add_data (mb, GUINT_TO_POINTER (target_handle));
7889
7890         /* we copy the signature, so that we can modify it */
7891         if (target_handle)
7892                 /* Need to free this later */
7893                 csig = mono_metadata_signature_dup (invoke_sig);
7894         else
7895                 csig = mono_metadata_signature_dup_full (method->klass->image, invoke_sig);
7896         csig->hasthis = 0;
7897         csig->pinvoke = 1;
7898
7899         memset (&m, 0, sizeof (m));
7900         m.mb = mb;
7901         m.sig = sig;
7902         m.piinfo = NULL;
7903         m.retobj_var = 0;
7904         m.csig = csig;
7905         m.image = method->klass->image;
7906
7907         mono_marshal_set_callconv_from_modopt (invoke, csig);
7908
7909         /* Handle the UnmanagedFunctionPointerAttribute */
7910         if (!UnmanagedFunctionPointerAttribute)
7911                 UnmanagedFunctionPointerAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
7912
7913         /* The attribute is only available in Net 2.0 */
7914         if (UnmanagedFunctionPointerAttribute) {
7915                 MonoCustomAttrInfo *cinfo;
7916                 MonoCustomAttrEntry *attr;
7917
7918                 /* 
7919                  * The pinvoke attributes are stored in a real custom attribute. Obtain the
7920                  * contents of the attribute without constructing it, as that might not be
7921                  * possible when running in cross-compiling mode.
7922                  */
7923                 cinfo = mono_custom_attrs_from_class (delegate_klass);
7924                 attr = NULL;
7925                 if (cinfo) {
7926                         for (i = 0; i < cinfo->num_attrs; ++i) {
7927                                 MonoClass *ctor_class = cinfo->attrs [i].ctor->klass;
7928                                 if (mono_class_has_parent (ctor_class, UnmanagedFunctionPointerAttribute)) {
7929                                         attr = &cinfo->attrs [i];
7930                                         break;
7931                                 }
7932                         }
7933                 }
7934                 if (attr) {
7935                         MonoArray *typed_args, *named_args;
7936                         CattrNamedArg *arginfo;
7937                         MonoObject *o;
7938                         gint32 call_conv;
7939                         gint32 charset = 0;
7940                         MonoBoolean set_last_error = 0;
7941                         MonoError error;
7942
7943                         mono_reflection_create_custom_attr_data_args (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7944                         g_assert (mono_error_ok (&error));
7945                         g_assert (mono_array_length (typed_args) == 1);
7946
7947                         /* typed args */
7948                         o = mono_array_get (typed_args, MonoObject*, 0);
7949                         call_conv = *(gint32*)mono_object_unbox (o);
7950
7951                         /* named args */
7952                         for (i = 0; i < mono_array_length (named_args); ++i) {
7953                                 CattrNamedArg *narg = &arginfo [i];
7954
7955                                 o = mono_array_get (named_args, MonoObject*, i);
7956
7957                                 g_assert (narg->field);
7958                                 if (!strcmp (narg->field->name, "CharSet")) {
7959                                         charset = *(gint32*)mono_object_unbox (o);
7960                                 } else if (!strcmp (narg->field->name, "SetLastError")) {
7961                                         set_last_error = *(MonoBoolean*)mono_object_unbox (o);
7962                                 } else if (!strcmp (narg->field->name, "BestFitMapping")) {
7963                                         // best_fit_mapping = *(MonoBoolean*)mono_object_unbox (o);
7964                                 } else if (!strcmp (narg->field->name, "ThrowOnUnmappableChar")) {
7965                                         // throw_on_unmappable = *(MonoBoolean*)mono_object_unbox (o);
7966                                 } else {
7967                                         g_assert_not_reached ();
7968                                 }
7969                         }
7970
7971                         g_free (arginfo);
7972
7973                         memset (&piinfo, 0, sizeof (piinfo));
7974                         m.piinfo = &piinfo;
7975                         piinfo.piflags = (call_conv << 8) | (charset ? (charset - 1) * 2 : 1) | set_last_error;
7976
7977                         csig->call_convention = call_conv - 1;
7978                 }
7979
7980                 if (cinfo && !cinfo->cached)
7981                         mono_custom_attrs_free (cinfo);
7982         }
7983
7984         mono_marshal_emit_managed_wrapper (mb, invoke_sig, mspecs, &m, method, target_handle);
7985
7986         if (!target_handle) {
7987                 WrapperInfo *info;
7988
7989                 // FIXME: Associate it with the method+delegate_klass pair
7990                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7991                 info->d.native_to_managed.method = method;
7992                 info->d.native_to_managed.klass = delegate_klass;
7993
7994                 res = mono_mb_create_and_cache_full (cache, method,
7995                                                                                          mb, csig, sig->param_count + 16,
7996                                                                                          info, NULL);
7997         } else {
7998 #ifndef DISABLE_JIT
7999                 mb->dynamic = TRUE;
8000 #endif
8001                 res = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
8002         }
8003         mono_mb_free (mb);
8004
8005         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8006                 if (mspecs [i])
8007                         mono_metadata_free_marshal_spec (mspecs [i]);
8008         g_free (mspecs);
8009
8010         /* mono_method_print_code (res); */
8011
8012         return res;
8013 }
8014
8015 gpointer
8016 mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
8017 {
8018         MonoMethod *method;
8019         MonoMethodSignature *sig;
8020         MonoMethodBuilder *mb;
8021         int i, param_count;
8022
8023         g_assert (token);
8024
8025         method = mono_get_method (image, token, NULL);
8026         g_assert (method);
8027
8028         if (type & (VTFIXUP_TYPE_FROM_UNMANAGED | VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN)) {
8029                 MonoMethodSignature *csig;
8030                 MonoMarshalSpec **mspecs;
8031                 EmitMarshalContext m;
8032
8033                 sig = mono_method_signature (method);
8034                 g_assert (!sig->hasthis);
8035
8036                 mspecs = g_new0 (MonoMarshalSpec*, sig->param_count + 1);
8037                 mono_method_get_marshal_info (method, mspecs);
8038
8039                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8040                 csig = mono_metadata_signature_dup_full (image, sig);
8041                 csig->hasthis = 0;
8042                 csig->pinvoke = 1;
8043
8044                 memset (&m, 0, sizeof (m));
8045                 m.mb = mb;
8046                 m.sig = sig;
8047                 m.piinfo = NULL;
8048                 m.retobj_var = 0;
8049                 m.csig = csig;
8050                 m.image = image;
8051
8052                 mono_marshal_set_callconv_from_modopt (method, csig);
8053
8054                 /* FIXME: Implement VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN. */
8055
8056                 mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, 0);
8057
8058 #ifndef DISABLE_JIT
8059                 mb->dynamic = TRUE;
8060 #endif
8061                 method = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
8062                 mono_mb_free (mb);
8063
8064                 for (i = sig->param_count; i >= 0; i--)
8065                         if (mspecs [i])
8066                                 mono_metadata_free_marshal_spec (mspecs [i]);
8067                 g_free (mspecs);
8068
8069                 return mono_compile_method (method);
8070         }
8071
8072         sig = mono_method_signature (method);
8073         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
8074
8075         param_count = sig->param_count + sig->hasthis;
8076 #ifndef DISABLE_JIT
8077         for (i = 0; i < param_count; i++)
8078                 mono_mb_emit_ldarg (mb, i);
8079
8080         if (type & VTFIXUP_TYPE_CALL_MOST_DERIVED)
8081                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
8082         else
8083                 mono_mb_emit_op (mb, CEE_CALL, method);
8084         mono_mb_emit_byte (mb, CEE_RET);
8085
8086         mb->dynamic = TRUE;
8087 #endif
8088
8089         method = mono_mb_create (mb, sig, param_count, NULL);
8090         mono_mb_free (mb);
8091
8092         return mono_compile_method (method);
8093 }
8094
8095 #ifndef DISABLE_JIT
8096
8097 /*
8098  * The code directly following this is the cache hit, value positive branch
8099  *
8100  * This function takes a new method builder with 0 locals and adds two locals
8101  * to create multiple out-branches and the fall through state of having the object
8102  * on the stack after a cache miss
8103  */
8104 static void
8105 generate_check_cache (int obj_arg_position, int class_arg_position, int cache_arg_position, // In-parameters
8106                                                                                         int *null_obj, int *cache_hit_neg, int *cache_hit_pos, // Out-parameters
8107                                                                                         MonoMethodBuilder *mb)
8108 {
8109         int cache_miss_pos;
8110
8111         /* allocate local 0 (pointer) obj_vtable */
8112         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8113         /* allocate local 1 (pointer) cached_vtable */
8114         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8115
8116         /*if (!obj)*/
8117         mono_mb_emit_ldarg (mb, obj_arg_position);
8118         *null_obj = mono_mb_emit_branch (mb, CEE_BRFALSE);
8119
8120         /*obj_vtable = obj->vtable;*/
8121         mono_mb_emit_ldarg (mb, obj_arg_position);
8122         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
8123         mono_mb_emit_byte (mb, CEE_LDIND_I);
8124         mono_mb_emit_stloc (mb, 0);
8125
8126         /* cached_vtable = *cache*/
8127         mono_mb_emit_ldarg (mb, cache_arg_position);
8128         mono_mb_emit_byte (mb, CEE_LDIND_I);
8129         mono_mb_emit_stloc (mb, 1);
8130
8131         mono_mb_emit_ldloc (mb, 1);
8132         mono_mb_emit_byte (mb, CEE_LDC_I4);
8133         mono_mb_emit_i4 (mb, ~0x1);
8134         mono_mb_emit_byte (mb, CEE_CONV_I);
8135         mono_mb_emit_byte (mb, CEE_AND);
8136         mono_mb_emit_ldloc (mb, 0);
8137         /*if ((cached_vtable & ~0x1)== obj_vtable)*/
8138         cache_miss_pos = mono_mb_emit_branch (mb, CEE_BNE_UN);
8139
8140         /*return (cached_vtable & 0x1) ? NULL : obj;*/
8141         mono_mb_emit_ldloc (mb, 1);
8142         mono_mb_emit_byte(mb, CEE_LDC_I4_1);
8143         mono_mb_emit_byte (mb, CEE_CONV_U);
8144         mono_mb_emit_byte (mb, CEE_AND);
8145         *cache_hit_neg = mono_mb_emit_branch (mb, CEE_BRTRUE);
8146         *cache_hit_pos = mono_mb_emit_branch (mb, CEE_BR);
8147
8148         // slow path
8149         mono_mb_patch_branch (mb, cache_miss_pos);
8150
8151         // if isinst
8152         mono_mb_emit_ldarg (mb, obj_arg_position);
8153         mono_mb_emit_ldarg (mb, class_arg_position);
8154         mono_mb_emit_ldarg (mb, cache_arg_position);
8155         mono_mb_emit_icall (mb, mono_marshal_isinst_with_cache);
8156 }
8157
8158 #endif /* DISABLE_JIT */
8159
8160 /*
8161  * This does the equivalent of mono_object_castclass_with_cache.
8162  * The wrapper info for the wrapper is a WrapperInfo structure.
8163  */
8164 MonoMethod *
8165 mono_marshal_get_castclass_with_cache (void)
8166 {
8167         static MonoMethod *cached;
8168         MonoMethod *res;
8169         MonoMethodBuilder *mb;
8170         MonoMethodSignature *sig;
8171         int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos, invalid_cast_pos;
8172         WrapperInfo *info;
8173
8174         const int obj_arg_position = 0;
8175         const int class_arg_position = 1;
8176         const int cache_arg_position = 2;
8177
8178         if (cached)
8179                 return cached;
8180
8181         mb = mono_mb_new (mono_defaults.object_class, "__castclass_with_cache", MONO_WRAPPER_CASTCLASS);
8182         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8183         sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
8184         sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
8185         sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
8186         sig->ret = &mono_defaults.object_class->byval_arg;
8187         sig->pinvoke = 0;
8188
8189 #ifndef DISABLE_JIT
8190         generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
8191                                                                                                 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
8192         invalid_cast_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8193
8194         /*return obj;*/
8195         mono_mb_patch_branch (mb, positive_cache_hit_pos);
8196         mono_mb_emit_ldarg (mb, obj_arg_position);
8197         mono_mb_emit_byte (mb, CEE_RET);
8198
8199         /*fails*/
8200         mono_mb_patch_branch (mb, negative_cache_hit_pos);
8201         mono_mb_patch_branch (mb, invalid_cast_pos);
8202         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8203
8204         /*return null*/
8205         mono_mb_patch_branch (mb, return_null_pos);
8206         mono_mb_emit_byte (mb, CEE_LDNULL);
8207         mono_mb_emit_byte (mb, CEE_RET);
8208 #endif /* DISABLE_JIT */
8209
8210         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE);
8211         res = mono_mb_create (mb, sig, 8, info);
8212         STORE_STORE_FENCE;
8213
8214         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8215                 mono_free_method (res);
8216                 mono_metadata_free_method_signature (sig);
8217         }
8218         mono_mb_free (mb);
8219
8220         return cached;
8221 }
8222
8223 static MonoObject *
8224 mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *cache)
8225 {
8226         MonoObject *isinst = mono_object_isinst (obj, klass);
8227
8228 #ifndef DISABLE_REMOTING
8229         if (obj->vtable->klass == mono_defaults.transparent_proxy_class)
8230                 return isinst;
8231 #endif
8232
8233         uintptr_t cache_update = (uintptr_t)obj->vtable;
8234         if (!isinst)
8235                 cache_update = cache_update | 0x1;
8236
8237         *cache = cache_update;
8238
8239         return isinst;
8240 }
8241
8242 /*
8243  * This does the equivalent of mono_object_isinst_with_cache.
8244  * The wrapper info for the wrapper is a WrapperInfo structure.
8245  */
8246 MonoMethod *
8247 mono_marshal_get_isinst_with_cache (void)
8248 {
8249         static MonoMethod *cached;
8250         MonoMethod *res;
8251         MonoMethodBuilder *mb;
8252         MonoMethodSignature *sig;
8253         int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos;
8254         WrapperInfo *info;
8255
8256         const int obj_arg_position = 0;
8257         const int class_arg_position = 1;
8258         const int cache_arg_position = 2;
8259
8260         if (cached)
8261                 return cached;
8262
8263         mb = mono_mb_new (mono_defaults.object_class, "__isinst_with_cache", MONO_WRAPPER_CASTCLASS);
8264         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8265         // The object
8266         sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
8267         // The class
8268         sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
8269         // The cache
8270         sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
8271         sig->ret = &mono_defaults.object_class->byval_arg;
8272         sig->pinvoke = 0;
8273
8274 #ifndef DISABLE_JIT
8275         generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
8276                 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
8277         // Return the object gotten via the slow path.
8278         mono_mb_emit_byte (mb, CEE_RET);
8279
8280         // return NULL;
8281         mono_mb_patch_branch (mb, negative_cache_hit_pos);
8282         mono_mb_patch_branch (mb, return_null_pos);
8283         mono_mb_emit_byte (mb, CEE_LDNULL);
8284         mono_mb_emit_byte (mb, CEE_RET);
8285
8286         // return obj
8287         mono_mb_patch_branch (mb, positive_cache_hit_pos);
8288         mono_mb_emit_ldarg (mb, 0);
8289         mono_mb_emit_byte (mb, CEE_RET);
8290 #endif
8291
8292         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ISINST_WITH_CACHE);
8293         res = mono_mb_create (mb, sig, 8, info);
8294         STORE_STORE_FENCE;
8295
8296         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8297                 mono_free_method (res);
8298                 mono_metadata_free_method_signature (sig);
8299         }
8300         mono_mb_free (mb);
8301
8302         return cached;
8303 }
8304
8305 /*
8306  * mono_marshal_get_isinst:
8307  * @klass: the type of the field
8308  *
8309  * This method generates a function which can be used to check if an object is
8310  * an instance of the given type, icluding the case where the object is a proxy.
8311  * The generated function has the following signature:
8312  * MonoObject* __isinst_wrapper_ (MonoObject *obj)
8313  */
8314 MonoMethod *
8315 mono_marshal_get_isinst (MonoClass *klass)
8316 {
8317         static MonoMethodSignature *isint_sig = NULL;
8318         GHashTable *cache;
8319         MonoMethod *res;
8320         WrapperInfo *info;
8321         int pos_was_ok, pos_end;
8322 #ifndef DISABLE_REMOTING
8323         int pos_end2, pos_failed;
8324 #endif
8325         char *name;
8326         MonoMethodBuilder *mb;
8327
8328         cache = get_cache (&klass->image->isinst_cache, mono_aligned_addr_hash, NULL);
8329         if ((res = mono_marshal_find_in_cache (cache, klass)))
8330                 return res;
8331
8332         if (!isint_sig) {
8333                 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8334                 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
8335                 isint_sig->ret = &mono_defaults.object_class->byval_arg;
8336                 isint_sig->pinvoke = 0;
8337         }
8338         
8339         name = g_strdup_printf ("__isinst_wrapper_%s", klass->name); 
8340         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ISINST);
8341         g_free (name);
8342         
8343         mb->method->save_lmf = 1;
8344
8345 #ifndef DISABLE_JIT
8346         /* check if the object is a proxy that needs special cast */
8347         mono_mb_emit_ldarg (mb, 0);
8348         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8349         mono_mb_emit_op (mb, CEE_MONO_CISINST, klass);
8350
8351         /* The result of MONO_CISINST can be:
8352                 0) the type check succeeded
8353                 1) the type check did not succeed
8354                 2) a CanCastTo call is needed */
8355 #ifndef DISABLE_REMOTING
8356         mono_mb_emit_byte (mb, CEE_DUP);
8357         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8358
8359         mono_mb_emit_byte (mb, CEE_LDC_I4_2);
8360         pos_failed = mono_mb_emit_branch (mb, CEE_BNE_UN);
8361         
8362         /* get the real proxy from the transparent proxy*/
8363
8364         mono_mb_emit_ldarg (mb, 0);
8365         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8366         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8367         
8368         /* fail */
8369         
8370         mono_mb_patch_branch (mb, pos_failed);
8371         mono_mb_emit_byte (mb, CEE_LDNULL);
8372         pos_end2 = mono_mb_emit_branch (mb, CEE_BR);
8373         
8374         /* success */
8375         
8376         mono_mb_patch_branch (mb, pos_was_ok);
8377         mono_mb_emit_byte (mb, CEE_POP);
8378         mono_mb_emit_ldarg (mb, 0);
8379         
8380         /* the end */
8381         
8382         mono_mb_patch_branch (mb, pos_end);
8383         mono_mb_patch_branch (mb, pos_end2);
8384         mono_mb_emit_byte (mb, CEE_RET);
8385 #else
8386         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8387
8388         /* fail */
8389
8390         mono_mb_emit_byte (mb, CEE_LDNULL);
8391         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8392
8393         /* success */
8394
8395         mono_mb_patch_branch (mb, pos_was_ok);
8396         mono_mb_emit_ldarg (mb, 0);
8397
8398         /* the end */
8399
8400         mono_mb_patch_branch (mb, pos_end);
8401         mono_mb_emit_byte (mb, CEE_RET);
8402 #endif /* DISABLE_REMOTING */
8403 #endif /* DISABLE_JIT */
8404
8405         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8406         info->d.proxy.klass = klass;
8407         res = mono_mb_create_and_cache_full (cache, klass, mb, isint_sig, isint_sig->param_count + 16, info, NULL);
8408         mono_mb_free (mb);
8409
8410         return res;
8411 }
8412
8413 /*
8414  * mono_marshal_get_castclass:
8415  * @klass: the type of the field
8416  *
8417  * This method generates a function which can be used to cast an object to
8418  * an instance of the given type, icluding the case where the object is a proxy.
8419  * The generated function has the following signature:
8420  * MonoObject* __castclass_wrapper_ (MonoObject *obj)
8421  * The wrapper info for the wrapper is a WrapperInfo structure.
8422  */
8423 MonoMethod *
8424 mono_marshal_get_castclass (MonoClass *klass)
8425 {
8426         static MonoMethodSignature *castclass_sig = NULL;
8427         GHashTable *cache;
8428         MonoMethod *res;
8429 #ifndef DISABLE_REMOTING
8430         int pos_was_ok, pos_was_ok2;
8431 #endif
8432         char *name;
8433         MonoMethodBuilder *mb;
8434         WrapperInfo *info;
8435
8436         cache = get_cache (&klass->image->castclass_cache, mono_aligned_addr_hash, NULL);
8437         if ((res = mono_marshal_find_in_cache (cache, klass)))
8438                 return res;
8439
8440         if (!castclass_sig) {
8441                 castclass_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8442                 castclass_sig->params [0] = &mono_defaults.object_class->byval_arg;
8443                 castclass_sig->ret = &mono_defaults.object_class->byval_arg;
8444                 castclass_sig->pinvoke = 0;
8445         }
8446         
8447         name = g_strdup_printf ("__castclass_wrapper_%s", klass->name); 
8448         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_CASTCLASS);
8449         g_free (name);
8450         
8451         mb->method->save_lmf = 1;
8452
8453 #ifndef DISABLE_JIT
8454         /* check if the object is a proxy that needs special cast */
8455         mono_mb_emit_ldarg (mb, 0);
8456         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8457         mono_mb_emit_op (mb, CEE_MONO_CCASTCLASS, klass);
8458
8459         /* The result of MONO_CCASTCLASS can be:
8460                 0) the cast is valid
8461                 1) cast of unknown proxy type
8462                 or an exception if the cast is is invalid
8463         */
8464 #ifndef DISABLE_REMOTING
8465         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8466
8467         /* get the real proxy from the transparent proxy*/
8468
8469         mono_mb_emit_ldarg (mb, 0);
8470         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8471         pos_was_ok2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
8472         
8473         /* fail */
8474         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8475         
8476         /* success */
8477         mono_mb_patch_branch (mb, pos_was_ok);
8478         mono_mb_patch_branch (mb, pos_was_ok2);
8479 #else
8480         /* MONO_CCASTCLASS leaves an int in the stack with the result, pop it. */
8481         mono_mb_emit_byte (mb, CEE_POP);
8482 #endif /* DISABLE_REMOTING */
8483
8484         mono_mb_emit_ldarg (mb, 0);
8485         
8486         /* the end */
8487         mono_mb_emit_byte (mb, CEE_RET);
8488 #endif /* DISABLE_JIT */
8489
8490         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8491
8492         res = mono_mb_create_and_cache_full (cache, klass, mb, castclass_sig, castclass_sig->param_count + 16,
8493                                                                                  info, NULL);
8494         mono_mb_free (mb);
8495
8496         return res;
8497 }
8498
8499 /**
8500  * mono_marshal_get_struct_to_ptr:
8501  * @klass:
8502  *
8503  * generates IL code for StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)
8504  * The wrapper info for the wrapper is a WrapperInfo structure.
8505  */
8506 MonoMethod *
8507 mono_marshal_get_struct_to_ptr (MonoClass *klass)
8508 {
8509         MonoMethodBuilder *mb;
8510         static MonoMethod *stoptr = NULL;
8511         MonoMethod *res;
8512         WrapperInfo *info;
8513
8514         g_assert (klass != NULL);
8515
8516         mono_marshal_load_type_info (klass);
8517
8518         if (klass->marshal_info->str_to_ptr)
8519                 return klass->marshal_info->str_to_ptr;
8520
8521         if (!stoptr) 
8522                 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
8523         g_assert (stoptr);
8524
8525         mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
8526
8527 #ifndef DISABLE_JIT
8528         if (klass->blittable) {
8529                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8530                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8531                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8532                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8533                 mono_mb_emit_byte (mb, CEE_PREFIX1);
8534                 mono_mb_emit_byte (mb, CEE_CPBLK);
8535         } else {
8536
8537                 /* allocate local 0 (pointer) src_ptr */
8538                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8539                 /* allocate local 1 (pointer) dst_ptr */
8540                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8541                 /* allocate local 2 (boolean) delete_old */
8542                 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8543                 mono_mb_emit_byte (mb, CEE_LDARG_2);
8544                 mono_mb_emit_stloc (mb, 2);
8545
8546                 /* initialize src_ptr to point to the start of object data */
8547                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8548                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8549                 mono_mb_emit_stloc (mb, 0);
8550
8551                 /* initialize dst_ptr */
8552                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8553                 mono_mb_emit_stloc (mb, 1);
8554
8555                 emit_struct_conv (mb, klass, FALSE);
8556         }
8557
8558         mono_mb_emit_byte (mb, CEE_RET);
8559 #endif
8560         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRUCTURE_TO_PTR);
8561         res = mono_mb_create (mb, mono_signature_no_pinvoke (stoptr), 0, info);
8562         mono_mb_free (mb);
8563
8564         klass->marshal_info->str_to_ptr = res;
8565         return res;
8566 }
8567
8568 /**
8569  * mono_marshal_get_ptr_to_struct:
8570  * @klass:
8571  *
8572  * generates IL code for PtrToStructure (IntPtr src, object structure)
8573  * The wrapper info for the wrapper is a WrapperInfo structure.
8574  */
8575 MonoMethod *
8576 mono_marshal_get_ptr_to_struct (MonoClass *klass)
8577 {
8578         MonoMethodBuilder *mb;
8579         static MonoMethodSignature *ptostr = NULL;
8580         MonoMethod *res;
8581         WrapperInfo *info;
8582
8583         g_assert (klass != NULL);
8584
8585         mono_marshal_load_type_info (klass);
8586
8587         if (klass->marshal_info->ptr_to_str)
8588                 return klass->marshal_info->ptr_to_str;
8589
8590         if (!ptostr) {
8591                 MonoMethodSignature *sig;
8592
8593                 /* Create the signature corresponding to
8594                           static void PtrToStructure (IntPtr ptr, object structure);
8595                    defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
8596                 sig = mono_create_icall_signature ("void ptr object");
8597                 sig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
8598                 sig->pinvoke = 0;
8599                 mono_memory_barrier ();
8600                 ptostr = sig;
8601         }
8602
8603         mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
8604
8605 #ifndef DISABLE_JIT
8606         if (klass->blittable) {
8607                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8608                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8609                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8610                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8611                 mono_mb_emit_byte (mb, CEE_PREFIX1);
8612                 mono_mb_emit_byte (mb, CEE_CPBLK);
8613         } else {
8614
8615                 /* allocate local 0 (pointer) src_ptr */
8616                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8617                 /* allocate local 1 (pointer) dst_ptr */
8618                 mono_mb_add_local (mb, &klass->this_arg);
8619                 
8620                 /* initialize src_ptr to point to the start of object data */
8621                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8622                 mono_mb_emit_stloc (mb, 0);
8623
8624                 /* initialize dst_ptr */
8625                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8626                 mono_mb_emit_op (mb, CEE_UNBOX, klass);
8627                 mono_mb_emit_stloc (mb, 1);
8628
8629                 emit_struct_conv (mb, klass, TRUE);
8630         }
8631
8632         mono_mb_emit_byte (mb, CEE_RET);
8633 #endif
8634         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PTR_TO_STRUCTURE);
8635         res = mono_mb_create (mb, ptostr, 0, info);
8636         mono_mb_free (mb);
8637
8638         klass->marshal_info->ptr_to_str = res;
8639         return res;
8640 }
8641
8642 /*
8643  * Return a dummy wrapper for METHOD which is called by synchronized wrappers.
8644  * This is used to avoid infinite recursion since it is hard to determine where to
8645  * replace a method with its synchronized wrapper, and where not.
8646  * The runtime should execute METHOD instead of the wrapper.
8647  * The wrapper info for the wrapper is a WrapperInfo structure.
8648  */
8649 MonoMethod *
8650 mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
8651 {
8652         MonoMethodBuilder *mb;
8653         WrapperInfo *info;
8654         MonoMethodSignature *sig;
8655         MonoMethod *res;
8656         MonoGenericContext *ctx = NULL;
8657         MonoGenericContainer *container = NULL;
8658
8659         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
8660                 ctx = &((MonoMethodInflated*)method)->context;
8661                 method = ((MonoMethodInflated*)method)->declaring;
8662                 container = mono_method_get_generic_container (method);
8663                 if (!container)
8664                         container = method->klass->generic_container;
8665                 g_assert (container);
8666         }
8667
8668         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
8669 #ifndef DISABLE_JIT
8670         mono_mb_emit_exception_full (mb, "System", "ExecutionEngineException", "Shouldn't be called.");
8671         mono_mb_emit_byte (mb, CEE_RET);
8672 #endif
8673         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
8674
8675         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_SYNCHRONIZED_INNER);
8676         info->d.synchronized_inner.method = method;
8677         res = mono_mb_create (mb, sig, 0, info);
8678         mono_mb_free (mb);
8679         if (ctx) {
8680                 MonoError error;
8681                 res = mono_class_inflate_generic_method_checked (res, ctx, &error);
8682                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8683         }
8684         return res;
8685 }
8686
8687 /*
8688  * generates IL code for the synchronized wrapper: the generated method
8689  * calls METHOD while locking 'this' or the parent type.
8690  */
8691 MonoMethod *
8692 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
8693 {
8694         static MonoMethod *enter_method, *exit_method, *gettypefromhandle_method;
8695         MonoMethodSignature *sig;
8696         MonoExceptionClause *clause;
8697         MonoMethodBuilder *mb;
8698         MonoMethod *res;
8699         GHashTable *cache;
8700         int i, pos, pos2, this_local, taken_local, ret_local = 0;
8701         MonoGenericContext *ctx = NULL;
8702         MonoMethod *orig_method = NULL;
8703         MonoGenericContainer *container = NULL;
8704
8705         g_assert (method);
8706
8707         if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
8708                 return method;
8709
8710         /* FIXME: Support generic methods too */
8711         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
8712                 orig_method = method;
8713                 ctx = &((MonoMethodInflated*)method)->context;
8714                 method = ((MonoMethodInflated*)method)->declaring;
8715                 container = mono_method_get_generic_container (method);
8716                 if (!container)
8717                         container = method->klass->generic_container;
8718                 g_assert (container);
8719         }
8720
8721         /*
8722          * Check cache
8723          */
8724         if (ctx) {
8725                 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
8726                 res = check_generic_wrapper_cache (cache, orig_method, orig_method, method);
8727                 if (res)
8728                         return res;
8729         } else {
8730                 cache = get_cache (&method->klass->image->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
8731                 if ((res = mono_marshal_find_in_cache (cache, method)))
8732                         return res;
8733         }
8734
8735         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
8736         sig->pinvoke = 0;
8737
8738         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
8739
8740 #ifndef DISABLE_JIT
8741         mb->skip_visibility = 1;
8742         /* result */
8743         if (!MONO_TYPE_IS_VOID (sig->ret))
8744                 ret_local = mono_mb_add_local (mb, sig->ret);
8745 #endif
8746
8747         if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
8748                 mono_class_set_failure (method->klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
8749 #ifndef DISABLE_JIT
8750                 /* This will throw the type load exception when the wrapper is compiled */
8751                 mono_mb_emit_byte (mb, CEE_LDNULL);
8752                 mono_mb_emit_op (mb, CEE_ISINST, method->klass);
8753                 mono_mb_emit_byte (mb, CEE_POP);
8754
8755                 if (!MONO_TYPE_IS_VOID (sig->ret))
8756                         mono_mb_emit_ldloc (mb, ret_local);
8757                 mono_mb_emit_byte (mb, CEE_RET);
8758 #endif
8759
8760                 res = mono_mb_create_and_cache (cache, method,
8761                                                                                 mb, sig, sig->param_count + 16);
8762                 mono_mb_free (mb);
8763
8764                 return res;
8765         }
8766
8767 #ifndef DISABLE_JIT
8768         /* this */
8769         this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
8770         taken_local = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8771
8772         clause = mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
8773         clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
8774 #endif
8775
8776         mono_marshal_lock ();
8777
8778         if (!enter_method) {
8779                 MonoMethodDesc *desc;
8780
8781                 desc = mono_method_desc_new ("Monitor:enter_with_atomic_var(object,bool&)", FALSE);
8782                 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
8783                 g_assert (enter_method);
8784                 mono_method_desc_free (desc);
8785
8786                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
8787                 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
8788                 g_assert (exit_method);
8789                 mono_method_desc_free (desc);
8790
8791                 desc = mono_method_desc_new ("Type:GetTypeFromHandle", FALSE);
8792                 gettypefromhandle_method = mono_method_desc_search_in_class (desc, mono_defaults.systemtype_class);
8793                 g_assert (gettypefromhandle_method);
8794                 mono_method_desc_free (desc);
8795         }
8796
8797         mono_marshal_unlock ();
8798
8799 #ifndef DISABLE_JIT
8800         /* Push this or the type object */
8801         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
8802                 /* We have special handling for this in the JIT */
8803                 int index = mono_mb_add_data (mb, method->klass);
8804                 mono_mb_add_data (mb, mono_defaults.typehandle_class);
8805                 mono_mb_emit_byte (mb, CEE_LDTOKEN);
8806                 mono_mb_emit_i4 (mb, index);
8807
8808                 mono_mb_emit_managed_call (mb, gettypefromhandle_method, NULL);
8809         }
8810         else
8811                 mono_mb_emit_ldarg (mb, 0);
8812         mono_mb_emit_stloc (mb, this_local);
8813
8814         /* Call Monitor::Enter() */
8815         mono_mb_emit_ldloc (mb, this_local);
8816         mono_mb_emit_ldloc_addr (mb, taken_local);
8817         mono_mb_emit_managed_call (mb, enter_method, NULL);
8818
8819         clause->try_offset = mono_mb_get_label (mb);
8820
8821         /* Call the method */
8822         if (sig->hasthis)
8823                 mono_mb_emit_ldarg (mb, 0);
8824         for (i = 0; i < sig->param_count; i++)
8825                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
8826
8827         if (ctx) {
8828                 MonoError error;
8829                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
8830                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8831         } else {
8832                 mono_mb_emit_managed_call (mb, method, NULL);
8833         }
8834
8835         if (!MONO_TYPE_IS_VOID (sig->ret))
8836                 mono_mb_emit_stloc (mb, ret_local);
8837
8838         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8839
8840         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
8841         clause->handler_offset = mono_mb_get_label (mb);
8842
8843         /* Call Monitor::Exit() if needed */
8844         mono_mb_emit_ldloc (mb, taken_local);
8845         pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
8846         mono_mb_emit_ldloc (mb, this_local);
8847         mono_mb_emit_managed_call (mb, exit_method, NULL);
8848         mono_mb_patch_branch (mb, pos2);
8849         mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8850
8851         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
8852
8853         mono_mb_patch_branch (mb, pos);
8854         if (!MONO_TYPE_IS_VOID (sig->ret))
8855                 mono_mb_emit_ldloc (mb, ret_local);
8856         mono_mb_emit_byte (mb, CEE_RET);
8857
8858         mono_mb_set_clauses (mb, 1, clause);
8859 #endif
8860
8861         if (ctx) {
8862                 MonoMethod *def;
8863                 def = mono_mb_create_and_cache (cache, method, mb, sig, sig->param_count + 16);
8864                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
8865         } else {
8866                 res = mono_mb_create_and_cache (cache, method,
8867                                                                                 mb, sig, sig->param_count + 16);
8868         }
8869         mono_mb_free (mb);
8870
8871         return res;     
8872 }
8873
8874
8875 /*
8876  * the returned method calls 'method' unboxing the this argument
8877  */
8878 MonoMethod *
8879 mono_marshal_get_unbox_wrapper (MonoMethod *method)
8880 {
8881         MonoMethodSignature *sig = mono_method_signature (method);
8882         int i;
8883         MonoMethodBuilder *mb;
8884         MonoMethod *res;
8885         GHashTable *cache;
8886
8887         cache = get_cache (&mono_method_get_wrapper_cache (method)->unbox_wrapper_cache, mono_aligned_addr_hash, NULL);
8888
8889         if ((res = mono_marshal_find_in_cache (cache, method)))
8890                 return res;
8891
8892         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
8893
8894         g_assert (sig->hasthis);
8895         
8896 #ifndef DISABLE_JIT
8897         mono_mb_emit_ldarg (mb, 0); 
8898         mono_mb_emit_icon (mb, sizeof (MonoObject));
8899         mono_mb_emit_byte (mb, CEE_ADD);
8900         for (i = 0; i < sig->param_count; ++i)
8901                 mono_mb_emit_ldarg (mb, i + 1);
8902         mono_mb_emit_managed_call (mb, method, NULL);
8903         mono_mb_emit_byte (mb, CEE_RET);
8904 #endif
8905
8906         res = mono_mb_create_and_cache (cache, method,
8907                                                                                  mb, sig, sig->param_count + 16);
8908         mono_mb_free (mb);
8909
8910         /* mono_method_print_code (res); */
8911
8912         return res;     
8913 }
8914
8915 enum {
8916         STELEMREF_OBJECT, /*no check at all*/
8917         STELEMREF_SEALED_CLASS, /*check vtable->klass->element_type */
8918         STELEMREF_CLASS, /*only the klass->parents check*/
8919         STELEMREF_INTERFACE, /*interfaces without variant generic arguments. */
8920         STELEMREF_COMPLEX, /*arrays, MBR or types with variant generic args - go straight to icalls*/
8921         STELEMREF_KIND_COUNT
8922 };
8923
8924 static const char *strelemref_wrapper_name[] = {
8925         "object", "sealed_class", "class", "interface", "complex"
8926 };
8927
8928 static gboolean
8929 is_monomorphic_array (MonoClass *klass)
8930 {
8931         MonoClass *element_class;
8932         if (klass->rank != 1)
8933                 return FALSE;
8934
8935         element_class = klass->element_class;
8936         return (element_class->flags & TYPE_ATTRIBUTE_SEALED) || element_class->valuetype;
8937 }
8938
8939 static int
8940 get_virtual_stelemref_kind (MonoClass *element_class)
8941 {
8942         if (element_class == mono_defaults.object_class)
8943                 return STELEMREF_OBJECT;
8944         if (is_monomorphic_array (element_class))
8945                 return STELEMREF_SEALED_CLASS;
8946         /* Compressed interface bitmaps require code that is quite complex, so don't optimize for it. */
8947         if (MONO_CLASS_IS_INTERFACE (element_class) && !mono_class_has_variant_generic_params (element_class))
8948 #ifdef COMPRESSED_INTERFACE_BITMAP
8949                 return STELEMREF_COMPLEX;
8950 #else
8951                 return STELEMREF_INTERFACE;
8952 #endif
8953         /*Arrays are sealed but are covariant on their element type, We can't use any of the fast paths.*/
8954         if (mono_class_is_marshalbyref (element_class) || element_class->rank || mono_class_has_variant_generic_params (element_class))
8955                 return STELEMREF_COMPLEX;
8956         if (element_class->flags & TYPE_ATTRIBUTE_SEALED)
8957                 return STELEMREF_SEALED_CLASS;
8958         return STELEMREF_CLASS;
8959 }
8960
8961 #ifndef DISABLE_JIT
8962
8963 static void
8964 load_array_element_address (MonoMethodBuilder *mb)
8965 {
8966         mono_mb_emit_ldarg (mb, 0);
8967         mono_mb_emit_ldarg (mb, 1);
8968         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
8969 }
8970
8971 static void
8972 load_array_class (MonoMethodBuilder *mb, int aklass)
8973 {
8974         mono_mb_emit_ldarg (mb, 0);
8975         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
8976         mono_mb_emit_byte (mb, CEE_LDIND_I);
8977         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
8978         mono_mb_emit_byte (mb, CEE_LDIND_I);
8979         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
8980         mono_mb_emit_byte (mb, CEE_LDIND_I);
8981         mono_mb_emit_stloc (mb, aklass);
8982 }
8983
8984 static void
8985 load_value_class (MonoMethodBuilder *mb, int vklass)
8986 {
8987         mono_mb_emit_ldarg (mb, 2);
8988         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
8989         mono_mb_emit_byte (mb, CEE_LDIND_I);
8990         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
8991         mono_mb_emit_byte (mb, CEE_LDIND_I);
8992         mono_mb_emit_stloc (mb, vklass);
8993 }
8994 #endif
8995
8996 #if 0
8997 static void
8998 record_slot_vstore (MonoObject *array, size_t index, MonoObject *value)
8999 {
9000         char *name = mono_type_get_full_name (array->vtable->klass->element_class);
9001         printf ("slow vstore of %s\n", name);
9002         g_free (name);
9003 }
9004 #endif
9005
9006 /*
9007  * The wrapper info for the wrapper is a WrapperInfo structure.
9008  *
9009  * TODO:
9010  *      - Separate simple interfaces from variant interfaces or mbr types. This way we can avoid the icall for them.
9011  *      - Emit a (new) mono bytecode that produces OP_COND_EXC_NE_UN to raise ArrayTypeMismatch
9012  *      - Maybe mve some MonoClass field into the vtable to reduce the number of loads
9013  *      - Add a case for arrays of arrays.
9014  */
9015 static MonoMethod*
9016 get_virtual_stelemref_wrapper (int kind)
9017 {
9018         static MonoMethod *cached_methods [STELEMREF_KIND_COUNT] = { NULL }; /*object iface sealed regular*/
9019         static MonoMethodSignature *signature;
9020         MonoMethodBuilder *mb;
9021         MonoMethod *res;
9022         char *name;
9023         const char *param_names [16];
9024         guint32 b1, b2, b3;
9025         int aklass, vklass, vtable, uiid;
9026         int array_slot_addr;
9027         WrapperInfo *info;
9028
9029         if (cached_methods [kind])
9030                 return cached_methods [kind];
9031
9032         name = g_strdup_printf ("virt_stelemref_%s", strelemref_wrapper_name [kind]);
9033         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STELEMREF);
9034         g_free (name);
9035
9036         if (!signature) {
9037                 MonoMethodSignature *sig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
9038
9039                 /* void this::stelemref (size_t idx, void* value) */
9040                 sig->ret = &mono_defaults.void_class->byval_arg;
9041                 sig->hasthis = TRUE;
9042                 sig->params [0] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9043                 sig->params [1] = &mono_defaults.object_class->byval_arg;
9044                 signature = sig;
9045         }
9046
9047 #ifndef DISABLE_JIT
9048         param_names [0] = "index";
9049         param_names [1] = "value";
9050         mono_mb_set_param_names (mb, param_names);
9051
9052         /*For now simply call plain old stelemref*/
9053         switch (kind) {
9054         case STELEMREF_OBJECT:
9055                 /* ldelema (implicit bound check) */
9056                 load_array_element_address (mb);
9057                 /* do_store */
9058                 mono_mb_emit_ldarg (mb, 2);
9059                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9060                 mono_mb_emit_byte (mb, CEE_RET);
9061                 break;
9062
9063         case STELEMREF_COMPLEX:
9064                 /*
9065                 <ldelema (bound check)>
9066                 if (!value)
9067                         goto store;
9068                 if (!mono_object_isinst (value, aklass))
9069                         goto do_exception;
9070
9071                  do_store:
9072                          *array_slot_addr = value;
9073
9074                 do_exception:
9075                         throw new ArrayTypeMismatchException ();
9076                 */
9077
9078                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9079                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9080
9081 #if 0
9082                 {
9083                         /*Use this to debug/record stores that are going thru the slow path*/
9084                         MonoMethodSignature *csig;
9085                         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9086                         csig->ret = &mono_defaults.void_class->byval_arg;
9087                         csig->params [0] = &mono_defaults.object_class->byval_arg;
9088                         csig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9089                         csig->params [2] = &mono_defaults.object_class->byval_arg;
9090                         mono_mb_emit_ldarg (mb, 0);
9091                         mono_mb_emit_ldarg (mb, 1);
9092                         mono_mb_emit_ldarg (mb, 2);
9093                         mono_mb_emit_native_call (mb, csig, record_slot_vstore);
9094                 }
9095 #endif
9096
9097                 /* ldelema (implicit bound check) */
9098                 load_array_element_address (mb);
9099                 mono_mb_emit_stloc (mb, array_slot_addr);
9100
9101                 /* if (!value) goto do_store */
9102                 mono_mb_emit_ldarg (mb, 2);
9103                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9104
9105                 /* aklass = array->vtable->klass->element_class */
9106                 load_array_class (mb, aklass);
9107
9108                 /*if (mono_object_isinst (value, aklass)) */
9109                 mono_mb_emit_ldarg (mb, 2);
9110                 mono_mb_emit_ldloc (mb, aklass);
9111                 mono_mb_emit_icall (mb, mono_object_isinst);
9112                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9113
9114                 /* do_store: */
9115                 mono_mb_patch_branch (mb, b1);
9116                 mono_mb_emit_ldloc (mb, array_slot_addr);
9117                 mono_mb_emit_ldarg (mb, 2);
9118                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9119                 mono_mb_emit_byte (mb, CEE_RET);
9120
9121                 /* do_exception: */
9122                 mono_mb_patch_branch (mb, b2);
9123
9124                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9125                 break;
9126
9127         case STELEMREF_SEALED_CLASS:
9128                 /*
9129                 <ldelema (bound check)>
9130                 if (!value)
9131                         goto store;
9132
9133                 aklass = array->vtable->klass->element_class;
9134                 vklass = value->vtable->klass;
9135
9136                 if (vklass != aklass)
9137                         goto do_exception;
9138
9139                 do_store:
9140                          *array_slot_addr = value;
9141
9142                 do_exception:
9143                         throw new ArrayTypeMismatchException ();
9144                 */
9145                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9146                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9147                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9148
9149
9150                 /* ldelema (implicit bound check) */
9151                 load_array_element_address (mb);
9152                 mono_mb_emit_stloc (mb, array_slot_addr);
9153
9154                 /* if (!value) goto do_store */
9155                 mono_mb_emit_ldarg (mb, 2);
9156                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9157
9158                 /* aklass = array->vtable->klass->element_class */
9159                 load_array_class (mb, aklass);
9160
9161                 /* vklass = value->vtable->klass */
9162                 load_value_class (mb, vklass);
9163
9164                 /*if (vklass != aklass) goto do_exception; */
9165                 mono_mb_emit_ldloc (mb, aklass);
9166                 mono_mb_emit_ldloc (mb, vklass);
9167                 b2 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9168
9169                 /* do_store: */
9170                 mono_mb_patch_branch (mb, b1);
9171                 mono_mb_emit_ldloc (mb, array_slot_addr);
9172                 mono_mb_emit_ldarg (mb, 2);
9173                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9174                 mono_mb_emit_byte (mb, CEE_RET);
9175
9176                 /* do_exception: */
9177                 mono_mb_patch_branch (mb, b2);
9178                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9179                 break;
9180
9181         case STELEMREF_CLASS:
9182                 /*
9183                 the method:
9184                 <ldelema (bound check)>
9185                 if (!value)
9186                         goto do_store;
9187
9188                 aklass = array->vtable->klass->element_class;
9189                 vklass = value->vtable->klass;
9190
9191                 if (vklass->idepth < aklass->idepth)
9192                         goto do_exception;
9193
9194                 if (vklass->supertypes [aklass->idepth - 1] != aklass)
9195                         goto do_exception;
9196
9197                 do_store:
9198                         *array_slot_addr = value;
9199                         return;
9200
9201                 long:
9202                         throw new ArrayTypeMismatchException ();
9203                 */
9204                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9205                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9206                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9207
9208                 /* ldelema (implicit bound check) */
9209                 load_array_element_address (mb);
9210                 mono_mb_emit_stloc (mb, array_slot_addr);
9211
9212                 /* if (!value) goto do_store */
9213                 mono_mb_emit_ldarg (mb, 2);
9214                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9215
9216                 /* aklass = array->vtable->klass->element_class */
9217                 load_array_class (mb, aklass);
9218
9219                 /* vklass = value->vtable->klass */
9220                 load_value_class (mb, vklass);
9221
9222                 /*if (mono_object_isinst (value, aklass)) */
9223                 mono_mb_emit_ldarg (mb, 2);
9224                 mono_mb_emit_ldloc (mb, aklass);
9225                 mono_mb_emit_icall (mb, mono_object_isinst);
9226                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9227
9228                 /* if (vklass->idepth < aklass->idepth) goto failue */
9229                 mono_mb_emit_ldloc (mb, vklass);
9230                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9231                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9232
9233                 mono_mb_emit_ldloc (mb, aklass);
9234                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9235                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9236
9237                 b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
9238
9239                 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
9240                 mono_mb_emit_ldloc (mb, vklass);
9241                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
9242                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9243
9244                 mono_mb_emit_ldloc (mb, aklass);
9245                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9246                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9247                 mono_mb_emit_icon (mb, 1);
9248                 mono_mb_emit_byte (mb, CEE_SUB);
9249                 mono_mb_emit_icon (mb, sizeof (void*));
9250                 mono_mb_emit_byte (mb, CEE_MUL);
9251                 mono_mb_emit_byte (mb, CEE_ADD);
9252                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9253
9254                 mono_mb_emit_ldloc (mb, aklass);
9255                 b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9256
9257                 /* do_store: */
9258                 mono_mb_patch_branch (mb, b1);
9259                 mono_mb_emit_ldloc (mb, array_slot_addr);
9260                 mono_mb_emit_ldarg (mb, 2);
9261                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9262                 mono_mb_emit_byte (mb, CEE_RET);
9263
9264                 /* do_exception: */
9265                 mono_mb_patch_branch (mb, b2);
9266                 mono_mb_patch_branch (mb, b3);
9267
9268                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9269                 break;
9270
9271         case STELEMREF_INTERFACE:
9272                 /*Mono *klass;
9273                 MonoVTable *vt;
9274                 unsigned uiid;
9275                 if (value == NULL)
9276                         goto store;
9277
9278                 klass = array->obj.vtable->klass->element_class;
9279                 vt = value->vtable;
9280                 uiid = klass->interface_id;
9281                 if (uiid > vt->max_interface_id)
9282                         goto exception;
9283                 if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7))))
9284                         goto exception;
9285                 store:
9286                         mono_array_setref (array, index, value);
9287                         return;
9288                 exception:
9289                         mono_raise_exception (mono_get_exception_array_type_mismatch ());*/
9290
9291                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9292                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9293                 vtable = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9294                 uiid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9295
9296                 /* ldelema (implicit bound check) */
9297                 load_array_element_address (mb);
9298                 mono_mb_emit_stloc (mb, array_slot_addr);
9299
9300                 /* if (!value) goto do_store */
9301                 mono_mb_emit_ldarg (mb, 2);
9302                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9303
9304                 /* klass = array->vtable->klass->element_class */
9305                 load_array_class (mb, aklass);
9306
9307                 /* vt = value->vtable */
9308                 mono_mb_emit_ldarg (mb, 2);
9309                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9310                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9311                 mono_mb_emit_stloc (mb, vtable);
9312
9313                 /* uiid = klass->interface_id; */
9314                 mono_mb_emit_ldloc (mb, aklass);
9315                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, interface_id));
9316                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9317                 mono_mb_emit_stloc (mb, uiid);
9318
9319                 /*if (uiid > vt->max_interface_id)*/
9320                 mono_mb_emit_ldloc (mb, uiid);
9321                 mono_mb_emit_ldloc (mb, vtable);
9322                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, max_interface_id));
9323                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9324                 b2 = mono_mb_emit_branch (mb, CEE_BGT_UN);
9325
9326                 /* if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7)))) */
9327
9328                 /*vt->interface_bitmap*/
9329                 mono_mb_emit_ldloc (mb, vtable);
9330                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, interface_bitmap));
9331                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9332
9333                 /*uiid >> 3*/
9334                 mono_mb_emit_ldloc (mb, uiid);
9335                 mono_mb_emit_icon (mb, 3);
9336                 mono_mb_emit_byte (mb, CEE_SHR_UN);
9337
9338                 /*vt->interface_bitmap [(uiid) >> 3]*/
9339                 mono_mb_emit_byte (mb, CEE_ADD); /*interface_bitmap is a guint8 array*/
9340                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
9341
9342                 /*(1 << ((uiid)&7)))*/
9343                 mono_mb_emit_icon (mb, 1);
9344                 mono_mb_emit_ldloc (mb, uiid);
9345                 mono_mb_emit_icon (mb, 7);
9346                 mono_mb_emit_byte (mb, CEE_AND);
9347                 mono_mb_emit_byte (mb, CEE_SHL);
9348
9349                 /*bitwise and the whole thing*/
9350                 mono_mb_emit_byte (mb, CEE_AND);
9351                 b3 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9352
9353                 /* do_store: */
9354                 mono_mb_patch_branch (mb, b1);
9355                 mono_mb_emit_ldloc (mb, array_slot_addr);
9356                 mono_mb_emit_ldarg (mb, 2);
9357                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9358                 mono_mb_emit_byte (mb, CEE_RET);
9359
9360                 /* do_exception: */
9361                 mono_mb_patch_branch (mb, b2);
9362                 mono_mb_patch_branch (mb, b3);
9363                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9364                 break;
9365
9366         default:
9367                 mono_mb_emit_ldarg (mb, 0);
9368                 mono_mb_emit_ldarg (mb, 1);
9369                 mono_mb_emit_ldarg (mb, 2);
9370                 mono_mb_emit_managed_call (mb, mono_marshal_get_stelemref (), NULL);
9371                 mono_mb_emit_byte (mb, CEE_RET);
9372                 g_assert (0);
9373         }
9374 #endif /* DISABLE_JIT */
9375         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_VIRTUAL_STELEMREF);
9376         info->d.virtual_stelemref.kind = kind;
9377         res = mono_mb_create (mb, signature, 4, info);
9378         res->flags |= METHOD_ATTRIBUTE_VIRTUAL;
9379
9380         mono_marshal_lock ();
9381         if (!cached_methods [kind]) {
9382                 cached_methods [kind] = res;
9383                 mono_marshal_unlock ();
9384         } else {
9385                 mono_marshal_unlock ();
9386                 mono_free_method (res);
9387         }
9388
9389         mono_mb_free (mb);
9390         return cached_methods [kind];
9391 }
9392
9393 MonoMethod*
9394 mono_marshal_get_virtual_stelemref (MonoClass *array_class)
9395 {
9396         int kind;
9397
9398         g_assert (array_class->rank == 1);
9399         kind = get_virtual_stelemref_kind (array_class->element_class);
9400
9401         return get_virtual_stelemref_wrapper (kind);
9402 }
9403
9404 MonoMethod**
9405 mono_marshal_get_virtual_stelemref_wrappers (int *nwrappers)
9406 {
9407         MonoMethod **res;
9408         int i;
9409
9410         *nwrappers = STELEMREF_KIND_COUNT;
9411         res = g_malloc0 (STELEMREF_KIND_COUNT * sizeof (MonoMethod*));
9412         for (i = 0; i < STELEMREF_KIND_COUNT; ++i)
9413                 res [i] = get_virtual_stelemref_wrapper (i);
9414         return res;
9415 }
9416
9417 /*
9418  * The wrapper info for the wrapper is a WrapperInfo structure.
9419  */
9420 MonoMethod*
9421 mono_marshal_get_stelemref (void)
9422 {
9423         static MonoMethod* ret = NULL;
9424         MonoMethodSignature *sig;
9425         MonoMethodBuilder *mb;
9426         WrapperInfo *info;
9427         
9428         guint32 b1, b2, b3, b4;
9429         guint32 copy_pos;
9430         int aklass, vklass;
9431         int array_slot_addr;
9432         
9433         if (ret)
9434                 return ret;
9435         
9436         mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
9437         
9438
9439         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9440
9441         /* void stelemref (void* array, int idx, void* value) */
9442         sig->ret = &mono_defaults.void_class->byval_arg;
9443         sig->params [0] = &mono_defaults.object_class->byval_arg;
9444         sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9445         sig->params [2] = &mono_defaults.object_class->byval_arg;
9446
9447 #ifndef DISABLE_JIT
9448         aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9449         vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9450         array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9451         
9452         /*
9453         the method:
9454         <ldelema (bound check)>
9455         if (!value)
9456                 goto store;
9457         
9458         aklass = array->vtable->klass->element_class;
9459         vklass = value->vtable->klass;
9460         
9461         if (vklass->idepth < aklass->idepth)
9462                 goto long;
9463         
9464         if (vklass->supertypes [aklass->idepth - 1] != aklass)
9465                 goto long;
9466         
9467         store:
9468                 *array_slot_addr = value;
9469                 return;
9470         
9471         long:
9472                 if (mono_object_isinst (value, aklass))
9473                         goto store;
9474                 
9475                 throw new ArrayTypeMismatchException ();
9476         */
9477         
9478         /* ldelema (implicit bound check) */
9479         mono_mb_emit_ldarg (mb, 0);
9480         mono_mb_emit_ldarg (mb, 1);
9481         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9482         mono_mb_emit_stloc (mb, array_slot_addr);
9483                 
9484         /* if (!value) goto do_store */
9485         mono_mb_emit_ldarg (mb, 2);
9486         b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9487         
9488         /* aklass = array->vtable->klass->element_class */
9489         mono_mb_emit_ldarg (mb, 0);
9490         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9491         mono_mb_emit_byte (mb, CEE_LDIND_I);
9492         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9493         mono_mb_emit_byte (mb, CEE_LDIND_I);
9494         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9495         mono_mb_emit_byte (mb, CEE_LDIND_I);
9496         mono_mb_emit_stloc (mb, aklass);
9497         
9498         /* vklass = value->vtable->klass */
9499         mono_mb_emit_ldarg (mb, 2);
9500         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9501         mono_mb_emit_byte (mb, CEE_LDIND_I);
9502         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9503         mono_mb_emit_byte (mb, CEE_LDIND_I);
9504         mono_mb_emit_stloc (mb, vklass);
9505         
9506         /* if (vklass->idepth < aklass->idepth) goto failue */
9507         mono_mb_emit_ldloc (mb, vklass);
9508         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9509         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9510         
9511         mono_mb_emit_ldloc (mb, aklass);
9512         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9513         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9514         
9515         b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
9516         
9517         /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
9518         mono_mb_emit_ldloc (mb, vklass);
9519         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
9520         mono_mb_emit_byte (mb, CEE_LDIND_I);
9521         
9522         mono_mb_emit_ldloc (mb, aklass);
9523         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9524         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9525         mono_mb_emit_icon (mb, 1);
9526         mono_mb_emit_byte (mb, CEE_SUB);
9527         mono_mb_emit_icon (mb, sizeof (void*));
9528         mono_mb_emit_byte (mb, CEE_MUL);
9529         mono_mb_emit_byte (mb, CEE_ADD);
9530         mono_mb_emit_byte (mb, CEE_LDIND_I);
9531         
9532         mono_mb_emit_ldloc (mb, aklass);
9533         
9534         b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9535         
9536         copy_pos = mono_mb_get_label (mb);
9537         /* do_store */
9538         mono_mb_patch_branch (mb, b1);
9539         mono_mb_emit_ldloc (mb, array_slot_addr);
9540         mono_mb_emit_ldarg (mb, 2);
9541         mono_mb_emit_byte (mb, CEE_STIND_REF);
9542         
9543         mono_mb_emit_byte (mb, CEE_RET);
9544         
9545         /* the hard way */
9546         mono_mb_patch_branch (mb, b2);
9547         mono_mb_patch_branch (mb, b3);
9548         
9549         mono_mb_emit_ldarg (mb, 2);
9550         mono_mb_emit_ldloc (mb, aklass);
9551         mono_mb_emit_icall (mb, mono_object_isinst);
9552         
9553         b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
9554         mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
9555         mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9556         
9557         mono_mb_emit_byte (mb, CEE_RET);
9558 #endif
9559         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9560         ret = mono_mb_create (mb, sig, 4, info);
9561         mono_mb_free (mb);
9562
9563         return ret;
9564 }
9565
9566 /*
9567  * mono_marshal_get_gsharedvt_in_wrapper:
9568  *
9569  *   This wrapper handles calls from normal code to gsharedvt code.
9570  *
9571  * The wrapper info for the wrapper is a WrapperInfo structure.
9572  */
9573 MonoMethod*
9574 mono_marshal_get_gsharedvt_in_wrapper (void)
9575 {
9576         static MonoMethod* ret = NULL;
9577         MonoMethodSignature *sig;
9578         MonoMethodBuilder *mb;
9579         WrapperInfo *info;
9580
9581         if (ret)
9582                 return ret;
9583         
9584         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_in", MONO_WRAPPER_UNKNOWN);
9585         
9586         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
9587         sig->ret = &mono_defaults.void_class->byval_arg;
9588
9589 #ifndef DISABLE_JIT
9590         /*
9591          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
9592          */
9593         mono_mb_emit_byte (mb, CEE_RET);
9594 #endif
9595         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_IN);
9596         ret = mono_mb_create (mb, sig, 4, info);
9597         mono_mb_free (mb);
9598
9599         return ret;
9600 }
9601
9602 /*
9603  * mono_marshal_get_gsharedvt_out_wrapper:
9604  *
9605  *   This wrapper handles calls from gsharedvt code to normal code.
9606  *
9607  * The wrapper info for the wrapper is a WrapperInfo structure.
9608  */
9609 MonoMethod*
9610 mono_marshal_get_gsharedvt_out_wrapper (void)
9611 {
9612         static MonoMethod* ret = NULL;
9613         MonoMethodSignature *sig;
9614         MonoMethodBuilder *mb;
9615         WrapperInfo *info;
9616
9617         if (ret)
9618                 return ret;
9619         
9620         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_out", MONO_WRAPPER_UNKNOWN);
9621         
9622         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
9623         sig->ret = &mono_defaults.void_class->byval_arg;
9624
9625 #ifndef DISABLE_JIT
9626         /*
9627          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
9628          */
9629         mono_mb_emit_byte (mb, CEE_RET);
9630 #endif
9631         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_OUT);
9632         ret = mono_mb_create (mb, sig, 4, info);
9633         mono_mb_free (mb);
9634
9635         return ret;
9636 }
9637
9638 typedef struct {
9639         int rank;
9640         int elem_size;
9641         MonoMethod *method;
9642 } ArrayElemAddr;
9643
9644 /* LOCKING: vars accessed under the marshal lock */
9645 static ArrayElemAddr *elem_addr_cache = NULL;
9646 static int elem_addr_cache_size = 0;
9647 static int elem_addr_cache_next = 0;
9648
9649 /**
9650  * mono_marshal_get_array_address:
9651  * @rank: rank of the array type
9652  * @elem_size: size in bytes of an element of an array.
9653  *
9654  * Returns a MonoMethod that implements the code to get the address
9655  * of an element in a multi-dimenasional array of @rank dimensions.
9656  * The returned method takes an array as the first argument and then
9657  * @rank indexes for the @rank dimensions.
9658  * If ELEM_SIZE is 0, read the array size from the array object.
9659  */
9660 MonoMethod*
9661 mono_marshal_get_array_address (int rank, int elem_size)
9662 {
9663         MonoMethod *ret;
9664         MonoMethodBuilder *mb;
9665         MonoMethodSignature *sig;
9666         WrapperInfo *info;
9667         char *name;
9668         int i, bounds, ind, realidx;
9669         int branch_pos, *branch_positions;
9670         int cached;
9671
9672         ret = NULL;
9673         mono_marshal_lock ();
9674         for (i = 0; i < elem_addr_cache_next; ++i) {
9675                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
9676                         ret = elem_addr_cache [i].method;
9677                         break;
9678                 }
9679         }
9680         mono_marshal_unlock ();
9681         if (ret)
9682                 return ret;
9683
9684         branch_positions = g_new0 (int, rank);
9685
9686         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1 + rank);
9687
9688         /* void* address (void* array, int idx0, int idx1, int idx2, ...) */
9689         sig->ret = &mono_defaults.int_class->byval_arg;
9690         sig->params [0] = &mono_defaults.object_class->byval_arg;
9691         for (i = 0; i < rank; ++i) {
9692                 sig->params [i + 1] = &mono_defaults.int32_class->byval_arg;
9693         }
9694
9695         name = g_strdup_printf ("ElementAddr_%d", elem_size);
9696         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
9697         g_free (name);
9698         
9699 #ifndef DISABLE_JIT
9700         bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9701         ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9702         realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9703
9704         /* bounds = array->bounds; */
9705         mono_mb_emit_ldarg (mb, 0);
9706         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, bounds));
9707         mono_mb_emit_byte (mb, CEE_LDIND_I);
9708         mono_mb_emit_stloc (mb, bounds);
9709
9710         /* ind is the overall element index, realidx is the partial index in a single dimension */
9711         /* ind = idx0 - bounds [0].lower_bound */
9712         mono_mb_emit_ldarg (mb, 1);
9713         mono_mb_emit_ldloc (mb, bounds);
9714         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
9715         mono_mb_emit_byte (mb, CEE_ADD);
9716         mono_mb_emit_byte (mb, CEE_LDIND_I4);
9717         mono_mb_emit_byte (mb, CEE_SUB);
9718         mono_mb_emit_stloc (mb, ind);
9719         /* if (ind >= bounds [0].length) goto exeception; */
9720         mono_mb_emit_ldloc (mb, ind);
9721         mono_mb_emit_ldloc (mb, bounds);
9722         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
9723         mono_mb_emit_byte (mb, CEE_ADD);
9724         mono_mb_emit_byte (mb, CEE_LDIND_I4);
9725         /* note that we use unsigned comparison */
9726         branch_pos = mono_mb_emit_branch (mb, CEE_BGE_UN);
9727
9728         /* For large ranks (> 4?) use a loop n IL later to reduce code size.
9729          * We could also decide to ignore the passed elem_size and get it
9730          * from the array object, to reduce the number of methods we generate:
9731          * the additional cost is 3 memory loads and a non-immediate mul.
9732          */
9733         for (i = 1; i < rank; ++i) {
9734                 /* realidx = idxi - bounds [i].lower_bound */
9735                 mono_mb_emit_ldarg (mb, 1 + i);
9736                 mono_mb_emit_ldloc (mb, bounds);
9737                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
9738                 mono_mb_emit_byte (mb, CEE_ADD);
9739                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9740                 mono_mb_emit_byte (mb, CEE_SUB);
9741                 mono_mb_emit_stloc (mb, realidx);
9742                 /* if (realidx >= bounds [i].length) goto exeception; */
9743                 mono_mb_emit_ldloc (mb, realidx);
9744                 mono_mb_emit_ldloc (mb, bounds);
9745                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
9746                 mono_mb_emit_byte (mb, CEE_ADD);
9747                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9748                 branch_positions [i] = mono_mb_emit_branch (mb, CEE_BGE_UN);
9749                 /* ind = ind * bounds [i].length + realidx */
9750                 mono_mb_emit_ldloc (mb, ind);
9751                 mono_mb_emit_ldloc (mb, bounds);
9752                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
9753                 mono_mb_emit_byte (mb, CEE_ADD);
9754                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9755                 mono_mb_emit_byte (mb, CEE_MUL);
9756                 mono_mb_emit_ldloc (mb, realidx);
9757                 mono_mb_emit_byte (mb, CEE_ADD);
9758                 mono_mb_emit_stloc (mb, ind);
9759         }
9760
9761         /* return array->vector + ind * element_size */
9762         mono_mb_emit_ldarg (mb, 0);
9763         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
9764         mono_mb_emit_ldloc (mb, ind);
9765         if (elem_size) {
9766                 mono_mb_emit_icon (mb, elem_size);
9767         } else {
9768                 /* Load arr->vtable->klass->sizes.element_class */
9769                 mono_mb_emit_ldarg (mb, 0);
9770                 mono_mb_emit_byte (mb, CEE_CONV_I);
9771                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9772                 mono_mb_emit_byte (mb, CEE_ADD);
9773                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9774                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9775                 mono_mb_emit_byte (mb, CEE_ADD);
9776                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9777                 /* sizes is an union, so this reads sizes.element_size */
9778                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
9779                 mono_mb_emit_byte (mb, CEE_ADD);
9780                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9781         }
9782                 mono_mb_emit_byte (mb, CEE_MUL);
9783         mono_mb_emit_byte (mb, CEE_ADD);
9784         mono_mb_emit_byte (mb, CEE_RET);
9785
9786         /* patch the branches to get here and throw */
9787         for (i = 1; i < rank; ++i) {
9788                 mono_mb_patch_branch (mb, branch_positions [i]);
9789         }
9790         mono_mb_patch_branch (mb, branch_pos);
9791         /* throw exception */
9792         mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
9793
9794         g_free (branch_positions);
9795 #endif /* DISABLE_JIT */
9796
9797         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ELEMENT_ADDR);
9798         info->d.element_addr.rank = rank;
9799         info->d.element_addr.elem_size = elem_size;
9800         ret = mono_mb_create (mb, sig, 4, info);
9801         mono_mb_free (mb);
9802
9803         /* cache the result */
9804         cached = 0;
9805         mono_marshal_lock ();
9806         for (i = 0; i < elem_addr_cache_next; ++i) {
9807                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
9808                         /* FIXME: free ret */
9809                         ret = elem_addr_cache [i].method;
9810                         cached = TRUE;
9811                         break;
9812                 }
9813         }
9814         if (!cached) {
9815                 if (elem_addr_cache_next >= elem_addr_cache_size) {
9816                         int new_size = elem_addr_cache_size + 4;
9817                         ArrayElemAddr *new_array = g_new0 (ArrayElemAddr, new_size);
9818                         memcpy (new_array, elem_addr_cache, elem_addr_cache_size * sizeof (ArrayElemAddr));
9819                         g_free (elem_addr_cache);
9820                         elem_addr_cache = new_array;
9821                         elem_addr_cache_size = new_size;
9822                 }
9823                 elem_addr_cache [elem_addr_cache_next].rank = rank;
9824                 elem_addr_cache [elem_addr_cache_next].elem_size = elem_size;
9825                 elem_addr_cache [elem_addr_cache_next].method = ret;
9826                 elem_addr_cache_next ++;
9827         }
9828         mono_marshal_unlock ();
9829         return ret;
9830 }
9831
9832 /*
9833  * mono_marshal_get_array_accessor_wrapper:
9834  *
9835  *   Return a wrapper which just calls METHOD, which should be an Array Get/Set/Address method.
9836  */
9837 MonoMethod *
9838 mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
9839 {
9840         MonoMethodSignature *sig;
9841         MonoMethodBuilder *mb;
9842         MonoMethod *res;
9843         GHashTable *cache;
9844         int i;
9845         MonoGenericContext *ctx = NULL;
9846         MonoMethod *orig_method = NULL;
9847         MonoGenericContainer *container = NULL;
9848         WrapperInfo *info;
9849
9850         /*
9851          * These wrappers are needed to avoid the JIT replacing the calls to these methods with intrinsics
9852          * inside runtime invoke wrappers, thereby making the wrappers not unshareable.
9853          * FIXME: Use generic methods.
9854          */
9855         /*
9856          * Check cache
9857          */
9858         if (ctx) {
9859                 cache = NULL;
9860                 g_assert_not_reached ();
9861         } else {
9862                 cache = get_cache (&method->klass->image->array_accessor_cache, mono_aligned_addr_hash, NULL);
9863                 if ((res = mono_marshal_find_in_cache (cache, method)))
9864                         return res;
9865         }
9866
9867         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9868         sig->pinvoke = 0;
9869
9870         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
9871
9872 #ifndef DISABLE_JIT
9873         /* Call the method */
9874         if (sig->hasthis)
9875                 mono_mb_emit_ldarg (mb, 0);
9876         for (i = 0; i < sig->param_count; i++)
9877                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
9878
9879         if (ctx) {
9880                 MonoError error;
9881                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
9882                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9883         } else {
9884                 mono_mb_emit_managed_call (mb, method, NULL);
9885         }
9886         mono_mb_emit_byte (mb, CEE_RET);
9887 #endif
9888
9889         if (ctx) {
9890                 MonoMethod *def;
9891                 def = mono_mb_create_and_cache (cache, method, mb, sig, sig->param_count + 16);
9892                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
9893         } else {
9894                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ARRAY_ACCESSOR);
9895                 info->d.array_accessor.method = method;
9896
9897                 res = mono_mb_create_and_cache_full (cache, method,
9898                                                                                          mb, sig, sig->param_count + 16,
9899                                                                                          info, NULL);
9900         }
9901         mono_mb_free (mb);
9902
9903         return res;     
9904 }
9905
9906 void*
9907 mono_marshal_alloc (gulong size)
9908 {
9909         gpointer res;
9910
9911 #ifdef HOST_WIN32
9912         res = CoTaskMemAlloc (size);
9913 #else
9914         res = g_try_malloc ((gulong)size);
9915         if (!res)
9916                 mono_gc_out_of_memory ((gulong)size);
9917 #endif
9918         return res;
9919 }
9920
9921 void
9922 mono_marshal_free (gpointer ptr)
9923 {
9924 #ifdef HOST_WIN32
9925         CoTaskMemFree (ptr);
9926 #else
9927         g_free (ptr);
9928 #endif
9929 }
9930
9931 void
9932 mono_marshal_free_array (gpointer *ptr, int size) 
9933 {
9934         int i;
9935
9936         if (!ptr)
9937                 return;
9938
9939         for (i = 0; i < size; i++)
9940                 if (ptr [i])
9941                         g_free (ptr [i]);
9942 }
9943
9944 void *
9945 mono_marshal_string_to_utf16 (MonoString *s)
9946 {
9947         return s ? mono_string_chars (s) : NULL;
9948 }
9949
9950 static void *
9951 mono_marshal_string_to_utf16_copy (MonoString *s)
9952 {
9953         if (s == NULL) {
9954                 return NULL;
9955         } else {
9956                 gunichar2 *res = mono_marshal_alloc ((mono_string_length (s) * 2) + 2);
9957                 memcpy (res, mono_string_chars (s), mono_string_length (s) * 2);
9958                 res [mono_string_length (s)] = 0;
9959                 return res;
9960         }
9961 }
9962
9963 /**
9964  * mono_marshal_set_last_error:
9965  *
9966  * This function is invoked to set the last error value from a P/Invoke call
9967  * which has SetLastError set.
9968  */
9969 void
9970 mono_marshal_set_last_error (void)
9971 {
9972 #ifdef WIN32
9973         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
9974 #else
9975         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (errno));
9976 #endif
9977 }
9978
9979 static void
9980 mono_marshal_set_last_error_windows (int error)
9981 {
9982 #ifdef WIN32
9983         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (error));
9984 #endif
9985 }
9986
9987 void
9988 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
9989                                                                     gpointer dest, gint32 length)
9990 {
9991         int element_size;
9992         void *source_addr;
9993
9994         MONO_CHECK_ARG_NULL (src,);
9995         MONO_CHECK_ARG_NULL (dest,);
9996
9997         if (src->obj.vtable->klass->rank != 1) {
9998                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
9999                 return;
10000         }
10001         if (start_index < 0) {
10002                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10003                 return;
10004         }
10005         if (length < 0) {
10006                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10007                 return;
10008         }
10009         if (start_index + length > mono_array_length (src)) {
10010                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10011                 return;
10012         }
10013
10014         element_size = mono_array_element_size (src->obj.vtable->klass);
10015
10016         /* no references should be involved */
10017         source_addr = mono_array_addr_with_size_fast (src, element_size, start_index);
10018
10019         memcpy (dest, source_addr, length * element_size);
10020 }
10021
10022 void
10023 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
10024                                                                       MonoArray *dest, gint32 length)
10025 {
10026         int element_size;
10027         void *dest_addr;
10028
10029         MONO_CHECK_ARG_NULL (src,);
10030         MONO_CHECK_ARG_NULL (dest,);
10031
10032         if (dest->obj.vtable->klass->rank != 1) {
10033                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10034                 return;
10035         }
10036         if (start_index < 0) {
10037                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10038                 return;
10039         }
10040         if (length < 0) {
10041                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10042                 return;
10043         }
10044         if (start_index + length > mono_array_length (dest)) {
10045                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10046                 return;
10047         }
10048         element_size = mono_array_element_size (dest->obj.vtable->klass);
10049           
10050         /* no references should be involved */
10051         dest_addr = mono_array_addr_with_size_fast (dest, element_size, start_index);
10052
10053         memcpy (dest_addr, src, length * element_size);
10054 }
10055
10056 MonoString *
10057 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr)
10058 {
10059         if (ptr == NULL)
10060                 return NULL;
10061         else
10062                 return mono_string_new (mono_domain_get (), ptr);
10063 }
10064
10065 MonoString *
10066 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
10067 {
10068         if (ptr == NULL) {
10069                 mono_set_pending_exception (mono_get_exception_argument_null ("ptr"));
10070                 return NULL;
10071         } else {
10072                 return mono_string_new_len (mono_domain_get (), ptr, len);
10073         }
10074 }
10075
10076 MonoString *
10077 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
10078 {
10079         MonoDomain *domain = mono_domain_get (); 
10080         int len = 0;
10081         guint16 *t = ptr;
10082
10083         if (ptr == NULL)
10084                 return NULL;
10085
10086         while (*t++)
10087                 len++;
10088
10089         return mono_string_new_utf16 (domain, ptr, len);
10090 }
10091
10092 MonoString *
10093 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
10094 {
10095         MonoDomain *domain = mono_domain_get (); 
10096
10097         if (ptr == NULL) {
10098                 mono_set_pending_exception (mono_get_exception_argument_null ("ptr"));
10099                 return NULL;
10100         } else {
10101                 return mono_string_new_utf16 (domain, ptr, len);
10102         }
10103 }
10104
10105 guint32 
10106 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
10107 {
10108         return (GPOINTER_TO_INT (mono_native_tls_get_value (last_error_tls_id)));
10109 }
10110
10111 guint32 
10112 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionType *rtype)
10113 {
10114         MonoClass *klass;
10115         MonoType *type;
10116         guint32 layout;
10117
10118         MONO_CHECK_ARG_NULL (rtype, 0);
10119
10120         type = rtype->type;
10121         klass = mono_class_from_mono_type (type);
10122         if (!mono_class_init (klass)) {
10123                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10124                 return 0;
10125         }
10126
10127         layout = (klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK);
10128
10129         if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
10130                 return sizeof (gpointer);
10131         } else if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
10132                 gchar *msg;
10133                 MonoException *exc;
10134
10135                 msg = g_strdup_printf ("Type %s cannot be marshaled as an unmanaged structure.", klass->name);
10136                 exc = mono_get_exception_argument ("t", msg);
10137                 g_free (msg);
10138                 mono_set_pending_exception (exc);
10139                 return 0;
10140         }
10141
10142         return mono_class_native_size (klass, NULL);
10143 }
10144
10145 void
10146 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
10147 {
10148         MonoMethod *method;
10149         gpointer pa [3];
10150
10151         MONO_CHECK_ARG_NULL (obj,);
10152         MONO_CHECK_ARG_NULL (dst,);
10153
10154         method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
10155
10156         pa [0] = obj;
10157         pa [1] = &dst;
10158         pa [2] = &delete_old;
10159
10160         mono_runtime_invoke (method, NULL, pa, NULL);
10161 }
10162
10163 static void
10164 ptr_to_structure (gpointer src, MonoObject *dst)
10165 {
10166         MonoMethod *method;
10167         gpointer pa [2];
10168
10169         method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
10170
10171         pa [0] = &src;
10172         pa [1] = dst;
10173
10174         mono_runtime_invoke (method, NULL, pa, NULL);
10175 }
10176
10177 void
10178 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
10179 {
10180         MonoType *t;
10181
10182         MONO_CHECK_ARG_NULL (src,);
10183         MONO_CHECK_ARG_NULL (dst,);
10184         
10185         t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
10186
10187         if (t->type == MONO_TYPE_VALUETYPE) {
10188                 MonoException *exc;
10189                 gchar *tmp;
10190
10191                 tmp = g_strdup_printf ("Destination is a boxed value type.");
10192                 exc = mono_get_exception_argument ("dst", tmp);
10193                 g_free (tmp);  
10194
10195                 mono_set_pending_exception (exc);
10196                 return;
10197         }
10198
10199         ptr_to_structure (src, dst);
10200 }
10201
10202 MonoObject *
10203 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
10204 {
10205         MonoClass *klass;
10206         MonoDomain *domain = mono_domain_get (); 
10207         MonoObject *res;
10208
10209         if (src == NULL)
10210                 return NULL;
10211         MONO_CHECK_ARG_NULL (type, NULL);
10212
10213         klass = mono_class_from_mono_type (type->type);
10214         if (!mono_class_init (klass)) {
10215                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10216                 return NULL;
10217         }
10218
10219         res = mono_object_new (domain, klass);
10220
10221         ptr_to_structure (src, res);
10222
10223         return res;
10224 }
10225
10226 int
10227 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *type, MonoString *field_name)
10228 {
10229         MonoMarshalType *info;
10230         MonoClass *klass;
10231         char *fname;
10232         int match_index = -1;
10233         
10234         MONO_CHECK_ARG_NULL (type, 0);
10235         MONO_CHECK_ARG_NULL (field_name, 0);
10236
10237         fname = mono_string_to_utf8 (field_name);
10238         klass = mono_class_from_mono_type (type->type);
10239         if (!mono_class_init (klass)) {
10240                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10241                 return 0;
10242         }
10243
10244         while (klass && match_index == -1) {
10245                 MonoClassField* field;
10246                 int i = 0;
10247                 gpointer iter = NULL;
10248                 while ((field = mono_class_get_fields (klass, &iter))) {
10249                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10250                                 continue;
10251                         if (!strcmp (fname, mono_field_get_name (field))) {
10252                                 match_index = i;
10253                                 break;
10254                         }
10255                         i ++;
10256                 }
10257
10258                 if (match_index == -1)
10259                         klass = klass->parent;
10260         }
10261
10262         g_free (fname);
10263
10264         if(match_index == -1) {
10265                 MonoException* exc;
10266                 gchar *tmp;
10267
10268                 /* Get back original class instance */
10269                 klass = mono_class_from_mono_type (type->type);
10270
10271                 tmp = g_strdup_printf ("Field passed in is not a marshaled member of the type %s", klass->name);
10272                 exc = mono_get_exception_argument ("fieldName", tmp);
10273                 g_free (tmp);
10274  
10275                 mono_set_pending_exception ((MonoException*)exc);
10276                 return 0;
10277         }
10278
10279         info = mono_marshal_load_type_info (klass);     
10280         return info->fields [match_index].offset;
10281 }
10282
10283 gpointer
10284 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
10285 {
10286 #ifdef HOST_WIN32
10287         char* tres, *ret;
10288         size_t len;
10289         tres = mono_string_to_utf8 (string);
10290         if (!tres)
10291                 return tres;
10292
10293         len = strlen (tres) + 1;
10294         ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len);
10295         memcpy (ret, tres, len);
10296         g_free (tres);
10297         return ret;
10298
10299 #else
10300         return mono_string_to_utf8 (string);
10301 #endif
10302 }
10303
10304 gpointer
10305 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
10306 {
10307         if (string == NULL)
10308                 return NULL;
10309         else {
10310 #ifdef TARGET_WIN32
10311                 gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal 
10312                         ((mono_string_length (string) + 1) * 2);
10313 #else
10314                 gunichar2 *res = g_malloc ((mono_string_length (string) + 1) * 2);              
10315 #endif
10316                 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
10317                 res [mono_string_length (string)] = 0;
10318                 return res;
10319         }
10320 }
10321
10322 static void
10323 mono_struct_delete_old (MonoClass *klass, char *ptr)
10324 {
10325         MonoMarshalType *info;
10326         int i;
10327
10328         info = mono_marshal_load_type_info (klass);
10329
10330         for (i = 0; i < info->num_fields; i++) {
10331                 MonoMarshalConv conv;
10332                 MonoType *ftype = info->fields [i].field->type;
10333                 char *cpos;
10334
10335                 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
10336                         continue;
10337
10338                 mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, 
10339                                 klass->unicode, &conv);
10340                         
10341                 cpos = ptr + info->fields [i].offset;
10342
10343                 switch (conv) {
10344                 case MONO_MARSHAL_CONV_NONE:
10345                         if (MONO_TYPE_ISSTRUCT (ftype)) {
10346                                 mono_struct_delete_old (ftype->data.klass, cpos);
10347                                 continue;
10348                         }
10349                         break;
10350                 case MONO_MARSHAL_CONV_STR_LPWSTR:
10351                         /* We assume this field points inside a MonoString */
10352                         break;
10353                 case MONO_MARSHAL_CONV_STR_LPTSTR:
10354 #ifdef TARGET_WIN32
10355                         /* We assume this field points inside a MonoString 
10356                          * on Win32 */
10357                         break;
10358 #endif
10359                 case MONO_MARSHAL_CONV_STR_LPSTR:
10360                 case MONO_MARSHAL_CONV_STR_BSTR:
10361                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
10362                 case MONO_MARSHAL_CONV_STR_TBSTR:
10363                         mono_marshal_free (*(gpointer *)cpos);
10364                         break;
10365
10366                 default:
10367                         continue;
10368                 }
10369         }
10370 }
10371
10372 void
10373 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
10374 {
10375         MonoClass *klass;
10376
10377         MONO_CHECK_ARG_NULL (src,);
10378         MONO_CHECK_ARG_NULL (type,);
10379
10380         klass = mono_class_from_mono_type (type->type);
10381         if (!mono_class_init (klass)) {
10382                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10383                 return;
10384         }
10385
10386         mono_struct_delete_old (klass, (char *)src);
10387 }
10388
10389 void*
10390 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (int size)
10391 {
10392         gpointer res;
10393
10394         if ((gulong)size == 0)
10395                 /* This returns a valid pointer for size 0 on MS.NET */
10396                 size = 4;
10397
10398 #ifdef HOST_WIN32
10399         res = GlobalAlloc (GMEM_FIXED, (gulong)size);
10400 #else
10401         res = g_try_malloc ((gulong)size);
10402 #endif
10403         if (!res)
10404                 mono_gc_out_of_memory ((gulong)size);
10405
10406         return res;
10407 }
10408
10409 gpointer
10410 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, int size)
10411 {
10412         gpointer res;
10413
10414         if (ptr == NULL) {
10415                 mono_gc_out_of_memory ((gulong)size);
10416                 return NULL;
10417         }
10418
10419 #ifdef HOST_WIN32
10420         res = GlobalReAlloc (ptr, (gulong)size, GMEM_MOVEABLE);
10421 #else
10422         res = g_try_realloc (ptr, (gulong)size);
10423 #endif
10424         if (!res)
10425                 mono_gc_out_of_memory ((gulong)size);
10426
10427         return res;
10428 }
10429
10430 void
10431 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
10432 {
10433 #ifdef HOST_WIN32
10434         GlobalFree (ptr);
10435 #else
10436         g_free (ptr);
10437 #endif
10438 }
10439
10440 void*
10441 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
10442 {
10443         void *res;
10444
10445 #ifdef HOST_WIN32
10446         res = CoTaskMemAlloc (size);
10447 #else
10448         if ((gulong)size == 0)
10449                 /* This returns a valid pointer for size 0 on MS.NET */
10450                 size = 4;
10451
10452         res = g_try_malloc ((gulong)size);
10453 #endif
10454         if (!res)
10455                 mono_gc_out_of_memory ((gulong)size);
10456         return res;
10457 }
10458
10459 void
10460 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
10461 {
10462 #ifdef HOST_WIN32
10463         CoTaskMemFree (ptr);
10464 #else
10465         g_free (ptr);
10466 #endif
10467 }
10468
10469 gpointer
10470 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
10471 {
10472         void *res;
10473
10474 #ifdef HOST_WIN32
10475         res = CoTaskMemRealloc (ptr, size);
10476 #else
10477         res = g_try_realloc (ptr, (gulong)size);
10478 #endif
10479         if (!res)
10480                 mono_gc_out_of_memory ((gulong)size);
10481         return res;
10482 }
10483
10484 void*
10485 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
10486 {
10487         return mono_array_addr_with_size_fast (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
10488 }
10489
10490 MonoDelegate*
10491 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionType *type)
10492 {
10493         MonoClass *klass = mono_type_get_class (type->type);
10494         if (!mono_class_init (klass)) {
10495                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10496                 return NULL;
10497         }
10498
10499         return mono_ftnptr_to_delegate (klass, ftn);
10500 }
10501
10502 /**
10503  * mono_marshal_is_loading_type_info:
10504  *
10505  *  Return whenever mono_marshal_load_type_info () is being executed for KLASS by this
10506  * thread.
10507  */
10508 static gboolean
10509 mono_marshal_is_loading_type_info (MonoClass *klass)
10510 {
10511         GSList *loads_list = mono_native_tls_get_value (load_type_info_tls_id);
10512
10513         return g_slist_find (loads_list, klass) != NULL;
10514 }
10515
10516 /**
10517  * mono_marshal_load_type_info:
10518  *
10519  *  Initialize klass->marshal_info using information from metadata. This function can
10520  * recursively call itself, and the caller is responsible to avoid that by calling 
10521  * mono_marshal_is_loading_type_info () beforehand.
10522  *
10523  * LOCKING: Acquires the loader lock.
10524  */
10525 MonoMarshalType *
10526 mono_marshal_load_type_info (MonoClass* klass)
10527 {
10528         int j, count = 0;
10529         guint32 native_size = 0, min_align = 1, packing;
10530         MonoMarshalType *info;
10531         MonoClassField* field;
10532         gpointer iter;
10533         guint32 layout;
10534         GSList *loads_list;
10535
10536         g_assert (klass != NULL);
10537
10538         if (klass->marshal_info)
10539                 return klass->marshal_info;
10540
10541         if (!klass->inited)
10542                 mono_class_init (klass);
10543
10544         if (klass->marshal_info)
10545                 return klass->marshal_info;
10546
10547         /*
10548          * This function can recursively call itself, so we keep the list of classes which are
10549          * under initialization in a TLS list.
10550          */
10551         g_assert (!mono_marshal_is_loading_type_info (klass));
10552         loads_list = mono_native_tls_get_value (load_type_info_tls_id);
10553         loads_list = g_slist_prepend (loads_list, klass);
10554         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
10555         
10556         iter = NULL;
10557         while ((field = mono_class_get_fields (klass, &iter))) {
10558                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10559                         continue;
10560                 if (mono_field_is_deleted (field))
10561                         continue;
10562                 count++;
10563         }
10564
10565         layout = klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
10566
10567         /* The mempool is protected by the loader lock */
10568         info = mono_image_alloc0 (klass->image, MONO_SIZEOF_MARSHAL_TYPE + sizeof (MonoMarshalField) * count);
10569         info->num_fields = count;
10570         
10571         /* Try to find a size for this type in metadata */
10572         mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
10573
10574         if (klass->parent) {
10575                 int parent_size = mono_class_native_size (klass->parent, NULL);
10576
10577                 /* Add parent size to real size */
10578                 native_size += parent_size;
10579                 info->native_size = parent_size;
10580         }
10581
10582         packing = klass->packing_size ? klass->packing_size : 8;
10583         iter = NULL;
10584         j = 0;
10585         while ((field = mono_class_get_fields (klass, &iter))) {
10586                 int size;
10587                 guint32 align;
10588                 
10589                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10590                         continue;
10591
10592                 if (mono_field_is_deleted (field))
10593                         continue;
10594                 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
10595                         mono_metadata_field_info_with_mempool (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1, 
10596                                                   NULL, NULL, &info->fields [j].mspec);
10597
10598                 info->fields [j].field = field;
10599
10600                 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
10601                         (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
10602                         /* This field is a hack inserted by MCS to empty structures */
10603                         continue;
10604                 }
10605
10606                 switch (layout) {
10607                 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
10608                 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
10609                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
10610                                                        &align, TRUE, klass->unicode);
10611                         align = klass->packing_size ? MIN (klass->packing_size, align): align;
10612                         min_align = MAX (align, min_align);
10613                         info->fields [j].offset = info->native_size;
10614                         info->fields [j].offset += align - 1;
10615                         info->fields [j].offset &= ~(align - 1);
10616                         info->native_size = info->fields [j].offset + size;
10617                         break;
10618                 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
10619                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
10620                                                        &align, TRUE, klass->unicode);
10621                         min_align = MAX (align, min_align);
10622                         info->fields [j].offset = field->offset - sizeof (MonoObject);
10623                         info->native_size = MAX (info->native_size, info->fields [j].offset + size);
10624                         break;
10625                 }       
10626                 j++;
10627         }
10628
10629         if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
10630                 info->native_size = MAX (native_size, info->native_size);
10631                 /*
10632                  * If the provided Size is equal or larger than the calculated size, and there
10633                  * was no Pack attribute, we set min_align to 1 to avoid native_size being increased
10634                  */
10635                 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
10636                         if (native_size && native_size == info->native_size && klass->packing_size == 0)
10637                                 min_align = 1;
10638                         else
10639                                 min_align = MIN (min_align, packing);
10640                 }
10641         }
10642
10643         if (info->native_size & (min_align - 1)) {
10644                 info->native_size += min_align - 1;
10645                 info->native_size &= ~(min_align - 1);
10646         }
10647
10648         info->min_align = min_align;
10649
10650         /* Update the class's blittable info, if the layouts don't match */
10651         if (info->native_size != mono_class_value_size (klass, NULL))
10652                 klass->blittable = FALSE;
10653
10654         /* If this is an array type, ensure that we have element info */
10655         if (klass->rank && !mono_marshal_is_loading_type_info (klass->element_class)) {
10656                 mono_marshal_load_type_info (klass->element_class);
10657         }
10658
10659         loads_list = mono_native_tls_get_value (load_type_info_tls_id);
10660         loads_list = g_slist_remove (loads_list, klass);
10661         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
10662
10663         mono_marshal_lock ();
10664         if (!klass->marshal_info) {
10665                 /*We do double-checking locking on marshal_info */
10666                 mono_memory_barrier ();
10667                 klass->marshal_info = info;
10668         }
10669         mono_marshal_unlock ();
10670
10671         return klass->marshal_info;
10672 }
10673
10674 /**
10675  * mono_class_native_size:
10676  * @klass: a class 
10677  * 
10678  * Returns: the native size of an object instance (when marshaled 
10679  * to unmanaged code) 
10680  */
10681 gint32
10682 mono_class_native_size (MonoClass *klass, guint32 *align)
10683 {       
10684         if (!klass->marshal_info) {
10685                 if (mono_marshal_is_loading_type_info (klass)) {
10686                         if (align)
10687                                 *align = 0;
10688                         return 0;
10689                 } else {
10690                         mono_marshal_load_type_info (klass);
10691                 }
10692         }
10693
10694         if (align)
10695                 *align = klass->marshal_info->min_align;
10696
10697         return klass->marshal_info->native_size;
10698 }
10699
10700 /*
10701  * mono_type_native_stack_size:
10702  * @t: the type to return the size it uses on the stack
10703  *
10704  * Returns: the number of bytes required to hold an instance of this
10705  * type on the native stack
10706  */
10707 int
10708 mono_type_native_stack_size (MonoType *t, guint32 *align)
10709 {
10710         guint32 tmp;
10711
10712         g_assert (t != NULL);
10713
10714         if (!align)
10715                 align = &tmp;
10716
10717         if (t->byref) {
10718                 *align = sizeof (gpointer);
10719                 return sizeof (gpointer);
10720         }
10721
10722         switch (t->type){
10723         case MONO_TYPE_BOOLEAN:
10724         case MONO_TYPE_CHAR:
10725         case MONO_TYPE_I1:
10726         case MONO_TYPE_U1:
10727         case MONO_TYPE_I2:
10728         case MONO_TYPE_U2:
10729         case MONO_TYPE_I4:
10730         case MONO_TYPE_U4:
10731                 *align = 4;
10732                 return 4;
10733         case MONO_TYPE_I:
10734         case MONO_TYPE_U:
10735         case MONO_TYPE_STRING:
10736         case MONO_TYPE_OBJECT:
10737         case MONO_TYPE_CLASS:
10738         case MONO_TYPE_SZARRAY:
10739         case MONO_TYPE_PTR:
10740         case MONO_TYPE_FNPTR:
10741         case MONO_TYPE_ARRAY:
10742                 *align = sizeof (gpointer);
10743                 return sizeof (gpointer);
10744         case MONO_TYPE_R4:
10745                 *align = 4;
10746                 return 4;
10747         case MONO_TYPE_R8:
10748                 *align = MONO_ABI_ALIGNOF (double);
10749                 return 8;
10750         case MONO_TYPE_I8:
10751         case MONO_TYPE_U8:
10752                 *align = MONO_ABI_ALIGNOF (gint64);
10753                 return 8;
10754         case MONO_TYPE_GENERICINST:
10755                 if (!mono_type_generic_inst_is_valuetype (t)) {
10756                         *align = sizeof (gpointer);
10757                         return sizeof (gpointer);
10758                 } 
10759                 /* Fall through */
10760         case MONO_TYPE_TYPEDBYREF:
10761         case MONO_TYPE_VALUETYPE: {
10762                 guint32 size;
10763                 MonoClass *klass = mono_class_from_mono_type (t);
10764
10765                 if (klass->enumtype)
10766                         return mono_type_native_stack_size (mono_class_enum_basetype (klass), align);
10767                 else {
10768                         size = mono_class_native_size (klass, align);
10769                         *align = *align + 3;
10770                         *align &= ~3;
10771                         
10772                         size +=  3;
10773                         size &= ~3;
10774
10775                         return size;
10776                 }
10777         }
10778         default:
10779                 g_error ("type 0x%02x unknown", t->type);
10780         }
10781         return 0;
10782 }
10783
10784 gint32
10785 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
10786                         gboolean as_field, gboolean unicode)
10787 {
10788         MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
10789         MonoClass *klass;
10790
10791         switch (native_type) {
10792         case MONO_NATIVE_BOOLEAN:
10793                 *align = 4;
10794                 return 4;
10795         case MONO_NATIVE_I1:
10796         case MONO_NATIVE_U1:
10797                 *align = 1;
10798                 return 1;
10799         case MONO_NATIVE_I2:
10800         case MONO_NATIVE_U2:
10801         case MONO_NATIVE_VARIANTBOOL:
10802                 *align = 2;
10803                 return 2;
10804         case MONO_NATIVE_I4:
10805         case MONO_NATIVE_U4:
10806         case MONO_NATIVE_ERROR:
10807                 *align = 4;
10808                 return 4;
10809         case MONO_NATIVE_I8:
10810         case MONO_NATIVE_U8:
10811                 *align = MONO_ABI_ALIGNOF (gint64);
10812                 return 8;
10813         case MONO_NATIVE_R4:
10814                 *align = 4;
10815                 return 4;
10816         case MONO_NATIVE_R8:
10817                 *align = MONO_ABI_ALIGNOF (double);
10818                 return 8;
10819         case MONO_NATIVE_INT:
10820         case MONO_NATIVE_UINT:
10821         case MONO_NATIVE_LPSTR:
10822         case MONO_NATIVE_LPWSTR:
10823         case MONO_NATIVE_LPTSTR:
10824         case MONO_NATIVE_BSTR:
10825         case MONO_NATIVE_ANSIBSTR:
10826         case MONO_NATIVE_TBSTR:
10827         case MONO_NATIVE_LPARRAY:
10828         case MONO_NATIVE_SAFEARRAY:
10829         case MONO_NATIVE_IUNKNOWN:
10830         case MONO_NATIVE_IDISPATCH:
10831         case MONO_NATIVE_INTERFACE:
10832         case MONO_NATIVE_ASANY:
10833         case MONO_NATIVE_FUNC:
10834         case MONO_NATIVE_LPSTRUCT:
10835                 *align = MONO_ABI_ALIGNOF (gpointer);
10836                 return sizeof (gpointer);
10837         case MONO_NATIVE_STRUCT: 
10838                 klass = mono_class_from_mono_type (type);
10839                 if (klass == mono_defaults.object_class &&
10840                         (mspec && mspec->native == MONO_NATIVE_STRUCT)) {
10841                 *align = 16;
10842                 return 16;
10843                 }
10844                 return mono_class_native_size (klass, align);
10845         case MONO_NATIVE_BYVALTSTR: {
10846                 int esize = unicode ? 2: 1;
10847                 g_assert (mspec);
10848                 *align = esize;
10849                 return mspec->data.array_data.num_elem * esize;
10850         }
10851         case MONO_NATIVE_BYVALARRAY: {
10852                 // FIXME: Have to consider ArraySubType
10853                 int esize;
10854                 klass = mono_class_from_mono_type (type);
10855                 if (klass->element_class == mono_defaults.char_class) {
10856                         esize = unicode ? 2 : 1;
10857                         *align = esize;
10858                 } else {
10859                         esize = mono_class_native_size (klass->element_class, align);
10860                 }
10861                 g_assert (mspec);
10862                 return mspec->data.array_data.num_elem * esize;
10863         }
10864         case MONO_NATIVE_CUSTOM:
10865                 *align = sizeof (gpointer);
10866                 return sizeof (gpointer);
10867                 break;
10868         case MONO_NATIVE_CURRENCY:
10869         case MONO_NATIVE_VBBYREFSTR:
10870         default:
10871                 g_error ("native type %02x not implemented", native_type); 
10872                 break;
10873         }
10874         g_assert_not_reached ();
10875         return 0;
10876 }
10877
10878 gpointer
10879 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
10880 {
10881         MonoType *t;
10882         MonoClass *klass;
10883
10884         if (o == NULL)
10885                 return NULL;
10886
10887         t = &o->vtable->klass->byval_arg;
10888         switch (t->type) {
10889         case MONO_TYPE_I4:
10890         case MONO_TYPE_U4:
10891         case MONO_TYPE_PTR:
10892         case MONO_TYPE_I1:
10893         case MONO_TYPE_U1:
10894         case MONO_TYPE_BOOLEAN:
10895         case MONO_TYPE_I2:
10896         case MONO_TYPE_U2:
10897         case MONO_TYPE_CHAR:
10898         case MONO_TYPE_I8:
10899         case MONO_TYPE_U8:
10900         case MONO_TYPE_R4:
10901         case MONO_TYPE_R8:
10902                 return mono_object_unbox (o);
10903                 break;
10904         case MONO_TYPE_STRING:
10905                 switch (string_encoding) {
10906                 case MONO_NATIVE_LPWSTR:
10907                         return mono_marshal_string_to_utf16_copy ((MonoString*)o);
10908                         break;
10909                 case MONO_NATIVE_LPSTR:
10910                         return mono_string_to_lpstr ((MonoString*)o);
10911                         break;
10912                 default:
10913                         g_warning ("marshaling conversion %d not implemented", string_encoding);
10914                         g_assert_not_reached ();
10915                 }
10916                 break;
10917         case MONO_TYPE_CLASS:
10918         case MONO_TYPE_VALUETYPE: {
10919                 MonoMethod *method;
10920                 gpointer pa [3];
10921                 gpointer res;
10922                 MonoBoolean delete_old = FALSE;
10923
10924                 klass = t->data.klass;
10925
10926                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
10927                         break;
10928
10929                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
10930                         klass->blittable || klass->enumtype))
10931                         return mono_object_unbox (o);
10932
10933                 res = mono_marshal_alloc (mono_class_native_size (klass, NULL));
10934
10935                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
10936                         method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
10937
10938                         pa [0] = o;
10939                         pa [1] = &res;
10940                         pa [2] = &delete_old;
10941
10942                         mono_runtime_invoke (method, NULL, pa, NULL);
10943                 }
10944
10945                 return res;
10946         }
10947         default:
10948                 break;
10949         }
10950         mono_raise_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
10951         return NULL;
10952 }
10953
10954 void
10955 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
10956 {
10957         MonoType *t;
10958         MonoClass *klass;
10959
10960         if (o == NULL)
10961                 return;
10962
10963         t = &o->vtable->klass->byval_arg;
10964         switch (t->type) {
10965         case MONO_TYPE_STRING:
10966                 switch (string_encoding) {
10967                 case MONO_NATIVE_LPWSTR:
10968                 case MONO_NATIVE_LPSTR:
10969                         mono_marshal_free (ptr);
10970                         break;
10971                 default:
10972                         g_warning ("marshaling conversion %d not implemented", string_encoding);
10973                         g_assert_not_reached ();
10974                 }
10975                 break;
10976         case MONO_TYPE_CLASS:
10977         case MONO_TYPE_VALUETYPE: {
10978                 klass = t->data.klass;
10979
10980                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
10981                                                                  klass->blittable || klass->enumtype))
10982                         break;
10983
10984                 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
10985                         MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
10986                         gpointer pa [2];
10987
10988                         pa [0] = &ptr;
10989                         pa [1] = o;
10990
10991                         mono_runtime_invoke (method, NULL, pa, NULL);
10992                 }
10993
10994                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
10995                         mono_struct_delete_old (klass, ptr);
10996                 }
10997
10998                 mono_marshal_free (ptr);
10999                 break;
11000         }
11001         default:
11002                 break;
11003         }
11004 }
11005
11006 MonoMethod *
11007 mono_marshal_get_generic_array_helper (MonoClass *class, MonoClass *iface, gchar *name, MonoMethod *method)
11008 {
11009         MonoMethodSignature *sig, *csig;
11010         MonoMethodBuilder *mb;
11011         MonoMethod *res;
11012         WrapperInfo *info;
11013         int i;
11014
11015         mb = mono_mb_new_no_dup_name (class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
11016         mb->method->slot = -1;
11017
11018         mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
11019                 METHOD_ATTRIBUTE_NEW_SLOT | METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
11020
11021         sig = mono_method_signature (method);
11022         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
11023         csig->generic_param_count = 0;
11024
11025 #ifndef DISABLE_JIT
11026         mono_mb_emit_ldarg (mb, 0);
11027         for (i = 0; i < csig->param_count; i++)
11028                 mono_mb_emit_ldarg (mb, i + 1);
11029         mono_mb_emit_managed_call (mb, method, NULL);
11030         mono_mb_emit_byte (mb, CEE_RET);
11031
11032         /* We can corlib internal methods */
11033         mb->skip_visibility = TRUE;
11034 #endif
11035         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER);
11036         info->d.generic_array_helper.method = method;
11037         res = mono_mb_create (mb, csig, csig->param_count + 16, info);
11038
11039         mono_mb_free (mb);
11040
11041         return res;
11042 }
11043
11044 /*
11045  * The mono_win32_compat_* functions are implementations of inline
11046  * Windows kernel32 APIs, which are DllImport-able under MS.NET,
11047  * although not exported by kernel32.
11048  *
11049  * We map the appropiate kernel32 entries to these functions using
11050  * dllmaps declared in the global etc/mono/config.
11051  */
11052
11053 void
11054 mono_win32_compat_CopyMemory (gpointer dest, gconstpointer source, gsize length)
11055 {
11056         if (!dest || !source)
11057                 return;
11058
11059         memcpy (dest, source, length);
11060 }
11061
11062 void
11063 mono_win32_compat_FillMemory (gpointer dest, gsize length, guchar fill)
11064 {
11065         memset (dest, fill, length);
11066 }
11067
11068 void
11069 mono_win32_compat_MoveMemory (gpointer dest, gconstpointer source, gsize length)
11070 {
11071         if (!dest || !source)
11072                 return;
11073
11074         memmove (dest, source, length);
11075 }
11076
11077 void
11078 mono_win32_compat_ZeroMemory (gpointer dest, gsize length)
11079 {
11080         memset (dest, 0, length);
11081 }
11082
11083 void
11084 mono_marshal_find_nonzero_bit_offset (guint8 *buf, int len, int *byte_offset, guint8 *bitmask)
11085 {
11086         int i;
11087         guint8 byte;
11088
11089         for (i = 0; i < len; ++i)
11090                 if (buf [i])
11091                         break;
11092
11093         g_assert (i < len);
11094
11095         byte = buf [i];
11096         while (byte && !(byte & 1))
11097                 byte >>= 1;
11098         g_assert (byte == 1);
11099
11100         *byte_offset = i;
11101         *bitmask = buf [i];
11102 }
11103
11104 MonoMethod *
11105 mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
11106 {
11107         MonoMethodBuilder *mb;
11108         MonoMethodSignature *sig, *csig;
11109         MonoExceptionClause *clause;
11110         MonoImage *image;
11111         MonoClass *klass;
11112         GHashTable *cache;
11113         MonoMethod *res;
11114         int i, param_count, sig_size, pos_leave;
11115 #ifdef USE_COOP_GC
11116         int coop_gc_var;
11117 #endif
11118
11119         g_assert (method);
11120
11121         klass = method->klass;
11122         image = method->klass->image;
11123
11124         cache = get_cache (&mono_method_get_wrapper_cache (method)->thunk_invoke_cache, mono_aligned_addr_hash, NULL);
11125
11126
11127         if ((res = mono_marshal_find_in_cache (cache, method)))
11128                 return res;
11129
11130         sig = mono_method_signature (method);
11131         mb = mono_mb_new (klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
11132
11133         /* add "this" and exception param */
11134         param_count = sig->param_count + sig->hasthis + 1;
11135
11136         /* dup & extend signature */
11137         csig = mono_metadata_signature_alloc (image, param_count);
11138         sig_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *);
11139         memcpy (csig, sig, sig_size);
11140         csig->param_count = param_count;
11141         csig->hasthis = 0;
11142         csig->pinvoke = 1;
11143         csig->call_convention = MONO_CALL_DEFAULT;
11144
11145         if (sig->hasthis) {
11146                 /* add "this" */
11147                 csig->params [0] = &klass->byval_arg;
11148                 /* move params up by one */
11149                 for (i = 0; i < sig->param_count; i++)
11150                         csig->params [i + 1] = sig->params [i];
11151         }
11152
11153         /* setup exception param as byref+[out] */
11154         csig->params [param_count - 1] = mono_metadata_type_dup (image,
11155                  &mono_defaults.exception_class->byval_arg);
11156         csig->params [param_count - 1]->byref = 1;
11157         csig->params [param_count - 1]->attrs = PARAM_ATTRIBUTE_OUT;
11158
11159         /* convert struct return to object */
11160         if (MONO_TYPE_ISSTRUCT (sig->ret))
11161                 csig->ret = &mono_defaults.object_class->byval_arg;
11162
11163 #ifndef DISABLE_JIT
11164         /* local 0 (temp for exception object) */
11165         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
11166
11167         /* local 1 (temp for result) */
11168         if (!MONO_TYPE_IS_VOID (sig->ret))
11169                 mono_mb_add_local (mb, sig->ret);
11170
11171 #ifdef USE_COOP_GC
11172         /* local 4, the local to be used when calling the reset_blocking funcs */
11173         /* tons of code hardcode 3 to be the return var */
11174         coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
11175 #endif
11176
11177         /* clear exception arg */
11178         mono_mb_emit_ldarg (mb, param_count - 1);
11179         mono_mb_emit_byte (mb, CEE_LDNULL);
11180         mono_mb_emit_byte (mb, CEE_STIND_REF);
11181
11182 #ifdef USE_COOP_GC
11183         /* FIXME this is technically wrong as the callback itself must be executed in gc unsafe context. */
11184         mono_mb_emit_icall (mb, mono_threads_reset_blocking_start);
11185         mono_mb_emit_stloc (mb, coop_gc_var);
11186 #endif
11187
11188         /* try */
11189         clause = mono_image_alloc0 (image, sizeof (MonoExceptionClause));
11190         clause->try_offset = mono_mb_get_label (mb);
11191
11192         /* push method's args */
11193         for (i = 0; i < param_count - 1; i++) {
11194                 MonoType *type;
11195                 MonoClass *klass;
11196
11197                 mono_mb_emit_ldarg (mb, i);
11198
11199                 /* get the byval type of the param */
11200                 klass = mono_class_from_mono_type (csig->params [i]);
11201                 type = &klass->byval_arg;
11202
11203                 /* unbox struct args */
11204                 if (MONO_TYPE_ISSTRUCT (type)) {
11205                         mono_mb_emit_op (mb, CEE_UNBOX, klass);
11206
11207                         /* byref args & and the "this" arg must remain a ptr.
11208                            Otherwise make a copy of the value type */
11209                         if (!(csig->params [i]->byref || (i == 0 && sig->hasthis)))
11210                                 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
11211
11212                         csig->params [i] = &mono_defaults.object_class->byval_arg;
11213                 }
11214         }
11215
11216         /* call */
11217         if (method->flags & METHOD_ATTRIBUTE_VIRTUAL)
11218                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
11219         else
11220                 mono_mb_emit_op (mb, CEE_CALL, method);
11221
11222         /* save result at local 1 */
11223         if (!MONO_TYPE_IS_VOID (sig->ret))
11224                 mono_mb_emit_stloc (mb, 1);
11225
11226         pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
11227
11228         /* catch */
11229         clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
11230         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
11231         clause->data.catch_class = mono_defaults.object_class;
11232
11233         clause->handler_offset = mono_mb_get_label (mb);
11234
11235         /* store exception at local 0 */
11236         mono_mb_emit_stloc (mb, 0);
11237         mono_mb_emit_ldarg (mb, param_count - 1);
11238         mono_mb_emit_ldloc (mb, 0);
11239         mono_mb_emit_byte (mb, CEE_STIND_REF);
11240         mono_mb_emit_branch (mb, CEE_LEAVE);
11241
11242         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
11243
11244         mono_mb_set_clauses (mb, 1, clause);
11245
11246         mono_mb_patch_branch (mb, pos_leave);
11247         /* end-try */
11248
11249         if (!MONO_TYPE_IS_VOID (sig->ret)) {
11250                 mono_mb_emit_ldloc (mb, 1);
11251
11252                 /* box the return value */
11253                 if (MONO_TYPE_ISSTRUCT (sig->ret))
11254                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
11255         }
11256
11257 #ifdef USE_COOP_GC
11258         /* XXX merge reset_blocking_end with detach */
11259         mono_mb_emit_ldloc (mb, coop_gc_var);
11260         mono_mb_emit_icall (mb, mono_threads_reset_blocking_end);
11261 #endif
11262
11263         mono_mb_emit_byte (mb, CEE_RET);
11264 #endif
11265
11266         res = mono_mb_create_and_cache (cache, method, mb, csig, param_count + 16);
11267         mono_mb_free (mb);
11268
11269         return res;
11270 }
11271
11272 /*
11273  * mono_marshal_free_dynamic_wrappers:
11274  *
11275  *   Free wrappers of the dynamic method METHOD.
11276  */
11277 void
11278 mono_marshal_free_dynamic_wrappers (MonoMethod *method)
11279 {
11280         MonoImage *image = method->klass->image;
11281
11282         g_assert (method_is_dynamic (method));
11283
11284         /* This could be called during shutdown */
11285         if (marshal_mutex_initialized)
11286                 mono_marshal_lock ();
11287         /* 
11288          * FIXME: We currently leak the wrappers. Freeing them would be tricky as
11289          * they could be shared with other methods ?
11290          */
11291         if (image->wrapper_caches.runtime_invoke_direct_cache)
11292                 g_hash_table_remove (image->wrapper_caches.runtime_invoke_direct_cache, method);
11293         if (image->wrapper_caches.delegate_abstract_invoke_cache)
11294                 g_hash_table_foreach_remove (image->wrapper_caches.delegate_abstract_invoke_cache, signature_pointer_pair_matches_pointer, method);
11295         // FIXME: Need to clear the caches in other images as well
11296         if (image->delegate_bound_static_invoke_cache)
11297                 g_hash_table_remove (image->delegate_bound_static_invoke_cache, mono_method_signature (method));
11298
11299         if (marshal_mutex_initialized)
11300                 mono_marshal_unlock ();
11301 }