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