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