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