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