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