4b49d2e9a9afe6f7223348456a68bd2544af108b
[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                 MONO_GC_REGISTER_ROOT_SINGLE (string_dummy, MONO_ROOT_SOURCE_MARSHAL, "dummy marshal string");
4032                 string_dummy = mono_string_new_wrapper ("dummy");
4033         }
4034
4035         if (virtual_) {
4036                 g_assert (sig->hasthis);
4037                 g_assert (method->flags & METHOD_ATTRIBUTE_VIRTUAL);
4038         }
4039
4040         if (sig->hasthis) {
4041                 if (string_ctor) {
4042                         if (mono_gc_is_moving ()) {
4043                                 mono_mb_emit_ptr (mb, &string_dummy);
4044                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
4045                         } else {
4046                                 mono_mb_emit_ptr (mb, string_dummy);
4047                         }
4048                 } else {
4049                         mono_mb_emit_ldarg (mb, 0);
4050                 }
4051         }
4052
4053         tmp_nullable_locals = g_new0 (int, sig->param_count);
4054
4055         for (i = 0; i < sig->param_count; i++) {
4056                 MonoType *t = sig->params [i];
4057                 int type;
4058
4059                 mono_mb_emit_ldarg (mb, 1);
4060                 if (i) {
4061                         mono_mb_emit_icon (mb, sizeof (gpointer) * i);
4062                         mono_mb_emit_byte (mb, CEE_ADD);
4063                 }
4064
4065                 if (t->byref) {
4066                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4067                         /* A Nullable<T> type don't have a boxed form, it's either null or a boxed T.
4068                          * So to make this work we unbox it to a local variablee and push a reference to that.
4069                          */
4070                         if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
4071                                 tmp_nullable_locals [i] = mono_mb_add_local (mb, &mono_class_from_mono_type (t)->byval_arg);
4072
4073                                 mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (t));
4074                                 mono_mb_emit_stloc (mb, tmp_nullable_locals [i]);
4075                                 mono_mb_emit_ldloc_addr (mb, tmp_nullable_locals [i]);
4076                         }
4077                         continue;
4078                 }
4079
4080                 /*FIXME 'this doesn't handle generic enums. Shouldn't we?*/
4081                 type = sig->params [i]->type;
4082 handle_enum:
4083                 switch (type) {
4084                 case MONO_TYPE_I1:
4085                 case MONO_TYPE_BOOLEAN:
4086                 case MONO_TYPE_U1:
4087                 case MONO_TYPE_I2:
4088                 case MONO_TYPE_U2:
4089                 case MONO_TYPE_CHAR:
4090                 case MONO_TYPE_I:
4091                 case MONO_TYPE_U:
4092                 case MONO_TYPE_I4:
4093                 case MONO_TYPE_U4:
4094                 case MONO_TYPE_R4:
4095                 case MONO_TYPE_R8:
4096                 case MONO_TYPE_I8:
4097                 case MONO_TYPE_U8:
4098                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4099                         mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
4100                         break;
4101                 case MONO_TYPE_STRING:
4102                 case MONO_TYPE_CLASS:  
4103                 case MONO_TYPE_ARRAY:
4104                 case MONO_TYPE_PTR:
4105                 case MONO_TYPE_SZARRAY:
4106                 case MONO_TYPE_OBJECT:
4107                         mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
4108                         break;
4109                 case MONO_TYPE_GENERICINST:
4110                         if (!mono_type_generic_inst_is_valuetype (sig->params [i])) {
4111                                 mono_mb_emit_byte (mb, mono_type_to_ldind (sig->params [i]));
4112                                 break;
4113                         }
4114
4115                         /* fall through */
4116                 case MONO_TYPE_VALUETYPE:
4117                         if (type == MONO_TYPE_VALUETYPE && t->data.klass->enumtype) {
4118                                 type = mono_class_enum_basetype (t->data.klass)->type;
4119                                 goto handle_enum;
4120                         }
4121                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4122                         if (mono_class_is_nullable (mono_class_from_mono_type (sig->params [i]))) {
4123                                 /* Need to convert a boxed vtype to an mp to a Nullable struct */
4124                                 mono_mb_emit_op (mb, CEE_UNBOX, mono_class_from_mono_type (sig->params [i]));
4125                                 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
4126                         } else {
4127                                 mono_mb_emit_op (mb, CEE_LDOBJ, mono_class_from_mono_type (sig->params [i]));
4128                         }
4129                         break;
4130                 default:
4131                         g_assert_not_reached ();
4132                 }
4133         }
4134         
4135         if (virtual_) {
4136                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
4137         } else if (need_direct_wrapper) {
4138                 mono_mb_emit_op (mb, CEE_CALL, method);
4139         } else {
4140                 mono_mb_emit_ldarg (mb, 3);
4141                 mono_mb_emit_calli (mb, callsig);
4142         }
4143
4144         if (sig->ret->byref) {
4145                 /* fixme: */
4146                 g_assert_not_reached ();
4147         }
4148
4149         switch (sig->ret->type) {
4150         case MONO_TYPE_VOID:
4151                 if (!string_ctor)
4152                         void_ret = TRUE;
4153                 break;
4154         case MONO_TYPE_BOOLEAN:
4155         case MONO_TYPE_CHAR:
4156         case MONO_TYPE_I1:
4157         case MONO_TYPE_U1:
4158         case MONO_TYPE_I2:
4159         case MONO_TYPE_U2:
4160         case MONO_TYPE_I4:
4161         case MONO_TYPE_U4:
4162         case MONO_TYPE_I:
4163         case MONO_TYPE_U:
4164         case MONO_TYPE_R4:
4165         case MONO_TYPE_R8:
4166         case MONO_TYPE_I8:
4167         case MONO_TYPE_U8:
4168         case MONO_TYPE_VALUETYPE:
4169         case MONO_TYPE_TYPEDBYREF:
4170         case MONO_TYPE_GENERICINST:
4171                 /* box value types */
4172                 mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
4173                 break;
4174         case MONO_TYPE_STRING:
4175         case MONO_TYPE_CLASS:  
4176         case MONO_TYPE_ARRAY:
4177         case MONO_TYPE_SZARRAY:
4178         case MONO_TYPE_OBJECT:
4179                 /* nothing to do */
4180                 break;
4181         case MONO_TYPE_PTR:
4182                 /* The result is an IntPtr */
4183                 mono_mb_emit_op (mb, CEE_BOX, mono_defaults.int_class);
4184                 break;
4185         default:
4186                 g_assert_not_reached ();
4187         }
4188
4189         if (!void_ret)
4190                 mono_mb_emit_stloc (mb, loc_res);
4191
4192         /* Convert back nullable-byref arguments */
4193         for (i = 0; i < sig->param_count; i++) {
4194                 MonoType *t = sig->params [i];
4195
4196                 /* 
4197                  * Box the result and put it back into the array, the caller will have
4198                  * to obtain it from there.
4199                  */
4200                 if (t->byref && t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
4201                         mono_mb_emit_ldarg (mb, 1);                     
4202                         mono_mb_emit_icon (mb, sizeof (gpointer) * i);
4203                         mono_mb_emit_byte (mb, CEE_ADD);
4204
4205                         mono_mb_emit_ldloc (mb, tmp_nullable_locals [i]);
4206                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
4207
4208                         mono_mb_emit_byte (mb, CEE_STIND_REF);
4209                 }
4210         }
4211
4212         g_free (tmp_nullable_locals);
4213 }
4214
4215 static void
4216 emit_runtime_invoke_body (MonoMethodBuilder *mb, MonoImage *image, MonoMethod *method,
4217                                                   MonoMethodSignature *sig, MonoMethodSignature *callsig,
4218                                                   gboolean virtual_, gboolean need_direct_wrapper)
4219 {
4220         gint32 labels [16];
4221         MonoExceptionClause *clause;
4222         int loc_res, loc_exc;
4223
4224         /* The wrapper looks like this:
4225          *
4226          * <interrupt check>
4227          * if (exc) {
4228          *       try {
4229          *         return <call>
4230          *       } catch (Exception e) {
4231          *     *exc = e;
4232          *   }
4233          * } else {
4234          *     return <call>
4235          * }
4236          */
4237
4238         /* allocate local 0 (object) tmp */
4239         loc_res = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4240         /* allocate local 1 (object) exc */
4241         loc_exc = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4242
4243         /* *exc is assumed to be initialized to NULL by the caller */
4244
4245         mono_mb_emit_byte (mb, CEE_LDARG_2);
4246         labels [0] = mono_mb_emit_branch (mb, CEE_BRFALSE);
4247
4248         /*
4249          * if (exc) case
4250          */
4251         labels [1] = mono_mb_get_label (mb);
4252         emit_thread_force_interrupt_checkpoint (mb);
4253         emit_invoke_call (mb, method, sig, callsig, loc_res, virtual_, need_direct_wrapper);
4254
4255         labels [2] = mono_mb_emit_branch (mb, CEE_LEAVE);
4256
4257         /* Add a try clause around the call */
4258         clause = (MonoExceptionClause *)mono_image_alloc0 (image, sizeof (MonoExceptionClause));
4259         clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
4260         clause->data.catch_class = mono_defaults.exception_class;
4261         clause->try_offset = labels [1];
4262         clause->try_len = mono_mb_get_label (mb) - labels [1];
4263
4264         clause->handler_offset = mono_mb_get_label (mb);
4265
4266         /* handler code */
4267         mono_mb_emit_stloc (mb, loc_exc);       
4268         mono_mb_emit_byte (mb, CEE_LDARG_2);
4269         mono_mb_emit_ldloc (mb, loc_exc);
4270         mono_mb_emit_byte (mb, CEE_STIND_REF);
4271
4272         mono_mb_emit_branch (mb, CEE_LEAVE);
4273
4274         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
4275
4276         mono_mb_set_clauses (mb, 1, clause);
4277
4278         mono_mb_patch_branch (mb, labels [2]);
4279         mono_mb_emit_ldloc (mb, loc_res);
4280         mono_mb_emit_byte (mb, CEE_RET);
4281
4282         /*
4283          * if (!exc) case
4284          */
4285         mono_mb_patch_branch (mb, labels [0]);
4286         emit_thread_force_interrupt_checkpoint (mb);
4287         emit_invoke_call (mb, method, sig, callsig, loc_res, virtual_, need_direct_wrapper);
4288
4289         mono_mb_emit_ldloc (mb, 0);
4290         mono_mb_emit_byte (mb, CEE_RET);
4291 }
4292 #endif
4293
4294 /**
4295  * mono_marshal_get_runtime_invoke:
4296  * Generates IL code for the runtime invoke function:
4297  *
4298  * <code>MonoObject *runtime_invoke (MonoObject *this_obj, void **params, MonoObject **exc, void* method)</code>
4299  *
4300  * We also catch exceptions if \p exc is not NULL.
4301  * If \p virtual is TRUE, then \p method is invoked virtually on \p this. This is useful since
4302  * it means that the compiled code for \p method does not have to be looked up 
4303  * before calling the runtime invoke wrapper. In this case, the wrapper ignores
4304  * its \p method argument.
4305  */
4306 MonoMethod *
4307 mono_marshal_get_runtime_invoke (MonoMethod *method, gboolean virtual_)
4308 {
4309         MonoMethodSignature *sig, *csig, *callsig;
4310         MonoMethodBuilder *mb;
4311         GHashTable *cache = NULL;
4312         MonoClass *target_klass;
4313         MonoMethod *res = NULL;
4314         static MonoMethodSignature *cctor_signature = NULL;
4315         static MonoMethodSignature *finalize_signature = NULL;
4316         char *name;
4317         const char *param_names [16];
4318         gboolean need_direct_wrapper = FALSE;
4319         WrapperInfo *info;
4320
4321         g_assert (method);
4322
4323         if (!cctor_signature) {
4324                 cctor_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4325                 cctor_signature->ret = &mono_defaults.void_class->byval_arg;
4326         }
4327         if (!finalize_signature) {
4328                 finalize_signature = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4329                 finalize_signature->ret = &mono_defaults.void_class->byval_arg;
4330                 finalize_signature->hasthis = 1;
4331         }
4332
4333         if (virtual_)
4334                 need_direct_wrapper = TRUE;
4335
4336         /* 
4337          * Use a separate cache indexed by methods to speed things up and to avoid the
4338          * boundless mempool growth caused by the signature_dup stuff below.
4339          */
4340         if (virtual_)
4341                 cache = get_cache (&method->klass->image->runtime_invoke_vcall_cache, mono_aligned_addr_hash, NULL);
4342         else
4343                 cache = get_cache (&mono_method_get_wrapper_cache (method)->runtime_invoke_direct_cache, mono_aligned_addr_hash, NULL);
4344
4345         res = mono_marshal_find_in_cache (cache, method);
4346         if (res)
4347                 return res;
4348                 
4349         if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
4350                 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
4351                 /* 
4352                  * Array Get/Set/Address methods. The JIT implements them using inline code
4353                  * so we need to create an invoke wrapper which calls the method directly.
4354                  */
4355                 need_direct_wrapper = TRUE;
4356         }
4357                 
4358         if (method->string_ctor) {
4359                 callsig = lookup_string_ctor_signature (mono_method_signature (method));
4360                 if (!callsig)
4361                         callsig = add_string_ctor_signature (method);
4362                 /* Can't share this as we push a string as this */
4363                 need_direct_wrapper = TRUE;
4364         } else {
4365                 if (method_is_dynamic (method))
4366                         callsig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
4367                 else
4368                         callsig = mono_method_signature (method);
4369         }
4370
4371         sig = mono_method_signature (method);
4372
4373         target_klass = get_wrapper_target_class (method->klass->image);
4374
4375         /* Try to share wrappers for non-corlib methods with simple signatures */
4376         if (mono_metadata_signature_equal (callsig, cctor_signature)) {
4377                 callsig = cctor_signature;
4378                 target_klass = mono_defaults.object_class;
4379         } else if (mono_metadata_signature_equal (callsig, finalize_signature)) {
4380                 callsig = finalize_signature;
4381                 target_klass = mono_defaults.object_class;
4382         }
4383
4384         if (need_direct_wrapper) {
4385                 /* Already searched at the start */
4386         } else {
4387                 MonoMethodSignature *tmp_sig;
4388
4389                 callsig = mono_marshal_get_runtime_invoke_sig (callsig);
4390                 GHashTable **cache_table = NULL;
4391
4392                 if (method->klass->valuetype && mono_method_signature (method)->hasthis)
4393                         cache_table = &mono_method_get_wrapper_cache (method)->runtime_invoke_vtype_cache;
4394                 else
4395                         cache_table = &mono_method_get_wrapper_cache (method)->runtime_invoke_cache;
4396
4397                 cache = get_cache (cache_table, (GHashFunc)mono_signature_hash,
4398                                                            (GCompareFunc)runtime_invoke_signature_equal);
4399
4400                 /* from mono_marshal_find_in_cache */
4401                 mono_marshal_lock ();
4402                 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4403                 mono_marshal_unlock ();
4404
4405                 if (res) {
4406                         g_free (callsig);
4407                         return res;
4408                 }
4409
4410                 /* Make a copy of the signature from the image mempool */
4411                 tmp_sig = callsig;
4412                 callsig = mono_metadata_signature_dup_full (target_klass->image, callsig);
4413                 g_free (tmp_sig);
4414         }
4415         
4416         csig = mono_metadata_signature_alloc (target_klass->image, 4);
4417
4418         csig->ret = &mono_defaults.object_class->byval_arg;
4419         if (method->klass->valuetype && mono_method_signature (method)->hasthis)
4420                 csig->params [0] = get_runtime_invoke_type (&method->klass->this_arg, FALSE);
4421         else
4422                 csig->params [0] = &mono_defaults.object_class->byval_arg;
4423         csig->params [1] = &mono_defaults.int_class->byval_arg;
4424         csig->params [2] = &mono_defaults.int_class->byval_arg;
4425         csig->params [3] = &mono_defaults.int_class->byval_arg;
4426         csig->pinvoke = 1;
4427 #if TARGET_WIN32
4428         /* This is called from runtime code so it has to be cdecl */
4429         csig->call_convention = MONO_CALL_C;
4430 #endif
4431
4432         name = mono_signature_to_name (callsig, virtual_ ? "runtime_invoke_virtual" : "runtime_invoke");
4433         mb = mono_mb_new (target_klass, name,  MONO_WRAPPER_RUNTIME_INVOKE);
4434         g_free (name);
4435
4436 #ifdef HAVE_ONLINE_VES
4437         param_names [0] = "this";
4438         param_names [1] = "params";
4439         param_names [2] = "exc";
4440         param_names [3] = "method";
4441         mono_mb_set_param_names (mb, param_names);
4442
4443         emit_runtime_invoke_body (mb, target_klass->image, method, sig, callsig, virtual_, need_direct_wrapper);
4444 #endif
4445
4446         if (need_direct_wrapper) {
4447 #ifdef HAVE_ONLINE_VES
4448                 mb->skip_visibility = 1;
4449 #endif
4450                 info = mono_wrapper_info_create (mb, virtual_ ? WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL : WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT);
4451                 info->d.runtime_invoke.method = method;
4452                 res = mono_mb_create_and_cache_full (cache, method, mb, csig, sig->param_count + 16, info, NULL);
4453         } else {
4454                 /* taken from mono_mb_create_and_cache */
4455                 mono_marshal_lock ();
4456                 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4457                 mono_marshal_unlock ();
4458
4459                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL);
4460                 info->d.runtime_invoke.sig = callsig;
4461
4462                 /* Somebody may have created it before us */
4463                 if (!res) {
4464                         MonoMethod *newm;
4465                         newm = mono_mb_create (mb, csig, sig->param_count + 16, info);
4466
4467                         mono_marshal_lock ();
4468                         res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4469                         if (!res) {
4470                                 GHashTable *direct_cache;
4471                                 res = newm;
4472                                 g_hash_table_insert (cache, callsig, res);
4473                                 /* Can't insert it into wrapper_hash since the key is a signature */
4474                                 direct_cache = mono_method_get_wrapper_cache (method)->runtime_invoke_direct_cache;
4475
4476                                 g_hash_table_insert (direct_cache, method, res);
4477                         } else {
4478                                 mono_free_method (newm);
4479                         }
4480                         mono_marshal_unlock ();
4481                 }
4482
4483                 /* end mono_mb_create_and_cache */
4484         }
4485
4486         mono_mb_free (mb);
4487
4488         return res;     
4489 }
4490
4491 /*
4492  * mono_marshal_get_runtime_invoke_dynamic:
4493  *
4494  *   Return a method which can be used to invoke managed methods from native code
4495  * dynamically.
4496  * The signature of the returned method is given by RuntimeInvokeDynamicFunction:
4497  * void runtime_invoke (void *args, MonoObject **exc, void *compiled_method)
4498  * ARGS should point to an architecture specific structure containing 
4499  * the arguments and space for the return value.
4500  * The other arguments are the same as for runtime_invoke (), except that
4501  * ARGS should contain the this argument too.
4502  * This wrapper serves the same purpose as the runtime-invoke wrappers, but there
4503  * is only one copy of it, which is useful in full-aot.
4504  */
4505 MonoMethod*
4506 mono_marshal_get_runtime_invoke_dynamic (void)
4507 {
4508         static MonoMethod *method;
4509         MonoMethodSignature *csig;
4510         MonoExceptionClause *clause;
4511         MonoMethodBuilder *mb;
4512         int pos;
4513         char *name;
4514         WrapperInfo *info;
4515
4516         if (method)
4517                 return method;
4518
4519         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
4520
4521         csig->ret = &mono_defaults.void_class->byval_arg;
4522         csig->params [0] = &mono_defaults.int_class->byval_arg;
4523         csig->params [1] = &mono_defaults.int_class->byval_arg;
4524         csig->params [2] = &mono_defaults.int_class->byval_arg;
4525         csig->params [3] = &mono_defaults.int_class->byval_arg;
4526
4527         name = g_strdup ("runtime_invoke_dynamic");
4528         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_RUNTIME_INVOKE);
4529         g_free (name);
4530
4531 #ifdef HAVE_ONLINE_VES
4532         /* allocate local 0 (object) tmp */
4533         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4534         /* allocate local 1 (object) exc */
4535         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4536
4537         /* cond set *exc to null */
4538         mono_mb_emit_byte (mb, CEE_LDARG_1);
4539         mono_mb_emit_byte (mb, CEE_BRFALSE_S);
4540         mono_mb_emit_byte (mb, 3);      
4541         mono_mb_emit_byte (mb, CEE_LDARG_1);
4542         mono_mb_emit_byte (mb, CEE_LDNULL);
4543         mono_mb_emit_byte (mb, CEE_STIND_REF);
4544
4545         emit_thread_force_interrupt_checkpoint (mb);
4546
4547         mono_mb_emit_byte (mb, CEE_LDARG_0);
4548         mono_mb_emit_byte (mb, CEE_LDARG_2);
4549         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4550         mono_mb_emit_byte (mb, CEE_MONO_DYN_CALL);
4551
4552         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
4553
4554         clause = (MonoExceptionClause *)mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
4555         clause->flags = MONO_EXCEPTION_CLAUSE_FILTER;
4556         clause->try_len = mono_mb_get_label (mb);
4557
4558         /* filter code */
4559         clause->data.filter_offset = mono_mb_get_label (mb);
4560         
4561         mono_mb_emit_byte (mb, CEE_POP);
4562         mono_mb_emit_byte (mb, CEE_LDARG_1);
4563         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
4564         mono_mb_emit_byte (mb, CEE_PREFIX1);
4565         mono_mb_emit_byte (mb, CEE_CGT_UN);
4566         mono_mb_emit_byte (mb, CEE_PREFIX1);
4567         mono_mb_emit_byte (mb, CEE_ENDFILTER);
4568
4569         clause->handler_offset = mono_mb_get_label (mb);
4570
4571         /* handler code */
4572         /* store exception */
4573         mono_mb_emit_stloc (mb, 1);
4574         
4575         mono_mb_emit_byte (mb, CEE_LDARG_1);
4576         mono_mb_emit_ldloc (mb, 1);
4577         mono_mb_emit_byte (mb, CEE_STIND_REF);
4578
4579         mono_mb_emit_byte (mb, CEE_LDNULL);
4580         mono_mb_emit_stloc (mb, 0);
4581
4582         mono_mb_emit_branch (mb, CEE_LEAVE);
4583
4584         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
4585
4586         mono_mb_set_clauses (mb, 1, clause);
4587
4588         /* return result */
4589         mono_mb_patch_branch (mb, pos);
4590         //mono_mb_emit_ldloc (mb, 0);
4591         mono_mb_emit_byte (mb, CEE_RET);
4592 #endif /* HAVE_ONLINE_VES */
4593
4594         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC);
4595
4596         mono_marshal_lock ();
4597         /* double-checked locking */
4598         if (!method)
4599                 method = mono_mb_create (mb, csig, 16, info);
4600
4601         mono_marshal_unlock ();
4602
4603         mono_mb_free (mb);
4604
4605         return method;
4606 }
4607
4608 /*
4609  * mono_marshal_get_runtime_invoke_for_sig:
4610  *
4611  *   Return a runtime invoke wrapper for a given signature.
4612  */
4613 MonoMethod *
4614 mono_marshal_get_runtime_invoke_for_sig (MonoMethodSignature *sig)
4615 {
4616         MonoMethodSignature *csig, *callsig;
4617         MonoMethodBuilder *mb;
4618         MonoImage *image;
4619         GHashTable *cache = NULL;
4620         GHashTable **cache_table = NULL;
4621         MonoMethod *res = NULL;
4622         char *name;
4623         const char *param_names [16];
4624         WrapperInfo *info;
4625
4626         /* A simplified version of mono_marshal_get_runtime_invoke */
4627
4628         image = mono_defaults.corlib;
4629
4630         callsig = mono_marshal_get_runtime_invoke_sig (sig);
4631
4632         cache_table = &image->wrapper_caches.runtime_invoke_sig_cache;
4633
4634         cache = get_cache (cache_table, (GHashFunc)mono_signature_hash,
4635                                            (GCompareFunc)runtime_invoke_signature_equal);
4636
4637         /* from mono_marshal_find_in_cache */
4638         mono_marshal_lock ();
4639         res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4640         mono_marshal_unlock ();
4641
4642         if (res) {
4643                 g_free (callsig);
4644                 return res;
4645         }
4646
4647         /* Make a copy of the signature from the image mempool */
4648         callsig = mono_metadata_signature_dup_full (image, callsig);
4649
4650         csig = mono_metadata_signature_alloc (image, 4);
4651         csig->ret = &mono_defaults.object_class->byval_arg;
4652         csig->params [0] = &mono_defaults.object_class->byval_arg;
4653         csig->params [1] = &mono_defaults.int_class->byval_arg;
4654         csig->params [2] = &mono_defaults.int_class->byval_arg;
4655         csig->params [3] = &mono_defaults.int_class->byval_arg;
4656         csig->pinvoke = 1;
4657 #if TARGET_WIN32
4658         /* This is called from runtime code so it has to be cdecl */
4659         csig->call_convention = MONO_CALL_C;
4660 #endif
4661
4662         name = mono_signature_to_name (callsig, "runtime_invoke_sig");
4663         mb = mono_mb_new (mono_defaults.object_class, name,  MONO_WRAPPER_RUNTIME_INVOKE);
4664         g_free (name);
4665
4666 #ifdef HAVE_ONLINE_VES
4667         param_names [0] = "this";
4668         param_names [1] = "params";
4669         param_names [2] = "exc";
4670         param_names [3] = "method";
4671         mono_mb_set_param_names (mb, param_names);
4672
4673         emit_runtime_invoke_body (mb, image, NULL, sig, callsig, FALSE, FALSE);
4674 #endif
4675
4676         /* taken from mono_mb_create_and_cache */
4677         mono_marshal_lock ();
4678         res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4679         mono_marshal_unlock ();
4680
4681         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL);
4682         info->d.runtime_invoke.sig = callsig;
4683
4684         /* Somebody may have created it before us */
4685         if (!res) {
4686                 MonoMethod *newm;
4687                 newm = mono_mb_create (mb, csig, sig->param_count + 16, info);
4688
4689                 mono_marshal_lock ();
4690                 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4691                 if (!res) {
4692                         res = newm;
4693                         g_hash_table_insert (cache, callsig, res);
4694                 } else {
4695                         mono_free_method (newm);
4696                 }
4697                 mono_marshal_unlock ();
4698         }
4699
4700         /* end mono_mb_create_and_cache */
4701
4702         mono_mb_free (mb);
4703
4704         return res;
4705 }
4706
4707 #ifdef HAVE_ONLINE_VES
4708 static void
4709 mono_mb_emit_auto_layout_exception (MonoMethodBuilder *mb, MonoClass *klass)
4710 {
4711         char *msg = g_strdup_printf ("The type `%s.%s' layout needs to be Sequential or Explicit",
4712                                      klass->name_space, klass->name);
4713
4714         mono_mb_emit_exception_marshal_directive (mb, msg);
4715 }
4716 #endif
4717
4718 /**
4719  * mono_marshal_get_icall_wrapper:
4720  * Generates IL code for the icall wrapper. The generated method
4721  * calls the unmanaged code in \p func.
4722  */
4723 MonoMethod *
4724 mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gconstpointer func, gboolean check_exceptions)
4725 {
4726         MonoMethodSignature *csig, *csig2;
4727         MonoMethodBuilder *mb;
4728         MonoMethod *res;
4729         int i;
4730         WrapperInfo *info;
4731         
4732         GHashTable *cache = get_cache (&mono_defaults.object_class->image->icall_wrapper_cache, mono_aligned_addr_hash, NULL);
4733         if ((res = mono_marshal_find_in_cache (cache, (gpointer) func)))
4734                 return res;
4735
4736         g_assert (sig->pinvoke);
4737
4738         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
4739
4740         mb->method->save_lmf = 1;
4741
4742         /* Add an explicit this argument */
4743         if (sig->hasthis)
4744                 csig2 = mono_metadata_signature_dup_add_this (mono_defaults.corlib, sig, mono_defaults.object_class);
4745         else
4746                 csig2 = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
4747
4748 #ifdef HAVE_ONLINE_VES
4749         if (sig->hasthis)
4750                 mono_mb_emit_byte (mb, CEE_LDARG_0);
4751
4752         for (i = 0; i < sig->param_count; i++)
4753                 mono_mb_emit_ldarg (mb, i + sig->hasthis);
4754
4755         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4756         mono_mb_emit_op (mb, CEE_MONO_JIT_ICALL_ADDR, (gpointer)func);
4757         mono_mb_emit_calli (mb, csig2);
4758         if (check_exceptions)
4759                 emit_thread_interrupt_checkpoint (mb);
4760         mono_mb_emit_byte (mb, CEE_RET);
4761 #endif
4762
4763         csig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
4764         csig->pinvoke = 0;
4765         if (csig->call_convention == MONO_CALL_VARARG)
4766                 csig->call_convention = 0;
4767
4768         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ICALL_WRAPPER);
4769         info->d.icall.func = (gpointer)func;
4770         res = mono_mb_create_and_cache_full (cache, (gpointer) func, mb, csig, csig->param_count + 16, info, NULL);
4771         mono_mb_free (mb);
4772
4773         return res;
4774 }
4775
4776 static int
4777 emit_marshal_custom (EmitMarshalContext *m, int argnum, MonoType *t,
4778                                          MonoMarshalSpec *spec, 
4779                                          int conv_arg, MonoType **conv_arg_type, 
4780                                          MarshalAction action)
4781 {
4782 #ifndef HAVE_ONLINE_VES
4783         if (action == MARSHAL_ACTION_CONV_IN && t->type == MONO_TYPE_VALUETYPE)
4784                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4785         return conv_arg;
4786 #else
4787         MonoError error;
4788         MonoType *mtype;
4789         MonoClass *mklass;
4790         static MonoClass *ICustomMarshaler = NULL;
4791         static MonoMethod *cleanup_native, *cleanup_managed;
4792         static MonoMethod *marshal_managed_to_native, *marshal_native_to_managed;
4793         MonoMethod *get_instance = NULL;
4794         MonoMethodBuilder *mb = m->mb;
4795         char *exception_msg = NULL;
4796         guint32 loc1;
4797         int pos2;
4798
4799         if (!ICustomMarshaler) {
4800                 MonoClass *klass = mono_class_try_get_icustom_marshaler_class ();
4801                 if (!klass) {
4802                         exception_msg = g_strdup ("Current profile doesn't support ICustomMarshaler");
4803                         goto handle_exception;
4804                 }
4805
4806                 cleanup_native = mono_class_get_method_from_name (klass, "CleanUpNativeData", 1);
4807                 g_assert (cleanup_native);
4808                 cleanup_managed = mono_class_get_method_from_name (klass, "CleanUpManagedData", 1);
4809                 g_assert (cleanup_managed);
4810                 marshal_managed_to_native = mono_class_get_method_from_name (klass, "MarshalManagedToNative", 1);
4811                 g_assert (marshal_managed_to_native);
4812                 marshal_native_to_managed = mono_class_get_method_from_name (klass, "MarshalNativeToManaged", 1);
4813                 g_assert (marshal_native_to_managed);
4814
4815                 mono_memory_barrier ();
4816                 ICustomMarshaler = klass;
4817         }
4818
4819         if (spec->data.custom_data.image)
4820                 mtype = mono_reflection_type_from_name_checked (spec->data.custom_data.custom_name, spec->data.custom_data.image, &error);
4821         else
4822                 mtype = mono_reflection_type_from_name_checked (spec->data.custom_data.custom_name, m->image, &error);
4823         g_assert (mtype != NULL);
4824         mono_error_assert_ok (&error);
4825         mklass = mono_class_from_mono_type (mtype);
4826         g_assert (mklass != NULL);
4827
4828         if (!mono_class_is_assignable_from (ICustomMarshaler, mklass))
4829                 exception_msg = g_strdup_printf ("Custom marshaler '%s' does not implement the ICustomMarshaler interface.", mklass->name);
4830
4831         get_instance = mono_class_get_method_from_name_flags (mklass, "GetInstance", 1, METHOD_ATTRIBUTE_STATIC);
4832         if (get_instance) {
4833                 MonoMethodSignature *get_sig = mono_method_signature (get_instance);
4834                 if ((get_sig->ret->type != MONO_TYPE_CLASS) ||
4835                         (mono_class_from_mono_type (get_sig->ret) != ICustomMarshaler) ||
4836                         (get_sig->params [0]->type != MONO_TYPE_STRING))
4837                         get_instance = NULL;
4838         }
4839
4840         if (!get_instance)
4841                 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);
4842
4843 handle_exception:
4844         /* Throw exception and emit compensation code if neccesary */
4845         if (exception_msg) {
4846                 switch (action) {
4847                 case MARSHAL_ACTION_CONV_IN:
4848                 case MARSHAL_ACTION_CONV_RESULT:
4849                 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4850                         if ((action == MARSHAL_ACTION_CONV_RESULT) || (action == MARSHAL_ACTION_MANAGED_CONV_RESULT))
4851                                 mono_mb_emit_byte (mb, CEE_POP);
4852
4853                         mono_mb_emit_exception_full (mb, "System", "ApplicationException", exception_msg);
4854
4855                         break;
4856                 case MARSHAL_ACTION_PUSH:
4857                         mono_mb_emit_byte (mb, CEE_LDNULL);
4858                         break;
4859                 default:
4860                         break;
4861                 }
4862                 return 0;
4863         }
4864
4865         /* FIXME: MS.NET seems to create one instance for each klass + cookie pair */
4866         /* FIXME: MS.NET throws an exception if GetInstance returns null */
4867
4868         switch (action) {
4869         case MARSHAL_ACTION_CONV_IN:
4870                 switch (t->type) {
4871                 case MONO_TYPE_CLASS:
4872                 case MONO_TYPE_OBJECT:
4873                 case MONO_TYPE_STRING:
4874                 case MONO_TYPE_ARRAY:
4875                 case MONO_TYPE_SZARRAY:
4876                 case MONO_TYPE_VALUETYPE:
4877                         break;
4878
4879                 default:
4880                         g_warning ("custom marshalling of type %x is currently not supported", t->type);
4881                         g_assert_not_reached ();
4882                         break;
4883                 }
4884
4885                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4886
4887                 mono_mb_emit_byte (mb, CEE_LDNULL);
4888                 mono_mb_emit_stloc (mb, conv_arg);
4889
4890                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT))
4891                         break;
4892
4893                 /* Minic MS.NET behavior */
4894                 if (!t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT) && !(t->attrs & PARAM_ATTRIBUTE_IN))
4895                         break;
4896
4897                 /* Check for null */
4898                 mono_mb_emit_ldarg (mb, argnum);
4899                 if (t->byref)
4900                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4901                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4902
4903                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4904
4905                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4906                                 
4907                 mono_mb_emit_ldarg (mb, argnum);
4908                 if (t->byref)
4909                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
4910
4911                 if (t->type == MONO_TYPE_VALUETYPE) {
4912                         /*
4913                          * Since we can't determine the type of the argument, we
4914                          * will assume the unmanaged function takes a pointer.
4915                          */
4916                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
4917
4918                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
4919                 }
4920
4921                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4922                 mono_mb_emit_stloc (mb, conv_arg);
4923
4924                 mono_mb_patch_branch (mb, pos2);
4925                 break;
4926
4927         case MARSHAL_ACTION_CONV_OUT:
4928                 /* Check for null */
4929                 mono_mb_emit_ldloc (mb, conv_arg);
4930                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4931
4932                 if (t->byref) {
4933                         mono_mb_emit_ldarg (mb, argnum);
4934
4935                         mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4936
4937                         mono_mb_emit_op (mb, CEE_CALL, get_instance);
4938
4939                         mono_mb_emit_ldloc (mb, conv_arg);
4940                         mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4941                         mono_mb_emit_byte (mb, CEE_STIND_REF);
4942                 } else if (t->attrs & PARAM_ATTRIBUTE_OUT) {
4943                         mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4944
4945                         mono_mb_emit_op (mb, CEE_CALL, get_instance);
4946
4947                         mono_mb_emit_ldloc (mb, conv_arg);
4948                         mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4949
4950                         /* We have nowhere to store the result */
4951                         mono_mb_emit_byte (mb, CEE_POP);
4952                 }
4953
4954                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4955
4956                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4957
4958                 mono_mb_emit_ldloc (mb, conv_arg);
4959
4960                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4961
4962                 mono_mb_patch_branch (mb, pos2);
4963                 break;
4964
4965         case MARSHAL_ACTION_PUSH:
4966                 if (t->byref)
4967                         mono_mb_emit_ldloc_addr (mb, conv_arg);
4968                 else
4969                         mono_mb_emit_ldloc (mb, conv_arg);
4970                 break;
4971
4972         case MARSHAL_ACTION_CONV_RESULT:
4973                 loc1 = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4974                         
4975                 mono_mb_emit_stloc (mb, 3);
4976
4977                 mono_mb_emit_ldloc (mb, 3);
4978                 mono_mb_emit_stloc (mb, loc1);
4979
4980                 /* Check for null */
4981                 mono_mb_emit_ldloc (mb, 3);
4982                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4983
4984                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4985
4986                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4987                 mono_mb_emit_byte (mb, CEE_DUP);
4988
4989                 mono_mb_emit_ldloc (mb, 3);
4990                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4991                 mono_mb_emit_stloc (mb, 3);
4992
4993                 mono_mb_emit_ldloc (mb, loc1);
4994                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4995
4996                 mono_mb_patch_branch (mb, pos2);
4997                 break;
4998
4999         case MARSHAL_ACTION_MANAGED_CONV_IN:
5000                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5001
5002                 mono_mb_emit_byte (mb, CEE_LDNULL);
5003                 mono_mb_emit_stloc (mb, conv_arg);
5004
5005                 if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
5006                         break;
5007
5008                 /* Check for null */
5009                 mono_mb_emit_ldarg (mb, argnum);
5010                 if (t->byref)
5011                         mono_mb_emit_byte (mb, CEE_LDIND_I);
5012                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5013
5014                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5015                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5016                                 
5017                 mono_mb_emit_ldarg (mb, argnum);
5018                 if (t->byref)
5019                         mono_mb_emit_byte (mb, CEE_LDIND_I);
5020                                 
5021                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
5022                 mono_mb_emit_stloc (mb, conv_arg);
5023
5024                 mono_mb_patch_branch (mb, pos2);
5025                 break;
5026
5027         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5028                 g_assert (!t->byref);
5029
5030                 loc1 = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5031                         
5032                 mono_mb_emit_stloc (mb, 3);
5033                         
5034                 mono_mb_emit_ldloc (mb, 3);
5035                 mono_mb_emit_stloc (mb, loc1);
5036
5037                 /* Check for null */
5038                 mono_mb_emit_ldloc (mb, 3);
5039                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5040
5041                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5042                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5043                 mono_mb_emit_byte (mb, CEE_DUP);
5044
5045                 mono_mb_emit_ldloc (mb, 3);
5046                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
5047                 mono_mb_emit_stloc (mb, 3);
5048
5049                 mono_mb_emit_ldloc (mb, loc1);
5050                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
5051
5052                 mono_mb_patch_branch (mb, pos2);
5053                 break;
5054
5055         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5056
5057                 /* Check for null */
5058                 mono_mb_emit_ldloc (mb, conv_arg);
5059                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5060
5061                 if (t->byref) {
5062                         mono_mb_emit_ldarg (mb, argnum);
5063
5064                         mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5065
5066                         mono_mb_emit_op (mb, CEE_CALL, get_instance);
5067
5068                         mono_mb_emit_ldloc (mb, conv_arg);
5069                         mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
5070                         mono_mb_emit_byte (mb, CEE_STIND_I);
5071                 }
5072
5073                 /* Call CleanUpManagedData */
5074                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
5075
5076                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
5077                                 
5078                 mono_mb_emit_ldloc (mb, conv_arg);
5079                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
5080
5081                 mono_mb_patch_branch (mb, pos2);
5082                 break;
5083
5084         default:
5085                 g_assert_not_reached ();
5086         }
5087         return conv_arg;
5088 #endif
5089
5090 }
5091
5092 static int
5093 emit_marshal_asany (EmitMarshalContext *m, int argnum, MonoType *t,
5094                                         MonoMarshalSpec *spec, 
5095                                         int conv_arg, MonoType **conv_arg_type, 
5096                                         MarshalAction action)
5097 {
5098 #ifdef HAVE_ONLINE_VES
5099         MonoMethodBuilder *mb = m->mb;
5100
5101         switch (action) {
5102         case MARSHAL_ACTION_CONV_IN: {
5103                 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
5104
5105                 g_assert (t->type == MONO_TYPE_OBJECT);
5106                 g_assert (!t->byref);
5107
5108                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5109                 mono_mb_emit_ldarg (mb, argnum);
5110                 mono_mb_emit_icon (mb, encoding);
5111                 mono_mb_emit_icon (mb, t->attrs);
5112                 mono_mb_emit_icall (mb, mono_marshal_asany);
5113                 mono_mb_emit_stloc (mb, conv_arg);
5114                 break;
5115         }
5116
5117         case MARSHAL_ACTION_PUSH:
5118                 mono_mb_emit_ldloc (mb, conv_arg);
5119                 break;
5120
5121         case MARSHAL_ACTION_CONV_OUT: {
5122                 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
5123
5124                 mono_mb_emit_ldarg (mb, argnum);
5125                 mono_mb_emit_ldloc (mb, conv_arg);
5126                 mono_mb_emit_icon (mb, encoding);
5127                 mono_mb_emit_icon (mb, t->attrs);
5128                 mono_mb_emit_icall (mb, mono_marshal_free_asany);
5129                 break;
5130         }
5131
5132         default:
5133                 g_assert_not_reached ();
5134         }
5135 #endif
5136         return conv_arg;
5137 }
5138
5139 static int
5140 emit_marshal_vtype (EmitMarshalContext *m, int argnum, MonoType *t,
5141                                         MonoMarshalSpec *spec, 
5142                                         int conv_arg, MonoType **conv_arg_type, 
5143                                         MarshalAction action)
5144 {
5145 #ifdef HAVE_ONLINE_VES
5146         MonoMethodBuilder *mb = m->mb;
5147         MonoClass *klass, *date_time_class;
5148         int pos = 0, pos2;
5149
5150         klass = mono_class_from_mono_type (t);
5151
5152         date_time_class = mono_class_get_date_time_class ();
5153
5154         switch (action) {
5155         case MARSHAL_ACTION_CONV_IN:
5156                 if (klass == date_time_class) {
5157                         /* Convert it to an OLE DATE type */
5158                         static MonoMethod *to_oadate;
5159
5160                         if (!to_oadate)
5161                                 to_oadate = mono_class_get_method_from_name (date_time_class, "ToOADate", 0);
5162                         g_assert (to_oadate);
5163
5164                         conv_arg = mono_mb_add_local (mb, &mono_defaults.double_class->byval_arg);
5165
5166                         if (t->byref) {
5167                                 mono_mb_emit_ldarg (mb, argnum);
5168                                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5169                         }
5170
5171                         if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
5172                                 if (!t->byref)
5173                                         m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.double_class->byval_arg;
5174
5175                                 mono_mb_emit_ldarg_addr (mb, argnum);
5176                                 mono_mb_emit_managed_call (mb, to_oadate, NULL);
5177                                 mono_mb_emit_stloc (mb, conv_arg);
5178                         }
5179
5180                         if (t->byref)
5181                                 mono_mb_patch_branch (mb, pos);
5182                         break;
5183                 }
5184
5185                 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5186                         break;
5187
5188                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5189                         
5190                 /* store the address of the source into local variable 0 */
5191                 if (t->byref)
5192                         mono_mb_emit_ldarg (mb, argnum);
5193                 else
5194                         mono_mb_emit_ldarg_addr (mb, argnum);
5195                 
5196                 mono_mb_emit_stloc (mb, 0);
5197                         
5198                 /* allocate space for the native struct and
5199                  * store the address into local variable 1 (dest) */
5200                 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5201                 mono_mb_emit_byte (mb, CEE_PREFIX1);
5202                 mono_mb_emit_byte (mb, CEE_LOCALLOC);
5203                 mono_mb_emit_stloc (mb, conv_arg);
5204
5205                 if (t->byref) {
5206                         mono_mb_emit_ldloc (mb, 0);
5207                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5208                 }
5209
5210                 if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
5211                         /* set dst_ptr */
5212                         mono_mb_emit_ldloc (mb, conv_arg);
5213                         mono_mb_emit_stloc (mb, 1);
5214
5215                         /* emit valuetype conversion code */
5216                         emit_struct_conv (mb, klass, FALSE);
5217                 }
5218
5219                 if (t->byref)
5220                         mono_mb_patch_branch (mb, pos);
5221                 break;
5222
5223         case MARSHAL_ACTION_PUSH:
5224                 if (spec && spec->native == MONO_NATIVE_LPSTRUCT) {
5225                         /* FIXME: */
5226                         g_assert (!t->byref);
5227
5228                         /* Have to change the signature since the vtype is passed byref */
5229                         m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.int_class->byval_arg;
5230
5231                         if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5232                                 mono_mb_emit_ldarg_addr (mb, argnum);
5233                         else
5234                                 mono_mb_emit_ldloc (mb, conv_arg);
5235                         break;
5236                 }
5237
5238                 if (klass == date_time_class) {
5239                         if (t->byref)
5240                                 mono_mb_emit_ldloc_addr (mb, conv_arg);
5241                         else
5242                                 mono_mb_emit_ldloc (mb, conv_arg);
5243                         break;
5244                 }
5245
5246                 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype) {
5247                         mono_mb_emit_ldarg (mb, argnum);
5248                         break;
5249                 }                       
5250                 mono_mb_emit_ldloc (mb, conv_arg);
5251                 if (!t->byref) {
5252                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5253                         mono_mb_emit_op (mb, CEE_MONO_LDNATIVEOBJ, klass);
5254                 }
5255                 break;
5256
5257         case MARSHAL_ACTION_CONV_OUT:
5258                 if (klass == date_time_class) {
5259                         /* Convert from an OLE DATE type */
5260                         static MonoMethod *from_oadate;
5261
5262                         if (!t->byref)
5263                                 break;
5264
5265                         if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
5266                                 if (!from_oadate)
5267                                         from_oadate = mono_class_get_method_from_name (date_time_class, "FromOADate", 1);
5268                                 g_assert (from_oadate);
5269
5270                                 mono_mb_emit_ldarg (mb, argnum);
5271                                 mono_mb_emit_ldloc (mb, conv_arg);
5272                                 mono_mb_emit_managed_call (mb, from_oadate, NULL);
5273                                 mono_mb_emit_op (mb, CEE_STOBJ, date_time_class);
5274                         }
5275                         break;
5276                 }
5277
5278                 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5279                         break;
5280
5281                 if (t->byref) {
5282                         /* dst = argument */
5283                         mono_mb_emit_ldarg (mb, argnum);
5284                         mono_mb_emit_stloc (mb, 1);
5285
5286                         mono_mb_emit_ldloc (mb, 1);
5287                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5288
5289                         if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
5290                                 /* src = tmp_locals [i] */
5291                                 mono_mb_emit_ldloc (mb, conv_arg);
5292                                 mono_mb_emit_stloc (mb, 0);
5293
5294                                 /* emit valuetype conversion code */
5295                                 emit_struct_conv (mb, klass, TRUE);
5296                         }
5297                 }
5298
5299                 emit_struct_free (mb, klass, conv_arg);
5300                 
5301                 if (t->byref)
5302                         mono_mb_patch_branch (mb, pos);
5303                 break;
5304
5305         case MARSHAL_ACTION_CONV_RESULT:
5306                 if (mono_class_is_explicit_layout (klass) || klass->blittable) {
5307                         mono_mb_emit_stloc (mb, 3);
5308                         break;
5309                 }
5310
5311                 /* load pointer to returned value type */
5312                 g_assert (m->vtaddr_var);
5313                 mono_mb_emit_ldloc (mb, m->vtaddr_var);
5314                 /* store the address of the source into local variable 0 */
5315                 mono_mb_emit_stloc (mb, 0);
5316                 /* set dst_ptr */
5317                 mono_mb_emit_ldloc_addr (mb, 3);
5318                 mono_mb_emit_stloc (mb, 1);
5319                                 
5320                 /* emit valuetype conversion code */
5321                 emit_struct_conv (mb, klass, TRUE);
5322                 break;
5323
5324         case MARSHAL_ACTION_MANAGED_CONV_IN:
5325                 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype) {
5326                         conv_arg = 0;
5327                         break;
5328                 }
5329
5330                 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
5331
5332                 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5333                         break;
5334
5335                 if (t->byref) 
5336                         mono_mb_emit_ldarg (mb, argnum);
5337                 else
5338                         mono_mb_emit_ldarg_addr (mb, argnum);
5339                 mono_mb_emit_stloc (mb, 0);
5340
5341                 if (t->byref) {
5342                         mono_mb_emit_ldloc (mb, 0);
5343                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5344                 }                       
5345
5346                 mono_mb_emit_ldloc_addr (mb, conv_arg);
5347                 mono_mb_emit_stloc (mb, 1);
5348
5349                 /* emit valuetype conversion code */
5350                 emit_struct_conv (mb, klass, TRUE);
5351
5352                 if (t->byref)
5353                         mono_mb_patch_branch (mb, pos);
5354                 break;
5355
5356         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5357                 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype)
5358                         break;
5359                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))
5360                         break;
5361
5362                 /* Check for null */
5363                 mono_mb_emit_ldarg (mb, argnum);
5364                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5365
5366                 /* Set src */
5367                 mono_mb_emit_ldloc_addr (mb, conv_arg);
5368                 mono_mb_emit_stloc (mb, 0);
5369
5370                 /* Set dest */
5371                 mono_mb_emit_ldarg (mb, argnum);
5372                 mono_mb_emit_stloc (mb, 1);
5373
5374                 /* emit valuetype conversion code */
5375                 emit_struct_conv (mb, klass, FALSE);
5376
5377                 mono_mb_patch_branch (mb, pos2);
5378                 break;
5379
5380         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5381                 if (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype) {
5382                         mono_mb_emit_stloc (mb, 3);
5383                         m->retobj_var = 0;
5384                         break;
5385                 }
5386                         
5387                 /* load pointer to returned value type */
5388                 g_assert (m->vtaddr_var);
5389                 mono_mb_emit_ldloc (mb, m->vtaddr_var);
5390                         
5391                 /* store the address of the source into local variable 0 */
5392                 mono_mb_emit_stloc (mb, 0);
5393                 /* allocate space for the native struct and
5394                  * store the address into dst_ptr */
5395                 m->retobj_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5396                 m->retobj_class = klass;
5397                 g_assert (m->retobj_var);
5398                 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5399                 mono_mb_emit_byte (mb, CEE_CONV_I);
5400                 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
5401                 mono_mb_emit_stloc (mb, 1);
5402                 mono_mb_emit_ldloc (mb, 1);
5403                 mono_mb_emit_stloc (mb, m->retobj_var);
5404
5405                 /* emit valuetype conversion code */
5406                 emit_struct_conv (mb, klass, FALSE);
5407                 break;
5408
5409         default:
5410                 g_assert_not_reached ();
5411         }
5412 #endif
5413         return conv_arg;
5414 }
5415
5416 static int
5417 emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
5418                                          MonoMarshalSpec *spec, 
5419                                          int conv_arg, MonoType **conv_arg_type, 
5420                                          MarshalAction action)
5421 {
5422 #ifndef HAVE_ONLINE_VES
5423         switch (action) {
5424         case MARSHAL_ACTION_CONV_IN:
5425                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5426                 break;
5427         case MARSHAL_ACTION_MANAGED_CONV_IN:
5428                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5429                 break;
5430         }
5431 #else
5432         MonoMethodBuilder *mb = m->mb;
5433         MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5434         MonoMarshalConv conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
5435         gboolean need_free;
5436
5437         switch (action) {
5438         case MARSHAL_ACTION_CONV_IN:
5439                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5440                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5441
5442                 if (t->byref) {
5443                         if (t->attrs & PARAM_ATTRIBUTE_OUT)
5444                                 break;
5445
5446                         mono_mb_emit_ldarg (mb, argnum);
5447                         mono_mb_emit_byte (mb, CEE_LDIND_I);                            
5448                 } else {
5449                         mono_mb_emit_ldarg (mb, argnum);
5450                 }
5451
5452                 if (conv == MONO_MARSHAL_CONV_INVALID) {
5453                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5454                         mono_mb_emit_exception_marshal_directive (mb, msg);
5455                 } else {
5456                         mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5457
5458                         mono_mb_emit_stloc (mb, conv_arg);
5459                 }
5460                 break;
5461
5462         case MARSHAL_ACTION_CONV_OUT:
5463                 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5464                 if (conv == MONO_MARSHAL_CONV_INVALID) {
5465                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5466                         mono_mb_emit_exception_marshal_directive (mb, msg);
5467                         break;
5468                 }
5469
5470                 if (encoding == MONO_NATIVE_VBBYREFSTR) {
5471                         static MonoMethod *m;
5472
5473                         if (!m) {
5474                                 m = mono_class_get_method_from_name_flags (mono_defaults.string_class, "get_Length", -1, 0);
5475                                 g_assert (m);
5476                         }
5477
5478                         if (!t->byref) {
5479                                 char *msg = g_strdup_printf ("VBByRefStr marshalling requires a ref parameter.", encoding);
5480                                 mono_mb_emit_exception_marshal_directive (mb, msg);
5481                                 break;
5482                         }
5483
5484                         /* 
5485                          * Have to allocate a new string with the same length as the original, and
5486                          * copy the contents of the buffer pointed to by CONV_ARG into it.
5487                          */
5488                         g_assert (t->byref);
5489                         mono_mb_emit_ldarg (mb, argnum);
5490                         mono_mb_emit_ldloc (mb, conv_arg);
5491                         mono_mb_emit_ldarg (mb, argnum);
5492                         mono_mb_emit_byte (mb, CEE_LDIND_I);                            
5493                         mono_mb_emit_managed_call (mb, m, NULL);
5494                         mono_mb_emit_icall (mb, mono_string_new_len_wrapper);
5495                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5496                 } else if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
5497                         int stind_op;
5498                         mono_mb_emit_ldarg (mb, argnum);
5499                         mono_mb_emit_ldloc (mb, conv_arg);
5500                         mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
5501                         mono_mb_emit_byte (mb, stind_op);
5502                         need_free = TRUE;
5503                 }
5504
5505                 if (need_free) {
5506                         mono_mb_emit_ldloc (mb, conv_arg);
5507                         if (conv == MONO_MARSHAL_CONV_BSTR_STR)
5508                                 mono_mb_emit_icall (mb, mono_free_bstr);
5509                         else
5510                                 mono_mb_emit_icall (mb, mono_marshal_free);
5511                 }
5512                 break;
5513
5514         case MARSHAL_ACTION_PUSH:
5515                 if (t->byref && encoding != MONO_NATIVE_VBBYREFSTR)
5516                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5517                 else
5518                         mono_mb_emit_ldloc (mb, conv_arg);
5519                 break;
5520
5521         case MARSHAL_ACTION_CONV_RESULT:
5522                 mono_mb_emit_stloc (mb, 0);
5523                                 
5524                 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5525                 if (conv == MONO_MARSHAL_CONV_INVALID) {
5526                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5527                         mono_mb_emit_exception_marshal_directive (mb, msg);
5528                         break;
5529                 }
5530
5531                 mono_mb_emit_ldloc (mb, 0);
5532                 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5533                 mono_mb_emit_stloc (mb, 3);
5534
5535                 /* free the string */
5536                 mono_mb_emit_ldloc (mb, 0);
5537                 if (conv == MONO_MARSHAL_CONV_BSTR_STR)
5538                         mono_mb_emit_icall (mb, mono_free_bstr);
5539                 else
5540                         mono_mb_emit_icall (mb, mono_marshal_free);
5541                 break;
5542
5543         case MARSHAL_ACTION_MANAGED_CONV_IN:
5544                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5545
5546                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5547
5548                 if (t->byref) {
5549                         if (t->attrs & PARAM_ATTRIBUTE_OUT)
5550                                 break;
5551                 }
5552
5553                 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5554                 if (conv == MONO_MARSHAL_CONV_INVALID) {
5555                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5556                         mono_mb_emit_exception_marshal_directive (mb, msg);
5557                         break;
5558                 }
5559
5560                 mono_mb_emit_ldarg (mb, argnum);
5561                 if (t->byref)
5562                         mono_mb_emit_byte (mb, CEE_LDIND_I);
5563                 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5564                 mono_mb_emit_stloc (mb, conv_arg);
5565                 break;
5566
5567         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5568                 if (t->byref) {
5569                         if (conv_arg) {
5570                                 int stind_op;
5571                                 mono_mb_emit_ldarg (mb, argnum);
5572                                 mono_mb_emit_ldloc (mb, conv_arg);
5573                                 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
5574                                 mono_mb_emit_byte (mb, stind_op);
5575                         }
5576                 }
5577                 break;
5578
5579         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5580                 if (conv_to_icall (conv, NULL) == mono_marshal_string_to_utf16)
5581                         /* We need to make a copy so the caller is able to free it */
5582                         mono_mb_emit_icall (mb, mono_marshal_string_to_utf16_copy);
5583                 else
5584                         mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5585                 mono_mb_emit_stloc (mb, 3);
5586                 break;
5587
5588         default:
5589                 g_assert_not_reached ();
5590         }
5591 #endif
5592         return conv_arg;
5593 }
5594
5595
5596 static int
5597 emit_marshal_safehandle (EmitMarshalContext *m, int argnum, MonoType *t, 
5598                          MonoMarshalSpec *spec, int conv_arg, 
5599                          MonoType **conv_arg_type, MarshalAction action)
5600 {
5601 #ifndef HAVE_ONLINE_VES
5602         if (action == MARSHAL_ACTION_CONV_IN)
5603                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5604 #else
5605         MonoMethodBuilder *mb = m->mb;
5606
5607         switch (action){
5608         case MARSHAL_ACTION_CONV_IN: {
5609                 MonoType *intptr_type;
5610                 int dar_release_slot, pos;
5611
5612                 intptr_type = &mono_defaults.int_class->byval_arg;
5613                 conv_arg = mono_mb_add_local (mb, intptr_type);
5614                 *conv_arg_type = intptr_type;
5615
5616                 if (!sh_dangerous_add_ref)
5617                         init_safe_handle ();
5618
5619                 mono_mb_emit_ldarg (mb, argnum);
5620                 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
5621                 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
5622                 
5623                 mono_mb_patch_branch (mb, pos);
5624                 if (t->byref){
5625                         /*
5626                          * My tests in show that ref SafeHandles are not really
5627                          * passed as ref objects.  Instead a NULL is passed as the
5628                          * value of the ref
5629                          */
5630                         mono_mb_emit_icon (mb, 0);
5631                         mono_mb_emit_stloc (mb, conv_arg);
5632                         break;
5633                 } 
5634
5635                 /* Create local to hold the ref parameter to DangerousAddRef */
5636                 dar_release_slot = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
5637
5638                 /* set release = false; */
5639                 mono_mb_emit_icon (mb, 0);
5640                 mono_mb_emit_stloc (mb, dar_release_slot);
5641
5642                 /* safehandle.DangerousAddRef (ref release) */
5643                 mono_mb_emit_ldarg (mb, argnum);
5644                 mono_mb_emit_ldloc_addr (mb, dar_release_slot);
5645                 mono_mb_emit_managed_call (mb, sh_dangerous_add_ref, NULL);
5646
5647                 /* Pull the handle field from SafeHandle */
5648                 mono_mb_emit_ldarg (mb, argnum);
5649                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5650                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5651                 mono_mb_emit_stloc (mb, conv_arg);
5652
5653                 break;
5654         }
5655
5656         case MARSHAL_ACTION_PUSH:
5657                 if (t->byref)
5658                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5659                 else 
5660                         mono_mb_emit_ldloc (mb, conv_arg);
5661                 break;
5662
5663         case MARSHAL_ACTION_CONV_OUT: {
5664                 /* The slot for the boolean is the next temporary created after conv_arg, see the CONV_IN code */
5665                 int dar_release_slot = conv_arg + 1;
5666                 int label_next;
5667
5668                 if (!sh_dangerous_release)
5669                         init_safe_handle ();
5670
5671                 if (t->byref){
5672                         MonoMethod *ctor;
5673                         
5674                         /*
5675                          * My tests indicate that ref SafeHandles parameters are not actually
5676                          * passed by ref, but instead a new Handle is created regardless of
5677                          * whether a change happens in the unmanaged side.
5678                          *
5679                          * Also, the Handle is created before calling into unmanaged code,
5680                          * but we do not support that mechanism (getting to the original
5681                          * handle) and it makes no difference where we create this
5682                          */
5683                         ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5684                         if (ctor == NULL){
5685                                 mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5686                                 break;
5687                         }
5688                         /* refval = new SafeHandleDerived ()*/
5689                         mono_mb_emit_ldarg (mb, argnum);
5690                         mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5691                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5692
5693                         /* refval.handle = returned_handle */
5694                         mono_mb_emit_ldarg (mb, argnum);
5695                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
5696                         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5697                         mono_mb_emit_ldloc (mb, conv_arg);
5698                         mono_mb_emit_byte (mb, CEE_STIND_I);
5699                 } else {
5700                         mono_mb_emit_ldloc (mb, dar_release_slot);
5701                         label_next = mono_mb_emit_branch (mb, CEE_BRFALSE);
5702                         mono_mb_emit_ldarg (mb, argnum);
5703                         mono_mb_emit_managed_call (mb, sh_dangerous_release, NULL);
5704                         mono_mb_patch_branch (mb, label_next);
5705                 }
5706                 break;
5707         }
5708                 
5709         case MARSHAL_ACTION_CONV_RESULT: {
5710                 MonoMethod *ctor = NULL;
5711                 int intptr_handle_slot;
5712                 
5713                 if (mono_class_is_abstract (t->data.klass)) {
5714                         mono_mb_emit_byte (mb, CEE_POP);
5715                         mono_mb_emit_exception_marshal_directive (mb, g_strdup ("Returned SafeHandles should not be abstract"));
5716                         break;
5717                 }
5718
5719                 ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5720                 if (ctor == NULL){
5721                         mono_mb_emit_byte (mb, CEE_POP);
5722                         mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5723                         break;
5724                 }
5725                 /* Store the IntPtr results into a local */
5726                 intptr_handle_slot = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5727                 mono_mb_emit_stloc (mb, intptr_handle_slot);
5728
5729                 /* Create return value */
5730                 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5731                 mono_mb_emit_stloc (mb, 3);
5732
5733                 /* Set the return.handle to the value, am using ldflda, not sure if thats a good idea */
5734                 mono_mb_emit_ldloc (mb, 3);
5735                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5736                 mono_mb_emit_ldloc (mb, intptr_handle_slot);
5737                 mono_mb_emit_byte (mb, CEE_STIND_I);
5738                 break;
5739         }
5740                 
5741         case MARSHAL_ACTION_MANAGED_CONV_IN:
5742                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5743                 break;
5744                 
5745         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5746                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5747                 break;
5748
5749         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5750                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5751                 break;
5752         default:
5753                 printf ("Unhandled case for MarshalAction: %d\n", action);
5754         }
5755 #endif
5756         return conv_arg;
5757 }
5758
5759
5760 static int
5761 emit_marshal_handleref (EmitMarshalContext *m, int argnum, MonoType *t, 
5762                         MonoMarshalSpec *spec, int conv_arg, 
5763                         MonoType **conv_arg_type, MarshalAction action)
5764 {
5765 #ifndef HAVE_ONLINE_VES
5766         if (action == MARSHAL_ACTION_CONV_IN)
5767                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5768 #else
5769         MonoMethodBuilder *mb = m->mb;
5770
5771         switch (action){
5772         case MARSHAL_ACTION_CONV_IN: {
5773                 MonoType *intptr_type;
5774
5775                 intptr_type = &mono_defaults.int_class->byval_arg;
5776                 conv_arg = mono_mb_add_local (mb, intptr_type);
5777                 *conv_arg_type = intptr_type;
5778
5779                 if (t->byref){
5780                         char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5781                         mono_mb_emit_exception_marshal_directive (mb, msg);
5782                         break;
5783                 } 
5784                 mono_mb_emit_ldarg_addr (mb, argnum);
5785                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoHandleRef, handle));
5786                 mono_mb_emit_byte (mb, CEE_ADD);
5787                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5788                 mono_mb_emit_stloc (mb, conv_arg);
5789                 break;
5790         }
5791
5792         case MARSHAL_ACTION_PUSH:
5793                 mono_mb_emit_ldloc (mb, conv_arg);
5794                 break;
5795
5796         case MARSHAL_ACTION_CONV_OUT: {
5797                 /* no resource release required */
5798                 break;
5799         }
5800                 
5801         case MARSHAL_ACTION_CONV_RESULT: {
5802                 char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5803                 mono_mb_emit_exception_marshal_directive (mb, msg);
5804                 break;
5805         }
5806                 
5807         case MARSHAL_ACTION_MANAGED_CONV_IN:
5808                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5809                 break;
5810                 
5811         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5812                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5813                 break;
5814
5815         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5816                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5817                 break;
5818         default:
5819                 fprintf (stderr, "Unhandled case for MarshalAction: %d\n", action);
5820         }
5821 #endif
5822         return conv_arg;
5823 }
5824
5825
5826 static int
5827 emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
5828                      MonoMarshalSpec *spec, 
5829                      int conv_arg, MonoType **conv_arg_type, 
5830                      MarshalAction action)
5831 {
5832 #ifndef HAVE_ONLINE_VES
5833         if (action == MARSHAL_ACTION_CONV_IN)
5834                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5835 #else
5836         MonoMethodBuilder *mb = m->mb;
5837         MonoClass *klass = mono_class_from_mono_type (t);
5838         int pos, pos2, loc;
5839
5840         switch (action) {
5841         case MARSHAL_ACTION_CONV_IN:
5842                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5843                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5844
5845                 m->orig_conv_args [argnum] = 0;
5846
5847                 if (mono_class_from_mono_type (t) == mono_defaults.object_class) {
5848                         char *msg = g_strdup_printf ("Marshalling of type object is not implemented");
5849                         mono_mb_emit_exception_marshal_directive (mb, msg);
5850                         break;
5851                 }
5852
5853                 if (klass->delegate) {
5854                         if (t->byref) {
5855                                 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5856                                         char *msg = g_strdup_printf ("Byref marshalling of delegates is not implemented.");
5857                                         mono_mb_emit_exception_marshal_directive (mb, msg);
5858                                 }
5859                                 mono_mb_emit_byte (mb, CEE_LDNULL);
5860                                 mono_mb_emit_stloc (mb, conv_arg);
5861                         } else {
5862                                 mono_mb_emit_ldarg (mb, argnum);
5863                                 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, NULL));
5864                                 mono_mb_emit_stloc (mb, conv_arg);
5865                         }
5866                 } else if (klass == mono_defaults.stringbuilder_class) {
5867                         MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5868                         MonoMarshalConv conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
5869
5870 #if 0                   
5871                         if (t->byref) {
5872                                 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5873                                         char *msg = g_strdup_printf ("Byref marshalling of stringbuilders is not implemented.");
5874                                         mono_mb_emit_exception_marshal_directive (mb, msg);
5875                                 }
5876                                 break;
5877                         }
5878 #endif
5879
5880                         if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))
5881                                 break;
5882
5883                         if (conv == MONO_MARSHAL_CONV_INVALID) {
5884                                 char *msg = g_strdup_printf ("stringbuilder marshalling conversion %d not implemented", encoding);
5885                                 mono_mb_emit_exception_marshal_directive (mb, msg);
5886                                 break;
5887                         }
5888
5889                         mono_mb_emit_ldarg (mb, argnum);
5890                         if (t->byref)
5891                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5892
5893                         mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5894                         mono_mb_emit_stloc (mb, conv_arg);
5895                 } else if (klass->blittable) {
5896                         mono_mb_emit_byte (mb, CEE_LDNULL);
5897                         mono_mb_emit_stloc (mb, conv_arg);
5898
5899                         mono_mb_emit_ldarg (mb, argnum);
5900                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5901
5902                         mono_mb_emit_ldarg (mb, argnum);
5903                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5904                         mono_mb_emit_stloc (mb, conv_arg);
5905
5906                         mono_mb_patch_branch (mb, pos);
5907                         break;
5908                 } else {
5909                         mono_mb_emit_byte (mb, CEE_LDNULL);
5910                         mono_mb_emit_stloc (mb, conv_arg);
5911
5912                         if (t->byref) {
5913                                 /* we dont need any conversions for out parameters */
5914                                 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5915                                         break;
5916
5917                                 mono_mb_emit_ldarg (mb, argnum);                                
5918                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5919
5920                         } else {
5921                                 mono_mb_emit_ldarg (mb, argnum);
5922                                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5923                                 mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
5924                         }
5925                                 
5926                         /* store the address of the source into local variable 0 */
5927                         mono_mb_emit_stloc (mb, 0);
5928                         mono_mb_emit_ldloc (mb, 0);
5929                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5930
5931                         /* allocate space for the native struct and store the address */
5932                         mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5933                         mono_mb_emit_byte (mb, CEE_PREFIX1);
5934                         mono_mb_emit_byte (mb, CEE_LOCALLOC);
5935                         mono_mb_emit_stloc (mb, conv_arg);
5936
5937                         if (t->byref) {
5938                                 /* Need to store the original buffer so we can free it later */
5939                                 m->orig_conv_args [argnum] = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5940                                 mono_mb_emit_ldloc (mb, conv_arg);
5941                                 mono_mb_emit_stloc (mb, m->orig_conv_args [argnum]);
5942                         }
5943
5944                         /* set the src_ptr */
5945                         mono_mb_emit_ldloc (mb, 0);
5946                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5947                         mono_mb_emit_stloc (mb, 0);
5948
5949                         /* set dst_ptr */
5950                         mono_mb_emit_ldloc (mb, conv_arg);
5951                         mono_mb_emit_stloc (mb, 1);
5952
5953                         /* emit valuetype conversion code */
5954                         emit_struct_conv (mb, klass, FALSE);
5955
5956                         mono_mb_patch_branch (mb, pos);
5957                 }
5958                 break;
5959
5960         case MARSHAL_ACTION_CONV_OUT:
5961                 if (klass == mono_defaults.stringbuilder_class) {
5962                         gboolean need_free;
5963                         MonoMarshalNative encoding;
5964                         MonoMarshalConv conv;
5965
5966                         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5967                         conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
5968
5969                         g_assert (encoding != -1);
5970
5971                         if (t->byref) {
5972                                 //g_assert (!(t->attrs & PARAM_ATTRIBUTE_OUT));
5973
5974                                 need_free = TRUE;
5975
5976                                 mono_mb_emit_ldarg (mb, argnum);
5977                                 mono_mb_emit_ldloc (mb, conv_arg);
5978
5979                                 switch (encoding) {
5980                                 case MONO_NATIVE_LPWSTR:
5981                                         mono_mb_emit_icall (mb, mono_string_utf16_to_builder2);
5982                                         break;
5983                                 case MONO_NATIVE_LPSTR:
5984                                         mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5985                                         break;
5986                                 case MONO_NATIVE_UTF8STR:
5987                                         mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5988                                         break;
5989                                 default:
5990                                         g_assert_not_reached ();
5991                                 }
5992
5993                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
5994                         } else {
5995                                 mono_mb_emit_ldarg (mb, argnum);
5996                                 mono_mb_emit_ldloc (mb, conv_arg);
5997
5998                                 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5999                         }
6000
6001                         if (need_free) {
6002                                 mono_mb_emit_ldloc (mb, conv_arg);
6003                                 mono_mb_emit_icall (mb, mono_marshal_free);
6004                         }
6005                         break;
6006                 }
6007
6008                 if (klass->delegate) {
6009                         if (t->byref) {
6010                                 mono_mb_emit_ldarg (mb, argnum);
6011                                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6012                                 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
6013                                 mono_mb_emit_ldloc (mb, conv_arg);
6014                                 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
6015                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
6016                         }
6017                         break;
6018                 }
6019
6020                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT)) {
6021                         /* allocate a new object */
6022                         mono_mb_emit_ldarg (mb, argnum);
6023                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6024                         mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
6025                         mono_mb_emit_byte (mb, CEE_STIND_REF);
6026                 }
6027
6028                 /* dst = *argument */
6029                 mono_mb_emit_ldarg (mb, argnum);
6030
6031                 if (t->byref)
6032                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6033
6034                 mono_mb_emit_stloc (mb, 1);
6035
6036                 mono_mb_emit_ldloc (mb, 1);
6037                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
6038
6039                 if (t->byref || (t->attrs & PARAM_ATTRIBUTE_OUT)) {
6040                         mono_mb_emit_ldloc (mb, 1);
6041                         mono_mb_emit_icon (mb, sizeof (MonoObject));
6042                         mono_mb_emit_byte (mb, CEE_ADD);
6043                         mono_mb_emit_stloc (mb, 1);
6044                         
6045                         /* src = tmp_locals [i] */
6046                         mono_mb_emit_ldloc (mb, conv_arg);
6047                         mono_mb_emit_stloc (mb, 0);
6048
6049                         /* emit valuetype conversion code */
6050                         emit_struct_conv (mb, klass, TRUE);
6051
6052                         /* Free the structure returned by the native code */
6053                         emit_struct_free (mb, klass, conv_arg);
6054
6055                         if (m->orig_conv_args [argnum]) {
6056                                 /* 
6057                                  * If the native function changed the pointer, then free
6058                                  * the original structure plus the new pointer.
6059                                  */
6060                                 mono_mb_emit_ldloc (mb, m->orig_conv_args [argnum]);
6061                                 mono_mb_emit_ldloc (mb, conv_arg);
6062                                 pos2 = mono_mb_emit_branch (mb, CEE_BEQ);
6063
6064                                 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
6065                                         g_assert (m->orig_conv_args [argnum]);
6066
6067                                         emit_struct_free (mb, klass, m->orig_conv_args [argnum]);
6068                                 }
6069
6070                                 mono_mb_emit_ldloc (mb, conv_arg);
6071                                 mono_mb_emit_icall (mb, mono_marshal_free);
6072
6073                                 mono_mb_patch_branch (mb, pos2);
6074                         }
6075                 }
6076                 else
6077                         /* Free the original structure passed to native code */
6078                         emit_struct_free (mb, klass, conv_arg);
6079
6080                 mono_mb_patch_branch (mb, pos);
6081                 break;
6082
6083         case MARSHAL_ACTION_PUSH:
6084                 if (t->byref)
6085                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6086                 else
6087                         mono_mb_emit_ldloc (mb, conv_arg);
6088                 break;
6089
6090         case MARSHAL_ACTION_CONV_RESULT:
6091                 if (klass->delegate) {
6092                         g_assert (!t->byref);
6093                         mono_mb_emit_stloc (mb, 0);
6094                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6095                         mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
6096                         mono_mb_emit_ldloc (mb, 0);
6097                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
6098                         mono_mb_emit_stloc (mb, 3);
6099                 } else if (klass == mono_defaults.stringbuilder_class) {
6100                         // FIXME:
6101                         char *msg = g_strdup_printf ("Return marshalling of stringbuilders is not implemented.");
6102                         mono_mb_emit_exception_marshal_directive (mb, msg);
6103                 } else {
6104                         /* set src */
6105                         mono_mb_emit_stloc (mb, 0);
6106         
6107                         /* Make a copy since emit_conv modifies local 0 */
6108                         loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6109                         mono_mb_emit_ldloc (mb, 0);
6110                         mono_mb_emit_stloc (mb, loc);
6111         
6112                         mono_mb_emit_byte (mb, CEE_LDNULL);
6113                         mono_mb_emit_stloc (mb, 3);
6114         
6115                         mono_mb_emit_ldloc (mb, 0);
6116                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
6117         
6118                         /* allocate result object */
6119         
6120                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6121                         mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);   
6122                         mono_mb_emit_stloc (mb, 3);
6123                                         
6124                         /* set dst  */
6125         
6126                         mono_mb_emit_ldloc (mb, 3);
6127                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6128                         mono_mb_emit_stloc (mb, 1);
6129                                                                 
6130                         /* emit conversion code */
6131                         emit_struct_conv (mb, klass, TRUE);
6132         
6133                         emit_struct_free (mb, klass, loc);
6134         
6135                         /* Free the pointer allocated by unmanaged code */
6136                         mono_mb_emit_ldloc (mb, loc);
6137                         mono_mb_emit_icall (mb, mono_marshal_free);
6138                         mono_mb_patch_branch (mb, pos);
6139                 }
6140                 break;
6141
6142         case MARSHAL_ACTION_MANAGED_CONV_IN:
6143                 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
6144
6145                 if (klass->delegate) {
6146                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6147                         mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
6148                         mono_mb_emit_ldarg (mb, argnum);
6149                         if (t->byref)
6150                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6151                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
6152                         mono_mb_emit_stloc (mb, conv_arg);
6153                         break;
6154                 }
6155
6156                 if (klass == mono_defaults.stringbuilder_class) {
6157                         MonoMarshalNative encoding;
6158
6159                         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
6160
6161                         // FIXME:
6162                         g_assert (encoding == MONO_NATIVE_LPSTR || encoding == MONO_NATIVE_UTF8STR);
6163
6164                         g_assert (!t->byref);
6165                         g_assert (encoding != -1);
6166
6167                         mono_mb_emit_ldarg (mb, argnum);
6168                         mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
6169                         mono_mb_emit_stloc (mb, conv_arg);
6170                         break;
6171                 }
6172
6173                 /* The class can not have an automatic layout */
6174                 if (mono_class_is_auto_layout (klass)) {
6175                         mono_mb_emit_auto_layout_exception (mb, klass);
6176                         break;
6177                 }
6178
6179                 if (t->attrs & PARAM_ATTRIBUTE_OUT) {
6180                         mono_mb_emit_byte (mb, CEE_LDNULL);
6181                         mono_mb_emit_stloc (mb, conv_arg);
6182                         break;
6183                 }
6184
6185                 /* Set src */
6186                 mono_mb_emit_ldarg (mb, argnum);
6187                 if (t->byref) {
6188                         int pos2;
6189
6190                         /* Check for NULL and raise an exception */
6191                         pos2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
6192
6193                         mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
6194
6195                         mono_mb_patch_branch (mb, pos2);
6196                         mono_mb_emit_ldarg (mb, argnum);
6197                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6198                 }                               
6199
6200                 mono_mb_emit_stloc (mb, 0);
6201
6202                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6203                 mono_mb_emit_stloc (mb, conv_arg);
6204
6205                 mono_mb_emit_ldloc (mb, 0);
6206                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
6207
6208                 /* Create and set dst */
6209                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
6210                 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);   
6211                 mono_mb_emit_stloc (mb, conv_arg);
6212                 mono_mb_emit_ldloc (mb, conv_arg);
6213                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6214                 mono_mb_emit_stloc (mb, 1); 
6215
6216                 /* emit valuetype conversion code */
6217                 emit_struct_conv (mb, klass, TRUE);
6218
6219                 mono_mb_patch_branch (mb, pos);
6220                 break;
6221
6222         case MARSHAL_ACTION_MANAGED_CONV_OUT:
6223                 if (klass->delegate) {
6224                         if (t->byref) {
6225                                 int stind_op;
6226                                 mono_mb_emit_ldarg (mb, argnum);
6227                                 mono_mb_emit_ldloc (mb, conv_arg);
6228                                 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, &stind_op));
6229                                 mono_mb_emit_byte (mb, stind_op);
6230                                 break;
6231                         }
6232                 }
6233
6234                 if (t->byref) {
6235                         /* Check for null */
6236                         mono_mb_emit_ldloc (mb, conv_arg);
6237                         pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
6238                         mono_mb_emit_ldarg (mb, argnum);
6239                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6240                         mono_mb_emit_byte (mb, CEE_STIND_REF);
6241                         pos2 = mono_mb_emit_branch (mb, CEE_BR);
6242
6243                         mono_mb_patch_branch (mb, pos);                 
6244                         
6245                         /* Set src */
6246                         mono_mb_emit_ldloc (mb, conv_arg);
6247                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6248                         mono_mb_emit_stloc (mb, 0);
6249
6250                         /* Allocate and set dest */
6251                         mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
6252                         mono_mb_emit_byte (mb, CEE_CONV_I);
6253                         mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
6254                         mono_mb_emit_stloc (mb, 1);
6255                         
6256                         /* Update argument pointer */
6257                         mono_mb_emit_ldarg (mb, argnum);
6258                         mono_mb_emit_ldloc (mb, 1);
6259                         mono_mb_emit_byte (mb, CEE_STIND_I);
6260                 
6261                         /* emit valuetype conversion code */
6262                         emit_struct_conv (mb, klass, FALSE);
6263
6264                         mono_mb_patch_branch (mb, pos2);
6265                 } else if (klass == mono_defaults.stringbuilder_class) {
6266                         // FIXME: What to do here ?
6267                 } else {
6268                         /* byval [Out] marshalling */
6269
6270                         /* FIXME: Handle null */
6271
6272                         /* Set src */
6273                         mono_mb_emit_ldloc (mb, conv_arg);
6274                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6275                         mono_mb_emit_stloc (mb, 0);
6276
6277                         /* Set dest */
6278                         mono_mb_emit_ldarg (mb, argnum);
6279                         mono_mb_emit_stloc (mb, 1);
6280                         
6281                         /* emit valuetype conversion code */
6282                         emit_struct_conv (mb, klass, FALSE);
6283                 }                       
6284                 break;
6285
6286         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
6287                 if (klass->delegate) {
6288                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, NULL));
6289                         mono_mb_emit_stloc (mb, 3);
6290                         break;
6291                 }
6292
6293                 /* The class can not have an automatic layout */
6294                 if (mono_class_is_auto_layout (klass)) {
6295                         mono_mb_emit_auto_layout_exception (mb, klass);
6296                         break;
6297                 }
6298
6299                 mono_mb_emit_stloc (mb, 0);
6300                 /* Check for null */
6301                 mono_mb_emit_ldloc (mb, 0);
6302                 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
6303                 mono_mb_emit_byte (mb, CEE_LDNULL);
6304                 mono_mb_emit_stloc (mb, 3);
6305                 pos2 = mono_mb_emit_branch (mb, CEE_BR);
6306
6307                 mono_mb_patch_branch (mb, pos);
6308
6309                 /* Set src */
6310                 mono_mb_emit_ldloc (mb, 0);
6311                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6312                 mono_mb_emit_stloc (mb, 0);
6313
6314                 /* Allocate and set dest */
6315                 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
6316                 mono_mb_emit_byte (mb, CEE_CONV_I);
6317                 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
6318                 mono_mb_emit_byte (mb, CEE_DUP);
6319                 mono_mb_emit_stloc (mb, 1);
6320                 mono_mb_emit_stloc (mb, 3);
6321
6322                 emit_struct_conv (mb, klass, FALSE);
6323
6324                 mono_mb_patch_branch (mb, pos2);
6325                 break;
6326
6327         default:
6328                 g_assert_not_reached ();
6329         }
6330 #endif
6331         return conv_arg;
6332 }
6333
6334 #ifdef HAVE_ONLINE_VES
6335 #ifndef DISABLE_COM
6336
6337 static int
6338 emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
6339                      MonoMarshalSpec *spec, 
6340                      int conv_arg, MonoType **conv_arg_type, 
6341                      MarshalAction action)
6342 {
6343         MonoMethodBuilder *mb = m->mb;
6344         static MonoMethod *get_object_for_native_variant = NULL;
6345         static MonoMethod *get_native_variant_for_object = NULL;
6346
6347         if (!get_object_for_native_variant)
6348                 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
6349         g_assert (get_object_for_native_variant);
6350
6351         if (!get_native_variant_for_object)
6352                 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
6353         g_assert (get_native_variant_for_object);
6354
6355         switch (action) {
6356         case MARSHAL_ACTION_CONV_IN: {
6357                 conv_arg = mono_mb_add_local (mb, &mono_class_get_variant_class ()->byval_arg);
6358                 
6359                 if (t->byref)
6360                         *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
6361                 else
6362                         *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
6363
6364                 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
6365                         break;
6366
6367                 mono_mb_emit_ldarg (mb, argnum);
6368                 if (t->byref)
6369                         mono_mb_emit_byte(mb, CEE_LDIND_REF);
6370                 mono_mb_emit_ldloc_addr (mb, conv_arg);
6371                 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6372                 break;
6373         }
6374
6375         case MARSHAL_ACTION_CONV_OUT: {
6376                 static MonoMethod *variant_clear = NULL;
6377
6378                 if (!variant_clear)
6379                         variant_clear = mono_class_get_method_from_name (mono_class_get_variant_class (), "Clear", 0);
6380                 g_assert (variant_clear);
6381
6382
6383                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
6384                         mono_mb_emit_ldarg (mb, argnum);
6385                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6386                         mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6387                         mono_mb_emit_byte (mb, CEE_STIND_REF);
6388                 }
6389
6390                 mono_mb_emit_ldloc_addr (mb, conv_arg);
6391                 mono_mb_emit_managed_call (mb, variant_clear, NULL);
6392                 break;
6393         }
6394
6395         case MARSHAL_ACTION_PUSH:
6396                 if (t->byref)
6397                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6398                 else
6399                         mono_mb_emit_ldloc (mb, conv_arg);
6400                 break;
6401
6402         case MARSHAL_ACTION_CONV_RESULT: {
6403                 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6404                 mono_mb_emit_exception_marshal_directive (mb, msg);
6405                 break;
6406         }
6407
6408         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6409                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6410
6411                 if (t->byref)
6412                         *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
6413                 else
6414                         *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
6415
6416                 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
6417                         break;
6418
6419                 if (t->byref)
6420                         mono_mb_emit_ldarg (mb, argnum);
6421                 else
6422                         mono_mb_emit_ldarg_addr (mb, argnum);
6423                 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6424                 mono_mb_emit_stloc (mb, conv_arg);
6425                 break;
6426         }
6427
6428         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6429                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
6430                         mono_mb_emit_ldloc (mb, conv_arg);
6431                         mono_mb_emit_ldarg (mb, argnum);
6432                         mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6433                 }
6434                 break;
6435         }
6436
6437         case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6438                 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6439                 mono_mb_emit_exception_marshal_directive (mb, msg);
6440                 break;
6441         }
6442
6443         default:
6444                 g_assert_not_reached ();
6445         }
6446
6447         return conv_arg;
6448 }
6449
6450 #endif /* DISABLE_COM */
6451 #endif /* HAVE_ONLINE_VES */
6452
6453 static gboolean
6454 mono_pinvoke_is_unicode (MonoMethodPInvoke *piinfo)
6455 {
6456         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
6457         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
6458                 return FALSE;
6459         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
6460                 return TRUE;
6461         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
6462         default:
6463 #ifdef TARGET_WIN32
6464                 return TRUE;
6465 #else
6466                 return FALSE;
6467 #endif
6468         }
6469 }
6470
6471
6472 static int
6473 emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
6474                                         MonoMarshalSpec *spec, 
6475                                         int conv_arg, MonoType **conv_arg_type, 
6476                                         MarshalAction action)
6477 {
6478 #ifndef HAVE_ONLINE_VES
6479         switch (action) {
6480         case MARSHAL_ACTION_CONV_IN:
6481                 *conv_arg_type = &mono_defaults.object_class->byval_arg;
6482                 break;
6483         case MARSHAL_ACTION_MANAGED_CONV_IN:
6484                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6485                 break;
6486         }
6487 #else
6488         MonoMethodBuilder *mb = m->mb;
6489         MonoClass *klass = mono_class_from_mono_type (t);
6490         gboolean need_convert, need_free;
6491         MonoMarshalNative encoding;
6492
6493         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
6494
6495         switch (action) {
6496         case MARSHAL_ACTION_CONV_IN:
6497                 *conv_arg_type = &mono_defaults.object_class->byval_arg;
6498                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6499
6500                 if (klass->element_class->blittable) {
6501                         mono_mb_emit_ldarg (mb, argnum);
6502                         if (t->byref)
6503                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6504                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_ARRAY_LPARRAY, NULL));
6505                         mono_mb_emit_stloc (mb, conv_arg);
6506                 } else {
6507                         MonoClass *eklass;
6508                         guint32 label1, label2, label3;
6509                         int index_var, src_var, dest_ptr, esize;
6510                         MonoMarshalConv conv;
6511                         gboolean is_string = FALSE;
6512
6513                         dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6514
6515                         eklass = klass->element_class;
6516
6517                         if (eklass == mono_defaults.string_class) {
6518                                 is_string = TRUE;
6519                                 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6520                         }
6521                         else if (eklass == mono_defaults.stringbuilder_class) {
6522                                 is_string = TRUE;
6523                                 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6524                         }
6525                         else
6526                                 conv = MONO_MARSHAL_CONV_INVALID;
6527
6528                         if (is_string && conv == MONO_MARSHAL_CONV_INVALID) {
6529                                 char *msg = g_strdup_printf ("string/stringbuilder marshalling conversion %d not implemented", encoding);
6530                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6531                                 break;
6532                         }
6533
6534                         src_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6535                         mono_mb_emit_ldarg (mb, argnum);
6536                         if (t->byref)
6537                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6538                         mono_mb_emit_stloc (mb, src_var);
6539
6540                         /* Check null */
6541                         mono_mb_emit_ldloc (mb, src_var);
6542                         mono_mb_emit_stloc (mb, conv_arg);
6543                         mono_mb_emit_ldloc (mb, src_var);
6544                         label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6545
6546                         if (is_string)
6547                                 esize = sizeof (gpointer);
6548                         else if (eklass == mono_defaults.char_class) /*can't call mono_marshal_type_size since it causes all sorts of asserts*/
6549                                 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6550                         else
6551                                 esize = mono_class_native_size (eklass, NULL);
6552
6553                         /* allocate space for the native struct and store the address */
6554                         mono_mb_emit_icon (mb, esize);
6555                         mono_mb_emit_ldloc (mb, src_var);
6556                         mono_mb_emit_byte (mb, CEE_LDLEN);
6557
6558                         if (eklass == mono_defaults.string_class) {
6559                                 /* Make the array bigger for the terminating null */
6560                                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6561                                 mono_mb_emit_byte (mb, CEE_ADD);
6562                         }
6563                         mono_mb_emit_byte (mb, CEE_MUL);
6564                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6565                         mono_mb_emit_byte (mb, CEE_LOCALLOC);
6566                         mono_mb_emit_stloc (mb, conv_arg);
6567
6568                         mono_mb_emit_ldloc (mb, conv_arg);
6569                         mono_mb_emit_stloc (mb, dest_ptr);
6570
6571                         /* Emit marshalling loop */
6572                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
6573                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6574                         mono_mb_emit_stloc (mb, index_var);
6575                         label2 = mono_mb_get_label (mb);
6576                         mono_mb_emit_ldloc (mb, index_var);
6577                         mono_mb_emit_ldloc (mb, src_var);
6578                         mono_mb_emit_byte (mb, CEE_LDLEN);
6579                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
6580
6581                         /* Emit marshalling code */
6582
6583                         if (is_string) {
6584                                 int stind_op;
6585                                 mono_mb_emit_ldloc (mb, dest_ptr);
6586                                 mono_mb_emit_ldloc (mb, src_var);
6587                                 mono_mb_emit_ldloc (mb, index_var);
6588                                 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6589                                 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
6590                                 mono_mb_emit_byte (mb, stind_op);
6591                         } else {
6592                                 /* set the src_ptr */
6593                                 mono_mb_emit_ldloc (mb, src_var);
6594                                 mono_mb_emit_ldloc (mb, index_var);
6595                                 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6596                                 mono_mb_emit_stloc (mb, 0);
6597
6598                                 /* set dst_ptr */
6599                                 mono_mb_emit_ldloc (mb, dest_ptr);
6600                                 mono_mb_emit_stloc (mb, 1);
6601
6602                                 /* emit valuetype conversion code */
6603                                 emit_struct_conv_full (mb, eklass, FALSE, 0, eklass == mono_defaults.char_class ? encoding : (MonoMarshalNative)-1);
6604                         }
6605
6606                         mono_mb_emit_add_to_local (mb, index_var, 1);
6607                         mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6608                         
6609                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
6610
6611                         mono_mb_patch_branch (mb, label3);
6612
6613                         if (eklass == mono_defaults.string_class) {
6614                                 /* Null terminate */
6615                                 mono_mb_emit_ldloc (mb, dest_ptr);
6616                                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6617                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
6618                         }
6619
6620                         mono_mb_patch_branch (mb, label1);
6621                 }
6622
6623                 break;
6624
6625         case MARSHAL_ACTION_CONV_OUT:
6626                 /* Unicode character arrays are implicitly marshalled as [Out] under MS.NET */
6627                 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);
6628                 need_free = mono_marshal_need_free (&klass->element_class->byval_arg, 
6629                                                                                         m->piinfo, spec);
6630
6631                 if ((t->attrs & PARAM_ATTRIBUTE_OUT) && spec && spec->native == MONO_NATIVE_LPARRAY && spec->data.array_data.param_num != -1) {
6632                         int param_num = spec->data.array_data.param_num;
6633                         MonoType *param_type;
6634
6635                         param_type = m->sig->params [param_num];
6636
6637                         if (param_type->byref && param_type->type != MONO_TYPE_I4) {
6638                                 char *msg = g_strdup ("Not implemented.");
6639                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6640                                 break;
6641                         }
6642
6643                         if (t->byref ) {
6644                                 mono_mb_emit_ldarg (mb, argnum);
6645
6646                                 /* Create the managed array */
6647                                 mono_mb_emit_ldarg (mb, param_num);
6648                                 if (m->sig->params [param_num]->byref)
6649                                         // FIXME: Support other types
6650                                         mono_mb_emit_byte (mb, CEE_LDIND_I4);
6651                                 mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6652                                 mono_mb_emit_op (mb, CEE_NEWARR, klass->element_class);
6653                                 /* Store into argument */
6654                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
6655                         }
6656                 }
6657
6658                 if (need_convert || need_free) {
6659                         /* FIXME: Optimize blittable case */
6660                         MonoClass *eklass;
6661                         guint32 label1, label2, label3;
6662                         int index_var, src_ptr, loc, esize;
6663
6664                         eklass = klass->element_class;
6665                         if ((eklass == mono_defaults.stringbuilder_class) || (eklass == mono_defaults.string_class))
6666                                 esize = sizeof (gpointer);
6667                         else if (eklass == mono_defaults.char_class)
6668                                 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6669                         else
6670                                 esize = mono_class_native_size (eklass, NULL);
6671                         src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6672                         loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6673
6674                         /* Check null */
6675                         mono_mb_emit_ldarg (mb, argnum);
6676                         if (t->byref)
6677                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6678                         label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6679
6680                         mono_mb_emit_ldloc (mb, conv_arg);
6681                         mono_mb_emit_stloc (mb, src_ptr);
6682
6683                         /* Emit marshalling loop */
6684                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
6685                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6686                         mono_mb_emit_stloc (mb, index_var);
6687                         label2 = mono_mb_get_label (mb);
6688                         mono_mb_emit_ldloc (mb, index_var);
6689                         mono_mb_emit_ldarg (mb, argnum);
6690                         if (t->byref)
6691                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6692                         mono_mb_emit_byte (mb, CEE_LDLEN);
6693                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
6694
6695                         /* Emit marshalling code */
6696
6697                         if (eklass == mono_defaults.stringbuilder_class) {
6698                                 gboolean need_free2;
6699                                 MonoMarshalConv conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free2);
6700
6701                                 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6702
6703                                 /* dest */
6704                                 mono_mb_emit_ldarg (mb, argnum);
6705                                 if (t->byref)
6706                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6707                                 mono_mb_emit_ldloc (mb, index_var);
6708                                 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6709
6710                                 /* src */
6711                                 mono_mb_emit_ldloc (mb, src_ptr);
6712                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6713
6714                                 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
6715
6716                                 if (need_free) {
6717                                         /* src */
6718                                         mono_mb_emit_ldloc (mb, src_ptr);
6719                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6720
6721                                         mono_mb_emit_icall (mb, mono_marshal_free);
6722                                 }
6723                         }
6724                         else if (eklass == mono_defaults.string_class) {
6725                                 if (need_free) {
6726                                         /* src */
6727                                         mono_mb_emit_ldloc (mb, src_ptr);
6728                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6729
6730                                         mono_mb_emit_icall (mb, mono_marshal_free);
6731                                 }
6732                         }
6733                         else {
6734                                 if (need_convert) {
6735                                         /* set the src_ptr */
6736                                         mono_mb_emit_ldloc (mb, src_ptr);
6737                                         mono_mb_emit_stloc (mb, 0);
6738
6739                                         /* set dst_ptr */
6740                                         mono_mb_emit_ldarg (mb, argnum);
6741                                         if (t->byref)
6742                                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6743                                         mono_mb_emit_ldloc (mb, index_var);
6744                                         mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6745                                         mono_mb_emit_stloc (mb, 1);
6746
6747                                         /* emit valuetype conversion code */
6748                                         emit_struct_conv_full (mb, eklass, TRUE, 0, eklass == mono_defaults.char_class ? encoding : (MonoMarshalNative)-1);
6749                                 }
6750
6751                                 if (need_free) {
6752                                         mono_mb_emit_ldloc (mb, src_ptr);
6753                                         mono_mb_emit_stloc (mb, loc);
6754                                         mono_mb_emit_ldloc (mb, loc);
6755
6756                                         emit_struct_free (mb, eklass, loc);
6757                                 }
6758                         }
6759
6760                         mono_mb_emit_add_to_local (mb, index_var, 1);
6761                         mono_mb_emit_add_to_local (mb, src_ptr, esize);
6762
6763                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
6764
6765                         mono_mb_patch_branch (mb, label1);
6766                         mono_mb_patch_branch (mb, label3);
6767                 }
6768                 
6769                 if (klass->element_class->blittable) {
6770                         /* free memory allocated (if any) by MONO_MARSHAL_CONV_ARRAY_LPARRAY */
6771
6772                         mono_mb_emit_ldarg (mb, argnum);
6773                         if (t->byref)
6774                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6775                         mono_mb_emit_ldloc (mb, conv_arg);
6776                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_FREE_LPARRAY, NULL));
6777                 }
6778
6779                 break;
6780
6781         case MARSHAL_ACTION_PUSH:
6782                 if (t->byref)
6783                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6784                 else
6785                         mono_mb_emit_ldloc (mb, conv_arg);
6786                 break;
6787
6788         case MARSHAL_ACTION_CONV_RESULT:
6789                 /* fixme: we need conversions here */
6790                 mono_mb_emit_stloc (mb, 3);
6791                 break;
6792
6793         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6794                 MonoClass *eklass;
6795                 guint32 label1, label2, label3;
6796                 int index_var, src_ptr, esize, param_num, num_elem;
6797                 MonoMarshalConv conv;
6798                 gboolean is_string = FALSE;
6799                 
6800                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6801                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6802
6803                 if (t->byref) {
6804                         char *msg = g_strdup ("Byref array marshalling to managed code is not implemented.");
6805                         mono_mb_emit_exception_marshal_directive (mb, msg);
6806                         return conv_arg;
6807                 }
6808                 if (!spec) {
6809                         char *msg = g_strdup ("[MarshalAs] attribute required to marshal arrays to managed code.");
6810                         mono_mb_emit_exception_marshal_directive (mb, msg);
6811                         return conv_arg;
6812                 }                       
6813                 if (spec->native != MONO_NATIVE_LPARRAY) {
6814                         char *msg = g_strdup ("Non LPArray marshalling of arrays to managed code is not implemented.");
6815                         mono_mb_emit_exception_marshal_directive (mb, msg);
6816                         return conv_arg;                        
6817                 }
6818
6819                 /* FIXME: t is from the method which is wrapped, not the delegate type */
6820                 /* g_assert (t->attrs & PARAM_ATTRIBUTE_IN); */
6821
6822                 param_num = spec->data.array_data.param_num;
6823                 num_elem = spec->data.array_data.num_elem;
6824                 if (spec->data.array_data.elem_mult == 0)
6825                         /* param_num is not specified */
6826                         param_num = -1;
6827
6828                 if (param_num == -1) {
6829                         if (num_elem <= 0) {
6830                                 char *msg = g_strdup ("Either SizeConst or SizeParamIndex should be specified when marshalling arrays to managed code.");
6831                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6832                                 return conv_arg;
6833                         }
6834                 }
6835
6836                 /* FIXME: Optimize blittable case */
6837
6838                 eklass = klass->element_class;
6839                 if (eklass == mono_defaults.string_class) {
6840                         is_string = TRUE;
6841                         conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
6842                 }
6843                 else if (eklass == mono_defaults.stringbuilder_class) {
6844                         is_string = TRUE;
6845                         conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
6846                 }
6847                 else
6848                         conv = MONO_MARSHAL_CONV_INVALID;
6849
6850                 mono_marshal_load_type_info (eklass);
6851
6852                 if (is_string)
6853                         esize = sizeof (gpointer);
6854                 else
6855                         esize = mono_class_native_size (eklass, NULL);
6856                 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6857
6858                 mono_mb_emit_byte (mb, CEE_LDNULL);
6859                 mono_mb_emit_stloc (mb, conv_arg);
6860
6861                 /* Check param index */
6862                 if (param_num != -1) {
6863                         if (param_num >= m->sig->param_count) {
6864                                 char *msg = g_strdup ("Array size control parameter index is out of range.");
6865                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6866                                 return conv_arg;
6867                         }
6868                         switch (m->sig->params [param_num]->type) {
6869                         case MONO_TYPE_I1:
6870                         case MONO_TYPE_U1:
6871                         case MONO_TYPE_I2:
6872                         case MONO_TYPE_U2:
6873                         case MONO_TYPE_I4:
6874                         case MONO_TYPE_U4:
6875                         case MONO_TYPE_I:
6876                         case MONO_TYPE_U:
6877                         case MONO_TYPE_I8:
6878                         case MONO_TYPE_U8:
6879                                 break;
6880                         default: {
6881                                 char *msg = g_strdup ("Array size control parameter must be an integral type.");
6882                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6883                                 return conv_arg;
6884                         }
6885                         }
6886                 }
6887
6888                 /* Check null */
6889                 mono_mb_emit_ldarg (mb, argnum);
6890                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6891
6892                 mono_mb_emit_ldarg (mb, argnum);
6893                 mono_mb_emit_stloc (mb, src_ptr);
6894
6895                 /* Create managed array */
6896                 /* 
6897                  * The LPArray marshalling spec says that sometimes param_num starts 
6898                  * from 1, sometimes it starts from 0. But MS seems to allways start
6899                  * from 0.
6900                  */
6901
6902                 if (param_num == -1) {
6903                         mono_mb_emit_icon (mb, num_elem);
6904                 } else {
6905                         mono_mb_emit_ldarg (mb, param_num);
6906                         if (num_elem > 0) {
6907                                 mono_mb_emit_icon (mb, num_elem);
6908                                 mono_mb_emit_byte (mb, CEE_ADD);
6909                         }
6910                         mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6911                 }
6912
6913                 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
6914                 mono_mb_emit_stloc (mb, conv_arg);
6915
6916                 if (eklass->blittable) {
6917                         mono_mb_emit_ldloc (mb, conv_arg);
6918                         mono_mb_emit_byte (mb, CEE_CONV_I);
6919                         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6920                         mono_mb_emit_byte (mb, CEE_ADD);
6921                         mono_mb_emit_ldarg (mb, argnum);
6922                         mono_mb_emit_ldloc (mb, conv_arg);
6923                         mono_mb_emit_byte (mb, CEE_LDLEN);
6924                         mono_mb_emit_icon (mb, esize);
6925                         mono_mb_emit_byte (mb, CEE_MUL);
6926                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6927                         mono_mb_emit_byte (mb, CEE_CPBLK);
6928                         mono_mb_patch_branch (mb, label1);
6929                         break;
6930                 }
6931
6932                 /* Emit marshalling loop */
6933                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6934                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6935                 mono_mb_emit_stloc (mb, index_var);
6936                 label2 = mono_mb_get_label (mb);
6937                 mono_mb_emit_ldloc (mb, index_var);
6938                 mono_mb_emit_ldloc (mb, conv_arg);
6939                 mono_mb_emit_byte (mb, CEE_LDLEN);
6940                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6941
6942                 /* Emit marshalling code */
6943                 if (is_string) {
6944                         g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6945
6946                         mono_mb_emit_ldloc (mb, conv_arg);
6947                         mono_mb_emit_ldloc (mb, index_var);
6948
6949                         mono_mb_emit_ldloc (mb, src_ptr);
6950                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6951
6952                         mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
6953                         mono_mb_emit_byte (mb, CEE_STELEM_REF);
6954                 }
6955                 else {
6956                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6957                         mono_mb_emit_exception_marshal_directive (mb, msg);
6958                         return conv_arg;
6959                 }
6960
6961                 mono_mb_emit_add_to_local (mb, index_var, 1);
6962                 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6963
6964                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6965
6966                 mono_mb_patch_branch (mb, label1);
6967                 mono_mb_patch_branch (mb, label3);
6968                 
6969                 break;
6970         }
6971         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6972                 MonoClass *eklass;
6973                 guint32 label1, label2, label3;
6974                 int index_var, dest_ptr, esize, param_num, num_elem;
6975                 MonoMarshalConv conv;
6976                 gboolean is_string = FALSE;
6977
6978                 if (!spec)
6979                         /* Already handled in CONV_IN */
6980                         break;
6981                 
6982                 /* These are already checked in CONV_IN */
6983                 g_assert (!t->byref);
6984                 g_assert (spec->native == MONO_NATIVE_LPARRAY);
6985                 g_assert (t->attrs & PARAM_ATTRIBUTE_OUT);
6986
6987                 param_num = spec->data.array_data.param_num;
6988                 num_elem = spec->data.array_data.num_elem;
6989
6990                 if (spec->data.array_data.elem_mult == 0)
6991                         /* param_num is not specified */
6992                         param_num = -1;
6993
6994                 if (param_num == -1) {
6995                         if (num_elem <= 0) {
6996                                 g_assert_not_reached ();
6997                         }
6998                 }
6999
7000                 /* FIXME: Optimize blittable case */
7001
7002                 eklass = klass->element_class;
7003                 if (eklass == mono_defaults.string_class) {
7004                         is_string = TRUE;
7005                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
7006                 }
7007                 else if (eklass == mono_defaults.stringbuilder_class) {
7008                         is_string = TRUE;
7009                         conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
7010                 }
7011                 else
7012                         conv = MONO_MARSHAL_CONV_INVALID;
7013
7014                 mono_marshal_load_type_info (eklass);
7015
7016                 if (is_string)
7017                         esize = sizeof (gpointer);
7018                 else
7019                         esize = mono_class_native_size (eklass, NULL);
7020
7021                 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7022
7023                 /* Check null */
7024                 mono_mb_emit_ldloc (mb, conv_arg);
7025                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
7026
7027                 mono_mb_emit_ldarg (mb, argnum);
7028                 mono_mb_emit_stloc (mb, dest_ptr);
7029
7030                 if (eklass->blittable) {
7031                         /* dest */
7032                         mono_mb_emit_ldarg (mb, argnum);
7033                         /* src */
7034                         mono_mb_emit_ldloc (mb, conv_arg);
7035                         mono_mb_emit_byte (mb, CEE_CONV_I);
7036                         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
7037                         mono_mb_emit_byte (mb, CEE_ADD);
7038                         /* length */
7039                         mono_mb_emit_ldloc (mb, conv_arg);
7040                         mono_mb_emit_byte (mb, CEE_LDLEN);
7041                         mono_mb_emit_icon (mb, esize);
7042                         mono_mb_emit_byte (mb, CEE_MUL);
7043                         mono_mb_emit_byte (mb, CEE_PREFIX1);
7044                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
7045                         break;
7046                 }
7047
7048                 /* Emit marshalling loop */
7049                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7050                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7051                 mono_mb_emit_stloc (mb, index_var);
7052                 label2 = mono_mb_get_label (mb);
7053                 mono_mb_emit_ldloc (mb, index_var);
7054                 mono_mb_emit_ldloc (mb, conv_arg);
7055                 mono_mb_emit_byte (mb, CEE_LDLEN);
7056                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
7057
7058                 /* Emit marshalling code */
7059                 if (is_string) {
7060                         int stind_op;
7061                         g_assert (conv != MONO_MARSHAL_CONV_INVALID);
7062
7063                         /* dest */
7064                         mono_mb_emit_ldloc (mb, dest_ptr);
7065
7066                         /* src */
7067                         mono_mb_emit_ldloc (mb, conv_arg);
7068                         mono_mb_emit_ldloc (mb, index_var);
7069
7070                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
7071
7072                         mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
7073                         mono_mb_emit_byte (mb, stind_op);
7074                 }
7075                 else {
7076                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
7077                         mono_mb_emit_exception_marshal_directive (mb, msg);
7078                         return conv_arg;
7079                 }
7080
7081                 mono_mb_emit_add_to_local (mb, index_var, 1);
7082                 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
7083
7084                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
7085
7086                 mono_mb_patch_branch (mb, label1);
7087                 mono_mb_patch_branch (mb, label3);
7088
7089                 break;
7090         }
7091         case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
7092                 MonoClass *eklass;
7093                 guint32 label1, label2, label3;
7094                 int index_var, src, dest, esize;
7095                 MonoMarshalConv conv = MONO_MARSHAL_CONV_INVALID;
7096                 gboolean is_string = FALSE;
7097                 
7098                 g_assert (!t->byref);
7099
7100                 eklass = klass->element_class;
7101
7102                 mono_marshal_load_type_info (eklass);
7103
7104                 if (eklass == mono_defaults.string_class) {
7105                         is_string = TRUE;
7106                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
7107                 }
7108                 else {
7109                         g_assert_not_reached ();
7110                 }
7111
7112                 if (is_string)
7113                         esize = sizeof (gpointer);
7114                 else if (eklass == mono_defaults.char_class)
7115                         esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
7116                 else
7117                         esize = mono_class_native_size (eklass, NULL);
7118
7119                 src = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
7120                 dest = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7121                         
7122                 mono_mb_emit_stloc (mb, src);
7123                 mono_mb_emit_ldloc (mb, src);
7124                 mono_mb_emit_stloc (mb, 3);
7125
7126                 /* Check for null */
7127                 mono_mb_emit_ldloc (mb, src);
7128                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
7129
7130                 /* Allocate native array */
7131                 mono_mb_emit_icon (mb, esize);
7132                 mono_mb_emit_ldloc (mb, src);
7133                 mono_mb_emit_byte (mb, CEE_LDLEN);
7134
7135                 if (eklass == mono_defaults.string_class) {
7136                         /* Make the array bigger for the terminating null */
7137                         mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7138                         mono_mb_emit_byte (mb, CEE_ADD);
7139                 }
7140                 mono_mb_emit_byte (mb, CEE_MUL);
7141                 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
7142                 mono_mb_emit_stloc (mb, dest);
7143                 mono_mb_emit_ldloc (mb, dest);
7144                 mono_mb_emit_stloc (mb, 3);
7145
7146                 /* Emit marshalling loop */
7147                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7148                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7149                 mono_mb_emit_stloc (mb, index_var);
7150                 label2 = mono_mb_get_label (mb);
7151                 mono_mb_emit_ldloc (mb, index_var);
7152                 mono_mb_emit_ldloc (mb, src);
7153                 mono_mb_emit_byte (mb, CEE_LDLEN);
7154                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
7155
7156                 /* Emit marshalling code */
7157                 if (is_string) {
7158                         int stind_op;
7159                         g_assert (conv != MONO_MARSHAL_CONV_INVALID);
7160
7161                         /* dest */
7162                         mono_mb_emit_ldloc (mb, dest);
7163
7164                         /* src */
7165                         mono_mb_emit_ldloc (mb, src);
7166                         mono_mb_emit_ldloc (mb, index_var);
7167
7168                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
7169
7170                         mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
7171                         mono_mb_emit_byte (mb, stind_op);
7172                 }
7173                 else {
7174                         char *msg = g_strdup ("Marshalling of non-string arrays to managed code is not implemented.");
7175                         mono_mb_emit_exception_marshal_directive (mb, msg);
7176                         return conv_arg;
7177                 }
7178
7179                 mono_mb_emit_add_to_local (mb, index_var, 1);
7180                 mono_mb_emit_add_to_local (mb, dest, esize);
7181
7182                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
7183
7184                 mono_mb_patch_branch (mb, label3);
7185                 mono_mb_patch_branch (mb, label1);
7186                 break;
7187         }
7188         default:
7189                 g_assert_not_reached ();
7190         }
7191 #endif
7192         return conv_arg;
7193 }
7194
7195 static MonoType*
7196 marshal_boolean_conv_in_get_local_type (MonoMarshalSpec *spec, guint8 *ldc_op /*out*/)
7197 {
7198         if (spec == NULL) {
7199                 return &mono_defaults.int32_class->byval_arg;
7200         } else {
7201                 switch (spec->native) {
7202                 case MONO_NATIVE_I1:
7203                 case MONO_NATIVE_U1:
7204                         return &mono_defaults.byte_class->byval_arg;
7205                 case MONO_NATIVE_VARIANTBOOL:
7206                         if (ldc_op) *ldc_op = CEE_LDC_I4_M1;
7207                         return &mono_defaults.int16_class->byval_arg;
7208                 case MONO_NATIVE_BOOLEAN:
7209                         return &mono_defaults.int32_class->byval_arg;
7210                 default:
7211                         g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
7212                         return &mono_defaults.int32_class->byval_arg;
7213                 }
7214         }
7215 }
7216
7217 static MonoClass*
7218 marshal_boolean_managed_conv_in_get_conv_arg_class (MonoMarshalSpec *spec, guint8 *ldop/*out*/)
7219 {
7220         MonoClass* conv_arg_class = mono_defaults.int32_class;
7221         if (spec) {
7222                 switch (spec->native) {
7223                 case MONO_NATIVE_I1:
7224                 case MONO_NATIVE_U1:
7225                         conv_arg_class = mono_defaults.byte_class;
7226                         if (ldop) *ldop = CEE_LDIND_I1;
7227                         break;
7228                 case MONO_NATIVE_VARIANTBOOL:
7229                         conv_arg_class = mono_defaults.int16_class;
7230                         if (ldop) *ldop = CEE_LDIND_I2;
7231                         break;
7232                 case MONO_NATIVE_BOOLEAN:
7233                         break;
7234                 default:
7235                         g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
7236                 }
7237         }
7238         return conv_arg_class;
7239 }
7240
7241 static int
7242 emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
7243                       MonoMarshalSpec *spec, 
7244                       int conv_arg, MonoType **conv_arg_type, 
7245                       MarshalAction action)
7246 {
7247 #ifndef HAVE_ONLINE_VES
7248         switch (action) {
7249         case MARSHAL_ACTION_CONV_IN:
7250                 if (t->byref)
7251                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
7252                 else
7253                         *conv_arg_type = marshal_boolean_conv_in_get_local_type (spec, NULL);
7254                 break;
7255
7256         case MARSHAL_ACTION_MANAGED_CONV_IN: {
7257                 MonoClass* conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, NULL);
7258                 if (t->byref)
7259                         *conv_arg_type = &conv_arg_class->this_arg;
7260                 else
7261                         *conv_arg_type = &conv_arg_class->byval_arg;
7262                 break;
7263         }
7264
7265         }
7266 #else
7267         MonoMethodBuilder *mb = m->mb;
7268
7269         switch (action) {
7270         case MARSHAL_ACTION_CONV_IN: {
7271                 MonoType *local_type;
7272                 int label_false;
7273                 guint8 ldc_op = CEE_LDC_I4_1;
7274
7275                 local_type = marshal_boolean_conv_in_get_local_type (spec, &ldc_op);
7276                 if (t->byref)
7277                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
7278                 else
7279                         *conv_arg_type = local_type;
7280                 conv_arg = mono_mb_add_local (mb, local_type);
7281                 
7282                 mono_mb_emit_ldarg (mb, argnum);
7283                 if (t->byref)
7284                         mono_mb_emit_byte (mb, CEE_LDIND_I1);
7285                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7286                 mono_mb_emit_byte (mb, ldc_op);
7287                 mono_mb_emit_stloc (mb, conv_arg);
7288                 mono_mb_patch_branch (mb, label_false);
7289
7290                 break;
7291         }
7292
7293         case MARSHAL_ACTION_CONV_OUT:
7294         {
7295                 int label_false, label_end;
7296                 if (!t->byref)
7297                         break;
7298
7299                 mono_mb_emit_ldarg (mb, argnum);
7300                 mono_mb_emit_ldloc (mb, conv_arg);
7301                 
7302                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7303                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7304
7305                 label_end = mono_mb_emit_branch (mb, CEE_BR);
7306                 mono_mb_patch_branch (mb, label_false);
7307                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7308                 mono_mb_patch_branch (mb, label_end);
7309
7310                 mono_mb_emit_byte (mb, CEE_STIND_I1);
7311                 break;
7312         }
7313
7314         case MARSHAL_ACTION_PUSH:
7315                 if (t->byref)
7316                         mono_mb_emit_ldloc_addr (mb, conv_arg);
7317                 else if (conv_arg)
7318                         mono_mb_emit_ldloc (mb, conv_arg);
7319                 else
7320                         mono_mb_emit_ldarg (mb, argnum);
7321                 break;
7322
7323         case MARSHAL_ACTION_CONV_RESULT:
7324                 /* maybe we need to make sure that it fits within 8 bits */
7325                 mono_mb_emit_stloc (mb, 3);
7326                 break;
7327
7328         case MARSHAL_ACTION_MANAGED_CONV_IN: {
7329                 MonoClass* conv_arg_class = mono_defaults.int32_class;
7330                 guint8 ldop = CEE_LDIND_I4;
7331                 int label_null, label_false;
7332
7333                 conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, &ldop);
7334                 conv_arg = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7335
7336                 if (t->byref)
7337                         *conv_arg_type = &conv_arg_class->this_arg;
7338                 else
7339                         *conv_arg_type = &conv_arg_class->byval_arg;
7340
7341
7342                 mono_mb_emit_ldarg (mb, argnum);
7343                 
7344                 /* Check null */
7345                 if (t->byref) {
7346                         label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
7347                         mono_mb_emit_ldarg (mb, argnum);
7348                         mono_mb_emit_byte (mb, ldop);
7349                 } else
7350                         label_null = 0;
7351
7352                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7353                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7354                 mono_mb_emit_stloc (mb, conv_arg);
7355                 mono_mb_patch_branch (mb, label_false);
7356
7357                 if (t->byref) 
7358                         mono_mb_patch_branch (mb, label_null);
7359                 break;
7360         }
7361
7362         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
7363                 guint8 stop = CEE_STIND_I4;
7364                 guint8 ldc_op = CEE_LDC_I4_1;
7365                 int label_null,label_false, label_end;;
7366
7367                 if (!t->byref)
7368                         break;
7369                 if (spec) {
7370                         switch (spec->native) {
7371                         case MONO_NATIVE_I1:
7372                         case MONO_NATIVE_U1:
7373                                 stop = CEE_STIND_I1;
7374                                 break;
7375                         case MONO_NATIVE_VARIANTBOOL:
7376                                 stop = CEE_STIND_I2;
7377                                 ldc_op = CEE_LDC_I4_M1;
7378                                 break;
7379                         default:
7380                                 break;
7381                         }
7382                 }
7383                 
7384                 /* Check null */
7385                 mono_mb_emit_ldarg (mb, argnum);
7386                 label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
7387
7388                 mono_mb_emit_ldarg (mb, argnum);
7389                 mono_mb_emit_ldloc (mb, conv_arg);
7390
7391                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7392                 mono_mb_emit_byte (mb, ldc_op);
7393                 label_end = mono_mb_emit_branch (mb, CEE_BR);
7394
7395                 mono_mb_patch_branch (mb, label_false);
7396                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7397                 mono_mb_patch_branch (mb, label_end);
7398
7399                 mono_mb_emit_byte (mb, stop);
7400                 mono_mb_patch_branch (mb, label_null);
7401                 break;
7402         }
7403
7404         default:
7405                 g_assert_not_reached ();
7406         }
7407 #endif
7408         return conv_arg;
7409 }
7410
7411 static int
7412 emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t, 
7413                   MonoMarshalSpec *spec, int conv_arg, 
7414                   MonoType **conv_arg_type, MarshalAction action)
7415 {
7416 #ifdef HAVE_ONLINE_VES
7417         MonoMethodBuilder *mb = m->mb;
7418
7419         switch (action) {
7420         case MARSHAL_ACTION_CONV_IN:
7421                 /* MS seems to allow this in some cases, ie. bxc #158 */
7422                 /*
7423                 if (MONO_TYPE_ISSTRUCT (t->data.type) && !mono_class_from_mono_type (t->data.type)->blittable) {
7424                         char *msg = g_strdup_printf ("Can not marshal 'parameter #%d': Pointers can not reference marshaled structures. Use byref instead.", argnum + 1);
7425                         mono_mb_emit_exception_marshal_directive (m->mb, msg);
7426                 }
7427                 */
7428                 break;
7429
7430         case MARSHAL_ACTION_PUSH:
7431                 mono_mb_emit_ldarg (mb, argnum);
7432                 break;
7433
7434         case MARSHAL_ACTION_CONV_RESULT:
7435                 /* no conversions necessary */
7436                 mono_mb_emit_stloc (mb, 3);
7437                 break;
7438
7439         default:
7440                 break;
7441         }
7442 #endif
7443         return conv_arg;
7444 }
7445
7446 static int
7447 emit_marshal_char (EmitMarshalContext *m, int argnum, MonoType *t, 
7448                    MonoMarshalSpec *spec, int conv_arg, 
7449                    MonoType **conv_arg_type, MarshalAction action)
7450 {
7451 #ifdef HAVE_ONLINE_VES
7452         MonoMethodBuilder *mb = m->mb;
7453
7454         switch (action) {
7455         case MARSHAL_ACTION_PUSH:
7456                 /* fixme: dont know how to marshal that. We cant simply
7457                  * convert it to a one byte UTF8 character, because an
7458                  * unicode character may need more that one byte in UTF8 */
7459                 mono_mb_emit_ldarg (mb, argnum);
7460                 break;
7461
7462         case MARSHAL_ACTION_CONV_RESULT:
7463                 /* fixme: we need conversions here */
7464                 mono_mb_emit_stloc (mb, 3);
7465                 break;
7466
7467         default:
7468                 break;
7469         }
7470 #endif
7471         return conv_arg;
7472 }
7473
7474 static int
7475 emit_marshal_scalar (EmitMarshalContext *m, int argnum, MonoType *t, 
7476                      MonoMarshalSpec *spec, int conv_arg, 
7477                      MonoType **conv_arg_type, MarshalAction action)
7478 {
7479 #ifdef HAVE_ONLINE_VES
7480         MonoMethodBuilder *mb = m->mb;
7481
7482         switch (action) {
7483         case MARSHAL_ACTION_PUSH:
7484                 mono_mb_emit_ldarg (mb, argnum);
7485                 break;
7486
7487         case MARSHAL_ACTION_CONV_RESULT:
7488                 /* no conversions necessary */
7489                 mono_mb_emit_stloc (mb, 3);
7490                 break;
7491
7492         default:
7493                 break;
7494         }
7495 #endif
7496         return conv_arg;
7497 }
7498
7499 static int
7500 emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t, 
7501               MonoMarshalSpec *spec, int conv_arg, 
7502               MonoType **conv_arg_type, MarshalAction action)
7503 {
7504         /* Ensure that we have marshalling info for this param */
7505         mono_marshal_load_type_info (mono_class_from_mono_type (t));
7506
7507         if (spec && spec->native == MONO_NATIVE_CUSTOM)
7508                 return emit_marshal_custom (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7509
7510         if (spec && spec->native == MONO_NATIVE_ASANY)
7511                 return emit_marshal_asany (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7512                         
7513         switch (t->type) {
7514         case MONO_TYPE_VALUETYPE:
7515                 if (t->data.klass == mono_defaults.handleref_class)
7516                         return emit_marshal_handleref (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7517                 
7518                 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7519         case MONO_TYPE_STRING:
7520                 return emit_marshal_string (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7521         case MONO_TYPE_CLASS:
7522         case MONO_TYPE_OBJECT:
7523 #if !defined(DISABLE_COM) && defined(HAVE_ONLINE_VES)
7524                 if (spec && spec->native == MONO_NATIVE_STRUCT)
7525                         return emit_marshal_variant (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7526 #endif
7527
7528 #if !defined(DISABLE_COM)
7529                 if (spec && (spec->native == MONO_NATIVE_IUNKNOWN ||
7530                         spec->native == MONO_NATIVE_IDISPATCH ||
7531                         spec->native == MONO_NATIVE_INTERFACE))
7532                         return mono_cominterop_emit_marshal_com_interface (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7533                 if (spec && (spec->native == MONO_NATIVE_SAFEARRAY) && 
7534                         (spec->data.safearray_data.elem_type == MONO_VARIANT_VARIANT) && 
7535                         ((action == MARSHAL_ACTION_CONV_OUT) || (action == MARSHAL_ACTION_CONV_IN) || (action == MARSHAL_ACTION_PUSH)))
7536                         return mono_cominterop_emit_marshal_safearray (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7537 #endif
7538
7539                 if (mono_class_try_get_safehandle_class () != NULL && t->data.klass &&
7540                     mono_class_is_subclass_of (t->data.klass,  mono_class_try_get_safehandle_class (), FALSE))
7541                         return emit_marshal_safehandle (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7542                 
7543                 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7544         case MONO_TYPE_ARRAY:
7545         case MONO_TYPE_SZARRAY:
7546                 return emit_marshal_array (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7547         case MONO_TYPE_BOOLEAN:
7548                 return emit_marshal_boolean (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7549         case MONO_TYPE_PTR:
7550                 return emit_marshal_ptr (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7551         case MONO_TYPE_CHAR:
7552                 return emit_marshal_char (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7553         case MONO_TYPE_I1:
7554         case MONO_TYPE_U1:
7555         case MONO_TYPE_I2:
7556         case MONO_TYPE_U2:
7557         case MONO_TYPE_I4:
7558         case MONO_TYPE_U4:
7559         case MONO_TYPE_I:
7560         case MONO_TYPE_U:
7561         case MONO_TYPE_R4:
7562         case MONO_TYPE_R8:
7563         case MONO_TYPE_I8:
7564         case MONO_TYPE_U8:
7565         case MONO_TYPE_FNPTR:
7566                 return emit_marshal_scalar (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7567         case MONO_TYPE_GENERICINST:
7568                 if (mono_type_generic_inst_is_valuetype (t))
7569                         return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7570                 else
7571                         return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7572         default:
7573                 return conv_arg;
7574         }
7575 }
7576
7577 /* How the arguments of an icall should be wrapped */
7578 typedef enum {
7579         /* Don't wrap at all, pass the argument as is */
7580         ICALL_HANDLES_WRAP_NONE,
7581         /* Wrap the argument in an object handle, pass the handle to the icall */
7582         ICALL_HANDLES_WRAP_OBJ,
7583         /* Wrap the argument in an object handle, pass the handle to the icall,
7584            write the value out from the handle when the icall returns */
7585         ICALL_HANDLES_WRAP_OBJ_INOUT,
7586         /* Initialized an object handle to null, pass to the icalls,
7587            write the value out from the handle when the icall returns */
7588         ICALL_HANDLES_WRAP_OBJ_OUT,
7589         /* Wrap the argument (a valuetype reference) in a handle to pin its enclosing object,
7590            but pass the raw reference to the icall */
7591         ICALL_HANDLES_WRAP_VALUETYPE_REF,
7592 } IcallHandlesWrap;
7593
7594 typedef struct {
7595         IcallHandlesWrap wrap;
7596         /* if wrap is NONE or OBJ or VALUETYPE_REF, this is not meaningful.
7597            if wrap is OBJ_INOUT it's the local var that holds the MonoObjectHandle.
7598         */
7599         int handle;
7600 }  IcallHandlesLocal;
7601
7602 /*
7603  * Describes how to wrap the given parameter.
7604  *
7605  */
7606 static IcallHandlesWrap
7607 signature_param_uses_handles (MonoMethodSignature *sig, int param)
7608 {
7609         if (MONO_TYPE_IS_REFERENCE (sig->params [param])) {
7610                 if (mono_signature_param_is_out (sig, param))
7611                         return ICALL_HANDLES_WRAP_OBJ_OUT;
7612                 else if (mono_type_is_byref (sig->params [param]))
7613                         return ICALL_HANDLES_WRAP_OBJ_INOUT;
7614                 else
7615                         return ICALL_HANDLES_WRAP_OBJ;
7616         } else if (mono_type_is_byref (sig->params [param]))
7617                 return ICALL_HANDLES_WRAP_VALUETYPE_REF;
7618         else
7619                 return ICALL_HANDLES_WRAP_NONE;
7620 }
7621
7622
7623 #ifdef HAVE_ONLINE_VES
7624 /**
7625  * mono_marshal_emit_native_wrapper:
7626  * \param image the image to use for looking up custom marshallers
7627  * \param sig The signature of the native function
7628  * \param piinfo Marshalling information
7629  * \param mspecs Marshalling information
7630  * \param aot whenever the created method will be compiled by the AOT compiler
7631  * \param method if non-NULL, the pinvoke method to call
7632  * \param check_exceptions Whenever to check for pending exceptions after the native call
7633  * \param func_param the function to call is passed as a boxed IntPtr as the first parameter
7634  *
7635  * generates IL code for the pinvoke wrapper, the generated code calls \p func .
7636  */
7637 void
7638 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)
7639 {
7640         EmitMarshalContext m;
7641         MonoMethodSignature *csig;
7642         MonoClass *klass;
7643         int i, argnum, *tmp_locals;
7644         int type, param_shift = 0;
7645         int coop_gc_stack_dummy, coop_gc_var;
7646
7647         memset (&m, 0, sizeof (m));
7648         m.mb = mb;
7649         m.sig = sig;
7650         m.piinfo = piinfo;
7651
7652         /* we copy the signature, so that we can set pinvoke to 0 */
7653         if (func_param) {
7654                 /* The function address is passed as the first argument */
7655                 g_assert (!sig->hasthis);
7656                 param_shift += 1;
7657         }
7658         csig = mono_metadata_signature_dup_full (mb->method->klass->image, sig);
7659         csig->pinvoke = 1;
7660         m.csig = csig;
7661         m.image = image;
7662
7663         if (sig->hasthis)
7664                 param_shift += 1;
7665
7666         /* we allocate local for use with emit_struct_conv() */
7667         /* allocate local 0 (pointer) src_ptr */
7668         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7669         /* allocate local 1 (pointer) dst_ptr */
7670         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7671         /* allocate local 2 (boolean) delete_old */
7672         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7673
7674         /* delete_old = FALSE */
7675         mono_mb_emit_icon (mb, 0);
7676         mono_mb_emit_stloc (mb, 2);
7677
7678         if (!MONO_TYPE_IS_VOID (sig->ret)) {
7679                 /* allocate local 3 to store the return value */
7680                 mono_mb_add_local (mb, sig->ret);
7681         }
7682
7683         if (mono_threads_is_coop_enabled ()) {
7684                 /* local 4, dummy local used to get a stack address for suspend funcs */
7685                 coop_gc_stack_dummy = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7686                 /* local 5, the local to be used when calling the suspend funcs */
7687                 coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7688         }
7689
7690         /*
7691          * cookie = mono_threads_enter_gc_safe_region_unbalanced (ref dummy);
7692          *
7693          * ret = method (...);
7694          *
7695          * mono_threads_exit_gc_safe_region_unbalanced (cookie, ref dummy);
7696          *
7697          * <interrupt check>
7698          *
7699          * return ret;
7700          */
7701
7702         if (MONO_TYPE_ISSTRUCT (sig->ret))
7703                 m.vtaddr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7704
7705         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7706                 /* Return type custom marshaling */
7707                 /*
7708                  * Since we can't determine the return type of the unmanaged function,
7709                  * we assume it returns a pointer, and pass that pointer to
7710                  * MarshalNativeToManaged.
7711                  */
7712                 csig->ret = &mono_defaults.int_class->byval_arg;
7713         }
7714
7715         /* we first do all conversions */
7716         tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
7717         m.orig_conv_args = (int *)alloca (sizeof (int) * (sig->param_count + 1));
7718
7719         for (i = 0; i < sig->param_count; i ++) {
7720                 tmp_locals [i] = emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_CONV_IN);
7721         }
7722
7723         // In coop mode need to register blocking state during native call
7724         if (mono_threads_is_coop_enabled ()) {
7725                 // Perform an extra, early lookup of the function address, so any exceptions
7726                 // potentially resulting from the lookup occur before entering blocking mode.
7727                 if (!func_param && !MONO_CLASS_IS_IMPORT (mb->method->klass) && aot) {
7728                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7729                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7730                         mono_mb_emit_byte (mb, CEE_POP); // Result not needed yet
7731                 }
7732
7733                 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7734                 mono_mb_emit_icall (mb, mono_threads_enter_gc_safe_region_unbalanced);
7735                 mono_mb_emit_stloc (mb, coop_gc_var);
7736         }
7737
7738         /* push all arguments */
7739
7740         if (sig->hasthis)
7741                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7742
7743         for (i = 0; i < sig->param_count; i++) {
7744                 emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
7745         }                       
7746
7747         /* call the native method */
7748         if (func_param) {
7749                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7750                 mono_mb_emit_op (mb, CEE_UNBOX, mono_defaults.int_class);
7751                 mono_mb_emit_byte (mb, CEE_LDIND_I);
7752                 mono_mb_emit_calli (mb, csig);
7753         } else if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
7754 #ifndef DISABLE_COM
7755                 mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
7756 #else
7757                 g_assert_not_reached ();
7758 #endif
7759         } else {
7760                 if (aot) {
7761                         /* Reuse the ICALL_ADDR opcode for pinvokes too */
7762                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7763                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7764                         mono_mb_emit_calli (mb, csig);
7765                 } else {                        
7766                         mono_mb_emit_native_call (mb, csig, func);
7767                 }
7768         }
7769
7770         /* Set LastError if needed */
7771         if (piinfo->piflags & PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR) {
7772 #ifdef TARGET_WIN32
7773                 if (!aot) {
7774                         static MonoMethodSignature *get_last_error_sig = NULL;
7775                         if (!get_last_error_sig) {
7776                                 get_last_error_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
7777                                 get_last_error_sig->ret = &mono_defaults.int_class->byval_arg;
7778                                 get_last_error_sig->pinvoke = 1;
7779                         }
7780
7781                         /*
7782                          * Have to call GetLastError () early and without a wrapper, since various runtime components could
7783                          * clobber its value.
7784                          */
7785                         mono_mb_emit_native_call (mb, get_last_error_sig, GetLastError);
7786                         mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7787                 } else {
7788                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7789                         mono_mb_emit_byte (mb, CEE_MONO_GET_LAST_ERROR);
7790                         mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7791                 }
7792 #else
7793                 mono_mb_emit_icall (mb, mono_marshal_set_last_error);
7794 #endif
7795         }
7796
7797         if (MONO_TYPE_ISSTRUCT (sig->ret)) {
7798                 MonoClass *klass = mono_class_from_mono_type (sig->ret);
7799                 mono_class_init (klass);
7800                 if (!(mono_class_is_explicit_layout (klass) || klass->blittable)) {
7801                         /* This is used by emit_marshal_vtype (), but it needs to go right before the call */
7802                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7803                         mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
7804                         mono_mb_emit_stloc (mb, m.vtaddr_var);
7805                 }
7806         }
7807
7808         /* Unblock before converting the result, since that can involve calls into the runtime */
7809         if (mono_threads_is_coop_enabled ()) {
7810                 mono_mb_emit_ldloc (mb, coop_gc_var);
7811                 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7812                 mono_mb_emit_icall (mb, mono_threads_exit_gc_safe_region_unbalanced);
7813         }
7814
7815         /* convert the result */
7816         if (!sig->ret->byref) {
7817                 MonoMarshalSpec *spec = mspecs [0];
7818                 type = sig->ret->type;
7819
7820                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7821                         emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7822                 } else {
7823                 handle_enum:
7824                         switch (type) {
7825                         case MONO_TYPE_VOID:
7826                                 break;
7827                         case MONO_TYPE_VALUETYPE:
7828                                 klass = sig->ret->data.klass;
7829                                 if (klass->enumtype) {
7830                                         type = mono_class_enum_basetype (sig->ret->data.klass)->type;
7831                                         goto handle_enum;
7832                                 }
7833                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7834                                 break;
7835                         case MONO_TYPE_I1:
7836                         case MONO_TYPE_U1:
7837                         case MONO_TYPE_I2:
7838                         case MONO_TYPE_U2:
7839                         case MONO_TYPE_I4:
7840                         case MONO_TYPE_U4:
7841                         case MONO_TYPE_I:
7842                         case MONO_TYPE_U:
7843                         case MONO_TYPE_R4:
7844                         case MONO_TYPE_R8:
7845                         case MONO_TYPE_I8:
7846                         case MONO_TYPE_U8:
7847                         case MONO_TYPE_FNPTR:
7848                         case MONO_TYPE_STRING:
7849                         case MONO_TYPE_CLASS:
7850                         case MONO_TYPE_OBJECT:
7851                         case MONO_TYPE_BOOLEAN:
7852                         case MONO_TYPE_ARRAY:
7853                         case MONO_TYPE_SZARRAY:
7854                         case MONO_TYPE_CHAR:
7855                         case MONO_TYPE_PTR:
7856                         case MONO_TYPE_GENERICINST:
7857                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7858                                 break;
7859                         case MONO_TYPE_TYPEDBYREF:
7860                         default:
7861                                 g_warning ("return type 0x%02x unknown", sig->ret->type);       
7862                                 g_assert_not_reached ();
7863                         }
7864                 }
7865         } else {
7866                 mono_mb_emit_stloc (mb, 3);
7867         }
7868
7869         /* 
7870          * Need to call this after converting the result since MONO_VTADDR needs 
7871          * to be adjacent to the call instruction.
7872          */
7873         if (check_exceptions)
7874                 emit_thread_interrupt_checkpoint (mb);
7875
7876         /* we need to convert byref arguments back and free string arrays */
7877         for (i = 0; i < sig->param_count; i++) {
7878                 MonoType *t = sig->params [i];
7879                 MonoMarshalSpec *spec = mspecs [i + 1];
7880
7881                 argnum = i + param_shift;
7882
7883                 if (spec && ((spec->native == MONO_NATIVE_CUSTOM) || (spec->native == MONO_NATIVE_ASANY))) {
7884                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7885                         continue;
7886                 }
7887
7888                 switch (t->type) {
7889                 case MONO_TYPE_STRING:
7890                 case MONO_TYPE_VALUETYPE:
7891                 case MONO_TYPE_CLASS:
7892                 case MONO_TYPE_OBJECT:
7893                 case MONO_TYPE_SZARRAY:
7894                 case MONO_TYPE_BOOLEAN:
7895                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7896                         break;
7897                 default:
7898                         break;
7899                 }
7900         }
7901
7902         if (!MONO_TYPE_IS_VOID(sig->ret))
7903                 mono_mb_emit_ldloc (mb, 3);
7904
7905         mono_mb_emit_byte (mb, CEE_RET);
7906 }
7907 #endif /* HAVE_ONLINE_VES */
7908
7909 /**
7910  * mono_marshal_get_native_wrapper:
7911  * \param method The \c MonoMethod to wrap.
7912  * \param check_exceptions Whenever to check for pending exceptions
7913  *
7914  * Generates IL code for the pinvoke wrapper. The generated method
7915  * calls the unmanaged code in \c piinfo->addr.
7916  */
7917 MonoMethod *
7918 mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
7919 {
7920         MonoMethodSignature *sig, *csig;
7921         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7922         MonoMethodBuilder *mb;
7923         MonoMarshalSpec **mspecs;
7924         MonoMethod *res;
7925         GHashTable *cache;
7926         gboolean pinvoke = FALSE;
7927         gpointer iter;
7928         int i;
7929         const char *exc_class = "MissingMethodException";
7930         const char *exc_arg = NULL;
7931         WrapperInfo *info;
7932
7933         g_assert (method != NULL);
7934         g_assert (mono_method_signature (method)->pinvoke);
7935
7936         GHashTable **cache_ptr;
7937
7938         if (aot) {
7939                 if (check_exceptions)
7940                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_check_cache;
7941                 else
7942                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_cache;
7943         } else {
7944                 if (check_exceptions)
7945                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_check_cache;
7946                 else
7947                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_cache;
7948         }
7949
7950         cache = get_cache (cache_ptr, mono_aligned_addr_hash, NULL);
7951
7952         if ((res = mono_marshal_find_in_cache (cache, method)))
7953                 return res;
7954
7955         if (MONO_CLASS_IS_IMPORT (method->klass)) {
7956                 /* The COM code is not AOT compatible, it calls mono_custom_attrs_get_attr_checked () */
7957                 if (aot)
7958                         return method;
7959 #ifndef DISABLE_COM
7960                 return mono_cominterop_get_native_wrapper (method);
7961 #else
7962                 g_assert_not_reached ();
7963 #endif
7964         }
7965
7966         sig = mono_method_signature (method);
7967
7968         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
7969             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7970                 pinvoke = TRUE;
7971
7972         if (!piinfo->addr) {
7973                 if (pinvoke) {
7974                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
7975                                 exc_arg = "Method contains unsupported native code";
7976                         else if (!aot)
7977                                 mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7978                 } else {
7979                         piinfo->addr = mono_lookup_internal_call (method);
7980                 }
7981         }
7982
7983         /* hack - redirect certain string constructors to CreateString */
7984         if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
7985                 g_assert (!pinvoke);
7986                 g_assert (method->string_ctor);
7987                 g_assert (sig->hasthis);
7988
7989                 /* CreateString returns a value */
7990                 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7991                 csig->ret = &mono_defaults.string_class->byval_arg;
7992                 csig->pinvoke = 0;
7993
7994                 iter = NULL;
7995                 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
7996                         if (!strcmp ("CreateString", res->name) &&
7997                                 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
7998                                 WrapperInfo *info;
7999
8000                                 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
8001                                 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
8002
8003                                 /* create a wrapper to preserve .ctor in stack trace */
8004                                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
8005
8006 #ifdef HAVE_ONLINE_VES
8007                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8008                                 for (i = 1; i <= csig->param_count; i++)
8009                                         mono_mb_emit_ldarg (mb, i);
8010                                 mono_mb_emit_managed_call (mb, res, NULL);
8011                                 mono_mb_emit_byte (mb, CEE_RET);
8012 #endif
8013
8014                                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRING_CTOR);
8015                                 info->d.string_ctor.method = method;
8016
8017                                 /* use native_wrapper_cache because internal calls are looked up there */
8018                                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
8019                                                                                                          csig->param_count + 1, info, NULL);
8020                                 mono_mb_free (mb);
8021
8022                                 return res;
8023                         }
8024                 }
8025
8026                 /* exception will be thrown */
8027                 piinfo->addr = NULL;
8028                 g_warning ("cannot find CreateString for .ctor");
8029         }
8030
8031         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8032
8033         mb->method->save_lmf = 1;
8034
8035         /*
8036          * In AOT mode and embedding scenarios, it is possible that the icall is not
8037          * registered in the runtime doing the AOT compilation.
8038          */
8039         if (!piinfo->addr && !aot) {
8040 #ifdef HAVE_ONLINE_VES
8041                 mono_mb_emit_exception (mb, exc_class, exc_arg);
8042 #endif
8043                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8044                 info->d.managed_to_native.method = method;
8045
8046                 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
8047                 csig->pinvoke = 0;
8048                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
8049                                                                                          csig->param_count + 16, info, NULL);
8050                 mono_mb_free (mb);
8051
8052                 return res;
8053         }
8054
8055         /* internal calls: we simply push all arguments and call the method (no conversions) */
8056         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
8057                 if (sig->hasthis)
8058                         csig = mono_metadata_signature_dup_add_this (method->klass->image, sig, method->klass);
8059                 else
8060                         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
8061
8062                 //printf ("%s\n", mono_method_full_name (method, 1));
8063
8064                 /* hack - string constructors returns a value */
8065                 if (method->string_ctor)
8066                         csig->ret = &mono_defaults.string_class->byval_arg;
8067
8068 #ifdef HAVE_ONLINE_VES
8069                 // FIXME:
8070                 MonoClass *handle_stack_mark_class;
8071                 MonoClass *error_class;
8072                 int thread_info_var = -1, stack_mark_var = -1, error_var = -1;
8073                 MonoMethodSignature *call_sig = csig;
8074                 gboolean uses_handles = FALSE;
8075                 gboolean save_handles_to_locals = FALSE;
8076                 IcallHandlesLocal *handles_locals = NULL;
8077
8078                 (void) mono_lookup_internal_call_full (method, &uses_handles);
8079
8080                 /* If it uses handles and MonoError, it had better check exceptions */
8081                 g_assert (!uses_handles || check_exceptions);
8082
8083                 if (uses_handles) {
8084                         MonoMethodSignature *ret;
8085
8086                         /* Add a MonoError argument and figure out which args need to be wrapped in handles */
8087                         // FIXME: The stuff from mono_metadata_signature_dup_internal_with_padding ()
8088                         ret = mono_metadata_signature_alloc (method->klass->image, csig->param_count + 1);
8089
8090                         ret->param_count = csig->param_count + 1;
8091                         ret->ret = csig->ret;
8092
8093                         handles_locals = g_new0 (IcallHandlesLocal, csig->param_count);
8094                         for (int i = 0; i < csig->param_count; ++i) {
8095                                 IcallHandlesWrap w = signature_param_uses_handles (csig, i);
8096                                 handles_locals [i].wrap = w;
8097                                 switch (w) {
8098                                 case ICALL_HANDLES_WRAP_OBJ:
8099                                 case ICALL_HANDLES_WRAP_OBJ_INOUT:
8100                                 case ICALL_HANDLES_WRAP_OBJ_OUT:
8101                                         ret->params [i] = mono_class_get_byref_type (mono_class_from_mono_type(csig->params[i]));
8102                                         if (w == ICALL_HANDLES_WRAP_OBJ_OUT || w == ICALL_HANDLES_WRAP_OBJ_INOUT)
8103                                                 save_handles_to_locals = TRUE;
8104                                         break;
8105                                 case ICALL_HANDLES_WRAP_NONE:
8106                                 case ICALL_HANDLES_WRAP_VALUETYPE_REF:
8107                                         ret->params [i] = csig->params [i];
8108                                         break;
8109                                 default:
8110                                         g_assert_not_reached ();
8111                                 }
8112                         }
8113                         /* Add MonoError* param */
8114                         ret->params [csig->param_count] = &mono_get_intptr_class ()->byval_arg;
8115                         ret->pinvoke = csig->pinvoke;
8116
8117                         call_sig = ret;
8118                 }
8119
8120                 if (uses_handles) {
8121                         handle_stack_mark_class = mono_class_load_from_name (mono_get_corlib (), "Mono", "RuntimeStructs/HandleStackMark");
8122                         error_class = mono_class_load_from_name (mono_get_corlib (), "Mono", "RuntimeStructs/MonoError");
8123
8124                         thread_info_var = mono_mb_add_local (mb, &mono_get_intptr_class ()->byval_arg);
8125                         stack_mark_var = mono_mb_add_local (mb, &handle_stack_mark_class->byval_arg);
8126                         error_var = mono_mb_add_local (mb, &error_class->byval_arg);
8127
8128                         if (save_handles_to_locals) {
8129                                 /* add a local var to hold the handles for each out arg */
8130                                 for (int i = 0; i < sig->param_count; ++i) {
8131                                         int j = i + sig->hasthis;
8132                                         switch (handles_locals[j].wrap) {
8133                                         case ICALL_HANDLES_WRAP_NONE:
8134                                         case ICALL_HANDLES_WRAP_OBJ:
8135                                         case ICALL_HANDLES_WRAP_VALUETYPE_REF:
8136                                                 handles_locals [j].handle = -1;
8137                                                 break;
8138                                         case ICALL_HANDLES_WRAP_OBJ_INOUT:
8139                                         case ICALL_HANDLES_WRAP_OBJ_OUT:
8140                                                 handles_locals [j].handle = mono_mb_add_local (mb, sig->params [i]);
8141                                                 break;
8142                                         default:
8143                                                 g_assert_not_reached ();
8144                                         }
8145                                 }
8146                         }
8147                 }
8148
8149                 if (sig->hasthis) {
8150                         int pos;
8151
8152                         /*
8153                          * Add a null check since public icalls can be called with 'call' which
8154                          * does no such check.
8155                          */
8156                         mono_mb_emit_byte (mb, CEE_LDARG_0);                    
8157                         pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
8158                         mono_mb_emit_exception (mb, "NullReferenceException", NULL);
8159                         mono_mb_patch_branch (mb, pos);
8160                 }
8161
8162                 if (uses_handles) {
8163                         mono_mb_emit_ldloc_addr (mb, stack_mark_var);
8164                         mono_mb_emit_ldloc_addr (mb, error_var);
8165                         mono_mb_emit_icall (mb, mono_icall_start);
8166                         mono_mb_emit_stloc (mb, thread_info_var);
8167
8168                         if (sig->hasthis) {
8169                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8170                                 /* TODO support adding wrappers to non-static struct methods */
8171                                 g_assert (!mono_class_is_valuetype(mono_method_get_class (method)));
8172                                 mono_mb_emit_icall (mb, mono_icall_handle_new);
8173                         }
8174                         for (i = 0; i < sig->param_count; i++) {
8175                                 /* load each argument. references into the managed heap get wrapped in handles */
8176                                 int j = i + sig->hasthis;
8177                                 switch (handles_locals[j].wrap) {
8178                                 case ICALL_HANDLES_WRAP_NONE:
8179                                         mono_mb_emit_ldarg (mb, j);
8180                                         break;
8181                                 case ICALL_HANDLES_WRAP_OBJ:
8182                                         /* argI = mono_handle_new (argI_raw) */
8183                                         mono_mb_emit_ldarg (mb, j);
8184                                         mono_mb_emit_icall (mb, mono_icall_handle_new);
8185                                         break;
8186                                 case ICALL_HANDLES_WRAP_OBJ_INOUT:
8187                                 case ICALL_HANDLES_WRAP_OBJ_OUT:
8188                                         /* if inout:
8189                                          *   handleI = argI = mono_handle_new (*argI_raw)
8190                                          * otherwise:
8191                                          *   handleI = argI = mono_handle_new (NULL)
8192                                          */
8193                                         if (handles_locals[j].wrap == ICALL_HANDLES_WRAP_OBJ_INOUT) {
8194                                                 mono_mb_emit_ldarg (mb, j);
8195                                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
8196                                         } else
8197                                                 mono_mb_emit_byte (mb, CEE_LDNULL);
8198                                         mono_mb_emit_icall (mb, mono_icall_handle_new);
8199                                         /* tmp = argI */
8200                                         mono_mb_emit_byte (mb, CEE_DUP);
8201                                         /* handleI = tmp */
8202                                         mono_mb_emit_stloc (mb, handles_locals[j].handle);
8203                                         break;
8204                                 case ICALL_HANDLES_WRAP_VALUETYPE_REF:
8205                                         /* (void) mono_handle_new (argI); argI */
8206                                         mono_mb_emit_ldarg (mb, j);
8207                                         mono_mb_emit_byte (mb, CEE_DUP);
8208                                         mono_mb_emit_icall (mb, mono_icall_handle_new_interior);
8209                                         mono_mb_emit_byte (mb, CEE_POP);
8210 #if 0
8211                                         fprintf (stderr, " Method %s.%s.%s has byref valuetype argument %d\n", method->klass->name_space, method->klass->name, method->name, i);
8212 #endif
8213                                         break;
8214                                 default:
8215                                         g_assert_not_reached ();
8216                                 }
8217                         }
8218                         mono_mb_emit_ldloc_addr (mb, error_var);
8219                 } else {
8220                         if (sig->hasthis)
8221                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8222                         for (i = 0; i < sig->param_count; i++)
8223                                 mono_mb_emit_ldarg (mb, i + sig->hasthis);
8224                 }
8225
8226                 if (aot) {
8227                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8228                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
8229                         mono_mb_emit_calli (mb, call_sig);
8230                 } else {
8231                         g_assert (piinfo->addr);
8232                         mono_mb_emit_native_call (mb, call_sig, piinfo->addr);
8233                 }
8234
8235                 if (uses_handles) {
8236                         if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
8237                                 // if (ret != NULL_HANDLE) {
8238                                 //   ret = MONO_HANDLE_RAW(ret)
8239                                 // }
8240                                 mono_mb_emit_byte (mb, CEE_DUP);
8241                                 int pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8242                                 mono_mb_emit_ldflda (mb, MONO_HANDLE_PAYLOAD_OFFSET (MonoObject));
8243                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
8244                                 mono_mb_patch_branch (mb, pos);
8245                         }
8246                         if (save_handles_to_locals) {
8247                                 for (i = 0; i < sig->param_count; i++) {
8248                                         int j = i + sig->hasthis;
8249                                         switch (handles_locals [j].wrap) {
8250                                         case ICALL_HANDLES_WRAP_NONE:
8251                                         case ICALL_HANDLES_WRAP_OBJ:
8252                                         case ICALL_HANDLES_WRAP_VALUETYPE_REF:
8253                                                 break;
8254                                         case ICALL_HANDLES_WRAP_OBJ_INOUT:
8255                                         case ICALL_HANDLES_WRAP_OBJ_OUT:
8256                                                 /* *argI_raw = MONO_HANDLE_RAW (handleI) */
8257
8258                                                 /* argI_raw */
8259                                                 mono_mb_emit_ldarg (mb, j);
8260                                                 /* handleI */
8261                                                 mono_mb_emit_ldloc (mb, handles_locals [j].handle);
8262                                                 /* MONO_HANDLE_RAW(handleI) */
8263                                                 mono_mb_emit_ldflda (mb, MONO_HANDLE_PAYLOAD_OFFSET (MonoObject));
8264                                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
8265                                                 /* *argI_raw = MONO_HANDLE_RAW(handleI) */
8266                                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
8267                                                 break;
8268                                         default:
8269                                                 g_assert_not_reached ();
8270                                         }
8271                                 }
8272                         }
8273                         g_free (handles_locals);
8274
8275                         mono_mb_emit_ldloc (mb, thread_info_var);
8276                         mono_mb_emit_ldloc_addr (mb, stack_mark_var);
8277                         mono_mb_emit_ldloc_addr (mb, error_var);
8278                         mono_mb_emit_icall (mb, mono_icall_end);
8279                 }
8280
8281                 if (check_exceptions)
8282                         emit_thread_interrupt_checkpoint (mb);
8283                 mono_mb_emit_byte (mb, CEE_RET);
8284 #endif
8285                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8286                 info->d.managed_to_native.method = method;
8287
8288                 csig = mono_metadata_signature_dup_full (method->klass->image, csig);
8289                 csig->pinvoke = 0;
8290                 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
8291                                                                                          info, NULL);
8292
8293                 mono_mb_free (mb);
8294                 return res;
8295         }
8296
8297         g_assert (pinvoke);
8298         if (!aot)
8299                 g_assert (piinfo->addr);
8300
8301 #ifdef HAVE_ONLINE_VES
8302         mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
8303         mono_method_get_marshal_info (method, mspecs);
8304
8305         mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr, aot, check_exceptions, FALSE);
8306 #endif
8307         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PINVOKE);
8308         info->d.managed_to_native.method = method;
8309
8310         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
8311         csig->pinvoke = 0;
8312         res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
8313                                                                                  info, NULL);
8314         mono_mb_free (mb);
8315
8316 #ifdef HAVE_ONLINE_VES
8317         for (i = sig->param_count; i >= 0; i--)
8318                 if (mspecs [i])
8319                         mono_metadata_free_marshal_spec (mspecs [i]);
8320         g_free (mspecs);
8321 #endif
8322
8323         /* mono_method_print_code (res); */
8324
8325         return res;
8326 }
8327
8328 /**
8329  * mono_marshal_get_native_func_wrapper:
8330  * \param image The image to use for memory allocation and for looking up custom marshallers.
8331  * \param sig The signature of the function
8332  * \param func The native function to wrap
8333  *
8334  * \returns a wrapper method around native functions, similar to the pinvoke
8335  * wrapper.
8336  */
8337 MonoMethod *
8338 mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig, 
8339                                                                           MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
8340 {
8341         MonoMethodSignature *csig;
8342
8343         SignaturePointerPair key, *new_key;
8344         MonoMethodBuilder *mb;
8345         MonoMethod *res;
8346         GHashTable *cache;
8347         gboolean found;
8348         char *name;
8349
8350         key.sig = sig;
8351         key.pointer = func;
8352
8353         // Generic types are not safe to place in MonoImage caches.
8354         g_assert (!sig->is_inflated);
8355
8356         cache = get_cache (&image->native_func_wrapper_cache, signature_pointer_pair_hash, signature_pointer_pair_equal);
8357         if ((res = mono_marshal_find_in_cache (cache, &key)))
8358                 return res;
8359
8360         name = g_strdup_printf ("wrapper_native_%p", func);
8361         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8362         mb->method->save_lmf = 1;
8363
8364 #ifdef HAVE_ONLINE_VES
8365         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE, FALSE);
8366 #endif
8367
8368         csig = mono_metadata_signature_dup_full (image, sig);
8369         csig->pinvoke = 0;
8370
8371         new_key = g_new (SignaturePointerPair,1);
8372         new_key->sig = csig;
8373         new_key->pointer = func;
8374
8375         res = mono_mb_create_and_cache_full (cache, new_key, mb, csig, csig->param_count + 16, NULL, &found);
8376         if (found)
8377                 g_free (new_key);
8378
8379         mono_mb_free (mb);
8380
8381         mono_marshal_set_wrapper_info (res, NULL);
8382
8383         return res;
8384 }
8385
8386 /*
8387  * The wrapper receives the native function as a boxed IntPtr as its 'this' argument. This is easier to support in
8388  * AOT.
8389  */
8390 MonoMethod*
8391 mono_marshal_get_native_func_wrapper_aot (MonoClass *klass)
8392 {
8393         MonoMethodSignature *sig, *csig;
8394         MonoMethodBuilder *mb;
8395         MonoMethod *res;
8396         GHashTable *cache;
8397         char *name;
8398         WrapperInfo *info;
8399         MonoMethodPInvoke mpiinfo;
8400         MonoMethodPInvoke *piinfo = &mpiinfo;
8401         MonoMarshalSpec **mspecs;
8402         MonoMethod *invoke = mono_get_delegate_invoke (klass);
8403         MonoImage *image = invoke->klass->image;
8404         int i;
8405
8406         // FIXME: include UnmanagedFunctionPointerAttribute info
8407
8408         /*
8409          * The wrapper is associated with the delegate type, to pick up the marshalling info etc.
8410          */
8411         cache = get_cache (&mono_method_get_wrapper_cache (invoke)->native_func_wrapper_aot_cache, mono_aligned_addr_hash, NULL);
8412
8413         if ((res = mono_marshal_find_in_cache (cache, invoke)))
8414                 return res;
8415
8416         memset (&mpiinfo, 0, sizeof (mpiinfo));
8417         parse_unmanaged_function_pointer_attr (klass, &mpiinfo);
8418
8419         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8420         mono_method_get_marshal_info (invoke, mspecs);
8421         /* Freed below so don't alloc from mempool */
8422         sig = mono_metadata_signature_dup (mono_method_signature (invoke));
8423         sig->hasthis = 0;
8424
8425         name = g_strdup_printf ("wrapper_aot_native");
8426         mb = mono_mb_new (invoke->klass, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8427         mb->method->save_lmf = 1;
8428
8429 #ifdef HAVE_ONLINE_VES
8430         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, NULL, FALSE, TRUE, TRUE);
8431 #endif
8432
8433         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NATIVE_FUNC_AOT);
8434         info->d.managed_to_native.method = invoke;
8435
8436         g_assert (!sig->hasthis);
8437         csig = mono_metadata_signature_dup_add_this (image, sig, mono_defaults.object_class);
8438         csig->pinvoke = 0;
8439         res = mono_mb_create_and_cache_full (cache, invoke,
8440                                                                                  mb, csig, csig->param_count + 16,
8441                                                                                  info, NULL);
8442         mono_mb_free (mb);
8443
8444         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8445                 if (mspecs [i])
8446                         mono_metadata_free_marshal_spec (mspecs [i]);
8447         g_free (mspecs);
8448         g_free (sig);
8449
8450         return res;
8451 }
8452
8453 /*
8454  * mono_marshal_emit_managed_wrapper:
8455  *
8456  *   Emit the body of a native-to-managed wrapper. INVOKE_SIG is the signature of
8457  * the delegate which wraps the managed method to be called. For closed delegates,
8458  * it could have fewer parameters than the method it wraps.
8459  * THIS_LOC is the memory location where the target of the delegate is stored.
8460  */
8461 void
8462 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, uint32_t target_handle)
8463 {
8464 #ifndef HAVE_ONLINE_VES
8465         MonoMethodSignature *sig, *csig;
8466         int i;
8467
8468         sig = m->sig;
8469         csig = m->csig;
8470
8471         /* we first do all conversions */
8472         for (i = 0; i < sig->param_count; i ++) {
8473                 MonoType *t = sig->params [i];
8474
8475                 switch (t->type) {
8476                 case MONO_TYPE_OBJECT:
8477                 case MONO_TYPE_CLASS:
8478                 case MONO_TYPE_VALUETYPE:
8479                 case MONO_TYPE_ARRAY:
8480                 case MONO_TYPE_SZARRAY:
8481                 case MONO_TYPE_STRING:
8482                 case MONO_TYPE_BOOLEAN:
8483                         emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
8484                 }
8485         }
8486
8487         if (!sig->ret->byref) {
8488                 switch (sig->ret->type) {
8489                 case MONO_TYPE_STRING:
8490                         csig->ret = &mono_defaults.int_class->byval_arg;
8491                         break;
8492                 default:
8493                         break;
8494                 }
8495         }
8496 #else
8497         MonoMethodSignature *sig, *csig;
8498         MonoExceptionClause *clauses, *clause_finally, *clause_catch;
8499         int i, *tmp_locals, ex_local, e_local, attach_cookie_local, attach_dummy_local;
8500         int leave_try_pos, leave_catch_pos, ex_m1_pos;
8501         gboolean closed = FALSE;
8502
8503         sig = m->sig;
8504         csig = m->csig;
8505
8506         /* allocate local 0 (pointer) src_ptr */
8507         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8508         /* allocate local 1 (pointer) dst_ptr */
8509         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8510         /* allocate local 2 (boolean) delete_old */
8511         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8512
8513         if (!sig->hasthis && sig->param_count != invoke_sig->param_count) {
8514                 /* Closed delegate */
8515                 g_assert (sig->param_count == invoke_sig->param_count + 1);
8516                 closed = TRUE;
8517                 /* Use a new signature without the first argument */
8518                 sig = mono_metadata_signature_dup (sig);
8519                 memmove (&sig->params [0], &sig->params [1], (sig->param_count - 1) * sizeof (MonoType*));
8520                 sig->param_count --;
8521         }
8522
8523         if (!MONO_TYPE_IS_VOID(sig->ret)) {
8524                 /* allocate local 3 to store the return value */
8525                 mono_mb_add_local (mb, sig->ret);
8526         }
8527
8528         if (MONO_TYPE_ISSTRUCT (sig->ret))
8529                 m->vtaddr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8530
8531         ex_local = mono_mb_add_local (mb, &mono_defaults.uint32_class->byval_arg);
8532         e_local = mono_mb_add_local (mb, &mono_defaults.exception_class->byval_arg);
8533
8534         attach_cookie_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8535         attach_dummy_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8536
8537         /*
8538          * guint32 ex = -1;
8539          * try {
8540          *   // does (STARTING|RUNNING|BLOCKING) -> RUNNING + set/switch domain
8541          *   mono_threads_attach_coop ();
8542          *
8543          *   <interrupt check>
8544          *
8545          *   ret = method (...);
8546          * } catch (Exception e) {
8547          *   ex = mono_gchandle_new (e, false);
8548          * } finally {
8549          *   // does RUNNING -> (RUNNING|BLOCKING) + unset/switch domain
8550          *   mono_threads_detach_coop ();
8551          *
8552          *   if (ex != -1)
8553          *     mono_marshal_ftnptr_eh_callback (ex);
8554          * }
8555          *
8556          * return ret;
8557          */
8558
8559         clauses = g_new0 (MonoExceptionClause, 2);
8560
8561         clause_catch = &clauses [0];
8562         clause_catch->flags = MONO_EXCEPTION_CLAUSE_NONE;
8563         clause_catch->data.catch_class = mono_defaults.exception_class;
8564
8565         clause_finally = &clauses [1];
8566         clause_finally->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
8567
8568         mono_mb_emit_icon (mb, 0);
8569         mono_mb_emit_stloc (mb, 2);
8570
8571         mono_mb_emit_icon (mb, -1);
8572         mono_mb_emit_byte (mb, CEE_CONV_U4);
8573         mono_mb_emit_stloc (mb, ex_local);
8574
8575         /* try { */
8576         clause_catch->try_offset = clause_finally->try_offset = mono_mb_get_label (mb);
8577
8578         if (!mono_threads_is_coop_enabled ()) {
8579                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8580                 mono_mb_emit_byte (mb, CEE_MONO_JIT_ATTACH);
8581         } else {
8582                 /* mono_threads_attach_coop (); */
8583                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8584                 mono_mb_emit_byte (mb, CEE_MONO_LDDOMAIN);
8585                 mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
8586                 mono_mb_emit_icall (mb, mono_threads_attach_coop);
8587                 mono_mb_emit_stloc (mb, attach_cookie_local);
8588         }
8589
8590         /* <interrupt check> */
8591         emit_thread_interrupt_checkpoint (mb);
8592
8593         /* we first do all conversions */
8594         tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
8595         for (i = 0; i < sig->param_count; i ++) {
8596                 MonoType *t = sig->params [i];
8597
8598                 switch (t->type) {
8599                 case MONO_TYPE_OBJECT:
8600                 case MONO_TYPE_CLASS:
8601                 case MONO_TYPE_VALUETYPE:
8602                 case MONO_TYPE_ARRAY:
8603                 case MONO_TYPE_SZARRAY:
8604                 case MONO_TYPE_STRING:
8605                 case MONO_TYPE_BOOLEAN:
8606                         tmp_locals [i] = emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
8607
8608                         break;
8609                 default:
8610                         tmp_locals [i] = 0;
8611                         break;
8612                 }
8613         }
8614
8615         if (sig->hasthis) {
8616                 if (target_handle) {
8617                         mono_mb_emit_icon (mb, (gint32)target_handle);
8618                         mono_mb_emit_icall (mb, mono_gchandle_get_target);
8619                 } else {
8620                         /* fixme: */
8621                         g_assert_not_reached ();
8622                 }
8623         } else if (closed) {
8624                 mono_mb_emit_icon (mb, (gint32)target_handle);
8625                 mono_mb_emit_icall (mb, mono_gchandle_get_target);
8626         }
8627
8628         for (i = 0; i < sig->param_count; i++) {
8629                 MonoType *t = sig->params [i];
8630
8631                 if (tmp_locals [i]) {
8632                         if (t->byref)
8633                                 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
8634                         else
8635                                 mono_mb_emit_ldloc (mb, tmp_locals [i]);
8636                 }
8637                 else
8638                         mono_mb_emit_ldarg (mb, i);
8639         }
8640
8641         /* ret = method (...) */
8642         mono_mb_emit_managed_call (mb, method, NULL);
8643
8644         if (MONO_TYPE_ISSTRUCT (sig->ret)) {
8645                 MonoClass *klass = mono_class_from_mono_type (sig->ret);
8646                 mono_class_init (klass);
8647                 if (!(mono_class_is_explicit_layout (klass) || klass->blittable)) {
8648                         /* This is used by emit_marshal_vtype (), but it needs to go right before the call */
8649                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8650                         mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
8651                         mono_mb_emit_stloc (mb, m->vtaddr_var);
8652                 }
8653         }
8654
8655         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
8656                 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8657         } else if (!sig->ret->byref) { 
8658                 switch (sig->ret->type) {
8659                 case MONO_TYPE_VOID:
8660                         break;
8661                 case MONO_TYPE_BOOLEAN:
8662                 case MONO_TYPE_I1:
8663                 case MONO_TYPE_U1:
8664                 case MONO_TYPE_CHAR:
8665                 case MONO_TYPE_I2:
8666                 case MONO_TYPE_U2:
8667                 case MONO_TYPE_I4:
8668                 case MONO_TYPE_U4:
8669                 case MONO_TYPE_I:
8670                 case MONO_TYPE_U:
8671                 case MONO_TYPE_PTR:
8672                 case MONO_TYPE_R4:
8673                 case MONO_TYPE_R8:
8674                 case MONO_TYPE_I8:
8675                 case MONO_TYPE_U8:
8676                 case MONO_TYPE_OBJECT:
8677                         mono_mb_emit_stloc (mb, 3);
8678                         break;
8679                 case MONO_TYPE_STRING:
8680                         csig->ret = &mono_defaults.int_class->byval_arg;
8681                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8682                         break;
8683                 case MONO_TYPE_VALUETYPE:
8684                 case MONO_TYPE_CLASS:
8685                 case MONO_TYPE_SZARRAY:
8686                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8687                         break;
8688                 default:
8689                         g_warning ("return type 0x%02x unknown", sig->ret->type);       
8690                         g_assert_not_reached ();
8691                 }
8692         } else {
8693                 mono_mb_emit_stloc (mb, 3);
8694         }
8695
8696         /* Convert byref arguments back */
8697         for (i = 0; i < sig->param_count; i ++) {
8698                 MonoType *t = sig->params [i];
8699                 MonoMarshalSpec *spec = mspecs [i + 1];
8700
8701                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
8702                         emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8703                 }
8704                 else if (t->byref) {
8705                         switch (t->type) {
8706                         case MONO_TYPE_CLASS:
8707                         case MONO_TYPE_VALUETYPE:
8708                         case MONO_TYPE_OBJECT:
8709                         case MONO_TYPE_STRING:
8710                         case MONO_TYPE_BOOLEAN:
8711                                 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8712                                 break;
8713                         default:
8714                                 break;
8715                         }
8716                 }
8717                 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
8718                         /* The [Out] information is encoded in the delegate signature */
8719                         switch (t->type) {
8720                         case MONO_TYPE_SZARRAY:
8721                         case MONO_TYPE_CLASS:
8722                         case MONO_TYPE_VALUETYPE:
8723                                 emit_marshal (m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8724                                 break;
8725                         default:
8726                                 g_assert_not_reached ();
8727                         }
8728                 }
8729         }
8730
8731         leave_try_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8732
8733         /* } [endtry] */
8734
8735         /* catch (Exception e) { */
8736         clause_catch->try_len = mono_mb_get_label (mb) - clause_catch->try_offset;
8737         clause_catch->handler_offset = mono_mb_get_label (mb);
8738
8739         mono_mb_emit_stloc (mb, e_local);
8740
8741         /* ex = mono_gchandle_new (e, false); */
8742         mono_mb_emit_ldloc (mb, e_local);
8743         mono_mb_emit_icon (mb, 0);
8744         mono_mb_emit_icall (mb, mono_gchandle_new);
8745         mono_mb_emit_stloc (mb, ex_local);
8746
8747         leave_catch_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8748
8749         /* } [endcatch] */
8750         clause_catch->handler_len = mono_mb_get_pos (mb) - clause_catch->handler_offset;
8751
8752         /* finally { */
8753         clause_finally->try_len = mono_mb_get_label (mb) - clause_finally->try_offset;
8754         clause_finally->handler_offset = mono_mb_get_label (mb);
8755
8756         if (!mono_threads_is_coop_enabled ()) {
8757                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8758                 mono_mb_emit_byte (mb, CEE_MONO_JIT_DETACH);
8759         } else {
8760                 /* mono_threads_detach_coop (); */
8761                 mono_mb_emit_ldloc (mb, attach_cookie_local);
8762                 mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
8763                 mono_mb_emit_icall (mb, mono_threads_detach_coop);
8764         }
8765
8766         /* if (ex != -1) */
8767         mono_mb_emit_ldloc (mb, ex_local);
8768         mono_mb_emit_icon (mb, -1);
8769         mono_mb_emit_byte (mb, CEE_CONV_U4);
8770         ex_m1_pos = mono_mb_emit_branch (mb, CEE_BEQ);
8771
8772         /* mono_marshal_ftnptr_eh_callback (ex) */
8773         mono_mb_emit_ldloc (mb, ex_local);
8774         mono_mb_emit_icall (mb, mono_marshal_ftnptr_eh_callback);
8775
8776         /* [ex == -1] */
8777         mono_mb_patch_branch (mb, ex_m1_pos);
8778
8779         mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8780
8781         /* } [endfinally] */
8782         clause_finally->handler_len = mono_mb_get_pos (mb) - clause_finally->handler_offset;
8783
8784         mono_mb_patch_branch (mb, leave_try_pos);
8785         mono_mb_patch_branch (mb, leave_catch_pos);
8786
8787         /* return ret; */
8788         if (m->retobj_var) {
8789                 mono_mb_emit_ldloc (mb, m->retobj_var);
8790                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8791                 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m->retobj_class);
8792         }
8793         else {
8794                 if (!MONO_TYPE_IS_VOID(sig->ret))
8795                         mono_mb_emit_ldloc (mb, 3);
8796                 mono_mb_emit_byte (mb, CEE_RET);
8797         }
8798
8799         mono_mb_set_clauses (mb, 2, clauses);
8800
8801         if (closed)
8802                 g_free (sig);
8803 #endif
8804 }
8805
8806 static void 
8807 mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *csig)
8808 {
8809         MonoMethodSignature *sig;
8810         int i;
8811
8812 #ifdef TARGET_WIN32
8813         /* 
8814          * Under windows, delegates passed to native code must use the STDCALL
8815          * calling convention.
8816          */
8817         csig->call_convention = MONO_CALL_STDCALL;
8818 #endif
8819
8820         sig = mono_method_signature (method);
8821
8822         /* Change default calling convention if needed */
8823         /* Why is this a modopt ? */
8824         if (sig->ret && sig->ret->num_mods) {
8825                 for (i = 0; i < sig->ret->num_mods; ++i) {
8826                         MonoError error;
8827                         MonoClass *cmod_class = mono_class_get_checked (method->klass->image, sig->ret->modifiers [i].token, &error);
8828                         g_assert (mono_error_ok (&error));
8829                         if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
8830                                 if (!strcmp (cmod_class->name, "CallConvCdecl"))
8831                                         csig->call_convention = MONO_CALL_C;
8832                                 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
8833                                         csig->call_convention = MONO_CALL_STDCALL;
8834                                 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
8835                                         csig->call_convention = MONO_CALL_FASTCALL;
8836                                 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
8837                                         csig->call_convention = MONO_CALL_THISCALL;
8838                         }
8839                 }
8840         }
8841 }
8842
8843 /**
8844  * mono_marshal_get_managed_wrapper:
8845  * Generates IL code to call managed methods from unmanaged code 
8846  * If \p target_handle is \c 0, the wrapper info will be a \c WrapperInfo structure.
8847  */
8848 MonoMethod *
8849 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle, MonoError *error)
8850 {
8851         MonoMethodSignature *sig, *csig, *invoke_sig;
8852         MonoMethodBuilder *mb;
8853         MonoMethod *res, *invoke;
8854         MonoMarshalSpec **mspecs;
8855         MonoMethodPInvoke piinfo;
8856         GHashTable *cache;
8857         int i;
8858         EmitMarshalContext m;
8859
8860         g_assert (method != NULL);
8861         error_init (error);
8862
8863         if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
8864                 mono_error_set_invalid_program (error, "Failed because method (%s) marked PInvokeCallback (managed method) and extern (unmanaged) simultaneously.", mono_method_full_name (method, TRUE));
8865                 return NULL;
8866         }
8867
8868         /* 
8869          * FIXME: Should cache the method+delegate type pair, since the same method
8870          * could be called with different delegates, thus different marshalling
8871          * options.
8872          */
8873         cache = get_cache (&mono_method_get_wrapper_cache (method)->managed_wrapper_cache, mono_aligned_addr_hash, NULL);
8874
8875         if (!target_handle && (res = mono_marshal_find_in_cache (cache, method)))
8876                 return res;
8877
8878         invoke = mono_get_delegate_invoke (delegate_klass);
8879         invoke_sig = mono_method_signature (invoke);
8880
8881         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8882         mono_method_get_marshal_info (invoke, mspecs);
8883
8884         sig = mono_method_signature (method);
8885
8886         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8887
8888         /*the target gchandle must be the first entry after size and the wrapper itself.*/
8889         mono_mb_add_data (mb, GUINT_TO_POINTER (target_handle));
8890
8891         /* we copy the signature, so that we can modify it */
8892         if (target_handle)
8893                 /* Need to free this later */
8894                 csig = mono_metadata_signature_dup (invoke_sig);
8895         else
8896                 csig = mono_metadata_signature_dup_full (method->klass->image, invoke_sig);
8897         csig->hasthis = 0;
8898         csig->pinvoke = 1;
8899
8900         memset (&m, 0, sizeof (m));
8901         m.mb = mb;
8902         m.sig = sig;
8903         m.piinfo = NULL;
8904         m.retobj_var = 0;
8905         m.csig = csig;
8906         m.image = method->klass->image;
8907
8908         mono_marshal_set_callconv_from_modopt (invoke, csig);
8909
8910         /* The attribute is only available in Net 2.0 */
8911         if (mono_class_try_get_unmanaged_function_pointer_attribute_class ()) {
8912                 MonoCustomAttrInfo *cinfo;
8913                 MonoCustomAttrEntry *attr;
8914
8915                 /* 
8916                  * The pinvoke attributes are stored in a real custom attribute. Obtain the
8917                  * contents of the attribute without constructing it, as that might not be
8918                  * possible when running in cross-compiling mode.
8919                  */
8920                 cinfo = mono_custom_attrs_from_class_checked (delegate_klass, error);
8921                 mono_error_assert_ok (error);
8922                 attr = NULL;
8923                 if (cinfo) {
8924                         for (i = 0; i < cinfo->num_attrs; ++i) {
8925                                 MonoClass *ctor_class = cinfo->attrs [i].ctor->klass;
8926                                 if (mono_class_has_parent (ctor_class, mono_class_try_get_unmanaged_function_pointer_attribute_class ())) {
8927                                         attr = &cinfo->attrs [i];
8928                                         break;
8929                                 }
8930                         }
8931                 }
8932                 if (attr) {
8933                         MonoArray *typed_args, *named_args;
8934                         CattrNamedArg *arginfo;
8935                         MonoObject *o;
8936                         gint32 call_conv;
8937                         gint32 charset = 0;
8938                         MonoBoolean set_last_error = 0;
8939                         MonoError error;
8940
8941                         mono_reflection_create_custom_attr_data_args (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8942                         g_assert (mono_error_ok (&error));
8943                         g_assert (mono_array_length (typed_args) == 1);
8944
8945                         /* typed args */
8946                         o = mono_array_get (typed_args, MonoObject*, 0);
8947                         call_conv = *(gint32*)mono_object_unbox (o);
8948
8949                         /* named args */
8950                         for (i = 0; i < mono_array_length (named_args); ++i) {
8951                                 CattrNamedArg *narg = &arginfo [i];
8952
8953                                 o = mono_array_get (named_args, MonoObject*, i);
8954
8955                                 g_assert (narg->field);
8956                                 if (!strcmp (narg->field->name, "CharSet")) {
8957                                         charset = *(gint32*)mono_object_unbox (o);
8958                                 } else if (!strcmp (narg->field->name, "SetLastError")) {
8959                                         set_last_error = *(MonoBoolean*)mono_object_unbox (o);
8960                                 } else if (!strcmp (narg->field->name, "BestFitMapping")) {
8961                                         // best_fit_mapping = *(MonoBoolean*)mono_object_unbox (o);
8962                                 } else if (!strcmp (narg->field->name, "ThrowOnUnmappableChar")) {
8963                                         // throw_on_unmappable = *(MonoBoolean*)mono_object_unbox (o);
8964                                 } else {
8965                                         g_assert_not_reached ();
8966                                 }
8967                         }
8968
8969                         g_free (arginfo);
8970
8971                         memset (&piinfo, 0, sizeof (piinfo));
8972                         m.piinfo = &piinfo;
8973                         piinfo.piflags = (call_conv << 8) | (charset ? (charset - 1) * 2 : 1) | set_last_error;
8974
8975                         csig->call_convention = call_conv - 1;
8976                 }
8977
8978                 if (cinfo && !cinfo->cached)
8979                         mono_custom_attrs_free (cinfo);
8980         }
8981
8982         mono_marshal_emit_managed_wrapper (mb, invoke_sig, mspecs, &m, method, target_handle);
8983
8984         if (!target_handle) {
8985                 WrapperInfo *info;
8986
8987                 // FIXME: Associate it with the method+delegate_klass pair
8988                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8989                 info->d.native_to_managed.method = method;
8990                 info->d.native_to_managed.klass = delegate_klass;
8991
8992                 res = mono_mb_create_and_cache_full (cache, method,
8993                                                                                          mb, csig, sig->param_count + 16,
8994                                                                                          info, NULL);
8995         } else {
8996 #ifdef HAVE_ONLINE_VES
8997                 mb->dynamic = TRUE;
8998 #endif
8999                 res = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
9000         }
9001         mono_mb_free (mb);
9002
9003         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
9004                 if (mspecs [i])
9005                         mono_metadata_free_marshal_spec (mspecs [i]);
9006         g_free (mspecs);
9007
9008         /* mono_method_print_code (res); */
9009
9010         return res;
9011 }
9012
9013 gpointer
9014 mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
9015 {
9016         MonoError error;
9017         MonoMethod *method;
9018         MonoMethodSignature *sig;
9019         MonoMethodBuilder *mb;
9020         int i, param_count;
9021
9022         g_assert (token);
9023
9024         method = mono_get_method_checked (image, token, NULL, NULL, &error);
9025         if (!method)
9026                 g_error ("Could not load vtfixup token 0x%x due to %s", token, mono_error_get_message (&error));
9027         g_assert (method);
9028
9029         if (type & (VTFIXUP_TYPE_FROM_UNMANAGED | VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN)) {
9030                 MonoMethodSignature *csig;
9031                 MonoMarshalSpec **mspecs;
9032                 EmitMarshalContext m;
9033
9034                 sig = mono_method_signature (method);
9035                 g_assert (!sig->hasthis);
9036
9037                 mspecs = g_new0 (MonoMarshalSpec*, sig->param_count + 1);
9038                 mono_method_get_marshal_info (method, mspecs);
9039
9040                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
9041                 csig = mono_metadata_signature_dup_full (image, sig);
9042                 csig->hasthis = 0;
9043                 csig->pinvoke = 1;
9044
9045                 memset (&m, 0, sizeof (m));
9046                 m.mb = mb;
9047                 m.sig = sig;
9048                 m.piinfo = NULL;
9049                 m.retobj_var = 0;
9050                 m.csig = csig;
9051                 m.image = image;
9052
9053                 mono_marshal_set_callconv_from_modopt (method, csig);
9054
9055                 /* FIXME: Implement VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN. */
9056
9057                 mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, 0);
9058
9059 #ifdef HAVE_ONLINE_VES
9060                 mb->dynamic = TRUE;
9061 #endif
9062                 method = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
9063                 mono_mb_free (mb);
9064
9065                 for (i = sig->param_count; i >= 0; i--)
9066                         if (mspecs [i])
9067                                 mono_metadata_free_marshal_spec (mspecs [i]);
9068                 g_free (mspecs);
9069
9070                 gpointer compiled_ptr = mono_compile_method_checked (method, &error);
9071                 mono_error_assert_ok (&error);
9072                 return compiled_ptr;
9073         }
9074
9075         sig = mono_method_signature (method);
9076         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
9077
9078         param_count = sig->param_count + sig->hasthis;
9079 #ifdef HAVE_ONLINE_VES
9080         for (i = 0; i < param_count; i++)
9081                 mono_mb_emit_ldarg (mb, i);
9082
9083         if (type & VTFIXUP_TYPE_CALL_MOST_DERIVED)
9084                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
9085         else
9086                 mono_mb_emit_op (mb, CEE_CALL, method);
9087         mono_mb_emit_byte (mb, CEE_RET);
9088
9089         mb->dynamic = TRUE;
9090 #endif
9091
9092         method = mono_mb_create (mb, sig, param_count, NULL);
9093         mono_mb_free (mb);
9094
9095         gpointer compiled_ptr = mono_compile_method_checked (method, &error);
9096         mono_error_assert_ok (&error);
9097         return compiled_ptr;
9098 }
9099
9100 #ifdef HAVE_ONLINE_VES
9101
9102 /*
9103  * The code directly following this is the cache hit, value positive branch
9104  *
9105  * This function takes a new method builder with 0 locals and adds two locals
9106  * to create multiple out-branches and the fall through state of having the object
9107  * on the stack after a cache miss
9108  */
9109 static void
9110 generate_check_cache (int obj_arg_position, int class_arg_position, int cache_arg_position, // In-parameters
9111                                                                                         int *null_obj, int *cache_hit_neg, int *cache_hit_pos, // Out-parameters
9112                                                                                         MonoMethodBuilder *mb)
9113 {
9114         int cache_miss_pos;
9115
9116         /* allocate local 0 (pointer) obj_vtable */
9117         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9118         /* allocate local 1 (pointer) cached_vtable */
9119         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9120
9121         /*if (!obj)*/
9122         mono_mb_emit_ldarg (mb, obj_arg_position);
9123         *null_obj = mono_mb_emit_branch (mb, CEE_BRFALSE);
9124
9125         /*obj_vtable = obj->vtable;*/
9126         mono_mb_emit_ldarg (mb, obj_arg_position);
9127         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9128         mono_mb_emit_byte (mb, CEE_LDIND_I);
9129         mono_mb_emit_stloc (mb, 0);
9130
9131         /* cached_vtable = *cache*/
9132         mono_mb_emit_ldarg (mb, cache_arg_position);
9133         mono_mb_emit_byte (mb, CEE_LDIND_I);
9134         mono_mb_emit_stloc (mb, 1);
9135
9136         mono_mb_emit_ldloc (mb, 1);
9137         mono_mb_emit_byte (mb, CEE_LDC_I4);
9138         mono_mb_emit_i4 (mb, ~0x1);
9139         mono_mb_emit_byte (mb, CEE_CONV_I);
9140         mono_mb_emit_byte (mb, CEE_AND);
9141         mono_mb_emit_ldloc (mb, 0);
9142         /*if ((cached_vtable & ~0x1)== obj_vtable)*/
9143         cache_miss_pos = mono_mb_emit_branch (mb, CEE_BNE_UN);
9144
9145         /*return (cached_vtable & 0x1) ? NULL : obj;*/
9146         mono_mb_emit_ldloc (mb, 1);
9147         mono_mb_emit_byte(mb, CEE_LDC_I4_1);
9148         mono_mb_emit_byte (mb, CEE_CONV_U);
9149         mono_mb_emit_byte (mb, CEE_AND);
9150         *cache_hit_neg = mono_mb_emit_branch (mb, CEE_BRTRUE);
9151         *cache_hit_pos = mono_mb_emit_branch (mb, CEE_BR);
9152
9153         // slow path
9154         mono_mb_patch_branch (mb, cache_miss_pos);
9155
9156         // if isinst
9157         mono_mb_emit_ldarg (mb, obj_arg_position);
9158         mono_mb_emit_ldarg (mb, class_arg_position);
9159         mono_mb_emit_ldarg (mb, cache_arg_position);
9160         mono_mb_emit_icall (mb, mono_marshal_isinst_with_cache);
9161 }
9162
9163 #endif /* HAVE_ONLINE_VES */
9164
9165 /**
9166  * mono_marshal_get_castclass_with_cache:
9167  * This does the equivalent of \c mono_object_castclass_with_cache.
9168  */
9169 MonoMethod *
9170 mono_marshal_get_castclass_with_cache (void)
9171 {
9172         static MonoMethod *cached;
9173         MonoMethod *res;
9174         MonoMethodBuilder *mb;
9175         MonoMethodSignature *sig;
9176         int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos, invalid_cast_pos;
9177         WrapperInfo *info;
9178
9179         const int obj_arg_position = 0;
9180         const int class_arg_position = 1;
9181         const int cache_arg_position = 2;
9182
9183         if (cached)
9184                 return cached;
9185
9186         mb = mono_mb_new (mono_defaults.object_class, "__castclass_with_cache", MONO_WRAPPER_CASTCLASS);
9187         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9188         sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
9189         sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
9190         sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
9191         sig->ret = &mono_defaults.object_class->byval_arg;
9192         sig->pinvoke = 0;
9193
9194 #ifdef HAVE_ONLINE_VES
9195         generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
9196                                                                                                 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
9197         invalid_cast_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
9198
9199         /*return obj;*/
9200         mono_mb_patch_branch (mb, positive_cache_hit_pos);
9201         mono_mb_emit_ldarg (mb, obj_arg_position);
9202         mono_mb_emit_byte (mb, CEE_RET);
9203
9204         /*fails*/
9205         mono_mb_patch_branch (mb, negative_cache_hit_pos);
9206         mono_mb_patch_branch (mb, invalid_cast_pos);
9207         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
9208
9209         /*return null*/
9210         mono_mb_patch_branch (mb, return_null_pos);
9211         mono_mb_emit_byte (mb, CEE_LDNULL);
9212         mono_mb_emit_byte (mb, CEE_RET);
9213 #endif /* HAVE_ONLINE_VES */
9214
9215         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE);
9216         res = mono_mb_create (mb, sig, 8, info);
9217         STORE_STORE_FENCE;
9218
9219         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
9220                 mono_free_method (res);
9221                 mono_metadata_free_method_signature (sig);
9222         }
9223         mono_mb_free (mb);
9224
9225         return cached;
9226 }
9227
9228 /* this is an icall */
9229 static MonoObject *
9230 mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *cache)
9231 {
9232         MonoError error;
9233         MonoObject *isinst = mono_object_isinst_checked (obj, klass, &error);
9234         if (mono_error_set_pending_exception (&error))
9235                 return NULL;
9236
9237         if (mono_object_is_transparent_proxy (obj))
9238                 return isinst;
9239
9240         uintptr_t cache_update = (uintptr_t)obj->vtable;
9241         if (!isinst)
9242                 cache_update = cache_update | 0x1;
9243
9244         *cache = cache_update;
9245
9246         return isinst;
9247 }
9248
9249 /**
9250  * mono_marshal_get_isinst_with_cache:
9251  * This does the equivalent of \c mono_marshal_isinst_with_cache.
9252  */
9253 MonoMethod *
9254 mono_marshal_get_isinst_with_cache (void)
9255 {
9256         static MonoMethod *cached;
9257         MonoMethod *res;
9258         MonoMethodBuilder *mb;
9259         MonoMethodSignature *sig;
9260         int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos;
9261         WrapperInfo *info;
9262
9263         const int obj_arg_position = 0;
9264         const int class_arg_position = 1;
9265         const int cache_arg_position = 2;
9266
9267         if (cached)
9268                 return cached;
9269
9270         mb = mono_mb_new (mono_defaults.object_class, "__isinst_with_cache", MONO_WRAPPER_CASTCLASS);
9271         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9272         // The object
9273         sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
9274         // The class
9275         sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
9276         // The cache
9277         sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
9278         sig->ret = &mono_defaults.object_class->byval_arg;
9279         sig->pinvoke = 0;
9280
9281 #ifdef HAVE_ONLINE_VES
9282         generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
9283                 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
9284         // Return the object gotten via the slow path.
9285         mono_mb_emit_byte (mb, CEE_RET);
9286
9287         // return NULL;
9288         mono_mb_patch_branch (mb, negative_cache_hit_pos);
9289         mono_mb_patch_branch (mb, return_null_pos);
9290         mono_mb_emit_byte (mb, CEE_LDNULL);
9291         mono_mb_emit_byte (mb, CEE_RET);
9292
9293         // return obj
9294         mono_mb_patch_branch (mb, positive_cache_hit_pos);
9295         mono_mb_emit_ldarg (mb, obj_arg_position);
9296         mono_mb_emit_byte (mb, CEE_RET);
9297 #endif
9298
9299         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ISINST_WITH_CACHE);
9300         res = mono_mb_create (mb, sig, 8, info);
9301         STORE_STORE_FENCE;
9302
9303         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
9304                 mono_free_method (res);
9305                 mono_metadata_free_method_signature (sig);
9306         }
9307         mono_mb_free (mb);
9308
9309         return cached;
9310 }
9311
9312 /**
9313  * mono_marshal_get_struct_to_ptr:
9314  * \param klass \c MonoClass
9315  *
9316  * Generates IL code for <code>StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)</code>
9317  */
9318 MonoMethod *
9319 mono_marshal_get_struct_to_ptr (MonoClass *klass)
9320 {
9321         MonoMethodBuilder *mb;
9322         static MonoMethod *stoptr = NULL;
9323         MonoMethod *res;
9324         WrapperInfo *info;
9325
9326         g_assert (klass != NULL);
9327
9328         mono_marshal_load_type_info (klass);
9329
9330         MonoMarshalType *marshal_info = mono_class_get_marshal_info (klass);
9331         if (marshal_info->str_to_ptr)
9332                 return marshal_info->str_to_ptr;
9333
9334         if (!stoptr) 
9335                 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
9336         g_assert (stoptr);
9337
9338         mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
9339
9340 #ifdef HAVE_ONLINE_VES
9341         if (klass->blittable) {
9342                 mono_mb_emit_byte (mb, CEE_LDARG_1);
9343                 mono_mb_emit_byte (mb, CEE_LDARG_0);
9344                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9345                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
9346                 mono_mb_emit_byte (mb, CEE_PREFIX1);
9347                 mono_mb_emit_byte (mb, CEE_CPBLK);
9348         } else {
9349
9350                 /* allocate local 0 (pointer) src_ptr */
9351                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9352                 /* allocate local 1 (pointer) dst_ptr */
9353                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9354                 /* allocate local 2 (boolean) delete_old */
9355                 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9356                 mono_mb_emit_byte (mb, CEE_LDARG_2);
9357                 mono_mb_emit_stloc (mb, 2);
9358
9359                 /* initialize src_ptr to point to the start of object data */
9360                 mono_mb_emit_byte (mb, CEE_LDARG_0);
9361                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9362                 mono_mb_emit_stloc (mb, 0);
9363
9364                 /* initialize dst_ptr */
9365                 mono_mb_emit_byte (mb, CEE_LDARG_1);
9366                 mono_mb_emit_stloc (mb, 1);
9367
9368                 emit_struct_conv (mb, klass, FALSE);
9369         }
9370
9371         mono_mb_emit_byte (mb, CEE_RET);
9372 #endif
9373         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRUCTURE_TO_PTR);
9374         res = mono_mb_create (mb, mono_signature_no_pinvoke (stoptr), 0, info);
9375         mono_mb_free (mb);
9376
9377         mono_marshal_lock ();
9378         if (!marshal_info->str_to_ptr)
9379                 marshal_info->str_to_ptr = res;
9380         else
9381                 res = marshal_info->str_to_ptr;
9382         mono_marshal_unlock ();
9383         return res;
9384 }
9385
9386 /**
9387  * mono_marshal_get_ptr_to_struct:
9388  * \param klass \c MonoClass
9389  * Generates IL code for <code>PtrToStructure (IntPtr src, object structure)</code>
9390  */
9391 MonoMethod *
9392 mono_marshal_get_ptr_to_struct (MonoClass *klass)
9393 {
9394         MonoMethodBuilder *mb;
9395         static MonoMethodSignature *ptostr = NULL;
9396         MonoMethod *res;
9397         WrapperInfo *info;
9398
9399         g_assert (klass != NULL);
9400
9401         mono_marshal_load_type_info (klass);
9402
9403         MonoMarshalType *marshal_info = mono_class_get_marshal_info (klass);
9404         if (marshal_info->ptr_to_str)
9405                 return marshal_info->ptr_to_str;
9406
9407         if (!ptostr) {
9408                 MonoMethodSignature *sig;
9409
9410                 /* Create the signature corresponding to
9411                           static void PtrToStructure (IntPtr ptr, object structure);
9412                    defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
9413                 sig = mono_create_icall_signature ("void ptr object");
9414                 sig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
9415                 sig->pinvoke = 0;
9416                 mono_memory_barrier ();
9417                 ptostr = sig;
9418         }
9419
9420         mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
9421
9422 #ifdef HAVE_ONLINE_VES
9423         if (klass->blittable) {
9424                 mono_mb_emit_byte (mb, CEE_LDARG_1);
9425                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9426                 mono_mb_emit_byte (mb, CEE_LDARG_0);
9427                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
9428                 mono_mb_emit_byte (mb, CEE_PREFIX1);
9429                 mono_mb_emit_byte (mb, CEE_CPBLK);
9430         } else {
9431
9432                 /* allocate local 0 (pointer) src_ptr */
9433                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9434                 /* allocate local 1 (pointer) dst_ptr */
9435                 mono_mb_add_local (mb, &klass->this_arg);
9436                 
9437                 /* initialize src_ptr to point to the start of object data */
9438                 mono_mb_emit_byte (mb, CEE_LDARG_0);
9439                 mono_mb_emit_stloc (mb, 0);
9440
9441                 /* initialize dst_ptr */
9442                 mono_mb_emit_byte (mb, CEE_LDARG_1);
9443                 mono_mb_emit_op (mb, CEE_UNBOX, klass);
9444                 mono_mb_emit_stloc (mb, 1);
9445
9446                 emit_struct_conv (mb, klass, TRUE);
9447         }
9448
9449         mono_mb_emit_byte (mb, CEE_RET);
9450 #endif
9451         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PTR_TO_STRUCTURE);
9452         res = mono_mb_create (mb, ptostr, 0, info);
9453         mono_mb_free (mb);
9454
9455         mono_marshal_lock ();
9456         if (!marshal_info->ptr_to_str)
9457                 marshal_info->ptr_to_str = res;
9458         else
9459                 res = marshal_info->ptr_to_str;
9460         mono_marshal_unlock ();
9461         return res;
9462 }
9463
9464 /*
9465  * Return a dummy wrapper for METHOD which is called by synchronized wrappers.
9466  * This is used to avoid infinite recursion since it is hard to determine where to
9467  * replace a method with its synchronized wrapper, and where not.
9468  * The runtime should execute METHOD instead of the wrapper.
9469  */
9470 MonoMethod *
9471 mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
9472 {
9473         MonoMethodBuilder *mb;
9474         WrapperInfo *info;
9475         MonoMethodSignature *sig;
9476         MonoMethod *res;
9477         MonoGenericContext *ctx = NULL;
9478         MonoGenericContainer *container = NULL;
9479
9480         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9481                 ctx = &((MonoMethodInflated*)method)->context;
9482                 method = ((MonoMethodInflated*)method)->declaring;
9483                 container = mono_method_get_generic_container (method);
9484                 if (!container)
9485                         container = mono_class_try_get_generic_container (method->klass); //FIXME is this a case of a try?
9486                 g_assert (container);
9487         }
9488
9489         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
9490 #ifdef HAVE_ONLINE_VES
9491         mono_mb_emit_exception_full (mb, "System", "ExecutionEngineException", "Shouldn't be called.");
9492         mono_mb_emit_byte (mb, CEE_RET);
9493 #endif
9494         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9495
9496         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_SYNCHRONIZED_INNER);
9497         info->d.synchronized_inner.method = method;
9498         res = mono_mb_create (mb, sig, 0, info);
9499         mono_mb_free (mb);
9500         if (ctx) {
9501                 MonoError error;
9502                 res = mono_class_inflate_generic_method_checked (res, ctx, &error);
9503                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9504         }
9505         return res;
9506 }
9507
9508 /**
9509  * mono_marshal_get_synchronized_wrapper:
9510  * Generates IL code for the synchronized wrapper: the generated method
9511  * calls \p method while locking \c this or the parent type.
9512  */
9513 MonoMethod *
9514 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
9515 {
9516         static MonoMethod *enter_method, *exit_method, *gettypefromhandle_method;
9517         MonoMethodSignature *sig;
9518         MonoExceptionClause *clause;
9519         MonoMethodBuilder *mb;
9520         MonoMethod *res;
9521         GHashTable *cache;
9522         WrapperInfo *info;
9523         int i, pos, pos2, this_local, taken_local, ret_local = 0;
9524         MonoGenericContext *ctx = NULL;
9525         MonoMethod *orig_method = NULL;
9526         MonoGenericContainer *container = NULL;
9527
9528         g_assert (method);
9529
9530         if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
9531                 return method;
9532
9533         /* FIXME: Support generic methods too */
9534         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9535                 orig_method = method;
9536                 ctx = &((MonoMethodInflated*)method)->context;
9537                 method = ((MonoMethodInflated*)method)->declaring;
9538                 container = mono_method_get_generic_container (method);
9539                 if (!container)
9540                         container = mono_class_try_get_generic_container (method->klass); //FIXME is this a case of a try?
9541                 g_assert (container);
9542         }
9543
9544         /*
9545          * Check cache
9546          */
9547         if (ctx) {
9548                 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9549                 res = check_generic_wrapper_cache (cache, orig_method, orig_method, method);
9550                 if (res)
9551                         return res;
9552         } else {
9553                 cache = get_cache (&method->klass->image->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9554                 if ((res = mono_marshal_find_in_cache (cache, method)))
9555                         return res;
9556         }
9557
9558         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9559         sig->pinvoke = 0;
9560
9561         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
9562
9563         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9564         info->d.synchronized.method = method;
9565
9566 #ifdef HAVE_ONLINE_VES
9567         mb->skip_visibility = 1;
9568         /* result */
9569         if (!MONO_TYPE_IS_VOID (sig->ret))
9570                 ret_local = mono_mb_add_local (mb, sig->ret);
9571 #endif
9572
9573         if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
9574                 /* FIXME Is this really the best way to signal an error here?  Isn't this called much later after class setup? -AK */
9575                 mono_class_set_type_load_failure (method->klass, "");
9576 #ifdef HAVE_ONLINE_VES
9577                 /* This will throw the type load exception when the wrapper is compiled */
9578                 mono_mb_emit_byte (mb, CEE_LDNULL);
9579                 mono_mb_emit_op (mb, CEE_ISINST, method->klass);
9580                 mono_mb_emit_byte (mb, CEE_POP);
9581
9582                 if (!MONO_TYPE_IS_VOID (sig->ret))
9583                         mono_mb_emit_ldloc (mb, ret_local);
9584                 mono_mb_emit_byte (mb, CEE_RET);
9585 #endif
9586
9587                 res = mono_mb_create_and_cache_full (cache, method,
9588                                                                                          mb, sig, sig->param_count + 16, info, NULL);
9589                 mono_mb_free (mb);
9590
9591                 return res;
9592         }
9593
9594 #ifdef HAVE_ONLINE_VES
9595         /* this */
9596         this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
9597         taken_local = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9598
9599         clause = (MonoExceptionClause *)mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
9600         clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
9601 #endif
9602
9603         mono_marshal_lock ();
9604
9605         if (!enter_method) {
9606                 MonoMethodDesc *desc;
9607
9608                 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
9609                 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9610                 g_assert (enter_method);
9611                 mono_method_desc_free (desc);
9612
9613                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
9614                 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9615                 g_assert (exit_method);
9616                 mono_method_desc_free (desc);
9617
9618                 desc = mono_method_desc_new ("Type:GetTypeFromHandle", FALSE);
9619                 gettypefromhandle_method = mono_method_desc_search_in_class (desc, mono_defaults.systemtype_class);
9620                 g_assert (gettypefromhandle_method);
9621                 mono_method_desc_free (desc);
9622         }
9623
9624         mono_marshal_unlock ();
9625
9626 #ifdef HAVE_ONLINE_VES
9627         /* Push this or the type object */
9628         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
9629                 /* We have special handling for this in the JIT */
9630                 int index = mono_mb_add_data (mb, method->klass);
9631                 mono_mb_add_data (mb, mono_defaults.typehandle_class);
9632                 mono_mb_emit_byte (mb, CEE_LDTOKEN);
9633                 mono_mb_emit_i4 (mb, index);
9634
9635                 mono_mb_emit_managed_call (mb, gettypefromhandle_method, NULL);
9636         }
9637         else
9638                 mono_mb_emit_ldarg (mb, 0);
9639         mono_mb_emit_stloc (mb, this_local);
9640
9641         /* Call Monitor::Enter() */
9642         mono_mb_emit_ldloc (mb, this_local);
9643         mono_mb_emit_ldloc_addr (mb, taken_local);
9644         mono_mb_emit_managed_call (mb, enter_method, NULL);
9645
9646         clause->try_offset = mono_mb_get_label (mb);
9647
9648         /* Call the method */
9649         if (sig->hasthis)
9650                 mono_mb_emit_ldarg (mb, 0);
9651         for (i = 0; i < sig->param_count; i++)
9652                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
9653
9654         if (ctx) {
9655                 MonoError error;
9656                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
9657                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9658         } else {
9659                 mono_mb_emit_managed_call (mb, method, NULL);
9660         }
9661
9662         if (!MONO_TYPE_IS_VOID (sig->ret))
9663                 mono_mb_emit_stloc (mb, ret_local);
9664
9665         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
9666
9667         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
9668         clause->handler_offset = mono_mb_get_label (mb);
9669
9670         /* Call Monitor::Exit() if needed */
9671         mono_mb_emit_ldloc (mb, taken_local);
9672         pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9673         mono_mb_emit_ldloc (mb, this_local);
9674         mono_mb_emit_managed_call (mb, exit_method, NULL);
9675         mono_mb_patch_branch (mb, pos2);
9676         mono_mb_emit_byte (mb, CEE_ENDFINALLY);
9677
9678         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
9679
9680         mono_mb_patch_branch (mb, pos);
9681         if (!MONO_TYPE_IS_VOID (sig->ret))
9682                 mono_mb_emit_ldloc (mb, ret_local);
9683         mono_mb_emit_byte (mb, CEE_RET);
9684
9685         mono_mb_set_clauses (mb, 1, clause);
9686 #endif
9687
9688         if (ctx) {
9689                 MonoMethod *def;
9690                 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
9691                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
9692         } else {
9693                 res = mono_mb_create_and_cache_full (cache, method,
9694                                                                                          mb, sig, sig->param_count + 16, info, NULL);
9695         }
9696         mono_mb_free (mb);
9697
9698         return res;     
9699 }
9700
9701
9702 /**
9703  * mono_marshal_get_unbox_wrapper:
9704  * The returned method calls \p method unboxing the \c this argument.
9705  */
9706 MonoMethod *
9707 mono_marshal_get_unbox_wrapper (MonoMethod *method)
9708 {
9709         MonoMethodSignature *sig = mono_method_signature (method);
9710         int i;
9711         MonoMethodBuilder *mb;
9712         MonoMethod *res;
9713         GHashTable *cache;
9714         WrapperInfo *info;
9715
9716         cache = get_cache (&mono_method_get_wrapper_cache (method)->unbox_wrapper_cache, mono_aligned_addr_hash, NULL);
9717
9718         if ((res = mono_marshal_find_in_cache (cache, method)))
9719                 return res;
9720
9721         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
9722
9723         g_assert (sig->hasthis);
9724         
9725 #ifdef HAVE_ONLINE_VES
9726         mono_mb_emit_ldarg (mb, 0); 
9727         mono_mb_emit_icon (mb, sizeof (MonoObject));
9728         mono_mb_emit_byte (mb, CEE_ADD);
9729         for (i = 0; i < sig->param_count; ++i)
9730                 mono_mb_emit_ldarg (mb, i + 1);
9731         mono_mb_emit_managed_call (mb, method, NULL);
9732         mono_mb_emit_byte (mb, CEE_RET);
9733 #endif
9734
9735         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9736         info->d.unbox.method = method;
9737
9738         res = mono_mb_create_and_cache_full (cache, method,
9739                                                                                  mb, sig, sig->param_count + 16, info, NULL);
9740         mono_mb_free (mb);
9741
9742         /* mono_method_print_code (res); */
9743
9744         return res;     
9745 }
9746
9747 enum {
9748         STELEMREF_OBJECT, /*no check at all*/
9749         STELEMREF_SEALED_CLASS, /*check vtable->klass->element_type */
9750         STELEMREF_CLASS, /*only the klass->parents check*/
9751         STELEMREF_CLASS_SMALL_IDEPTH, /* like STELEMREF_CLASS bit without the idepth check */
9752         STELEMREF_INTERFACE, /*interfaces without variant generic arguments. */
9753         STELEMREF_COMPLEX, /*arrays, MBR or types with variant generic args - go straight to icalls*/
9754         STELEMREF_KIND_COUNT
9755 };
9756
9757 static const char *strelemref_wrapper_name[] = {
9758         "object", "sealed_class", "class", "class_small_idepth", "interface", "complex"
9759 };
9760
9761 static gboolean
9762 is_monomorphic_array (MonoClass *klass)
9763 {
9764         MonoClass *element_class;
9765         if (klass->rank != 1)
9766                 return FALSE;
9767
9768         element_class = klass->element_class;
9769         return mono_class_is_sealed (element_class) || element_class->valuetype;
9770 }
9771
9772 static int
9773 get_virtual_stelemref_kind (MonoClass *element_class)
9774 {
9775         if (element_class == mono_defaults.object_class)
9776                 return STELEMREF_OBJECT;
9777         if (is_monomorphic_array (element_class))
9778                 return STELEMREF_SEALED_CLASS;
9779         /* Compressed interface bitmaps require code that is quite complex, so don't optimize for it. */
9780         if (MONO_CLASS_IS_INTERFACE (element_class) && !mono_class_has_variant_generic_params (element_class))
9781 #ifdef COMPRESSED_INTERFACE_BITMAP
9782                 return STELEMREF_COMPLEX;
9783 #else
9784                 return STELEMREF_INTERFACE;
9785 #endif
9786         /*Arrays are sealed but are covariant on their element type, We can't use any of the fast paths.*/
9787         if (mono_class_is_marshalbyref (element_class) || element_class->rank || mono_class_has_variant_generic_params (element_class))
9788                 return STELEMREF_COMPLEX;
9789         if (mono_class_is_sealed (element_class))
9790                 return STELEMREF_SEALED_CLASS;
9791         if (element_class->idepth <= MONO_DEFAULT_SUPERTABLE_SIZE)
9792                 return STELEMREF_CLASS_SMALL_IDEPTH;
9793
9794         return STELEMREF_CLASS;
9795 }
9796
9797 #ifdef HAVE_ONLINE_VES
9798
9799 static void
9800 load_array_element_address (MonoMethodBuilder *mb)
9801 {
9802         mono_mb_emit_ldarg (mb, 0);
9803         mono_mb_emit_ldarg (mb, 1);
9804         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9805 }
9806
9807 static void
9808 load_array_class (MonoMethodBuilder *mb, int aklass)
9809 {
9810         mono_mb_emit_ldarg (mb, 0);
9811         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9812         mono_mb_emit_byte (mb, CEE_LDIND_I);
9813         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9814         mono_mb_emit_byte (mb, CEE_LDIND_I);
9815         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9816         mono_mb_emit_byte (mb, CEE_LDIND_I);
9817         mono_mb_emit_stloc (mb, aklass);
9818 }
9819
9820 static void
9821 load_value_class (MonoMethodBuilder *mb, int vklass)
9822 {
9823         mono_mb_emit_ldarg (mb, 2);
9824         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9825         mono_mb_emit_byte (mb, CEE_LDIND_I);
9826         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9827         mono_mb_emit_byte (mb, CEE_LDIND_I);
9828         mono_mb_emit_stloc (mb, vklass);
9829 }
9830 #endif
9831
9832 #if 0
9833 static void
9834 record_slot_vstore (MonoObject *array, size_t index, MonoObject *value)
9835 {
9836         char *name = mono_type_get_full_name (array->vtable->klass->element_class);
9837         printf ("slow vstore of %s\n", name);
9838         g_free (name);
9839 }
9840 #endif
9841
9842 /*
9843  * TODO:
9844  *      - Separate simple interfaces from variant interfaces or mbr types. This way we can avoid the icall for them.
9845  *      - Emit a (new) mono bytecode that produces OP_COND_EXC_NE_UN to raise ArrayTypeMismatch
9846  *      - Maybe mve some MonoClass field into the vtable to reduce the number of loads
9847  *      - Add a case for arrays of arrays.
9848  */
9849 static MonoMethod*
9850 get_virtual_stelemref_wrapper (int kind)
9851 {
9852         static MonoMethod *cached_methods [STELEMREF_KIND_COUNT] = { NULL }; /*object iface sealed regular*/
9853         static MonoMethodSignature *signature;
9854         MonoMethodBuilder *mb;
9855         MonoMethod *res;
9856         char *name;
9857         const char *param_names [16];
9858         guint32 b1, b2, b3, b4;
9859         int aklass, vklass, vtable, uiid;
9860         int array_slot_addr;
9861         WrapperInfo *info;
9862
9863         if (cached_methods [kind])
9864                 return cached_methods [kind];
9865
9866         name = g_strdup_printf ("virt_stelemref_%s", strelemref_wrapper_name [kind]);
9867         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STELEMREF);
9868         g_free (name);
9869
9870         if (!signature) {
9871                 MonoMethodSignature *sig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
9872
9873                 /* void this::stelemref (size_t idx, void* value) */
9874                 sig->ret = &mono_defaults.void_class->byval_arg;
9875                 sig->hasthis = TRUE;
9876                 sig->params [0] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9877                 sig->params [1] = &mono_defaults.object_class->byval_arg;
9878                 signature = sig;
9879         }
9880
9881 #ifdef HAVE_ONLINE_VES
9882         param_names [0] = "index";
9883         param_names [1] = "value";
9884         mono_mb_set_param_names (mb, param_names);
9885
9886         /*For now simply call plain old stelemref*/
9887         switch (kind) {
9888         case STELEMREF_OBJECT:
9889                 /* ldelema (implicit bound check) */
9890                 load_array_element_address (mb);
9891                 /* do_store */
9892                 mono_mb_emit_ldarg (mb, 2);
9893                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9894                 mono_mb_emit_byte (mb, CEE_RET);
9895                 break;
9896
9897         case STELEMREF_COMPLEX: {
9898                 int b_fast;
9899                 /*
9900                 <ldelema (bound check)>
9901                 if (!value)
9902                         goto store;
9903                 if (!mono_object_isinst (value, aklass))
9904                         goto do_exception;
9905
9906                  do_store:
9907                          *array_slot_addr = value;
9908
9909                 do_exception:
9910                         throw new ArrayTypeMismatchException ();
9911                 */
9912
9913                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9914                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9915                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9916
9917 #if 0
9918                 {
9919                         /*Use this to debug/record stores that are going thru the slow path*/
9920                         MonoMethodSignature *csig;
9921                         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9922                         csig->ret = &mono_defaults.void_class->byval_arg;
9923                         csig->params [0] = &mono_defaults.object_class->byval_arg;
9924                         csig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9925                         csig->params [2] = &mono_defaults.object_class->byval_arg;
9926                         mono_mb_emit_ldarg (mb, 0);
9927                         mono_mb_emit_ldarg (mb, 1);
9928                         mono_mb_emit_ldarg (mb, 2);
9929                         mono_mb_emit_native_call (mb, csig, record_slot_vstore);
9930                 }
9931 #endif
9932
9933                 /* ldelema (implicit bound check) */
9934                 load_array_element_address (mb);
9935                 mono_mb_emit_stloc (mb, array_slot_addr);
9936
9937                 /* if (!value) goto do_store */
9938                 mono_mb_emit_ldarg (mb, 2);
9939                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9940
9941                 /* aklass = array->vtable->klass->element_class */
9942                 load_array_class (mb, aklass);
9943                 /* vklass = value->vtable->klass */
9944                 load_value_class (mb, vklass);
9945
9946                 /* fastpath */
9947                 mono_mb_emit_ldloc (mb, vklass);
9948                 mono_mb_emit_ldloc (mb, aklass);
9949                 b_fast = mono_mb_emit_branch (mb, CEE_BEQ);
9950
9951                 /*if (mono_object_isinst (value, aklass)) */
9952                 mono_mb_emit_ldarg (mb, 2);
9953                 mono_mb_emit_ldloc (mb, aklass);
9954                 mono_mb_emit_icall (mb, mono_object_isinst_icall);
9955                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9956
9957                 /* do_store: */
9958                 mono_mb_patch_branch (mb, b1);
9959                 mono_mb_patch_branch (mb, b_fast);
9960                 mono_mb_emit_ldloc (mb, array_slot_addr);
9961                 mono_mb_emit_ldarg (mb, 2);
9962                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9963                 mono_mb_emit_byte (mb, CEE_RET);
9964
9965                 /* do_exception: */
9966                 mono_mb_patch_branch (mb, b2);
9967
9968                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9969                 break;
9970         }
9971         case STELEMREF_SEALED_CLASS:
9972                 /*
9973                 <ldelema (bound check)>
9974                 if (!value)
9975                         goto store;
9976
9977                 aklass = array->vtable->klass->element_class;
9978                 vklass = value->vtable->klass;
9979
9980                 if (vklass != aklass)
9981                         goto do_exception;
9982
9983                 do_store:
9984                          *array_slot_addr = value;
9985
9986                 do_exception:
9987                         throw new ArrayTypeMismatchException ();
9988                 */
9989                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9990                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9991                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9992
9993                 /* ldelema (implicit bound check) */
9994                 load_array_element_address (mb);
9995                 mono_mb_emit_stloc (mb, array_slot_addr);
9996
9997                 /* if (!value) goto do_store */
9998                 mono_mb_emit_ldarg (mb, 2);
9999                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10000
10001                 /* aklass = array->vtable->klass->element_class */
10002                 load_array_class (mb, aklass);
10003
10004                 /* vklass = value->vtable->klass */
10005                 load_value_class (mb, vklass);
10006
10007                 /*if (vklass != aklass) goto do_exception; */
10008                 mono_mb_emit_ldloc (mb, aklass);
10009                 mono_mb_emit_ldloc (mb, vklass);
10010                 b2 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10011
10012                 /* do_store: */
10013                 mono_mb_patch_branch (mb, b1);
10014                 mono_mb_emit_ldloc (mb, array_slot_addr);
10015                 mono_mb_emit_ldarg (mb, 2);
10016                 mono_mb_emit_byte (mb, CEE_STIND_REF);
10017                 mono_mb_emit_byte (mb, CEE_RET);
10018
10019                 /* do_exception: */
10020                 mono_mb_patch_branch (mb, b2);
10021                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10022                 break;
10023
10024         case STELEMREF_CLASS: {
10025                 /*
10026                 the method:
10027                 <ldelema (bound check)>
10028                 if (!value)
10029                         goto do_store;
10030
10031                 aklass = array->vtable->klass->element_class;
10032                 vklass = value->vtable->klass;
10033
10034                 if (vklass->idepth < aklass->idepth)
10035                         goto do_exception;
10036
10037                 if (vklass->supertypes [aklass->idepth - 1] != aklass)
10038                         goto do_exception;
10039
10040                 do_store:
10041                         *array_slot_addr = value;
10042                         return;
10043
10044                 long:
10045                         throw new ArrayTypeMismatchException ();
10046                 */
10047                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10048                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10049                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10050
10051                 /* ldelema (implicit bound check) */
10052                 load_array_element_address (mb);
10053                 mono_mb_emit_stloc (mb, array_slot_addr);
10054
10055                 /* if (!value) goto do_store */
10056                 mono_mb_emit_ldarg (mb, 2);
10057                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10058
10059                 /* aklass = array->vtable->klass->element_class */
10060                 load_array_class (mb, aklass);
10061
10062                 /* vklass = value->vtable->klass */
10063                 load_value_class (mb, vklass);
10064
10065                 /* if (vklass->idepth < aklass->idepth) goto failue */
10066                 mono_mb_emit_ldloc (mb, vklass);
10067                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10068                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10069
10070                 mono_mb_emit_ldloc (mb, aklass);
10071                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10072                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10073
10074                 b3 = mono_mb_emit_branch (mb, CEE_BLT_UN);
10075
10076                 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
10077                 mono_mb_emit_ldloc (mb, vklass);
10078                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
10079                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10080
10081                 mono_mb_emit_ldloc (mb, aklass);
10082                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10083                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10084                 mono_mb_emit_icon (mb, 1);
10085                 mono_mb_emit_byte (mb, CEE_SUB);
10086                 mono_mb_emit_icon (mb, sizeof (void*));
10087                 mono_mb_emit_byte (mb, CEE_MUL);
10088                 mono_mb_emit_byte (mb, CEE_ADD);
10089                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10090
10091                 mono_mb_emit_ldloc (mb, aklass);
10092                 b4 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10093
10094                 /* do_store: */
10095                 mono_mb_patch_branch (mb, b1);
10096                 mono_mb_emit_ldloc (mb, array_slot_addr);
10097                 mono_mb_emit_ldarg (mb, 2);
10098                 mono_mb_emit_byte (mb, CEE_STIND_REF);
10099                 mono_mb_emit_byte (mb, CEE_RET);
10100
10101                 /* do_exception: */
10102                 mono_mb_patch_branch (mb, b3);
10103                 mono_mb_patch_branch (mb, b4);
10104
10105                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10106                 break;
10107         }
10108
10109         case STELEMREF_CLASS_SMALL_IDEPTH:
10110                 /*
10111                 the method:
10112                 <ldelema (bound check)>
10113                 if (!value)
10114                         goto do_store;
10115
10116                 aklass = array->vtable->klass->element_class;
10117                 vklass = value->vtable->klass;
10118
10119                 if (vklass->supertypes [aklass->idepth - 1] != aklass)
10120                         goto do_exception;
10121
10122                 do_store:
10123                         *array_slot_addr = value;
10124                         return;
10125
10126                 long:
10127                         throw new ArrayTypeMismatchException ();
10128                 */
10129                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10130                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10131                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10132
10133                 /* ldelema (implicit bound check) */
10134                 load_array_element_address (mb);
10135                 mono_mb_emit_stloc (mb, array_slot_addr);
10136
10137                 /* if (!value) goto do_store */
10138                 mono_mb_emit_ldarg (mb, 2);
10139                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10140
10141                 /* aklass = array->vtable->klass->element_class */
10142                 load_array_class (mb, aklass);
10143
10144                 /* vklass = value->vtable->klass */
10145                 load_value_class (mb, vklass);
10146
10147                 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
10148                 mono_mb_emit_ldloc (mb, vklass);
10149                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
10150                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10151
10152                 mono_mb_emit_ldloc (mb, aklass);
10153                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10154                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
10155                 mono_mb_emit_icon (mb, 1);
10156                 mono_mb_emit_byte (mb, CEE_SUB);
10157                 mono_mb_emit_icon (mb, sizeof (void*));
10158                 mono_mb_emit_byte (mb, CEE_MUL);
10159                 mono_mb_emit_byte (mb, CEE_ADD);
10160                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10161
10162                 mono_mb_emit_ldloc (mb, aklass);
10163                 b4 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10164
10165                 /* do_store: */
10166                 mono_mb_patch_branch (mb, b1);
10167                 mono_mb_emit_ldloc (mb, array_slot_addr);
10168                 mono_mb_emit_ldarg (mb, 2);
10169                 mono_mb_emit_byte (mb, CEE_STIND_REF);
10170                 mono_mb_emit_byte (mb, CEE_RET);
10171
10172                 /* do_exception: */
10173                 mono_mb_patch_branch (mb, b4);
10174
10175                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10176                 break;
10177
10178         case STELEMREF_INTERFACE:
10179                 /*Mono *klass;
10180                 MonoVTable *vt;
10181                 unsigned uiid;
10182                 if (value == NULL)
10183                         goto store;
10184
10185                 klass = array->obj.vtable->klass->element_class;
10186                 vt = value->vtable;
10187                 uiid = klass->interface_id;
10188                 if (uiid > vt->max_interface_id)
10189                         goto exception;
10190                 if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7))))
10191                         goto exception;
10192                 store:
10193                         mono_array_setref (array, index, value);
10194                         return;
10195                 exception:
10196                         mono_raise_exception (mono_get_exception_array_type_mismatch ());*/
10197
10198                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10199                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10200                 vtable = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10201                 uiid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10202
10203                 /* ldelema (implicit bound check) */
10204                 load_array_element_address (mb);
10205                 mono_mb_emit_stloc (mb, array_slot_addr);
10206
10207                 /* if (!value) goto do_store */
10208                 mono_mb_emit_ldarg (mb, 2);
10209                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10210
10211                 /* klass = array->vtable->klass->element_class */
10212                 load_array_class (mb, aklass);
10213
10214                 /* vt = value->vtable */
10215                 mono_mb_emit_ldarg (mb, 2);
10216                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10217                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10218                 mono_mb_emit_stloc (mb, vtable);
10219
10220                 /* uiid = klass->interface_id; */
10221                 mono_mb_emit_ldloc (mb, aklass);
10222                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, interface_id));
10223                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
10224                 mono_mb_emit_stloc (mb, uiid);
10225
10226                 /*if (uiid > vt->max_interface_id)*/
10227                 mono_mb_emit_ldloc (mb, uiid);
10228                 mono_mb_emit_ldloc (mb, vtable);
10229                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, max_interface_id));
10230                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
10231                 b2 = mono_mb_emit_branch (mb, CEE_BGT_UN);
10232
10233                 /* if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7)))) */
10234
10235                 /*vt->interface_bitmap*/
10236                 mono_mb_emit_ldloc (mb, vtable);
10237                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, interface_bitmap));
10238                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10239
10240                 /*uiid >> 3*/
10241                 mono_mb_emit_ldloc (mb, uiid);
10242                 mono_mb_emit_icon (mb, 3);
10243                 mono_mb_emit_byte (mb, CEE_SHR_UN);
10244
10245                 /*vt->interface_bitmap [(uiid) >> 3]*/
10246                 mono_mb_emit_byte (mb, CEE_ADD); /*interface_bitmap is a guint8 array*/
10247                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
10248
10249                 /*(1 << ((uiid)&7)))*/
10250                 mono_mb_emit_icon (mb, 1);
10251                 mono_mb_emit_ldloc (mb, uiid);
10252                 mono_mb_emit_icon (mb, 7);
10253                 mono_mb_emit_byte (mb, CEE_AND);
10254                 mono_mb_emit_byte (mb, CEE_SHL);
10255
10256                 /*bitwise and the whole thing*/
10257                 mono_mb_emit_byte (mb, CEE_AND);
10258                 b3 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10259
10260                 /* do_store: */
10261                 mono_mb_patch_branch (mb, b1);
10262                 mono_mb_emit_ldloc (mb, array_slot_addr);
10263                 mono_mb_emit_ldarg (mb, 2);
10264                 mono_mb_emit_byte (mb, CEE_STIND_REF);
10265                 mono_mb_emit_byte (mb, CEE_RET);
10266
10267                 /* do_exception: */
10268                 mono_mb_patch_branch (mb, b2);
10269                 mono_mb_patch_branch (mb, b3);
10270                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10271                 break;
10272
10273         default:
10274                 mono_mb_emit_ldarg (mb, 0);
10275                 mono_mb_emit_ldarg (mb, 1);
10276                 mono_mb_emit_ldarg (mb, 2);
10277                 mono_mb_emit_managed_call (mb, mono_marshal_get_stelemref (), NULL);
10278                 mono_mb_emit_byte (mb, CEE_RET);
10279                 g_assert (0);
10280         }
10281 #endif /* HAVE_ONLINE_VES */
10282         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_VIRTUAL_STELEMREF);
10283         info->d.virtual_stelemref.kind = kind;
10284         res = mono_mb_create (mb, signature, 4, info);
10285         res->flags |= METHOD_ATTRIBUTE_VIRTUAL;
10286
10287         mono_marshal_lock ();
10288         if (!cached_methods [kind]) {
10289                 cached_methods [kind] = res;
10290                 mono_marshal_unlock ();
10291         } else {
10292                 mono_marshal_unlock ();
10293                 mono_free_method (res);
10294         }
10295
10296         mono_mb_free (mb);
10297         return cached_methods [kind];
10298 }
10299
10300 MonoMethod*
10301 mono_marshal_get_virtual_stelemref (MonoClass *array_class)
10302 {
10303         int kind;
10304
10305         g_assert (array_class->rank == 1);
10306         kind = get_virtual_stelemref_kind (array_class->element_class);
10307
10308         return get_virtual_stelemref_wrapper (kind);
10309 }
10310
10311 MonoMethod**
10312 mono_marshal_get_virtual_stelemref_wrappers (int *nwrappers)
10313 {
10314         MonoMethod **res;
10315         int i;
10316
10317         *nwrappers = STELEMREF_KIND_COUNT;
10318         res = (MonoMethod **)g_malloc0 (STELEMREF_KIND_COUNT * sizeof (MonoMethod*));
10319         for (i = 0; i < STELEMREF_KIND_COUNT; ++i)
10320                 res [i] = get_virtual_stelemref_wrapper (i);
10321         return res;
10322 }
10323
10324 /**
10325  * mono_marshal_get_stelemref:
10326  */
10327 MonoMethod*
10328 mono_marshal_get_stelemref (void)
10329 {
10330         static MonoMethod* ret = NULL;
10331         MonoMethodSignature *sig;
10332         MonoMethodBuilder *mb;
10333         WrapperInfo *info;
10334         
10335         guint32 b1, b2, b3, b4;
10336         guint32 copy_pos;
10337         int aklass, vklass;
10338         int array_slot_addr;
10339         
10340         if (ret)
10341                 return ret;
10342         
10343         mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
10344         
10345
10346         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
10347
10348         /* void stelemref (void* array, int idx, void* value) */
10349         sig->ret = &mono_defaults.void_class->byval_arg;
10350         sig->params [0] = &mono_defaults.object_class->byval_arg;
10351         sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
10352         sig->params [2] = &mono_defaults.object_class->byval_arg;
10353
10354 #ifdef HAVE_ONLINE_VES
10355         aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10356         vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10357         array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10358         
10359         /*
10360         the method:
10361         <ldelema (bound check)>
10362         if (!value)
10363                 goto store;
10364         
10365         aklass = array->vtable->klass->element_class;
10366         vklass = value->vtable->klass;
10367         
10368         if (vklass->idepth < aklass->idepth)
10369                 goto long;
10370         
10371         if (vklass->supertypes [aklass->idepth - 1] != aklass)
10372                 goto long;
10373         
10374         store:
10375                 *array_slot_addr = value;
10376                 return;
10377         
10378         long:
10379                 if (mono_object_isinst (value, aklass))
10380                         goto store;
10381                 
10382                 throw new ArrayTypeMismatchException ();
10383         */
10384         
10385         /* ldelema (implicit bound check) */
10386         mono_mb_emit_ldarg (mb, 0);
10387         mono_mb_emit_ldarg (mb, 1);
10388         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
10389         mono_mb_emit_stloc (mb, array_slot_addr);
10390                 
10391         /* if (!value) goto do_store */
10392         mono_mb_emit_ldarg (mb, 2);
10393         b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10394         
10395         /* aklass = array->vtable->klass->element_class */
10396         mono_mb_emit_ldarg (mb, 0);
10397         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10398         mono_mb_emit_byte (mb, CEE_LDIND_I);
10399         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10400         mono_mb_emit_byte (mb, CEE_LDIND_I);
10401         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
10402         mono_mb_emit_byte (mb, CEE_LDIND_I);
10403         mono_mb_emit_stloc (mb, aklass);
10404         
10405         /* vklass = value->vtable->klass */
10406         mono_mb_emit_ldarg (mb, 2);
10407         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10408         mono_mb_emit_byte (mb, CEE_LDIND_I);
10409         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10410         mono_mb_emit_byte (mb, CEE_LDIND_I);
10411         mono_mb_emit_stloc (mb, vklass);
10412         
10413         /* if (vklass->idepth < aklass->idepth) goto failue */
10414         mono_mb_emit_ldloc (mb, vklass);
10415         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10416         mono_mb_emit_byte (mb, CEE_LDIND_U2);
10417         
10418         mono_mb_emit_ldloc (mb, aklass);
10419         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10420         mono_mb_emit_byte (mb, CEE_LDIND_U2);
10421         
10422         b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
10423         
10424         /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
10425         mono_mb_emit_ldloc (mb, vklass);
10426         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
10427         mono_mb_emit_byte (mb, CEE_LDIND_I);
10428         
10429         mono_mb_emit_ldloc (mb, aklass);
10430         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10431         mono_mb_emit_byte (mb, CEE_LDIND_U2);
10432         mono_mb_emit_icon (mb, 1);
10433         mono_mb_emit_byte (mb, CEE_SUB);
10434         mono_mb_emit_icon (mb, sizeof (void*));
10435         mono_mb_emit_byte (mb, CEE_MUL);
10436         mono_mb_emit_byte (mb, CEE_ADD);
10437         mono_mb_emit_byte (mb, CEE_LDIND_I);
10438         
10439         mono_mb_emit_ldloc (mb, aklass);
10440         
10441         b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10442         
10443         copy_pos = mono_mb_get_label (mb);
10444         /* do_store */
10445         mono_mb_patch_branch (mb, b1);
10446         mono_mb_emit_ldloc (mb, array_slot_addr);
10447         mono_mb_emit_ldarg (mb, 2);
10448         mono_mb_emit_byte (mb, CEE_STIND_REF);
10449         
10450         mono_mb_emit_byte (mb, CEE_RET);
10451         
10452         /* the hard way */
10453         mono_mb_patch_branch (mb, b2);
10454         mono_mb_patch_branch (mb, b3);
10455         
10456         mono_mb_emit_ldarg (mb, 2);
10457         mono_mb_emit_ldloc (mb, aklass);
10458         mono_mb_emit_icall (mb, mono_object_isinst_icall);
10459         
10460         b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
10461         mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
10462         mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10463         
10464         mono_mb_emit_byte (mb, CEE_RET);
10465 #endif
10466         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
10467         ret = mono_mb_create (mb, sig, 4, info);
10468         mono_mb_free (mb);
10469
10470         return ret;
10471 }
10472
10473 /*
10474  * mono_marshal_get_gsharedvt_in_wrapper:
10475  *
10476  *   This wrapper handles calls from normal code to gsharedvt code.
10477  */
10478 MonoMethod*
10479 mono_marshal_get_gsharedvt_in_wrapper (void)
10480 {
10481         static MonoMethod* ret = NULL;
10482         MonoMethodSignature *sig;
10483         MonoMethodBuilder *mb;
10484         WrapperInfo *info;
10485
10486         if (ret)
10487                 return ret;
10488         
10489         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_in", MONO_WRAPPER_UNKNOWN);
10490         
10491         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
10492         sig->ret = &mono_defaults.void_class->byval_arg;
10493
10494 #ifdef HAVE_ONLINE_VES
10495         /*
10496          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
10497          */
10498         mono_mb_emit_byte (mb, CEE_RET);
10499 #endif
10500         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_IN);
10501         ret = mono_mb_create (mb, sig, 4, info);
10502         mono_mb_free (mb);
10503
10504         return ret;
10505 }
10506
10507 /*
10508  * mono_marshal_get_gsharedvt_out_wrapper:
10509  *
10510  *   This wrapper handles calls from gsharedvt code to normal code.
10511  */
10512 MonoMethod*
10513 mono_marshal_get_gsharedvt_out_wrapper (void)
10514 {
10515         static MonoMethod* ret = NULL;
10516         MonoMethodSignature *sig;
10517         MonoMethodBuilder *mb;
10518         WrapperInfo *info;
10519
10520         if (ret)
10521                 return ret;
10522         
10523         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_out", MONO_WRAPPER_UNKNOWN);
10524         
10525         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
10526         sig->ret = &mono_defaults.void_class->byval_arg;
10527
10528 #ifdef HAVE_ONLINE_VES
10529         /*
10530          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
10531          */
10532         mono_mb_emit_byte (mb, CEE_RET);
10533 #endif
10534         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_OUT);
10535         ret = mono_mb_create (mb, sig, 4, info);
10536         mono_mb_free (mb);
10537
10538         return ret;
10539 }
10540
10541 typedef struct {
10542         int rank;
10543         int elem_size;
10544         MonoMethod *method;
10545 } ArrayElemAddr;
10546
10547 /* LOCKING: vars accessed under the marshal lock */
10548 static ArrayElemAddr *elem_addr_cache = NULL;
10549 static int elem_addr_cache_size = 0;
10550 static int elem_addr_cache_next = 0;
10551
10552 /**
10553  * mono_marshal_get_array_address:
10554  * \param rank rank of the array type
10555  * \param elem_size size in bytes of an element of an array.
10556  *
10557  * Returns a MonoMethod that implements the code to get the address
10558  * of an element in a multi-dimenasional array of \p rank dimensions.
10559  * The returned method takes an array as the first argument and then
10560  * \p rank indexes for the \p rank dimensions.
10561  * If ELEM_SIZE is 0, read the array size from the array object.
10562  */
10563 MonoMethod*
10564 mono_marshal_get_array_address (int rank, int elem_size)
10565 {
10566         MonoMethod *ret;
10567         MonoMethodBuilder *mb;
10568         MonoMethodSignature *sig;
10569         WrapperInfo *info;
10570         char *name;
10571         int i, bounds, ind, realidx;
10572         int branch_pos, *branch_positions;
10573         int cached;
10574
10575         ret = NULL;
10576         mono_marshal_lock ();
10577         for (i = 0; i < elem_addr_cache_next; ++i) {
10578                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10579                         ret = elem_addr_cache [i].method;
10580                         break;
10581                 }
10582         }
10583         mono_marshal_unlock ();
10584         if (ret)
10585                 return ret;
10586
10587         branch_positions = g_new0 (int, rank);
10588
10589         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1 + rank);
10590
10591         /* void* address (void* array, int idx0, int idx1, int idx2, ...) */
10592         sig->ret = &mono_defaults.int_class->byval_arg;
10593         sig->params [0] = &mono_defaults.object_class->byval_arg;
10594         for (i = 0; i < rank; ++i) {
10595                 sig->params [i + 1] = &mono_defaults.int32_class->byval_arg;
10596         }
10597
10598         name = g_strdup_printf ("ElementAddr_%d", elem_size);
10599         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
10600         g_free (name);
10601         
10602 #ifdef HAVE_ONLINE_VES
10603         bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10604         ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10605         realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10606
10607         /* bounds = array->bounds; */
10608         mono_mb_emit_ldarg (mb, 0);
10609         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, bounds));
10610         mono_mb_emit_byte (mb, CEE_LDIND_I);
10611         mono_mb_emit_stloc (mb, bounds);
10612
10613         /* ind is the overall element index, realidx is the partial index in a single dimension */
10614         /* ind = idx0 - bounds [0].lower_bound */
10615         mono_mb_emit_ldarg (mb, 1);
10616         mono_mb_emit_ldloc (mb, bounds);
10617         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10618         mono_mb_emit_byte (mb, CEE_ADD);
10619         mono_mb_emit_byte (mb, CEE_LDIND_I4);
10620         mono_mb_emit_byte (mb, CEE_SUB);
10621         mono_mb_emit_stloc (mb, ind);
10622         /* if (ind >= bounds [0].length) goto exeception; */
10623         mono_mb_emit_ldloc (mb, ind);
10624         mono_mb_emit_ldloc (mb, bounds);
10625         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10626         mono_mb_emit_byte (mb, CEE_ADD);
10627         mono_mb_emit_byte (mb, CEE_LDIND_I4);
10628         /* note that we use unsigned comparison */
10629         branch_pos = mono_mb_emit_branch (mb, CEE_BGE_UN);
10630
10631         /* For large ranks (> 4?) use a loop n IL later to reduce code size.
10632          * We could also decide to ignore the passed elem_size and get it
10633          * from the array object, to reduce the number of methods we generate:
10634          * the additional cost is 3 memory loads and a non-immediate mul.
10635          */
10636         for (i = 1; i < rank; ++i) {
10637                 /* realidx = idxi - bounds [i].lower_bound */
10638                 mono_mb_emit_ldarg (mb, 1 + i);
10639                 mono_mb_emit_ldloc (mb, bounds);
10640                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10641                 mono_mb_emit_byte (mb, CEE_ADD);
10642                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10643                 mono_mb_emit_byte (mb, CEE_SUB);
10644                 mono_mb_emit_stloc (mb, realidx);
10645                 /* if (realidx >= bounds [i].length) goto exeception; */
10646                 mono_mb_emit_ldloc (mb, realidx);
10647                 mono_mb_emit_ldloc (mb, bounds);
10648                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10649                 mono_mb_emit_byte (mb, CEE_ADD);
10650                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10651                 branch_positions [i] = mono_mb_emit_branch (mb, CEE_BGE_UN);
10652                 /* ind = ind * bounds [i].length + realidx */
10653                 mono_mb_emit_ldloc (mb, ind);
10654                 mono_mb_emit_ldloc (mb, bounds);
10655                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10656                 mono_mb_emit_byte (mb, CEE_ADD);
10657                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10658                 mono_mb_emit_byte (mb, CEE_MUL);
10659                 mono_mb_emit_ldloc (mb, realidx);
10660                 mono_mb_emit_byte (mb, CEE_ADD);
10661                 mono_mb_emit_stloc (mb, ind);
10662         }
10663
10664         /* return array->vector + ind * element_size */
10665         mono_mb_emit_ldarg (mb, 0);
10666         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
10667         mono_mb_emit_ldloc (mb, ind);
10668         if (elem_size) {
10669                 mono_mb_emit_icon (mb, elem_size);
10670         } else {
10671                 /* Load arr->vtable->klass->sizes.element_class */
10672                 mono_mb_emit_ldarg (mb, 0);
10673                 mono_mb_emit_byte (mb, CEE_CONV_I);
10674                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10675                 mono_mb_emit_byte (mb, CEE_ADD);
10676                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10677                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10678                 mono_mb_emit_byte (mb, CEE_ADD);
10679                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10680                 /* sizes is an union, so this reads sizes.element_size */
10681                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
10682                 mono_mb_emit_byte (mb, CEE_ADD);
10683                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10684         }
10685                 mono_mb_emit_byte (mb, CEE_MUL);
10686         mono_mb_emit_byte (mb, CEE_ADD);
10687         mono_mb_emit_byte (mb, CEE_RET);
10688
10689         /* patch the branches to get here and throw */
10690         for (i = 1; i < rank; ++i) {
10691                 mono_mb_patch_branch (mb, branch_positions [i]);
10692         }
10693         mono_mb_patch_branch (mb, branch_pos);
10694         /* throw exception */
10695         mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
10696
10697         g_free (branch_positions);
10698 #endif /* HAVE_ONLINE_VES */
10699
10700         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ELEMENT_ADDR);
10701         info->d.element_addr.rank = rank;
10702         info->d.element_addr.elem_size = elem_size;
10703         ret = mono_mb_create (mb, sig, 4, info);
10704         mono_mb_free (mb);
10705
10706         /* cache the result */
10707         cached = 0;
10708         mono_marshal_lock ();
10709         for (i = 0; i < elem_addr_cache_next; ++i) {
10710                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10711                         /* FIXME: free ret */
10712                         ret = elem_addr_cache [i].method;
10713                         cached = TRUE;
10714                         break;
10715                 }
10716         }
10717         if (!cached) {
10718                 if (elem_addr_cache_next >= elem_addr_cache_size) {
10719                         int new_size = elem_addr_cache_size + 4;
10720                         ArrayElemAddr *new_array = g_new0 (ArrayElemAddr, new_size);
10721                         memcpy (new_array, elem_addr_cache, elem_addr_cache_size * sizeof (ArrayElemAddr));
10722                         g_free (elem_addr_cache);
10723                         elem_addr_cache = new_array;
10724                         elem_addr_cache_size = new_size;
10725                 }
10726                 elem_addr_cache [elem_addr_cache_next].rank = rank;
10727                 elem_addr_cache [elem_addr_cache_next].elem_size = elem_size;
10728                 elem_addr_cache [elem_addr_cache_next].method = ret;
10729                 elem_addr_cache_next ++;
10730         }
10731         mono_marshal_unlock ();
10732         return ret;
10733 }
10734
10735 /*
10736  * mono_marshal_get_array_accessor_wrapper:
10737  *
10738  *   Return a wrapper which just calls METHOD, which should be an Array Get/Set/Address method.
10739  */
10740 MonoMethod *
10741 mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
10742 {
10743         MonoMethodSignature *sig;
10744         MonoMethodBuilder *mb;
10745         MonoMethod *res;
10746         GHashTable *cache;
10747         int i;
10748         MonoGenericContext *ctx = NULL;
10749         MonoMethod *orig_method = NULL;
10750         MonoGenericContainer *container = NULL;
10751         WrapperInfo *info;
10752
10753         /*
10754          * These wrappers are needed to avoid the JIT replacing the calls to these methods with intrinsics
10755          * inside runtime invoke wrappers, thereby making the wrappers not unshareable.
10756          * FIXME: Use generic methods.
10757          */
10758         /*
10759          * Check cache
10760          */
10761         if (ctx) {
10762                 cache = NULL;
10763                 g_assert_not_reached ();
10764         } else {
10765                 cache = get_cache (&method->klass->image->array_accessor_cache, mono_aligned_addr_hash, NULL);
10766                 if ((res = mono_marshal_find_in_cache (cache, method)))
10767                         return res;
10768         }
10769
10770         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
10771         sig->pinvoke = 0;
10772
10773         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
10774
10775 #ifdef HAVE_ONLINE_VES
10776         /* Call the method */
10777         if (sig->hasthis)
10778                 mono_mb_emit_ldarg (mb, 0);
10779         for (i = 0; i < sig->param_count; i++)
10780                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
10781
10782         if (ctx) {
10783                 MonoError error;
10784                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
10785                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
10786         } else {
10787                 mono_mb_emit_managed_call (mb, method, NULL);
10788         }
10789         mono_mb_emit_byte (mb, CEE_RET);
10790 #endif
10791
10792         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ARRAY_ACCESSOR);
10793         info->d.array_accessor.method = method;
10794
10795         if (ctx) {
10796                 MonoMethod *def;
10797                 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
10798                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
10799         } else {
10800                 res = mono_mb_create_and_cache_full (cache, method,
10801                                                                                          mb, sig, sig->param_count + 16,
10802                                                                                          info, NULL);
10803         }
10804         mono_mb_free (mb);
10805
10806         return res;     
10807 }
10808
10809 #ifndef HOST_WIN32
10810 static inline void*
10811 mono_marshal_alloc_co_task_mem (size_t size)
10812 {
10813         if ((gulong)size == 0)
10814                 /* This returns a valid pointer for size 0 on MS.NET */
10815                 size = 4;
10816
10817         return g_try_malloc ((gulong)size);
10818 }
10819 #endif
10820
10821 /**
10822  * mono_marshal_alloc:
10823  */
10824 void*
10825 mono_marshal_alloc (gsize size, MonoError *error)
10826 {
10827         gpointer res;
10828
10829         error_init (error);
10830
10831         res = mono_marshal_alloc_co_task_mem (size);
10832         if (!res)
10833                 mono_error_set_out_of_memory (error, "Could not allocate %lu bytes", size);
10834
10835         return res;
10836 }
10837
10838 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10839 static void*
10840 ves_icall_marshal_alloc (gsize size)
10841 {
10842         MonoError error;
10843         void *ret = mono_marshal_alloc (size, &error);
10844         if (!mono_error_ok (&error)) {
10845                 mono_error_set_pending_exception (&error);
10846                 return NULL;
10847         }
10848
10849         return ret;
10850 }
10851
10852 #ifndef HOST_WIN32
10853 static inline void
10854 mono_marshal_free_co_task_mem (void *ptr)
10855 {
10856         g_free (ptr);
10857         return;
10858 }
10859 #endif
10860
10861 /**
10862  * mono_marshal_free:
10863  */
10864 void
10865 mono_marshal_free (gpointer ptr)
10866 {
10867         mono_marshal_free_co_task_mem (ptr);
10868 }
10869
10870 /**
10871  * mono_marshal_free_array:
10872  */
10873 void
10874 mono_marshal_free_array (gpointer *ptr, int size) 
10875 {
10876         int i;
10877
10878         if (!ptr)
10879                 return;
10880
10881         for (i = 0; i < size; i++)
10882                 if (ptr [i])
10883                         g_free (ptr [i]);
10884 }
10885
10886 void *
10887 mono_marshal_string_to_utf16 (MonoString *s)
10888 {
10889         return s ? mono_string_chars (s) : NULL;
10890 }
10891
10892 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10893 static void *
10894 mono_marshal_string_to_utf16_copy (MonoString *s)
10895 {
10896         if (s == NULL) {
10897                 return NULL;
10898         } else {
10899                 MonoError error;
10900                 gunichar2 *res = (gunichar2 *)mono_marshal_alloc ((mono_string_length (s) * 2) + 2, &error);
10901                 if (!mono_error_ok (&error)) {
10902                         mono_error_set_pending_exception (&error);
10903                         return NULL;
10904                 }
10905                 memcpy (res, mono_string_chars (s), mono_string_length (s) * 2);
10906                 res [mono_string_length (s)] = 0;
10907                 return res;
10908         }
10909 }
10910
10911 /**
10912  * mono_marshal_set_last_error:
10913  *
10914  * This function is invoked to set the last error value from a P/Invoke call
10915  * which has \c SetLastError set.
10916  */
10917 void
10918 mono_marshal_set_last_error (void)
10919 {
10920 #ifdef WIN32
10921         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
10922 #else
10923         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (errno));
10924 #endif
10925 }
10926
10927 static void
10928 mono_marshal_set_last_error_windows (int error)
10929 {
10930 #ifdef WIN32
10931         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (error));
10932 #endif
10933 }
10934
10935 void
10936 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
10937                                                                     gpointer dest, gint32 length)
10938 {
10939         int element_size;
10940         void *source_addr;
10941
10942         MONO_CHECK_ARG_NULL (src,);
10943         MONO_CHECK_ARG_NULL (dest,);
10944
10945         if (src->obj.vtable->klass->rank != 1) {
10946                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10947                 return;
10948         }
10949         if (start_index < 0) {
10950                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10951                 return;
10952         }
10953         if (length < 0) {
10954                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10955                 return;
10956         }
10957         if (start_index + length > mono_array_length (src)) {
10958                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10959                 return;
10960         }
10961
10962         element_size = mono_array_element_size (src->obj.vtable->klass);
10963
10964         /* no references should be involved */
10965         source_addr = mono_array_addr_with_size_fast (src, element_size, start_index);
10966
10967         memcpy (dest, source_addr, length * element_size);
10968 }
10969
10970 void
10971 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
10972                                                                       MonoArray *dest, gint32 length)
10973 {
10974         int element_size;
10975         void *dest_addr;
10976
10977         MONO_CHECK_ARG_NULL (src,);
10978         MONO_CHECK_ARG_NULL (dest,);
10979
10980         if (dest->obj.vtable->klass->rank != 1) {
10981                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10982                 return;
10983         }
10984         if (start_index < 0) {
10985                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10986                 return;
10987         }
10988         if (length < 0) {
10989                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10990                 return;
10991         }
10992         if (start_index + length > mono_array_length (dest)) {
10993                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10994                 return;
10995         }
10996         element_size = mono_array_element_size (dest->obj.vtable->klass);
10997           
10998         /* no references should be involved */
10999         dest_addr = mono_array_addr_with_size_fast (dest, element_size, start_index);
11000
11001         memcpy (dest_addr, src, length * element_size);
11002 }
11003
11004 MonoStringHandle
11005 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr, MonoError *error)
11006 {
11007         error_init (error);
11008         if (ptr == NULL)
11009                 return MONO_HANDLE_CAST (MonoString, NULL_HANDLE);
11010         else
11011                 return mono_string_new_handle (mono_domain_get (), ptr, error);
11012 }
11013
11014 MonoString *
11015 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
11016 {
11017         MonoError error;
11018         MonoString *result = NULL;
11019         error_init (&error);
11020         if (ptr == NULL)
11021                 mono_error_set_argument_null (&error, "ptr", "");
11022         else
11023                 result = mono_string_new_len_checked (mono_domain_get (), ptr, len, &error);
11024         mono_error_set_pending_exception (&error);
11025         return result;
11026 }
11027
11028 MonoString *
11029 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
11030 {
11031         MonoError error;
11032         MonoString *res = NULL;
11033         MonoDomain *domain = mono_domain_get (); 
11034         int len = 0;
11035         guint16 *t = ptr;
11036
11037         if (ptr == NULL)
11038                 return NULL;
11039
11040         while (*t++)
11041                 len++;
11042
11043         res = mono_string_new_utf16_checked (domain, ptr, len, &error);
11044         if (!mono_error_ok (&error)) {
11045                 mono_error_set_pending_exception (&error);
11046                 return NULL;
11047         }
11048         return res;
11049 }
11050
11051 MonoString *
11052 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
11053 {
11054         MonoError error;
11055         MonoString *res = NULL;
11056         MonoDomain *domain = mono_domain_get (); 
11057
11058         error_init (&error);
11059
11060         if (ptr == NULL) {
11061                 res = NULL;
11062                 mono_error_set_argument_null (&error, "ptr", "");
11063         } else {
11064                 res = mono_string_new_utf16_checked (domain, ptr, len, &error);
11065         }
11066
11067         if (!mono_error_ok (&error))
11068                 mono_error_set_pending_exception (&error);
11069         return res;
11070 }
11071
11072 guint32 
11073 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
11074 {
11075         return (GPOINTER_TO_INT (mono_native_tls_get_value (last_error_tls_id)));
11076 }
11077
11078 guint32 
11079 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionTypeHandle rtype, MonoError *error)
11080 {
11081         MonoClass *klass;
11082         MonoType *type;
11083         guint32 layout;
11084
11085         error_init (error);
11086
11087         if (MONO_HANDLE_IS_NULL (rtype)) {
11088                 mono_error_set_argument_null (error, "type", "");
11089                 return 0;
11090         }
11091
11092         type = MONO_HANDLE_GETVAL (rtype, type);
11093         klass = mono_class_from_mono_type (type);
11094         if (!mono_class_init (klass)) {
11095                 mono_error_set_for_class_failure (error, klass);
11096                 return 0;
11097         }
11098
11099         layout = (mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK);
11100
11101         if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
11102                 return sizeof (gpointer);
11103         } else if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
11104                 mono_error_set_argument (error, "t", "Type %s cannot be marshaled as an unmanaged structure.", klass->name);
11105                 return 0;
11106         }
11107
11108         return mono_class_native_size (klass, NULL);
11109 }
11110
11111 void
11112 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
11113 {
11114         MonoError error;
11115         MonoMethod *method;
11116         gpointer pa [3];
11117
11118         MONO_CHECK_ARG_NULL (obj,);
11119         MONO_CHECK_ARG_NULL (dst,);
11120
11121         method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
11122
11123         pa [0] = obj;
11124         pa [1] = &dst;
11125         pa [2] = &delete_old;
11126
11127         mono_runtime_invoke_checked (method, NULL, pa, &error);
11128         if (!mono_error_ok (&error))
11129                 mono_error_set_pending_exception (&error);
11130 }
11131
11132 static void
11133 ptr_to_structure (gpointer src, MonoObject *dst, MonoError *error)
11134 {
11135         MonoMethod *method;
11136         gpointer pa [2];
11137
11138         error_init (error);
11139
11140         method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
11141
11142         pa [0] = &src;
11143         pa [1] = dst;
11144
11145         mono_runtime_invoke_checked (method, NULL, pa, error);
11146 }
11147
11148 void
11149 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
11150 {
11151         MonoType *t;
11152         MonoError error;
11153
11154         MONO_CHECK_ARG_NULL (src,);
11155         MONO_CHECK_ARG_NULL (dst,);
11156         
11157         t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
11158
11159         if (t->type == MONO_TYPE_VALUETYPE) {
11160                 MonoException *exc;
11161                 gchar *tmp;
11162
11163                 tmp = g_strdup_printf ("Destination is a boxed value type.");
11164                 exc = mono_get_exception_argument ("dst", tmp);
11165                 g_free (tmp);  
11166
11167                 mono_set_pending_exception (exc);
11168                 return;
11169         }
11170
11171         ptr_to_structure (src, dst, &error);
11172         if (!mono_error_ok (&error))
11173                 mono_error_set_pending_exception (&error);
11174 }
11175
11176 MonoObject *
11177 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
11178 {
11179         MonoError error;
11180         MonoClass *klass;
11181         MonoDomain *domain = mono_domain_get (); 
11182         MonoObject *res;
11183
11184         if (src == NULL)
11185                 return NULL;
11186         MONO_CHECK_ARG_NULL (type, NULL);
11187
11188         klass = mono_class_from_mono_type (type->type);
11189         if (!mono_class_init (klass)) {
11190                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
11191                 return NULL;
11192         }
11193
11194         res = mono_object_new_checked (domain, klass, &error);
11195         if (!mono_error_ok (&error)) {
11196                 mono_error_set_pending_exception (&error);
11197                 return NULL;
11198         }
11199
11200         ptr_to_structure (src, res, &error);
11201         if (!mono_error_ok (&error)) {
11202                 mono_error_set_pending_exception (&error);
11203                 return NULL;
11204         }
11205
11206         return res;
11207 }
11208
11209 int
11210 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionTypeHandle ref_type, MonoStringHandle field_name, MonoError *error)
11211 {
11212         error_init (error);
11213         if (MONO_HANDLE_IS_NULL (ref_type)) {
11214                 mono_error_set_argument_null (error, "type", "");
11215                 return 0;
11216         }
11217         if (MONO_HANDLE_IS_NULL (field_name)) {
11218                 mono_error_set_argument_null (error, "fieldName", "");
11219                 return 0;
11220         }
11221
11222         char *fname = mono_string_handle_to_utf8 (field_name, error);
11223         return_val_if_nok (error, 0);
11224
11225         MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
11226         MonoClass *klass = mono_class_from_mono_type (type);
11227         if (!mono_class_init (klass)) {
11228                 mono_error_set_for_class_failure (error, klass);
11229                 return 0;
11230         }
11231
11232         int match_index = -1;
11233         while (klass && match_index == -1) {
11234                 MonoClassField* field;
11235                 int i = 0;
11236                 gpointer iter = NULL;
11237                 while ((field = mono_class_get_fields (klass, &iter))) {
11238                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11239                                 continue;
11240                         if (!strcmp (fname, mono_field_get_name (field))) {
11241                                 match_index = i;
11242                                 break;
11243                         }
11244                         i ++;
11245                 }
11246
11247                 if (match_index == -1)
11248                         klass = klass->parent;
11249         }
11250
11251         g_free (fname);
11252
11253         if(match_index == -1) {
11254                 /* Get back original class instance */
11255                 klass = mono_class_from_mono_type (type);
11256
11257                 mono_error_set_argument (error, "fieldName", "Field passed in is not a marshaled member of the type %s", klass->name);
11258                 return 0;
11259         }
11260
11261         MonoMarshalType *info = mono_marshal_load_type_info (klass);
11262         return info->fields [match_index].offset;
11263 }
11264
11265 #ifndef HOST_WIN32
11266 gpointer
11267 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
11268 {
11269         MonoError error;
11270         char *ret = mono_string_to_utf8_checked (string, &error);
11271         mono_error_set_pending_exception (&error);
11272         return ret;
11273 }
11274
11275 gpointer
11276 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
11277 {
11278         if (string == NULL)
11279                 return NULL;
11280         else {
11281                 gunichar2 *res = (gunichar2 *)g_malloc ((mono_string_length (string) + 1) * 2);
11282
11283                 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
11284                 res [mono_string_length (string)] = 0;
11285                 return res;
11286         }
11287 }
11288 #endif /* !HOST_WIN32 */
11289
11290 static void
11291 mono_struct_delete_old (MonoClass *klass, char *ptr)
11292 {
11293         MonoMarshalType *info;
11294         int i;
11295
11296         info = mono_marshal_load_type_info (klass);
11297
11298         for (i = 0; i < info->num_fields; i++) {
11299                 MonoMarshalConv conv;
11300                 MonoType *ftype = info->fields [i].field->type;
11301                 char *cpos;
11302
11303                 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
11304                         continue;
11305
11306                 mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, 
11307                                 klass->unicode, &conv);
11308                         
11309                 cpos = ptr + info->fields [i].offset;
11310
11311                 switch (conv) {
11312                 case MONO_MARSHAL_CONV_NONE:
11313                         if (MONO_TYPE_ISSTRUCT (ftype)) {
11314                                 mono_struct_delete_old (ftype->data.klass, cpos);
11315                                 continue;
11316                         }
11317                         break;
11318                 case MONO_MARSHAL_CONV_STR_LPWSTR:
11319                         /* We assume this field points inside a MonoString */
11320                         break;
11321                 case MONO_MARSHAL_CONV_STR_LPTSTR:
11322 #ifdef TARGET_WIN32
11323                         /* We assume this field points inside a MonoString 
11324                          * on Win32 */
11325                         break;
11326 #endif
11327                 case MONO_MARSHAL_CONV_STR_LPSTR:
11328                 case MONO_MARSHAL_CONV_STR_BSTR:
11329                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
11330                 case MONO_MARSHAL_CONV_STR_TBSTR:
11331                 case MONO_MARSHAL_CONV_STR_UTF8STR:
11332                         mono_marshal_free (*(gpointer *)cpos);
11333                         break;
11334
11335                 default:
11336                         continue;
11337                 }
11338         }
11339 }
11340
11341 void
11342 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
11343 {
11344         MonoClass *klass;
11345
11346         MONO_CHECK_ARG_NULL (src,);
11347         MONO_CHECK_ARG_NULL (type,);
11348
11349         klass = mono_class_from_mono_type (type->type);
11350         if (!mono_class_init (klass)) {
11351                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
11352                 return;
11353         }
11354
11355         mono_struct_delete_old (klass, (char *)src);
11356 }
11357
11358 #ifndef HOST_WIN32
11359 static inline void *
11360 mono_marshal_alloc_hglobal (size_t size)
11361 {
11362         return g_try_malloc (size);
11363 }
11364 #endif
11365
11366 void*
11367 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
11368 {
11369         gpointer res;
11370         size_t s = (size_t)size;
11371
11372         if (s == 0)
11373                 /* This returns a valid pointer for size 0 on MS.NET */
11374                 s = 4;
11375
11376         res = mono_marshal_alloc_hglobal (s);
11377
11378         if (!res) {
11379                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11380                 return NULL;
11381         }
11382
11383         return res;
11384 }
11385
11386 #ifndef HOST_WIN32
11387 static inline gpointer
11388 mono_marshal_realloc_hglobal (gpointer ptr, size_t size)
11389 {
11390         return g_try_realloc (ptr, size);
11391 }
11392 #endif
11393
11394 gpointer
11395 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, gpointer size)
11396 {
11397         gpointer res;
11398         size_t s = (size_t)size;
11399
11400         if (ptr == NULL) {
11401                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11402                 return NULL;
11403         }
11404
11405         res = mono_marshal_realloc_hglobal (ptr, s);
11406
11407         if (!res) {
11408                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11409                 return NULL;
11410         }
11411
11412         return res;
11413 }
11414
11415 #ifndef HOST_WIN32
11416 static inline void
11417 mono_marshal_free_hglobal (gpointer ptr)
11418 {
11419         g_free (ptr);
11420         return;
11421 }
11422 #endif
11423
11424 void
11425 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
11426 {
11427         mono_marshal_free_hglobal (ptr);
11428 }
11429
11430 void*
11431 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
11432 {
11433         void *res = mono_marshal_alloc_co_task_mem (size);
11434
11435         if (!res) {
11436                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11437                 return NULL;
11438         }
11439         return res;
11440 }
11441
11442 void*
11443 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMemSize (gulong size)
11444 {
11445         void *res = mono_marshal_alloc_co_task_mem (size);
11446
11447         if (!res) {
11448                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11449                 return NULL;
11450         }
11451         return res;
11452 }
11453
11454 void
11455 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
11456 {
11457         mono_marshal_free_co_task_mem (ptr);
11458         return;
11459 }
11460
11461 #ifndef HOST_WIN32
11462 static inline gpointer
11463 mono_marshal_realloc_co_task_mem (gpointer ptr, size_t size)
11464 {
11465         return g_try_realloc (ptr, (gulong)size);
11466 }
11467 #endif
11468
11469 gpointer
11470 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
11471 {
11472         void *res = mono_marshal_realloc_co_task_mem (ptr, size);
11473
11474         if (!res) {
11475                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11476                 return NULL;
11477         }
11478         return res;
11479 }
11480
11481 void*
11482 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
11483 {
11484         return mono_array_addr_with_size_fast (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
11485 }
11486
11487 MonoDelegateHandle
11488 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionTypeHandle type, MonoError *error)
11489 {
11490         error_init (error);
11491         MonoClass *klass = mono_type_get_class (MONO_HANDLE_GETVAL (type, type));
11492         if (!mono_class_init (klass)) {
11493                 mono_error_set_for_class_failure (error, klass);
11494                 return NULL;
11495         }
11496
11497         return mono_ftnptr_to_delegate_handle (klass, ftn, error);
11498 }
11499
11500 gpointer
11501 ves_icall_System_Runtime_InteropServices_Marshal_GetFunctionPointerForDelegateInternal (MonoDelegateHandle delegate, MonoError *error)
11502 {
11503         error_init (error);
11504         return mono_delegate_handle_to_ftnptr (delegate, error);
11505 }
11506
11507 /**
11508  * mono_marshal_is_loading_type_info:
11509  *
11510  *  Return whenever mono_marshal_load_type_info () is being executed for KLASS by this
11511  * thread.
11512  */
11513 static gboolean
11514 mono_marshal_is_loading_type_info (MonoClass *klass)
11515 {
11516         GSList *loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11517
11518         return g_slist_find (loads_list, klass) != NULL;
11519 }
11520
11521 /**
11522  * mono_marshal_load_type_info:
11523  *
11524  * Initialize \c klass::marshal_info using information from metadata. This function can
11525  * recursively call itself, and the caller is responsible to avoid that by calling 
11526  * \c mono_marshal_is_loading_type_info beforehand.
11527  *
11528  * LOCKING: Acquires the loader lock.
11529  */
11530 MonoMarshalType *
11531 mono_marshal_load_type_info (MonoClass* klass)
11532 {
11533         int j, count = 0;
11534         guint32 native_size = 0, min_align = 1, packing;
11535         MonoMarshalType *info;
11536         MonoClassField* field;
11537         gpointer iter;
11538         guint32 layout;
11539         GSList *loads_list;
11540
11541         g_assert (klass != NULL);
11542
11543         info = mono_class_get_marshal_info (klass);
11544         if (info)
11545                 return info;
11546
11547         if (!klass->inited)
11548                 mono_class_init (klass);
11549
11550         info = mono_class_get_marshal_info (klass);
11551         if (info)
11552                 return info;
11553
11554         /*
11555          * This function can recursively call itself, so we keep the list of classes which are
11556          * under initialization in a TLS list.
11557          */
11558         g_assert (!mono_marshal_is_loading_type_info (klass));
11559         loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11560         loads_list = g_slist_prepend (loads_list, klass);
11561         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11562         
11563         iter = NULL;
11564         while ((field = mono_class_get_fields (klass, &iter))) {
11565                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11566                         continue;
11567                 if (mono_field_is_deleted (field))
11568                         continue;
11569                 count++;
11570         }
11571
11572         layout = mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK;
11573
11574         /* The mempool is protected by the loader lock */
11575         info = (MonoMarshalType *)mono_image_alloc0 (klass->image, MONO_SIZEOF_MARSHAL_TYPE + sizeof (MonoMarshalField) * count);
11576         info->num_fields = count;
11577         
11578         /* Try to find a size for this type in metadata */
11579         mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
11580
11581         if (klass->parent) {
11582                 int parent_size = mono_class_native_size (klass->parent, NULL);
11583
11584                 /* Add parent size to real size */
11585                 native_size += parent_size;
11586                 info->native_size = parent_size;
11587         }
11588
11589         packing = klass->packing_size ? klass->packing_size : 8;
11590         iter = NULL;
11591         j = 0;
11592         while ((field = mono_class_get_fields (klass, &iter))) {
11593                 int size;
11594                 guint32 align;
11595                 
11596                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11597                         continue;
11598
11599                 if (mono_field_is_deleted (field))
11600                         continue;
11601                 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
11602                         mono_metadata_field_info_with_mempool (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1, 
11603                                                   NULL, NULL, &info->fields [j].mspec);
11604
11605                 info->fields [j].field = field;
11606
11607                 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
11608                         (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
11609                         /* This field is a hack inserted by MCS to empty structures */
11610                         continue;
11611                 }
11612
11613                 switch (layout) {
11614                 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
11615                 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
11616                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
11617                                                        &align, TRUE, klass->unicode);
11618                         align = klass->packing_size ? MIN (klass->packing_size, align): align;
11619                         min_align = MAX (align, min_align);
11620                         info->fields [j].offset = info->native_size;
11621                         info->fields [j].offset += align - 1;
11622                         info->fields [j].offset &= ~(align - 1);
11623                         info->native_size = info->fields [j].offset + size;
11624                         break;
11625                 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
11626                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
11627                                                        &align, TRUE, klass->unicode);
11628                         min_align = MAX (align, min_align);
11629                         info->fields [j].offset = field->offset - sizeof (MonoObject);
11630                         info->native_size = MAX (info->native_size, info->fields [j].offset + size);
11631                         break;
11632                 }       
11633                 j++;
11634         }
11635
11636         if (klass->byval_arg.type == MONO_TYPE_PTR)
11637                 info->native_size = sizeof (gpointer);
11638
11639         if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
11640                 info->native_size = MAX (native_size, info->native_size);
11641                 /*
11642                  * If the provided Size is equal or larger than the calculated size, and there
11643                  * was no Pack attribute, we set min_align to 1 to avoid native_size being increased
11644                  */
11645                 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
11646                         if (native_size && native_size == info->native_size && klass->packing_size == 0)
11647                                 min_align = 1;
11648                         else
11649                                 min_align = MIN (min_align, packing);
11650                 }
11651         }
11652
11653         if (info->native_size & (min_align - 1)) {
11654                 info->native_size += min_align - 1;
11655                 info->native_size &= ~(min_align - 1);
11656         }
11657
11658         info->min_align = min_align;
11659
11660         /* Update the class's blittable info, if the layouts don't match */
11661         if (info->native_size != mono_class_value_size (klass, NULL))
11662                 klass->blittable = FALSE;
11663
11664         /* If this is an array type, ensure that we have element info */
11665         if (klass->rank && !mono_marshal_is_loading_type_info (klass->element_class)) {
11666                 mono_marshal_load_type_info (klass->element_class);
11667         }
11668
11669         loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11670         loads_list = g_slist_remove (loads_list, klass);
11671         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11672
11673         mono_marshal_lock ();
11674         MonoMarshalType *info2 = mono_class_get_marshal_info (klass);
11675         if (!info2) {
11676                 /*We do double-checking locking on marshal_info */
11677                 mono_memory_barrier ();
11678                 mono_class_set_marshal_info (klass, info);
11679                 ++class_marshal_info_count;
11680                 info2 = info;
11681         }
11682         mono_marshal_unlock ();
11683
11684         return info2;
11685 }
11686
11687 /**
11688  * mono_class_native_size:
11689  * \param klass a class 
11690  * \returns the native size of an object instance (when marshaled 
11691  * to unmanaged code) 
11692  */
11693 gint32
11694 mono_class_native_size (MonoClass *klass, guint32 *align)
11695 {
11696         MonoMarshalType *info = mono_class_get_marshal_info (klass);
11697         if (!info) {
11698                 if (mono_marshal_is_loading_type_info (klass)) {
11699                         if (align)
11700                                 *align = 0;
11701                         return 0;
11702                 } else {
11703                         mono_marshal_load_type_info (klass);
11704                 }
11705                 info = mono_class_get_marshal_info (klass);
11706         }
11707
11708         if (align)
11709                 *align = info->min_align;
11710
11711         return info->native_size;
11712 }
11713
11714 /*
11715  * mono_type_native_stack_size:
11716  * @t: the type to return the size it uses on the stack
11717  *
11718  * Returns: the number of bytes required to hold an instance of this
11719  * type on the native stack
11720  */
11721 int
11722 mono_type_native_stack_size (MonoType *t, guint32 *align)
11723 {
11724         guint32 tmp;
11725
11726         g_assert (t != NULL);
11727
11728         if (!align)
11729                 align = &tmp;
11730
11731         if (t->byref) {
11732                 *align = sizeof (gpointer);
11733                 return sizeof (gpointer);
11734         }
11735
11736         switch (t->type){
11737         case MONO_TYPE_BOOLEAN:
11738         case MONO_TYPE_CHAR:
11739         case MONO_TYPE_I1:
11740         case MONO_TYPE_U1:
11741         case MONO_TYPE_I2:
11742         case MONO_TYPE_U2:
11743         case MONO_TYPE_I4:
11744         case MONO_TYPE_U4:
11745                 *align = 4;
11746                 return 4;
11747         case MONO_TYPE_I:
11748         case MONO_TYPE_U:
11749         case MONO_TYPE_STRING:
11750         case MONO_TYPE_OBJECT:
11751         case MONO_TYPE_CLASS:
11752         case MONO_TYPE_SZARRAY:
11753         case MONO_TYPE_PTR:
11754         case MONO_TYPE_FNPTR:
11755         case MONO_TYPE_ARRAY:
11756                 *align = sizeof (gpointer);
11757                 return sizeof (gpointer);
11758         case MONO_TYPE_R4:
11759                 *align = 4;
11760                 return 4;
11761         case MONO_TYPE_R8:
11762                 *align = MONO_ABI_ALIGNOF (double);
11763                 return 8;
11764         case MONO_TYPE_I8:
11765         case MONO_TYPE_U8:
11766                 *align = MONO_ABI_ALIGNOF (gint64);
11767                 return 8;
11768         case MONO_TYPE_GENERICINST:
11769                 if (!mono_type_generic_inst_is_valuetype (t)) {
11770                         *align = sizeof (gpointer);
11771                         return sizeof (gpointer);
11772                 } 
11773                 /* Fall through */
11774         case MONO_TYPE_TYPEDBYREF:
11775         case MONO_TYPE_VALUETYPE: {
11776                 guint32 size;
11777                 MonoClass *klass = mono_class_from_mono_type (t);
11778
11779                 if (klass->enumtype)
11780                         return mono_type_native_stack_size (mono_class_enum_basetype (klass), align);
11781                 else {
11782                         size = mono_class_native_size (klass, align);
11783                         *align = *align + 3;
11784                         *align &= ~3;
11785                         
11786                         size +=  3;
11787                         size &= ~3;
11788
11789                         return size;
11790                 }
11791         }
11792         default:
11793                 g_error ("type 0x%02x unknown", t->type);
11794         }
11795         return 0;
11796 }
11797
11798 /**
11799  * mono_marshal_type_size:
11800  */
11801 gint32
11802 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
11803                         gboolean as_field, gboolean unicode)
11804 {
11805         MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
11806         MonoClass *klass;
11807
11808         switch (native_type) {
11809         case MONO_NATIVE_BOOLEAN:
11810                 *align = 4;
11811                 return 4;
11812         case MONO_NATIVE_I1:
11813         case MONO_NATIVE_U1:
11814                 *align = 1;
11815                 return 1;
11816         case MONO_NATIVE_I2:
11817         case MONO_NATIVE_U2:
11818         case MONO_NATIVE_VARIANTBOOL:
11819                 *align = 2;
11820                 return 2;
11821         case MONO_NATIVE_I4:
11822         case MONO_NATIVE_U4:
11823         case MONO_NATIVE_ERROR:
11824                 *align = 4;
11825                 return 4;
11826         case MONO_NATIVE_I8:
11827         case MONO_NATIVE_U8:
11828                 *align = MONO_ABI_ALIGNOF (gint64);
11829                 return 8;
11830         case MONO_NATIVE_R4:
11831                 *align = 4;
11832                 return 4;
11833         case MONO_NATIVE_R8:
11834                 *align = MONO_ABI_ALIGNOF (double);
11835                 return 8;
11836         case MONO_NATIVE_INT:
11837         case MONO_NATIVE_UINT:
11838         case MONO_NATIVE_LPSTR:
11839         case MONO_NATIVE_LPWSTR:
11840         case MONO_NATIVE_LPTSTR:
11841         case MONO_NATIVE_BSTR:
11842         case MONO_NATIVE_ANSIBSTR:
11843         case MONO_NATIVE_TBSTR:
11844         case MONO_NATIVE_UTF8STR:
11845         case MONO_NATIVE_LPARRAY:
11846         case MONO_NATIVE_SAFEARRAY:
11847         case MONO_NATIVE_IUNKNOWN:
11848         case MONO_NATIVE_IDISPATCH:
11849         case MONO_NATIVE_INTERFACE:
11850         case MONO_NATIVE_ASANY:
11851         case MONO_NATIVE_FUNC:
11852         case MONO_NATIVE_LPSTRUCT:
11853                 *align = MONO_ABI_ALIGNOF (gpointer);
11854                 return sizeof (gpointer);
11855         case MONO_NATIVE_STRUCT: 
11856                 klass = mono_class_from_mono_type (type);
11857                 if (klass == mono_defaults.object_class &&
11858                         (mspec && mspec->native == MONO_NATIVE_STRUCT)) {
11859                 *align = 16;
11860                 return 16;
11861                 }
11862                 return mono_class_native_size (klass, align);
11863         case MONO_NATIVE_BYVALTSTR: {
11864                 int esize = unicode ? 2: 1;
11865                 g_assert (mspec);
11866                 *align = esize;
11867                 return mspec->data.array_data.num_elem * esize;
11868         }
11869         case MONO_NATIVE_BYVALARRAY: {
11870                 // FIXME: Have to consider ArraySubType
11871                 int esize;
11872                 klass = mono_class_from_mono_type (type);
11873                 if (klass->element_class == mono_defaults.char_class) {
11874                         esize = unicode ? 2 : 1;
11875                         *align = esize;
11876                 } else {
11877                         esize = mono_class_native_size (klass->element_class, align);
11878                 }
11879                 g_assert (mspec);
11880                 return mspec->data.array_data.num_elem * esize;
11881         }
11882         case MONO_NATIVE_CUSTOM:
11883                 *align = sizeof (gpointer);
11884                 return sizeof (gpointer);
11885                 break;
11886         case MONO_NATIVE_CURRENCY:
11887         case MONO_NATIVE_VBBYREFSTR:
11888         default:
11889                 g_error ("native type %02x not implemented", native_type); 
11890                 break;
11891         }
11892         g_assert_not_reached ();
11893         return 0;
11894 }
11895
11896 /**
11897  * mono_marshal_asany:
11898  * This is a JIT icall, it sets the pending exception and returns NULL on error.
11899  */
11900 gpointer
11901 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
11902 {
11903         MonoError error;
11904         MonoType *t;
11905         MonoClass *klass;
11906
11907         if (o == NULL)
11908                 return NULL;
11909
11910         t = &o->vtable->klass->byval_arg;
11911         switch (t->type) {
11912         case MONO_TYPE_I4:
11913         case MONO_TYPE_U4:
11914         case MONO_TYPE_PTR:
11915         case MONO_TYPE_I1:
11916         case MONO_TYPE_U1:
11917         case MONO_TYPE_BOOLEAN:
11918         case MONO_TYPE_I2:
11919         case MONO_TYPE_U2:
11920         case MONO_TYPE_CHAR:
11921         case MONO_TYPE_I8:
11922         case MONO_TYPE_U8:
11923         case MONO_TYPE_R4:
11924         case MONO_TYPE_R8:
11925                 return mono_object_unbox (o);
11926                 break;
11927         case MONO_TYPE_STRING:
11928                 switch (string_encoding) {
11929                 case MONO_NATIVE_LPWSTR:
11930                         return mono_marshal_string_to_utf16_copy ((MonoString*)o);
11931                 case MONO_NATIVE_LPSTR:
11932                 case MONO_NATIVE_UTF8STR:
11933                         // Same code path, because in Mono, we treated strings as Utf8
11934                         return mono_string_to_utf8str ((MonoString*)o);
11935                 default:
11936                         g_warning ("marshaling conversion %d not implemented", string_encoding);
11937                         g_assert_not_reached ();
11938                 }
11939                 break;
11940         case MONO_TYPE_CLASS:
11941         case MONO_TYPE_VALUETYPE: {
11942                 MonoMethod *method;
11943                 gpointer pa [3];
11944                 gpointer res;
11945                 MonoBoolean delete_old = FALSE;
11946
11947                 klass = t->data.klass;
11948
11949                 if (mono_class_is_auto_layout (klass))
11950                         break;
11951
11952                 if (klass->valuetype && (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype))
11953                         return mono_object_unbox (o);
11954
11955                 res = mono_marshal_alloc (mono_class_native_size (klass, NULL), &error);
11956                 if (!mono_error_ok (&error)) {
11957                         mono_error_set_pending_exception (&error);
11958                         return NULL;
11959                 }
11960
11961                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11962                         method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
11963
11964                         pa [0] = o;
11965                         pa [1] = &res;
11966                         pa [2] = &delete_old;
11967
11968                         mono_runtime_invoke_checked (method, NULL, pa, &error);
11969                         if (!mono_error_ok (&error)) {
11970                                 mono_error_set_pending_exception (&error);
11971                                 return NULL;
11972                         }
11973                 }
11974
11975                 return res;
11976         }
11977         default:
11978                 break;
11979         }
11980         mono_set_pending_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
11981         return NULL;
11982 }
11983
11984 /**
11985  * mono_marshal_free_asany:
11986  * This is a JIT icall, it sets the pending exception
11987  */
11988 void
11989 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
11990 {
11991         MonoError error;
11992         MonoType *t;
11993         MonoClass *klass;
11994
11995         if (o == NULL)
11996                 return;
11997
11998         t = &o->vtable->klass->byval_arg;
11999         switch (t->type) {
12000         case MONO_TYPE_STRING:
12001                 switch (string_encoding) {
12002                 case MONO_NATIVE_LPWSTR:
12003                 case MONO_NATIVE_LPSTR:
12004                 case MONO_NATIVE_UTF8STR:
12005                         mono_marshal_free (ptr);
12006                         break;
12007                 default:
12008                         g_warning ("marshaling conversion %d not implemented", string_encoding);
12009                         g_assert_not_reached ();
12010                 }
12011                 break;
12012         case MONO_TYPE_CLASS:
12013         case MONO_TYPE_VALUETYPE: {
12014                 klass = t->data.klass;
12015
12016                 if (klass->valuetype && (mono_class_is_explicit_layout (klass) || klass->blittable || klass->enumtype))
12017                         break;
12018
12019                 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
12020                         MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
12021                         gpointer pa [2];
12022
12023                         pa [0] = &ptr;
12024                         pa [1] = o;
12025
12026                         mono_runtime_invoke_checked (method, NULL, pa, &error);
12027                         if (!mono_error_ok (&error)) {
12028                                 mono_error_set_pending_exception (&error);
12029                                 return;
12030                         }
12031                 }
12032
12033                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
12034                         mono_struct_delete_old (klass, (char *)ptr);
12035                 }
12036
12037                 mono_marshal_free (ptr);
12038                 break;
12039         }
12040         default:
12041                 break;
12042         }
12043 }
12044
12045 /*
12046  * mono_marshal_get_generic_array_helper:
12047  *
12048  *   Return a wrapper which is used to implement the implicit interfaces on arrays.
12049  * The wrapper routes calls to METHOD, which is one of the InternalArray_ methods in Array.
12050  */
12051 MonoMethod *
12052 mono_marshal_get_generic_array_helper (MonoClass *klass, gchar *name, MonoMethod *method)
12053 {
12054         MonoMethodSignature *sig, *csig;
12055         MonoMethodBuilder *mb;
12056         MonoMethod *res;
12057         WrapperInfo *info;
12058         int i;
12059
12060         mb = mono_mb_new_no_dup_name (klass, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
12061         mb->method->slot = -1;
12062
12063         mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
12064                 METHOD_ATTRIBUTE_NEW_SLOT | METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
12065
12066         sig = mono_method_signature (method);
12067         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
12068         csig->generic_param_count = 0;
12069
12070 #ifdef HAVE_ONLINE_VES
12071         mono_mb_emit_ldarg (mb, 0);
12072         for (i = 0; i < csig->param_count; i++)
12073                 mono_mb_emit_ldarg (mb, i + 1);
12074         mono_mb_emit_managed_call (mb, method, NULL);
12075         mono_mb_emit_byte (mb, CEE_RET);
12076
12077         /* We can corlib internal methods */
12078         mb->skip_visibility = TRUE;
12079 #endif
12080         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER);
12081         info->d.generic_array_helper.method = method;
12082         res = mono_mb_create (mb, csig, csig->param_count + 16, info);
12083
12084         mono_mb_free (mb);
12085
12086         return res;
12087 }
12088
12089 /*
12090  * The mono_win32_compat_* functions are implementations of inline
12091  * Windows kernel32 APIs, which are DllImport-able under MS.NET,
12092  * although not exported by kernel32.
12093  *
12094  * We map the appropiate kernel32 entries to these functions using
12095  * dllmaps declared in the global etc/mono/config.
12096  */
12097
12098 void
12099 mono_win32_compat_CopyMemory (gpointer dest, gconstpointer source, gsize length)
12100 {
12101         if (!dest || !source)
12102                 return;
12103
12104         memcpy (dest, source, length);
12105 }
12106
12107 void
12108 mono_win32_compat_FillMemory (gpointer dest, gsize length, guchar fill)
12109 {
12110         memset (dest, fill, length);
12111 }
12112
12113 void
12114 mono_win32_compat_MoveMemory (gpointer dest, gconstpointer source, gsize length)
12115 {
12116         if (!dest || !source)
12117                 return;
12118
12119         memmove (dest, source, length);
12120 }
12121
12122 void
12123 mono_win32_compat_ZeroMemory (gpointer dest, gsize length)
12124 {
12125         memset (dest, 0, length);
12126 }
12127
12128 void
12129 mono_marshal_find_nonzero_bit_offset (guint8 *buf, int len, int *byte_offset, guint8 *bitmask)
12130 {
12131         int i;
12132         guint8 byte;
12133
12134         for (i = 0; i < len; ++i)
12135                 if (buf [i])
12136                         break;
12137
12138         g_assert (i < len);
12139
12140         byte = buf [i];
12141         while (byte && !(byte & 1))
12142                 byte >>= 1;
12143         g_assert (byte == 1);
12144
12145         *byte_offset = i;
12146         *bitmask = buf [i];
12147 }
12148
12149 MonoMethod *
12150 mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
12151 {
12152         MonoMethodBuilder *mb;
12153         MonoMethodSignature *sig, *csig;
12154         MonoExceptionClause *clause;
12155         MonoImage *image;
12156         MonoClass *klass;
12157         GHashTable *cache;
12158         MonoMethod *res;
12159         int i, param_count, sig_size, pos_leave;
12160
12161         g_assert (method);
12162
12163         // FIXME: we need to store the exception into a MonoHandle
12164         g_assert (!mono_threads_is_coop_enabled ());
12165
12166         klass = method->klass;
12167         image = method->klass->image;
12168
12169         cache = get_cache (&mono_method_get_wrapper_cache (method)->thunk_invoke_cache, mono_aligned_addr_hash, NULL);
12170
12171         if ((res = mono_marshal_find_in_cache (cache, method)))
12172                 return res;
12173
12174         sig = mono_method_signature (method);
12175         mb = mono_mb_new (klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
12176
12177         /* add "this" and exception param */
12178         param_count = sig->param_count + sig->hasthis + 1;
12179
12180         /* dup & extend signature */
12181         csig = mono_metadata_signature_alloc (image, param_count);
12182         sig_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *);
12183         memcpy (csig, sig, sig_size);
12184         csig->param_count = param_count;
12185         csig->hasthis = 0;
12186         csig->pinvoke = 1;
12187         csig->call_convention = MONO_CALL_DEFAULT;
12188
12189         if (sig->hasthis) {
12190                 /* add "this" */
12191                 csig->params [0] = &klass->byval_arg;
12192                 /* move params up by one */
12193                 for (i = 0; i < sig->param_count; i++)
12194                         csig->params [i + 1] = sig->params [i];
12195         }
12196
12197         /* setup exception param as byref+[out] */
12198         csig->params [param_count - 1] = mono_metadata_type_dup (image,
12199                  &mono_defaults.exception_class->byval_arg);
12200         csig->params [param_count - 1]->byref = 1;
12201         csig->params [param_count - 1]->attrs = PARAM_ATTRIBUTE_OUT;
12202
12203         /* convert struct return to object */
12204         if (MONO_TYPE_ISSTRUCT (sig->ret))
12205                 csig->ret = &mono_defaults.object_class->byval_arg;
12206
12207 #ifdef HAVE_ONLINE_VES
12208         /* local 0 (temp for exception object) */
12209         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
12210
12211         /* local 1 (temp for result) */
12212         if (!MONO_TYPE_IS_VOID (sig->ret))
12213                 mono_mb_add_local (mb, sig->ret);
12214
12215         /* clear exception arg */
12216         mono_mb_emit_ldarg (mb, param_count - 1);
12217         mono_mb_emit_byte (mb, CEE_LDNULL);
12218         mono_mb_emit_byte (mb, CEE_STIND_REF);
12219
12220         /* try */
12221         clause = (MonoExceptionClause *)mono_image_alloc0 (image, sizeof (MonoExceptionClause));
12222         clause->try_offset = mono_mb_get_label (mb);
12223
12224         /* push method's args */
12225         for (i = 0; i < param_count - 1; i++) {
12226                 MonoType *type;
12227                 MonoClass *klass;
12228
12229                 mono_mb_emit_ldarg (mb, i);
12230
12231                 /* get the byval type of the param */
12232                 klass = mono_class_from_mono_type (csig->params [i]);
12233                 type = &klass->byval_arg;
12234
12235                 /* unbox struct args */
12236                 if (MONO_TYPE_ISSTRUCT (type)) {
12237                         mono_mb_emit_op (mb, CEE_UNBOX, klass);
12238
12239                         /* byref args & and the "this" arg must remain a ptr.
12240                            Otherwise make a copy of the value type */
12241                         if (!(csig->params [i]->byref || (i == 0 && sig->hasthis)))
12242                                 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
12243
12244                         csig->params [i] = &mono_defaults.object_class->byval_arg;
12245                 }
12246         }
12247
12248         /* call */
12249         if (method->flags & METHOD_ATTRIBUTE_VIRTUAL)
12250                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
12251         else
12252                 mono_mb_emit_op (mb, CEE_CALL, method);
12253
12254         /* save result at local 1 */
12255         if (!MONO_TYPE_IS_VOID (sig->ret))
12256                 mono_mb_emit_stloc (mb, 1);
12257
12258         pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
12259
12260         /* catch */
12261         clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
12262         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
12263         clause->data.catch_class = mono_defaults.object_class;
12264
12265         clause->handler_offset = mono_mb_get_label (mb);
12266
12267         /* store exception at local 0 */
12268         mono_mb_emit_stloc (mb, 0);
12269         mono_mb_emit_ldarg (mb, param_count - 1);
12270         mono_mb_emit_ldloc (mb, 0);
12271         mono_mb_emit_byte (mb, CEE_STIND_REF);
12272         mono_mb_emit_branch (mb, CEE_LEAVE);
12273
12274         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
12275
12276         mono_mb_set_clauses (mb, 1, clause);
12277
12278         mono_mb_patch_branch (mb, pos_leave);
12279         /* end-try */
12280
12281         if (!MONO_TYPE_IS_VOID (sig->ret)) {
12282                 mono_mb_emit_ldloc (mb, 1);
12283
12284                 /* box the return value */
12285                 if (MONO_TYPE_ISSTRUCT (sig->ret))
12286                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
12287         }
12288
12289         mono_mb_emit_byte (mb, CEE_RET);
12290 #endif
12291
12292         res = mono_mb_create_and_cache (cache, method, mb, csig, param_count + 16);
12293         mono_mb_free (mb);
12294
12295         return res;
12296 }
12297
12298 /*
12299  * mono_marshal_free_dynamic_wrappers:
12300  *
12301  *   Free wrappers of the dynamic method METHOD.
12302  */
12303 void
12304 mono_marshal_free_dynamic_wrappers (MonoMethod *method)
12305 {
12306         MonoImage *image = method->klass->image;
12307
12308         g_assert (method_is_dynamic (method));
12309
12310         /* This could be called during shutdown */
12311         if (marshal_mutex_initialized)
12312                 mono_marshal_lock ();
12313         /* 
12314          * FIXME: We currently leak the wrappers. Freeing them would be tricky as
12315          * they could be shared with other methods ?
12316          */
12317         if (image->wrapper_caches.runtime_invoke_direct_cache)
12318                 g_hash_table_remove (image->wrapper_caches.runtime_invoke_direct_cache, method);
12319         if (image->wrapper_caches.delegate_abstract_invoke_cache)
12320                 g_hash_table_foreach_remove (image->wrapper_caches.delegate_abstract_invoke_cache, signature_pointer_pair_matches_pointer, method);
12321         // FIXME: Need to clear the caches in other images as well
12322         if (image->delegate_bound_static_invoke_cache)
12323                 g_hash_table_remove (image->delegate_bound_static_invoke_cache, mono_method_signature (method));
12324
12325         if (marshal_mutex_initialized)
12326                 mono_marshal_unlock ();
12327 }
12328
12329 static void
12330 mono_marshal_ftnptr_eh_callback (guint32 gchandle)
12331 {
12332         g_assert (ftnptr_eh_callback);
12333         ftnptr_eh_callback (gchandle);
12334 }
12335
12336 static void
12337 ftnptr_eh_callback_default (guint32 gchandle)
12338 {
12339         MonoException *exc;
12340         gpointer stackdata;
12341
12342         mono_threads_enter_gc_unsafe_region_unbalanced (&stackdata);
12343
12344         exc = (MonoException*) mono_gchandle_get_target (gchandle);
12345
12346         mono_gchandle_free (gchandle);
12347
12348         mono_raise_exception (exc);
12349 }
12350
12351 /*
12352  * mono_install_ftnptr_eh_callback:
12353  *
12354  *   Install a callback that should be called when there is a managed exception
12355  *   in a native-to-managed wrapper. This is mainly used by iOS to convert a
12356  *   managed exception to a native exception, to properly unwind the native
12357  *   stack; this native exception will then be converted back to a managed
12358  *   exception in their managed-to-native wrapper.
12359  */
12360 void
12361 mono_install_ftnptr_eh_callback (MonoFtnPtrEHCallback callback)
12362 {
12363         ftnptr_eh_callback = callback;
12364 }
12365
12366 static MonoThreadInfo*
12367 mono_icall_start (HandleStackMark *stackmark, MonoError *error)
12368 {
12369         MonoThreadInfo *info = mono_thread_info_current ();
12370
12371         mono_stack_mark_init (info, stackmark);
12372         error_init (error);
12373         return info;
12374 }
12375
12376 static void
12377 mono_icall_end (MonoThreadInfo *info, HandleStackMark *stackmark, MonoError *error)
12378 {
12379         mono_stack_mark_pop (info, stackmark);
12380         if (G_UNLIKELY (!is_ok (error)))
12381                 mono_error_set_pending_exception (error);
12382 }
12383
12384 static MonoObjectHandle
12385 mono_icall_handle_new (gpointer rawobj)
12386 {
12387 #ifdef MONO_HANDLE_TRACK_OWNER
12388         return mono_handle_new (rawobj, "<marshal args>");
12389 #else
12390         return mono_handle_new (rawobj);
12391 #endif
12392 }
12393
12394 static MonoObjectHandle
12395 mono_icall_handle_new_interior (gpointer rawobj)
12396 {
12397 #ifdef MONO_HANDLE_TRACK_OWNER
12398         return mono_handle_new_interior (rawobj, "<marshal args>");
12399 #else
12400         return mono_handle_new_interior (rawobj);
12401 #endif
12402 }