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