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