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