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