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