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