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