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