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