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