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