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