[sgen] Fix critical/normal finalization order at domain unload
[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  */
4224 MonoMethod*
4225 mono_marshal_get_runtime_invoke_dynamic (void)
4226 {
4227         static MonoMethod *method;
4228         MonoMethodSignature *csig;
4229         MonoExceptionClause *clause;
4230         MonoMethodBuilder *mb;
4231         int pos, posna;
4232         char *name;
4233         WrapperInfo *info;
4234
4235         if (method)
4236                 return method;
4237
4238         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
4239
4240         csig->ret = &mono_defaults.void_class->byval_arg;
4241         csig->params [0] = &mono_defaults.int_class->byval_arg;
4242         csig->params [1] = &mono_defaults.int_class->byval_arg;
4243         csig->params [2] = &mono_defaults.int_class->byval_arg;
4244         csig->params [3] = &mono_defaults.int_class->byval_arg;
4245
4246         name = g_strdup ("runtime_invoke_dynamic");
4247         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_RUNTIME_INVOKE);
4248         g_free (name);
4249
4250 #ifndef DISABLE_JIT
4251         /* allocate local 0 (object) tmp */
4252         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4253         /* allocate local 1 (object) exc */
4254         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4255
4256         /* cond set *exc to null */
4257         mono_mb_emit_byte (mb, CEE_LDARG_1);
4258         mono_mb_emit_byte (mb, CEE_BRFALSE_S);
4259         mono_mb_emit_byte (mb, 3);      
4260         mono_mb_emit_byte (mb, CEE_LDARG_1);
4261         mono_mb_emit_byte (mb, CEE_LDNULL);
4262         mono_mb_emit_byte (mb, CEE_STIND_REF);
4263
4264         emit_thread_force_interrupt_checkpoint (mb);
4265
4266         mono_mb_emit_byte (mb, CEE_LDARG_0);
4267         mono_mb_emit_byte (mb, CEE_LDARG_2);
4268         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4269         mono_mb_emit_byte (mb, CEE_MONO_DYN_CALL);
4270
4271         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
4272
4273         clause = (MonoExceptionClause *)mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
4274         clause->flags = MONO_EXCEPTION_CLAUSE_FILTER;
4275         clause->try_len = mono_mb_get_label (mb);
4276
4277         /* filter code */
4278         clause->data.filter_offset = mono_mb_get_label (mb);
4279         
4280         mono_mb_emit_byte (mb, CEE_POP);
4281         mono_mb_emit_byte (mb, CEE_LDARG_1);
4282         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
4283         mono_mb_emit_byte (mb, CEE_PREFIX1);
4284         mono_mb_emit_byte (mb, CEE_CGT_UN);
4285         mono_mb_emit_byte (mb, CEE_PREFIX1);
4286         mono_mb_emit_byte (mb, CEE_ENDFILTER);
4287
4288         clause->handler_offset = mono_mb_get_label (mb);
4289
4290         /* handler code */
4291         /* store exception */
4292         mono_mb_emit_stloc (mb, 1);
4293         
4294         mono_mb_emit_byte (mb, CEE_LDARG_1);
4295         mono_mb_emit_ldloc (mb, 1);
4296         mono_mb_emit_byte (mb, CEE_STIND_REF);
4297
4298         mono_mb_emit_byte (mb, CEE_LDNULL);
4299         mono_mb_emit_stloc (mb, 0);
4300
4301         /* Check for the abort exception */
4302         mono_mb_emit_ldloc (mb, 1);
4303         mono_mb_emit_op (mb, CEE_ISINST, mono_defaults.threadabortexception_class);
4304         posna = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
4305
4306         /* Delay the abort exception */
4307         mono_mb_emit_icall (mb, ves_icall_System_Threading_Thread_ResetAbort);
4308
4309         mono_mb_patch_short_branch (mb, posna);
4310         mono_mb_emit_branch (mb, CEE_LEAVE);
4311
4312         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
4313
4314         mono_mb_set_clauses (mb, 1, clause);
4315
4316         /* return result */
4317         mono_mb_patch_branch (mb, pos);
4318         //mono_mb_emit_ldloc (mb, 0);
4319         mono_mb_emit_byte (mb, CEE_RET);
4320 #endif /* DISABLE_JIT */
4321
4322         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC);
4323
4324         mono_marshal_lock ();
4325         /* double-checked locking */
4326         if (!method)
4327                 method = mono_mb_create (mb, csig, 16, info);
4328
4329         mono_marshal_unlock ();
4330
4331         mono_mb_free (mb);
4332
4333         return method;
4334 }
4335
4336 /*
4337  * mono_marshal_get_runtime_invoke_for_sig:
4338  *
4339  *   Return a runtime invoke wrapper for a given signature.
4340  */
4341 MonoMethod *
4342 mono_marshal_get_runtime_invoke_for_sig (MonoMethodSignature *sig)
4343 {
4344         MonoMethodSignature *csig, *callsig;
4345         MonoMethodBuilder *mb;
4346         MonoImage *image;
4347         GHashTable *cache = NULL;
4348         GHashTable **cache_table = NULL;
4349         MonoMethod *res = NULL;
4350         char *name;
4351         const char *param_names [16];
4352         WrapperInfo *info;
4353
4354         /* A simplified version of mono_marshal_get_runtime_invoke */
4355
4356         image = mono_defaults.corlib;
4357
4358         callsig = mono_marshal_get_runtime_invoke_sig (sig);
4359
4360         cache_table = &image->wrapper_caches.runtime_invoke_sig_cache;
4361
4362         cache = get_cache (cache_table, (GHashFunc)mono_signature_hash,
4363                                            (GCompareFunc)runtime_invoke_signature_equal);
4364
4365         /* from mono_marshal_find_in_cache */
4366         mono_marshal_lock ();
4367         res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4368         mono_marshal_unlock ();
4369
4370         if (res) {
4371                 g_free (callsig);
4372                 return res;
4373         }
4374
4375         /* Make a copy of the signature from the image mempool */
4376         callsig = mono_metadata_signature_dup_full (image, callsig);
4377
4378         csig = mono_metadata_signature_alloc (image, 4);
4379         csig->ret = &mono_defaults.object_class->byval_arg;
4380         csig->params [0] = &mono_defaults.object_class->byval_arg;
4381         csig->params [1] = &mono_defaults.int_class->byval_arg;
4382         csig->params [2] = &mono_defaults.int_class->byval_arg;
4383         csig->params [3] = &mono_defaults.int_class->byval_arg;
4384         csig->pinvoke = 1;
4385 #if TARGET_WIN32
4386         /* This is called from runtime code so it has to be cdecl */
4387         csig->call_convention = MONO_CALL_C;
4388 #endif
4389
4390         name = mono_signature_to_name (callsig, "runtime_invoke_sig");
4391         mb = mono_mb_new (mono_defaults.object_class, name,  MONO_WRAPPER_RUNTIME_INVOKE);
4392         g_free (name);
4393
4394 #ifndef DISABLE_JIT
4395         param_names [0] = "this";
4396         param_names [1] = "params";
4397         param_names [2] = "exc";
4398         param_names [3] = "method";
4399         mono_mb_set_param_names (mb, param_names);
4400
4401         emit_runtime_invoke_body (mb, image, NULL, sig, callsig, FALSE, FALSE);
4402 #endif
4403
4404         /* taken from mono_mb_create_and_cache */
4405         mono_marshal_lock ();
4406         res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4407         mono_marshal_unlock ();
4408
4409         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL);
4410         info->d.runtime_invoke.sig = callsig;
4411
4412         /* Somebody may have created it before us */
4413         if (!res) {
4414                 MonoMethod *newm;
4415                 newm = mono_mb_create (mb, csig, sig->param_count + 16, info);
4416
4417                 mono_marshal_lock ();
4418                 res = (MonoMethod *)g_hash_table_lookup (cache, callsig);
4419                 if (!res) {
4420                         res = newm;
4421                         g_hash_table_insert (cache, callsig, res);
4422                 } else {
4423                         mono_free_method (newm);
4424                 }
4425                 mono_marshal_unlock ();
4426         }
4427
4428         /* end mono_mb_create_and_cache */
4429
4430         mono_mb_free (mb);
4431
4432         return res;
4433 }
4434
4435 #ifndef DISABLE_JIT
4436 static void
4437 mono_mb_emit_auto_layout_exception (MonoMethodBuilder *mb, MonoClass *klass)
4438 {
4439         char *msg = g_strdup_printf ("The type `%s.%s' layout needs to be Sequential or Explicit",
4440                                      klass->name_space, klass->name);
4441
4442         mono_mb_emit_exception_marshal_directive (mb, msg);
4443 }
4444 #endif
4445
4446 /*
4447  * generates IL code for the icall wrapper (the generated method
4448  * calls the unmanaged code in func)
4449  */
4450 MonoMethod *
4451 mono_marshal_get_icall_wrapper (MonoMethodSignature *sig, const char *name, gconstpointer func, gboolean check_exceptions)
4452 {
4453         MonoMethodSignature *csig, *csig2;
4454         MonoMethodBuilder *mb;
4455         MonoMethod *res;
4456         int i;
4457         WrapperInfo *info;
4458         
4459         GHashTable *cache = get_cache (&mono_defaults.object_class->image->icall_wrapper_cache, mono_aligned_addr_hash, NULL);
4460         if ((res = mono_marshal_find_in_cache (cache, (gpointer) func)))
4461                 return res;
4462
4463         g_assert (sig->pinvoke);
4464
4465         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
4466
4467         mb->method->save_lmf = 1;
4468
4469         /* Add an explicit this argument */
4470         if (sig->hasthis)
4471                 csig2 = mono_metadata_signature_dup_add_this (mono_defaults.corlib, sig, mono_defaults.object_class);
4472         else
4473                 csig2 = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
4474
4475 #ifndef DISABLE_JIT
4476         if (sig->hasthis)
4477                 mono_mb_emit_byte (mb, CEE_LDARG_0);
4478
4479         for (i = 0; i < sig->param_count; i++)
4480                 mono_mb_emit_ldarg (mb, i + sig->hasthis);
4481
4482         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4483         mono_mb_emit_op (mb, CEE_MONO_JIT_ICALL_ADDR, (gpointer)func);
4484         mono_mb_emit_calli (mb, csig2);
4485         if (check_exceptions)
4486                 emit_thread_interrupt_checkpoint (mb);
4487         mono_mb_emit_byte (mb, CEE_RET);
4488 #endif
4489
4490         csig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
4491         csig->pinvoke = 0;
4492         if (csig->call_convention == MONO_CALL_VARARG)
4493                 csig->call_convention = 0;
4494
4495         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ICALL_WRAPPER);
4496         info->d.icall.func = (gpointer)func;
4497         res = mono_mb_create_and_cache_full (cache, (gpointer) func, mb, csig, csig->param_count + 16, info, NULL);
4498         mono_mb_free (mb);
4499
4500         return res;
4501 }
4502
4503 static int
4504 emit_marshal_custom (EmitMarshalContext *m, int argnum, MonoType *t,
4505                                          MonoMarshalSpec *spec, 
4506                                          int conv_arg, MonoType **conv_arg_type, 
4507                                          MarshalAction action)
4508 {
4509 #ifdef DISABLE_JIT
4510         if (action == MARSHAL_ACTION_CONV_IN && t->type == MONO_TYPE_VALUETYPE)
4511                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
4512         return conv_arg;
4513 #else
4514         MonoError error;
4515         MonoType *mtype;
4516         MonoClass *mklass;
4517         static MonoClass *ICustomMarshaler = NULL;
4518         static MonoMethod *cleanup_native, *cleanup_managed;
4519         static MonoMethod *marshal_managed_to_native, *marshal_native_to_managed;
4520         MonoMethod *get_instance = NULL;
4521         MonoMethodBuilder *mb = m->mb;
4522         char *exception_msg = NULL;
4523         guint32 loc1;
4524         int pos2;
4525
4526         if (!ICustomMarshaler) {
4527                 MonoClass *klass = mono_class_try_get_icustom_marshaler_class ();
4528                 if (!klass) {
4529                         exception_msg = g_strdup ("Current profile doesn't support ICustomMarshaler");
4530                         goto handle_exception;
4531                 }
4532
4533                 cleanup_native = mono_class_get_method_from_name (klass, "CleanUpNativeData", 1);
4534                 g_assert (cleanup_native);
4535                 cleanup_managed = mono_class_get_method_from_name (klass, "CleanUpManagedData", 1);
4536                 g_assert (cleanup_managed);
4537                 marshal_managed_to_native = mono_class_get_method_from_name (klass, "MarshalManagedToNative", 1);
4538                 g_assert (marshal_managed_to_native);
4539                 marshal_native_to_managed = mono_class_get_method_from_name (klass, "MarshalNativeToManaged", 1);
4540                 g_assert (marshal_native_to_managed);
4541
4542                 mono_memory_barrier ();
4543                 ICustomMarshaler = klass;
4544         }
4545
4546         if (spec->data.custom_data.image)
4547                 mtype = mono_reflection_type_from_name_checked (spec->data.custom_data.custom_name, spec->data.custom_data.image, &error);
4548         else
4549                 mtype = mono_reflection_type_from_name_checked (spec->data.custom_data.custom_name, m->image, &error);
4550         g_assert (mtype != NULL);
4551         mono_error_assert_ok (&error);
4552         mklass = mono_class_from_mono_type (mtype);
4553         g_assert (mklass != NULL);
4554
4555         if (!mono_class_is_assignable_from (ICustomMarshaler, mklass))
4556                 exception_msg = g_strdup_printf ("Custom marshaler '%s' does not implement the ICustomMarshaler interface.", mklass->name);
4557
4558         get_instance = mono_class_get_method_from_name_flags (mklass, "GetInstance", 1, METHOD_ATTRIBUTE_STATIC);
4559         if (get_instance) {
4560                 MonoMethodSignature *get_sig = mono_method_signature (get_instance);
4561                 if ((get_sig->ret->type != MONO_TYPE_CLASS) ||
4562                         (mono_class_from_mono_type (get_sig->ret) != ICustomMarshaler) ||
4563                         (get_sig->params [0]->type != MONO_TYPE_STRING))
4564                         get_instance = NULL;
4565         }
4566
4567         if (!get_instance)
4568                 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);
4569
4570 handle_exception:
4571         /* Throw exception and emit compensation code if neccesary */
4572         if (exception_msg) {
4573                 switch (action) {
4574                 case MARSHAL_ACTION_CONV_IN:
4575                 case MARSHAL_ACTION_CONV_RESULT:
4576                 case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4577                         if ((action == MARSHAL_ACTION_CONV_RESULT) || (action == MARSHAL_ACTION_MANAGED_CONV_RESULT))
4578                                 mono_mb_emit_byte (mb, CEE_POP);
4579
4580                         mono_mb_emit_exception_full (mb, "System", "ApplicationException", exception_msg);
4581                         g_free (exception_msg);
4582
4583                         break;
4584                 case MARSHAL_ACTION_PUSH:
4585                         mono_mb_emit_byte (mb, CEE_LDNULL);
4586                         break;
4587                 default:
4588                         break;
4589                 }
4590                 return 0;
4591         }
4592
4593         /* FIXME: MS.NET seems to create one instance for each klass + cookie pair */
4594         /* FIXME: MS.NET throws an exception if GetInstance returns null */
4595
4596         switch (action) {
4597         case MARSHAL_ACTION_CONV_IN:
4598                 switch (t->type) {
4599                 case MONO_TYPE_CLASS:
4600                 case MONO_TYPE_OBJECT:
4601                 case MONO_TYPE_STRING:
4602                 case MONO_TYPE_ARRAY:
4603                 case MONO_TYPE_SZARRAY:
4604                 case MONO_TYPE_VALUETYPE:
4605                         break;
4606
4607                 default:
4608                         g_warning ("custom marshalling of type %x is currently not supported", t->type);
4609                         g_assert_not_reached ();
4610                         break;
4611                 }
4612
4613                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4614
4615                 mono_mb_emit_byte (mb, CEE_LDNULL);
4616                 mono_mb_emit_stloc (mb, conv_arg);
4617
4618                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT))
4619                         break;
4620
4621                 /* Minic MS.NET behavior */
4622                 if (!t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT) && !(t->attrs & PARAM_ATTRIBUTE_IN))
4623                         break;
4624
4625                 /* Check for null */
4626                 mono_mb_emit_ldarg (mb, argnum);
4627                 if (t->byref)
4628                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4629                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4630
4631                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4632
4633                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4634                                 
4635                 mono_mb_emit_ldarg (mb, argnum);
4636                 if (t->byref)
4637                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
4638
4639                 if (t->type == MONO_TYPE_VALUETYPE) {
4640                         /*
4641                          * Since we can't determine the type of the argument, we
4642                          * will assume the unmanaged function takes a pointer.
4643                          */
4644                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
4645
4646                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (t));
4647                 }
4648
4649                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4650                 mono_mb_emit_stloc (mb, conv_arg);
4651
4652                 mono_mb_patch_branch (mb, pos2);
4653                 break;
4654
4655         case MARSHAL_ACTION_CONV_OUT:
4656                 /* Check for null */
4657                 mono_mb_emit_ldloc (mb, conv_arg);
4658                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4659
4660                 if (t->byref) {
4661                         mono_mb_emit_ldarg (mb, argnum);
4662
4663                         mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4664
4665                         mono_mb_emit_op (mb, CEE_CALL, get_instance);
4666
4667                         mono_mb_emit_ldloc (mb, conv_arg);
4668                         mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4669                         mono_mb_emit_byte (mb, CEE_STIND_REF);
4670                 } else if (t->attrs & PARAM_ATTRIBUTE_OUT) {
4671                         mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4672
4673                         mono_mb_emit_op (mb, CEE_CALL, get_instance);
4674
4675                         mono_mb_emit_ldloc (mb, conv_arg);
4676                         mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4677
4678                         /* We have nowhere to store the result */
4679                         mono_mb_emit_byte (mb, CEE_POP);
4680                 }
4681
4682                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4683
4684                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4685
4686                 mono_mb_emit_ldloc (mb, conv_arg);
4687
4688                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4689
4690                 mono_mb_patch_branch (mb, pos2);
4691                 break;
4692
4693         case MARSHAL_ACTION_PUSH:
4694                 if (t->byref)
4695                         mono_mb_emit_ldloc_addr (mb, conv_arg);
4696                 else
4697                         mono_mb_emit_ldloc (mb, conv_arg);
4698                 break;
4699
4700         case MARSHAL_ACTION_CONV_RESULT:
4701                 loc1 = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4702                         
4703                 mono_mb_emit_stloc (mb, 3);
4704
4705                 mono_mb_emit_ldloc (mb, 3);
4706                 mono_mb_emit_stloc (mb, loc1);
4707
4708                 /* Check for null */
4709                 mono_mb_emit_ldloc (mb, 3);
4710                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4711
4712                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4713
4714                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4715                 mono_mb_emit_byte (mb, CEE_DUP);
4716
4717                 mono_mb_emit_ldloc (mb, 3);
4718                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4719                 mono_mb_emit_stloc (mb, 3);
4720
4721                 mono_mb_emit_ldloc (mb, loc1);
4722                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_native);
4723
4724                 mono_mb_patch_branch (mb, pos2);
4725                 break;
4726
4727         case MARSHAL_ACTION_MANAGED_CONV_IN:
4728                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4729
4730                 mono_mb_emit_byte (mb, CEE_LDNULL);
4731                 mono_mb_emit_stloc (mb, conv_arg);
4732
4733                 if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
4734                         break;
4735
4736                 /* Check for null */
4737                 mono_mb_emit_ldarg (mb, argnum);
4738                 if (t->byref)
4739                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4740                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4741
4742                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4743                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4744                                 
4745                 mono_mb_emit_ldarg (mb, argnum);
4746                 if (t->byref)
4747                         mono_mb_emit_byte (mb, CEE_LDIND_I);
4748                                 
4749                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_native_to_managed);
4750                 mono_mb_emit_stloc (mb, conv_arg);
4751
4752                 mono_mb_patch_branch (mb, pos2);
4753                 break;
4754
4755         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
4756                 g_assert (!t->byref);
4757
4758                 loc1 = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
4759                         
4760                 mono_mb_emit_stloc (mb, 3);
4761                         
4762                 mono_mb_emit_ldloc (mb, 3);
4763                 mono_mb_emit_stloc (mb, loc1);
4764
4765                 /* Check for null */
4766                 mono_mb_emit_ldloc (mb, 3);
4767                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4768
4769                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4770                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4771                 mono_mb_emit_byte (mb, CEE_DUP);
4772
4773                 mono_mb_emit_ldloc (mb, 3);
4774                 mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4775                 mono_mb_emit_stloc (mb, 3);
4776
4777                 mono_mb_emit_ldloc (mb, loc1);
4778                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
4779
4780                 mono_mb_patch_branch (mb, pos2);
4781                 break;
4782
4783         case MARSHAL_ACTION_MANAGED_CONV_OUT:
4784
4785                 /* Check for null */
4786                 mono_mb_emit_ldloc (mb, conv_arg);
4787                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
4788
4789                 if (t->byref) {
4790                         mono_mb_emit_ldarg (mb, argnum);
4791
4792                         mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4793
4794                         mono_mb_emit_op (mb, CEE_CALL, get_instance);
4795
4796                         mono_mb_emit_ldloc (mb, conv_arg);
4797                         mono_mb_emit_op (mb, CEE_CALLVIRT, marshal_managed_to_native);
4798                         mono_mb_emit_byte (mb, CEE_STIND_I);
4799                 }
4800
4801                 /* Call CleanUpManagedData */
4802                 mono_mb_emit_ldstr (mb, g_strdup (spec->data.custom_data.cookie));
4803
4804                 mono_mb_emit_op (mb, CEE_CALL, get_instance);
4805                                 
4806                 mono_mb_emit_ldloc (mb, conv_arg);
4807                 mono_mb_emit_op (mb, CEE_CALLVIRT, cleanup_managed);
4808
4809                 mono_mb_patch_branch (mb, pos2);
4810                 break;
4811
4812         default:
4813                 g_assert_not_reached ();
4814         }
4815         return conv_arg;
4816 #endif
4817
4818 }
4819
4820 static int
4821 emit_marshal_asany (EmitMarshalContext *m, int argnum, MonoType *t,
4822                                         MonoMarshalSpec *spec, 
4823                                         int conv_arg, MonoType **conv_arg_type, 
4824                                         MarshalAction action)
4825 {
4826 #ifndef DISABLE_JIT
4827         MonoMethodBuilder *mb = m->mb;
4828
4829         switch (action) {
4830         case MARSHAL_ACTION_CONV_IN: {
4831                 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
4832
4833                 g_assert (t->type == MONO_TYPE_OBJECT);
4834                 g_assert (!t->byref);
4835
4836                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4837                 mono_mb_emit_ldarg (mb, argnum);
4838                 mono_mb_emit_icon (mb, encoding);
4839                 mono_mb_emit_icon (mb, t->attrs);
4840                 mono_mb_emit_icall (mb, mono_marshal_asany);
4841                 mono_mb_emit_stloc (mb, conv_arg);
4842                 break;
4843         }
4844
4845         case MARSHAL_ACTION_PUSH:
4846                 mono_mb_emit_ldloc (mb, conv_arg);
4847                 break;
4848
4849         case MARSHAL_ACTION_CONV_OUT: {
4850                 MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, NULL);
4851
4852                 mono_mb_emit_ldarg (mb, argnum);
4853                 mono_mb_emit_ldloc (mb, conv_arg);
4854                 mono_mb_emit_icon (mb, encoding);
4855                 mono_mb_emit_icon (mb, t->attrs);
4856                 mono_mb_emit_icall (mb, mono_marshal_free_asany);
4857                 break;
4858         }
4859
4860         default:
4861                 g_assert_not_reached ();
4862         }
4863 #endif
4864         return conv_arg;
4865 }
4866
4867 static int
4868 emit_marshal_vtype (EmitMarshalContext *m, int argnum, MonoType *t,
4869                                         MonoMarshalSpec *spec, 
4870                                         int conv_arg, MonoType **conv_arg_type, 
4871                                         MarshalAction action)
4872 {
4873 #ifndef DISABLE_JIT
4874         MonoMethodBuilder *mb = m->mb;
4875         MonoClass *klass, *date_time_class;
4876         int pos = 0, pos2;
4877
4878         klass = mono_class_from_mono_type (t);
4879
4880         date_time_class = mono_class_get_date_time_class ();
4881
4882         switch (action) {
4883         case MARSHAL_ACTION_CONV_IN:
4884                 if (klass == date_time_class) {
4885                         /* Convert it to an OLE DATE type */
4886                         static MonoMethod *to_oadate;
4887
4888                         if (!to_oadate)
4889                                 to_oadate = mono_class_get_method_from_name (date_time_class, "ToOADate", 0);
4890                         g_assert (to_oadate);
4891
4892                         conv_arg = mono_mb_add_local (mb, &mono_defaults.double_class->byval_arg);
4893
4894                         if (t->byref) {
4895                                 mono_mb_emit_ldarg (mb, argnum);
4896                                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
4897                         }
4898
4899                         if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
4900                                 if (!t->byref)
4901                                         m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.double_class->byval_arg;
4902
4903                                 mono_mb_emit_ldarg_addr (mb, argnum);
4904                                 mono_mb_emit_managed_call (mb, to_oadate, NULL);
4905                                 mono_mb_emit_stloc (mb, conv_arg);
4906                         }
4907
4908                         if (t->byref)
4909                                 mono_mb_patch_branch (mb, pos);
4910                         break;
4911                 }
4912
4913                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4914                         klass->blittable || klass->enumtype)
4915                         break;
4916
4917                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
4918                         
4919                 /* store the address of the source into local variable 0 */
4920                 if (t->byref)
4921                         mono_mb_emit_ldarg (mb, argnum);
4922                 else
4923                         mono_mb_emit_ldarg_addr (mb, argnum);
4924                 
4925                 mono_mb_emit_stloc (mb, 0);
4926                         
4927                 /* allocate space for the native struct and
4928                  * store the address into local variable 1 (dest) */
4929                 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
4930                 mono_mb_emit_byte (mb, CEE_PREFIX1);
4931                 mono_mb_emit_byte (mb, CEE_LOCALLOC);
4932                 mono_mb_emit_stloc (mb, conv_arg);
4933
4934                 if (t->byref) {
4935                         mono_mb_emit_ldloc (mb, 0);
4936                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
4937                 }
4938
4939                 if (!(t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))) {
4940                         /* set dst_ptr */
4941                         mono_mb_emit_ldloc (mb, conv_arg);
4942                         mono_mb_emit_stloc (mb, 1);
4943
4944                         /* emit valuetype conversion code */
4945                         emit_struct_conv (mb, klass, FALSE);
4946                 }
4947
4948                 if (t->byref)
4949                         mono_mb_patch_branch (mb, pos);
4950                 break;
4951
4952         case MARSHAL_ACTION_PUSH:
4953                 if (spec && spec->native == MONO_NATIVE_LPSTRUCT) {
4954                         /* FIXME: */
4955                         g_assert (!t->byref);
4956
4957                         /* Have to change the signature since the vtype is passed byref */
4958                         m->csig->params [argnum - m->csig->hasthis] = &mono_defaults.int_class->byval_arg;
4959
4960                         if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4961                                 klass->blittable || klass->enumtype)
4962                                 mono_mb_emit_ldarg_addr (mb, argnum);
4963                         else
4964                                 mono_mb_emit_ldloc (mb, conv_arg);
4965                         break;
4966                 }
4967
4968                 if (klass == date_time_class) {
4969                         if (t->byref)
4970                                 mono_mb_emit_ldloc_addr (mb, conv_arg);
4971                         else
4972                                 mono_mb_emit_ldloc (mb, conv_arg);
4973                         break;
4974                 }
4975
4976                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
4977                         klass->blittable || klass->enumtype) {
4978                         mono_mb_emit_ldarg (mb, argnum);
4979                         break;
4980                 }                       
4981                 mono_mb_emit_ldloc (mb, conv_arg);
4982                 if (!t->byref) {
4983                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4984                         mono_mb_emit_op (mb, CEE_MONO_LDNATIVEOBJ, klass);
4985                 }
4986                 break;
4987
4988         case MARSHAL_ACTION_CONV_OUT:
4989                 if (klass == date_time_class) {
4990                         /* Convert from an OLE DATE type */
4991                         static MonoMethod *from_oadate;
4992
4993                         if (!t->byref)
4994                                 break;
4995
4996                         if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
4997                                 if (!from_oadate)
4998                                         from_oadate = mono_class_get_method_from_name (date_time_class, "FromOADate", 1);
4999                                 g_assert (from_oadate);
5000
5001                                 mono_mb_emit_ldarg (mb, argnum);
5002                                 mono_mb_emit_ldloc (mb, conv_arg);
5003                                 mono_mb_emit_managed_call (mb, from_oadate, NULL);
5004                                 mono_mb_emit_op (mb, CEE_STOBJ, date_time_class);
5005                         }
5006                         break;
5007                 }
5008
5009                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5010                         klass->blittable || klass->enumtype)
5011                         break;
5012
5013                 if (t->byref) {
5014                         /* dst = argument */
5015                         mono_mb_emit_ldarg (mb, argnum);
5016                         mono_mb_emit_stloc (mb, 1);
5017
5018                         mono_mb_emit_ldloc (mb, 1);
5019                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5020
5021                         if (!((t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))) {
5022                                 /* src = tmp_locals [i] */
5023                                 mono_mb_emit_ldloc (mb, conv_arg);
5024                                 mono_mb_emit_stloc (mb, 0);
5025
5026                                 /* emit valuetype conversion code */
5027                                 emit_struct_conv (mb, klass, TRUE);
5028                         }
5029                 }
5030
5031                 emit_struct_free (mb, klass, conv_arg);
5032                 
5033                 if (t->byref)
5034                         mono_mb_patch_branch (mb, pos);
5035                 break;
5036
5037         case MARSHAL_ACTION_CONV_RESULT:
5038                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5039                         klass->blittable) {
5040                         mono_mb_emit_stloc (mb, 3);
5041                         break;
5042                 }
5043
5044                 /* load pointer to returned value type */
5045                 g_assert (m->vtaddr_var);
5046                 mono_mb_emit_ldloc (mb, m->vtaddr_var);
5047                 /* store the address of the source into local variable 0 */
5048                 mono_mb_emit_stloc (mb, 0);
5049                 /* set dst_ptr */
5050                 mono_mb_emit_ldloc_addr (mb, 3);
5051                 mono_mb_emit_stloc (mb, 1);
5052                                 
5053                 /* emit valuetype conversion code */
5054                 emit_struct_conv (mb, klass, TRUE);
5055                 break;
5056
5057         case MARSHAL_ACTION_MANAGED_CONV_IN:
5058                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5059                         klass->blittable || klass->enumtype) {
5060                         conv_arg = 0;
5061                         break;
5062                 }
5063
5064                 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
5065
5066                 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5067                         break;
5068
5069                 if (t->byref) 
5070                         mono_mb_emit_ldarg (mb, argnum);
5071                 else
5072                         mono_mb_emit_ldarg_addr (mb, argnum);
5073                 mono_mb_emit_stloc (mb, 0);
5074
5075                 if (t->byref) {
5076                         mono_mb_emit_ldloc (mb, 0);
5077                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5078                 }                       
5079
5080                 mono_mb_emit_ldloc_addr (mb, conv_arg);
5081                 mono_mb_emit_stloc (mb, 1);
5082
5083                 /* emit valuetype conversion code */
5084                 emit_struct_conv (mb, klass, TRUE);
5085
5086                 if (t->byref)
5087                         mono_mb_patch_branch (mb, pos);
5088                 break;
5089
5090         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5091                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5092                         klass->blittable || klass->enumtype) {
5093                         break;
5094                 }
5095
5096                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_IN) && !(t->attrs & PARAM_ATTRIBUTE_OUT))
5097                         break;
5098
5099                 /* Check for null */
5100                 mono_mb_emit_ldarg (mb, argnum);
5101                 pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
5102
5103                 /* Set src */
5104                 mono_mb_emit_ldloc_addr (mb, conv_arg);
5105                 mono_mb_emit_stloc (mb, 0);
5106
5107                 /* Set dest */
5108                 mono_mb_emit_ldarg (mb, argnum);
5109                 mono_mb_emit_stloc (mb, 1);
5110
5111                 /* emit valuetype conversion code */
5112                 emit_struct_conv (mb, klass, FALSE);
5113
5114                 mono_mb_patch_branch (mb, pos2);
5115                 break;
5116
5117         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5118                 if (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
5119                         klass->blittable || klass->enumtype) {
5120                         mono_mb_emit_stloc (mb, 3);
5121                         m->retobj_var = 0;
5122                         break;
5123                 }
5124                         
5125                 /* load pointer to returned value type */
5126                 g_assert (m->vtaddr_var);
5127                 mono_mb_emit_ldloc (mb, m->vtaddr_var);
5128                         
5129                 /* store the address of the source into local variable 0 */
5130                 mono_mb_emit_stloc (mb, 0);
5131                 /* allocate space for the native struct and
5132                  * store the address into dst_ptr */
5133                 m->retobj_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5134                 m->retobj_class = klass;
5135                 g_assert (m->retobj_var);
5136                 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5137                 mono_mb_emit_byte (mb, CEE_CONV_I);
5138                 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
5139                 mono_mb_emit_stloc (mb, 1);
5140                 mono_mb_emit_ldloc (mb, 1);
5141                 mono_mb_emit_stloc (mb, m->retobj_var);
5142
5143                 /* emit valuetype conversion code */
5144                 emit_struct_conv (mb, klass, FALSE);
5145                 break;
5146
5147         default:
5148                 g_assert_not_reached ();
5149         }
5150 #endif
5151         return conv_arg;
5152 }
5153
5154 static int
5155 emit_marshal_string (EmitMarshalContext *m, int argnum, MonoType *t,
5156                                          MonoMarshalSpec *spec, 
5157                                          int conv_arg, MonoType **conv_arg_type, 
5158                                          MarshalAction action)
5159 {
5160 #ifdef DISABLE_JIT
5161         switch (action) {
5162         case MARSHAL_ACTION_CONV_IN:
5163                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5164                 break;
5165         case MARSHAL_ACTION_MANAGED_CONV_IN:
5166                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5167                 break;
5168         }
5169 #else
5170         MonoMethodBuilder *mb = m->mb;
5171         MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5172         MonoMarshalConv conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
5173         gboolean need_free;
5174
5175         switch (action) {
5176         case MARSHAL_ACTION_CONV_IN:
5177                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5178                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5179
5180                 if (t->byref) {
5181                         if (t->attrs & PARAM_ATTRIBUTE_OUT)
5182                                 break;
5183
5184                         mono_mb_emit_ldarg (mb, argnum);
5185                         mono_mb_emit_byte (mb, CEE_LDIND_I);                            
5186                 } else {
5187                         mono_mb_emit_ldarg (mb, argnum);
5188                 }
5189
5190                 if (conv == MONO_MARSHAL_CONV_INVALID) {
5191                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5192                         mono_mb_emit_exception_marshal_directive (mb, msg);
5193                 } else {
5194                         mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5195
5196                         mono_mb_emit_stloc (mb, conv_arg);
5197                 }
5198                 break;
5199
5200         case MARSHAL_ACTION_CONV_OUT:
5201                 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5202                 if (conv == MONO_MARSHAL_CONV_INVALID) {
5203                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5204                         mono_mb_emit_exception_marshal_directive (mb, msg);
5205                         break;
5206                 }
5207
5208                 if (encoding == MONO_NATIVE_VBBYREFSTR) {
5209                         static MonoMethod *m;
5210
5211                         if (!m) {
5212                                 m = mono_class_get_method_from_name_flags (mono_defaults.string_class, "get_Length", -1, 0);
5213                                 g_assert (m);
5214                         }
5215
5216                         if (!t->byref) {
5217                                 char *msg = g_strdup_printf ("VBByRefStr marshalling requires a ref parameter.", encoding);
5218                                 mono_mb_emit_exception_marshal_directive (mb, msg);
5219                                 break;
5220                         }
5221
5222                         /* 
5223                          * Have to allocate a new string with the same length as the original, and
5224                          * copy the contents of the buffer pointed to by CONV_ARG into it.
5225                          */
5226                         g_assert (t->byref);
5227                         mono_mb_emit_ldarg (mb, argnum);
5228                         mono_mb_emit_ldloc (mb, conv_arg);
5229                         mono_mb_emit_ldarg (mb, argnum);
5230                         mono_mb_emit_byte (mb, CEE_LDIND_I);                            
5231                         mono_mb_emit_managed_call (mb, m, NULL);
5232                         mono_mb_emit_icall (mb, mono_string_new_len_wrapper);
5233                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5234                 } else if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
5235                         int stind_op;
5236                         mono_mb_emit_ldarg (mb, argnum);
5237                         mono_mb_emit_ldloc (mb, conv_arg);
5238                         mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
5239                         mono_mb_emit_byte (mb, stind_op);
5240                         need_free = TRUE;
5241                 }
5242
5243                 if (need_free) {
5244                         mono_mb_emit_ldloc (mb, conv_arg);
5245                         if (conv == MONO_MARSHAL_CONV_BSTR_STR)
5246                                 mono_mb_emit_icall (mb, mono_free_bstr);
5247                         else
5248                                 mono_mb_emit_icall (mb, mono_marshal_free);
5249                 }
5250                 break;
5251
5252         case MARSHAL_ACTION_PUSH:
5253                 if (t->byref && encoding != MONO_NATIVE_VBBYREFSTR)
5254                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5255                 else
5256                         mono_mb_emit_ldloc (mb, conv_arg);
5257                 break;
5258
5259         case MARSHAL_ACTION_CONV_RESULT:
5260                 mono_mb_emit_stloc (mb, 0);
5261                                 
5262                 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5263                 if (conv == MONO_MARSHAL_CONV_INVALID) {
5264                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5265                         mono_mb_emit_exception_marshal_directive (mb, msg);
5266                         break;
5267                 }
5268
5269                 mono_mb_emit_ldloc (mb, 0);
5270                 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5271                 mono_mb_emit_stloc (mb, 3);
5272
5273                 /* free the string */
5274                 mono_mb_emit_ldloc (mb, 0);
5275                 if (conv == MONO_MARSHAL_CONV_BSTR_STR)
5276                         mono_mb_emit_icall (mb, mono_free_bstr);
5277                 else
5278                         mono_mb_emit_icall (mb, mono_marshal_free);
5279                 break;
5280
5281         case MARSHAL_ACTION_MANAGED_CONV_IN:
5282                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
5283
5284                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5285
5286                 if (t->byref) {
5287                         if (t->attrs & PARAM_ATTRIBUTE_OUT)
5288                                 break;
5289                 }
5290
5291                 conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
5292                 if (conv == MONO_MARSHAL_CONV_INVALID) {
5293                         char *msg = g_strdup_printf ("string marshalling conversion %d not implemented", encoding);
5294                         mono_mb_emit_exception_marshal_directive (mb, msg);
5295                         break;
5296                 }
5297
5298                 mono_mb_emit_ldarg (mb, argnum);
5299                 if (t->byref)
5300                         mono_mb_emit_byte (mb, CEE_LDIND_I);
5301                 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5302                 mono_mb_emit_stloc (mb, conv_arg);
5303                 break;
5304
5305         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5306                 if (t->byref) {
5307                         if (conv_arg) {
5308                                 int stind_op;
5309                                 mono_mb_emit_ldarg (mb, argnum);
5310                                 mono_mb_emit_ldloc (mb, conv_arg);
5311                                 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
5312                                 mono_mb_emit_byte (mb, stind_op);
5313                         }
5314                 }
5315                 break;
5316
5317         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5318                 if (conv_to_icall (conv, NULL) == mono_marshal_string_to_utf16)
5319                         /* We need to make a copy so the caller is able to free it */
5320                         mono_mb_emit_icall (mb, mono_marshal_string_to_utf16_copy);
5321                 else
5322                         mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5323                 mono_mb_emit_stloc (mb, 3);
5324                 break;
5325
5326         default:
5327                 g_assert_not_reached ();
5328         }
5329 #endif
5330         return conv_arg;
5331 }
5332
5333
5334 static int
5335 emit_marshal_safehandle (EmitMarshalContext *m, int argnum, MonoType *t, 
5336                          MonoMarshalSpec *spec, int conv_arg, 
5337                          MonoType **conv_arg_type, MarshalAction action)
5338 {
5339 #ifdef DISABLE_JIT
5340         if (action == MARSHAL_ACTION_CONV_IN)
5341                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5342 #else
5343         MonoMethodBuilder *mb = m->mb;
5344
5345         switch (action){
5346         case MARSHAL_ACTION_CONV_IN: {
5347                 MonoType *intptr_type;
5348                 int dar_release_slot, pos;
5349
5350                 intptr_type = &mono_defaults.int_class->byval_arg;
5351                 conv_arg = mono_mb_add_local (mb, intptr_type);
5352                 *conv_arg_type = intptr_type;
5353
5354                 if (!sh_dangerous_add_ref)
5355                         init_safe_handle ();
5356
5357                 mono_mb_emit_ldarg (mb, argnum);
5358                 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
5359                 mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
5360                 
5361                 mono_mb_patch_branch (mb, pos);
5362                 if (t->byref){
5363                         /*
5364                          * My tests in show that ref SafeHandles are not really
5365                          * passed as ref objects.  Instead a NULL is passed as the
5366                          * value of the ref
5367                          */
5368                         mono_mb_emit_icon (mb, 0);
5369                         mono_mb_emit_stloc (mb, conv_arg);
5370                         break;
5371                 } 
5372
5373                 /* Create local to hold the ref parameter to DangerousAddRef */
5374                 dar_release_slot = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
5375
5376                 /* set release = false; */
5377                 mono_mb_emit_icon (mb, 0);
5378                 mono_mb_emit_stloc (mb, dar_release_slot);
5379
5380                 /* safehandle.DangerousAddRef (ref release) */
5381                 mono_mb_emit_ldarg (mb, argnum);
5382                 mono_mb_emit_ldloc_addr (mb, dar_release_slot);
5383                 mono_mb_emit_managed_call (mb, sh_dangerous_add_ref, NULL);
5384
5385                 /* Pull the handle field from SafeHandle */
5386                 mono_mb_emit_ldarg (mb, argnum);
5387                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5388                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5389                 mono_mb_emit_stloc (mb, conv_arg);
5390
5391                 break;
5392         }
5393
5394         case MARSHAL_ACTION_PUSH:
5395                 if (t->byref)
5396                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5397                 else 
5398                         mono_mb_emit_ldloc (mb, conv_arg);
5399                 break;
5400
5401         case MARSHAL_ACTION_CONV_OUT: {
5402                 /* The slot for the boolean is the next temporary created after conv_arg, see the CONV_IN code */
5403                 int dar_release_slot = conv_arg + 1;
5404                 int label_next;
5405
5406                 if (!sh_dangerous_release)
5407                         init_safe_handle ();
5408
5409                 if (t->byref){
5410                         MonoMethod *ctor;
5411                         
5412                         /*
5413                          * My tests indicate that ref SafeHandles parameters are not actually
5414                          * passed by ref, but instead a new Handle is created regardless of
5415                          * whether a change happens in the unmanaged side.
5416                          *
5417                          * Also, the Handle is created before calling into unmanaged code,
5418                          * but we do not support that mechanism (getting to the original
5419                          * handle) and it makes no difference where we create this
5420                          */
5421                         ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5422                         if (ctor == NULL){
5423                                 mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5424                                 break;
5425                         }
5426                         /* refval = new SafeHandleDerived ()*/
5427                         mono_mb_emit_ldarg (mb, argnum);
5428                         mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5429                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5430
5431                         /* refval.handle = returned_handle */
5432                         mono_mb_emit_ldarg (mb, argnum);
5433                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
5434                         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5435                         mono_mb_emit_ldloc (mb, conv_arg);
5436                         mono_mb_emit_byte (mb, CEE_STIND_I);
5437                 } else {
5438                         mono_mb_emit_ldloc (mb, dar_release_slot);
5439                         label_next = mono_mb_emit_branch (mb, CEE_BRFALSE);
5440                         mono_mb_emit_ldarg (mb, argnum);
5441                         mono_mb_emit_managed_call (mb, sh_dangerous_release, NULL);
5442                         mono_mb_patch_branch (mb, label_next);
5443                 }
5444                 break;
5445         }
5446                 
5447         case MARSHAL_ACTION_CONV_RESULT: {
5448                 MonoMethod *ctor = NULL;
5449                 int intptr_handle_slot;
5450                 
5451                 if (t->data.klass->flags & TYPE_ATTRIBUTE_ABSTRACT){
5452                         mono_mb_emit_byte (mb, CEE_POP);
5453                         mono_mb_emit_exception_marshal_directive (mb, g_strdup ("Returned SafeHandles should not be abstract"));
5454                         break;
5455                 }
5456
5457                 ctor = mono_class_get_method_from_name (t->data.klass, ".ctor", 0);
5458                 if (ctor == NULL){
5459                         mono_mb_emit_byte (mb, CEE_POP);
5460                         mono_mb_emit_exception (mb, "MissingMethodException", "paramterless constructor required");
5461                         break;
5462                 }
5463                 /* Store the IntPtr results into a local */
5464                 intptr_handle_slot = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5465                 mono_mb_emit_stloc (mb, intptr_handle_slot);
5466
5467                 /* Create return value */
5468                 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
5469                 mono_mb_emit_stloc (mb, 3);
5470
5471                 /* Set the return.handle to the value, am using ldflda, not sure if thats a good idea */
5472                 mono_mb_emit_ldloc (mb, 3);
5473                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoSafeHandle, handle));
5474                 mono_mb_emit_ldloc (mb, intptr_handle_slot);
5475                 mono_mb_emit_byte (mb, CEE_STIND_I);
5476                 break;
5477         }
5478                 
5479         case MARSHAL_ACTION_MANAGED_CONV_IN:
5480                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5481                 break;
5482                 
5483         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5484                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5485                 break;
5486
5487         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5488                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5489                 break;
5490         default:
5491                 printf ("Unhandled case for MarshalAction: %d\n", action);
5492         }
5493 #endif
5494         return conv_arg;
5495 }
5496
5497
5498 static int
5499 emit_marshal_handleref (EmitMarshalContext *m, int argnum, MonoType *t, 
5500                         MonoMarshalSpec *spec, int conv_arg, 
5501                         MonoType **conv_arg_type, MarshalAction action)
5502 {
5503 #ifdef DISABLE_JIT
5504         if (action == MARSHAL_ACTION_CONV_IN)
5505                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5506 #else
5507         MonoMethodBuilder *mb = m->mb;
5508
5509         switch (action){
5510         case MARSHAL_ACTION_CONV_IN: {
5511                 MonoType *intptr_type;
5512
5513                 intptr_type = &mono_defaults.int_class->byval_arg;
5514                 conv_arg = mono_mb_add_local (mb, intptr_type);
5515                 *conv_arg_type = intptr_type;
5516
5517                 if (t->byref){
5518                         char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5519                         mono_mb_emit_exception_marshal_directive (mb, msg);
5520                         break;
5521                 } 
5522                 mono_mb_emit_ldarg_addr (mb, argnum);
5523                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoHandleRef, handle));
5524                 mono_mb_emit_byte (mb, CEE_ADD);
5525                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5526                 mono_mb_emit_stloc (mb, conv_arg);
5527                 break;
5528         }
5529
5530         case MARSHAL_ACTION_PUSH:
5531                 mono_mb_emit_ldloc (mb, conv_arg);
5532                 break;
5533
5534         case MARSHAL_ACTION_CONV_OUT: {
5535                 /* no resource release required */
5536                 break;
5537         }
5538                 
5539         case MARSHAL_ACTION_CONV_RESULT: {
5540                 char *msg = g_strdup ("HandleRefs can not be returned from unmanaged code (or passed by ref)");
5541                 mono_mb_emit_exception_marshal_directive (mb, msg);
5542                 break;
5543         }
5544                 
5545         case MARSHAL_ACTION_MANAGED_CONV_IN:
5546                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_IN\n");
5547                 break;
5548                 
5549         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5550                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_OUT\n");
5551                 break;
5552
5553         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
5554                 fprintf (stderr, "mono/marshal: SafeHandles missing MANAGED_CONV_RESULT\n");
5555                 break;
5556         default:
5557                 fprintf (stderr, "Unhandled case for MarshalAction: %d\n", action);
5558         }
5559 #endif
5560         return conv_arg;
5561 }
5562
5563
5564 static int
5565 emit_marshal_object (EmitMarshalContext *m, int argnum, MonoType *t,
5566                      MonoMarshalSpec *spec, 
5567                      int conv_arg, MonoType **conv_arg_type, 
5568                      MarshalAction action)
5569 {
5570 #ifdef DISABLE_JIT
5571         if (action == MARSHAL_ACTION_CONV_IN)
5572                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5573 #else
5574         MonoMethodBuilder *mb = m->mb;
5575         MonoClass *klass = mono_class_from_mono_type (t);
5576         int pos, pos2, loc;
5577
5578         switch (action) {
5579         case MARSHAL_ACTION_CONV_IN:
5580                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
5581                 conv_arg = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5582
5583                 m->orig_conv_args [argnum] = 0;
5584
5585                 if (mono_class_from_mono_type (t) == mono_defaults.object_class) {
5586                         char *msg = g_strdup_printf ("Marshalling of type object is not implemented");
5587                         mono_mb_emit_exception_marshal_directive (mb, msg);
5588                         break;
5589                 }
5590
5591                 if (klass->delegate) {
5592                         if (t->byref) {
5593                                 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5594                                         char *msg = g_strdup_printf ("Byref marshalling of delegates is not implemented.");
5595                                         mono_mb_emit_exception_marshal_directive (mb, msg);
5596                                 }
5597                                 mono_mb_emit_byte (mb, CEE_LDNULL);
5598                                 mono_mb_emit_stloc (mb, conv_arg);
5599                         } else {
5600                                 mono_mb_emit_ldarg (mb, argnum);
5601                                 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, NULL));
5602                                 mono_mb_emit_stloc (mb, conv_arg);
5603                         }
5604                 } else if (klass == mono_defaults.stringbuilder_class) {
5605                         MonoMarshalNative encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5606                         MonoMarshalConv conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
5607
5608 #if 0                   
5609                         if (t->byref) {
5610                                 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5611                                         char *msg = g_strdup_printf ("Byref marshalling of stringbuilders is not implemented.");
5612                                         mono_mb_emit_exception_marshal_directive (mb, msg);
5613                                 }
5614                                 break;
5615                         }
5616 #endif
5617
5618                         if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && (t->attrs & PARAM_ATTRIBUTE_OUT))
5619                                 break;
5620
5621                         if (conv == MONO_MARSHAL_CONV_INVALID) {
5622                                 char *msg = g_strdup_printf ("stringbuilder marshalling conversion %d not implemented", encoding);
5623                                 mono_mb_emit_exception_marshal_directive (mb, msg);
5624                                 break;
5625                         }
5626
5627                         mono_mb_emit_ldarg (mb, argnum);
5628                         if (t->byref)
5629                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5630
5631                         mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5632                         mono_mb_emit_stloc (mb, conv_arg);
5633                 } else if (klass->blittable) {
5634                         mono_mb_emit_byte (mb, CEE_LDNULL);
5635                         mono_mb_emit_stloc (mb, conv_arg);
5636
5637                         mono_mb_emit_ldarg (mb, argnum);
5638                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5639
5640                         mono_mb_emit_ldarg (mb, argnum);
5641                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5642                         mono_mb_emit_stloc (mb, conv_arg);
5643
5644                         mono_mb_patch_branch (mb, pos);
5645                         break;
5646                 } else {
5647                         mono_mb_emit_byte (mb, CEE_LDNULL);
5648                         mono_mb_emit_stloc (mb, conv_arg);
5649
5650                         if (t->byref) {
5651                                 /* we dont need any conversions for out parameters */
5652                                 if (t->attrs & PARAM_ATTRIBUTE_OUT)
5653                                         break;
5654
5655                                 mono_mb_emit_ldarg (mb, argnum);                                
5656                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5657
5658                         } else {
5659                                 mono_mb_emit_ldarg (mb, argnum);
5660                                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5661                                 mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
5662                         }
5663                                 
5664                         /* store the address of the source into local variable 0 */
5665                         mono_mb_emit_stloc (mb, 0);
5666                         mono_mb_emit_ldloc (mb, 0);
5667                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5668
5669                         /* allocate space for the native struct and store the address */
5670                         mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5671                         mono_mb_emit_byte (mb, CEE_PREFIX1);
5672                         mono_mb_emit_byte (mb, CEE_LOCALLOC);
5673                         mono_mb_emit_stloc (mb, conv_arg);
5674
5675                         if (t->byref) {
5676                                 /* Need to store the original buffer so we can free it later */
5677                                 m->orig_conv_args [argnum] = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5678                                 mono_mb_emit_ldloc (mb, conv_arg);
5679                                 mono_mb_emit_stloc (mb, m->orig_conv_args [argnum]);
5680                         }
5681
5682                         /* set the src_ptr */
5683                         mono_mb_emit_ldloc (mb, 0);
5684                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5685                         mono_mb_emit_stloc (mb, 0);
5686
5687                         /* set dst_ptr */
5688                         mono_mb_emit_ldloc (mb, conv_arg);
5689                         mono_mb_emit_stloc (mb, 1);
5690
5691                         /* emit valuetype conversion code */
5692                         emit_struct_conv (mb, klass, FALSE);
5693
5694                         mono_mb_patch_branch (mb, pos);
5695                 }
5696                 break;
5697
5698         case MARSHAL_ACTION_CONV_OUT:
5699                 if (klass == mono_defaults.stringbuilder_class) {
5700                         gboolean need_free;
5701                         MonoMarshalNative encoding;
5702                         MonoMarshalConv conv;
5703
5704                         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5705                         conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
5706
5707                         g_assert (encoding != -1);
5708
5709                         if (t->byref) {
5710                                 //g_assert (!(t->attrs & PARAM_ATTRIBUTE_OUT));
5711
5712                                 need_free = TRUE;
5713
5714                                 mono_mb_emit_ldarg (mb, argnum);
5715                                 mono_mb_emit_ldloc (mb, conv_arg);
5716
5717                                 switch (encoding) {
5718                                 case MONO_NATIVE_LPWSTR:
5719                                         mono_mb_emit_icall (mb, mono_string_utf16_to_builder2);
5720                                         break;
5721                                 case MONO_NATIVE_LPSTR:
5722                                         mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5723                                         break;
5724                                 default:
5725                                         g_assert_not_reached ();
5726                                 }
5727
5728                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
5729                         } else {
5730                                 mono_mb_emit_ldarg (mb, argnum);
5731                                 mono_mb_emit_ldloc (mb, conv_arg);
5732
5733                                 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
5734                         }
5735
5736                         if (need_free) {
5737                                 mono_mb_emit_ldloc (mb, conv_arg);
5738                                 mono_mb_emit_icall (mb, mono_marshal_free);
5739                         }
5740                         break;
5741                 }
5742
5743                 if (klass->delegate) {
5744                         if (t->byref) {
5745                                 mono_mb_emit_ldarg (mb, argnum);
5746                                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5747                                 mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5748                                 mono_mb_emit_ldloc (mb, conv_arg);
5749                                 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
5750                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
5751                         }
5752                         break;
5753                 }
5754
5755                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT)) {
5756                         /* allocate a new object */
5757                         mono_mb_emit_ldarg (mb, argnum);
5758                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5759                         mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);
5760                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5761                 }
5762
5763                 /* dst = *argument */
5764                 mono_mb_emit_ldarg (mb, argnum);
5765
5766                 if (t->byref)
5767                         mono_mb_emit_byte (mb, CEE_LDIND_I);
5768
5769                 mono_mb_emit_stloc (mb, 1);
5770
5771                 mono_mb_emit_ldloc (mb, 1);
5772                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5773
5774                 if (t->byref || (t->attrs & PARAM_ATTRIBUTE_OUT)) {
5775                         mono_mb_emit_ldloc (mb, 1);
5776                         mono_mb_emit_icon (mb, sizeof (MonoObject));
5777                         mono_mb_emit_byte (mb, CEE_ADD);
5778                         mono_mb_emit_stloc (mb, 1);
5779                         
5780                         /* src = tmp_locals [i] */
5781                         mono_mb_emit_ldloc (mb, conv_arg);
5782                         mono_mb_emit_stloc (mb, 0);
5783
5784                         /* emit valuetype conversion code */
5785                         emit_struct_conv (mb, klass, TRUE);
5786
5787                         /* Free the structure returned by the native code */
5788                         emit_struct_free (mb, klass, conv_arg);
5789
5790                         if (m->orig_conv_args [argnum]) {
5791                                 /* 
5792                                  * If the native function changed the pointer, then free
5793                                  * the original structure plus the new pointer.
5794                                  */
5795                                 mono_mb_emit_ldloc (mb, m->orig_conv_args [argnum]);
5796                                 mono_mb_emit_ldloc (mb, conv_arg);
5797                                 pos2 = mono_mb_emit_branch (mb, CEE_BEQ);
5798
5799                                 if (!(t->attrs & PARAM_ATTRIBUTE_OUT)) {
5800                                         g_assert (m->orig_conv_args [argnum]);
5801
5802                                         emit_struct_free (mb, klass, m->orig_conv_args [argnum]);
5803                                 }
5804
5805                                 mono_mb_emit_ldloc (mb, conv_arg);
5806                                 mono_mb_emit_icall (mb, mono_marshal_free);
5807
5808                                 mono_mb_patch_branch (mb, pos2);
5809                         }
5810                 }
5811                 else
5812                         /* Free the original structure passed to native code */
5813                         emit_struct_free (mb, klass, conv_arg);
5814
5815                 mono_mb_patch_branch (mb, pos);
5816                 break;
5817
5818         case MARSHAL_ACTION_PUSH:
5819                 if (t->byref)
5820                         mono_mb_emit_ldloc_addr (mb, conv_arg);
5821                 else
5822                         mono_mb_emit_ldloc (mb, conv_arg);
5823                 break;
5824
5825         case MARSHAL_ACTION_CONV_RESULT:
5826                 if (klass->delegate) {
5827                         g_assert (!t->byref);
5828                         mono_mb_emit_stloc (mb, 0);
5829                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5830                         mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5831                         mono_mb_emit_ldloc (mb, 0);
5832                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
5833                         mono_mb_emit_stloc (mb, 3);
5834                 } else {
5835                         /* set src */
5836                         mono_mb_emit_stloc (mb, 0);
5837         
5838                         /* Make a copy since emit_conv modifies local 0 */
5839                         loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
5840                         mono_mb_emit_ldloc (mb, 0);
5841                         mono_mb_emit_stloc (mb, loc);
5842         
5843                         mono_mb_emit_byte (mb, CEE_LDNULL);
5844                         mono_mb_emit_stloc (mb, 3);
5845         
5846                         mono_mb_emit_ldloc (mb, 0);
5847                         pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5848         
5849                         /* allocate result object */
5850         
5851                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5852                         mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);   
5853                         mono_mb_emit_stloc (mb, 3);
5854                                         
5855                         /* set dst  */
5856         
5857                         mono_mb_emit_ldloc (mb, 3);
5858                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5859                         mono_mb_emit_stloc (mb, 1);
5860                                                                 
5861                         /* emit conversion code */
5862                         emit_struct_conv (mb, klass, TRUE);
5863         
5864                         emit_struct_free (mb, klass, loc);
5865         
5866                         /* Free the pointer allocated by unmanaged code */
5867                         mono_mb_emit_ldloc (mb, loc);
5868                         mono_mb_emit_icall (mb, mono_marshal_free);
5869                         mono_mb_patch_branch (mb, pos);
5870                 }
5871                 break;
5872
5873         case MARSHAL_ACTION_MANAGED_CONV_IN:
5874                 conv_arg = mono_mb_add_local (mb, &klass->byval_arg);
5875
5876                 if (klass->delegate) {
5877                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5878                         mono_mb_emit_op (mb, CEE_MONO_CLASSCONST, klass);
5879                         mono_mb_emit_ldarg (mb, argnum);
5880                         if (t->byref)
5881                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
5882                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_FTN_DEL, NULL));
5883                         mono_mb_emit_stloc (mb, conv_arg);
5884                         break;
5885                 }
5886
5887                 if (klass == mono_defaults.stringbuilder_class) {
5888                         MonoMarshalNative encoding;
5889
5890                         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
5891
5892                         // FIXME:
5893                         g_assert (encoding == MONO_NATIVE_LPSTR);
5894
5895                         g_assert (!t->byref);
5896                         g_assert (encoding != -1);
5897
5898                         mono_mb_emit_ldarg (mb, argnum);
5899                         mono_mb_emit_icall (mb, mono_string_utf8_to_builder2);
5900                         mono_mb_emit_stloc (mb, conv_arg);
5901                         break;
5902                 }
5903
5904                 /* The class can not have an automatic layout */
5905                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
5906                         mono_mb_emit_auto_layout_exception (mb, klass);
5907                         break;
5908                 }
5909
5910                 if (t->attrs & PARAM_ATTRIBUTE_OUT) {
5911                         mono_mb_emit_byte (mb, CEE_LDNULL);
5912                         mono_mb_emit_stloc (mb, conv_arg);
5913                         break;
5914                 }
5915
5916                 /* Set src */
5917                 mono_mb_emit_ldarg (mb, argnum);
5918                 if (t->byref) {
5919                         int pos2;
5920
5921                         /* Check for NULL and raise an exception */
5922                         pos2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
5923
5924                         mono_mb_emit_exception (mb, "ArgumentNullException", NULL);
5925
5926                         mono_mb_patch_branch (mb, pos2);
5927                         mono_mb_emit_ldarg (mb, argnum);
5928                         mono_mb_emit_byte (mb, CEE_LDIND_I);
5929                 }                               
5930
5931                 mono_mb_emit_stloc (mb, 0);
5932
5933                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
5934                 mono_mb_emit_stloc (mb, conv_arg);
5935
5936                 mono_mb_emit_ldloc (mb, 0);
5937                 pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
5938
5939                 /* Create and set dst */
5940                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5941                 mono_mb_emit_op (mb, CEE_MONO_NEWOBJ, klass);   
5942                 mono_mb_emit_stloc (mb, conv_arg);
5943                 mono_mb_emit_ldloc (mb, conv_arg);
5944                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5945                 mono_mb_emit_stloc (mb, 1); 
5946
5947                 /* emit valuetype conversion code */
5948                 emit_struct_conv (mb, klass, TRUE);
5949
5950                 mono_mb_patch_branch (mb, pos);
5951                 break;
5952
5953         case MARSHAL_ACTION_MANAGED_CONV_OUT:
5954                 if (klass->delegate) {
5955                         if (t->byref) {
5956                                 int stind_op;
5957                                 mono_mb_emit_ldarg (mb, argnum);
5958                                 mono_mb_emit_ldloc (mb, conv_arg);
5959                                 mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, &stind_op));
5960                                 mono_mb_emit_byte (mb, stind_op);
5961                                 break;
5962                         }
5963                 }
5964
5965                 if (t->byref) {
5966                         /* Check for null */
5967                         mono_mb_emit_ldloc (mb, conv_arg);
5968                         pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
5969                         mono_mb_emit_ldarg (mb, argnum);
5970                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
5971                         mono_mb_emit_byte (mb, CEE_STIND_REF);
5972                         pos2 = mono_mb_emit_branch (mb, CEE_BR);
5973
5974                         mono_mb_patch_branch (mb, pos);                 
5975                         
5976                         /* Set src */
5977                         mono_mb_emit_ldloc (mb, conv_arg);
5978                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
5979                         mono_mb_emit_stloc (mb, 0);
5980
5981                         /* Allocate and set dest */
5982                         mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
5983                         mono_mb_emit_byte (mb, CEE_CONV_I);
5984                         mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
5985                         mono_mb_emit_stloc (mb, 1);
5986                         
5987                         /* Update argument pointer */
5988                         mono_mb_emit_ldarg (mb, argnum);
5989                         mono_mb_emit_ldloc (mb, 1);
5990                         mono_mb_emit_byte (mb, CEE_STIND_I);
5991                 
5992                         /* emit valuetype conversion code */
5993                         emit_struct_conv (mb, klass, FALSE);
5994
5995                         mono_mb_patch_branch (mb, pos2);
5996                 } else if (klass == mono_defaults.stringbuilder_class) {
5997                         // FIXME: What to do here ?
5998                 } else {
5999                         /* byval [Out] marshalling */
6000
6001                         /* FIXME: Handle null */
6002
6003                         /* Set src */
6004                         mono_mb_emit_ldloc (mb, conv_arg);
6005                         mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6006                         mono_mb_emit_stloc (mb, 0);
6007
6008                         /* Set dest */
6009                         mono_mb_emit_ldarg (mb, argnum);
6010                         mono_mb_emit_stloc (mb, 1);
6011                         
6012                         /* emit valuetype conversion code */
6013                         emit_struct_conv (mb, klass, FALSE);
6014                 }                       
6015                 break;
6016
6017         case MARSHAL_ACTION_MANAGED_CONV_RESULT:
6018                 if (klass->delegate) {
6019                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_DEL_FTN, NULL));
6020                         mono_mb_emit_stloc (mb, 3);
6021                         break;
6022                 }
6023
6024                 /* The class can not have an automatic layout */
6025                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
6026                         mono_mb_emit_auto_layout_exception (mb, klass);
6027                         break;
6028                 }
6029
6030                 mono_mb_emit_stloc (mb, 0);
6031                 /* Check for null */
6032                 mono_mb_emit_ldloc (mb, 0);
6033                 pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
6034                 mono_mb_emit_byte (mb, CEE_LDNULL);
6035                 mono_mb_emit_stloc (mb, 3);
6036                 pos2 = mono_mb_emit_branch (mb, CEE_BR);
6037
6038                 mono_mb_patch_branch (mb, pos);
6039
6040                 /* Set src */
6041                 mono_mb_emit_ldloc (mb, 0);
6042                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
6043                 mono_mb_emit_stloc (mb, 0);
6044
6045                 /* Allocate and set dest */
6046                 mono_mb_emit_icon (mb, mono_class_native_size (klass, NULL));
6047                 mono_mb_emit_byte (mb, CEE_CONV_I);
6048                 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
6049                 mono_mb_emit_byte (mb, CEE_DUP);
6050                 mono_mb_emit_stloc (mb, 1);
6051                 mono_mb_emit_stloc (mb, 3);
6052
6053                 emit_struct_conv (mb, klass, FALSE);
6054
6055                 mono_mb_patch_branch (mb, pos2);
6056                 break;
6057
6058         default:
6059                 g_assert_not_reached ();
6060         }
6061 #endif
6062         return conv_arg;
6063 }
6064
6065 #ifndef DISABLE_JIT
6066
6067 #ifndef DISABLE_COM
6068
6069 static int
6070 emit_marshal_variant (EmitMarshalContext *m, int argnum, MonoType *t,
6071                      MonoMarshalSpec *spec, 
6072                      int conv_arg, MonoType **conv_arg_type, 
6073                      MarshalAction action)
6074 {
6075         MonoMethodBuilder *mb = m->mb;
6076         static MonoMethod *get_object_for_native_variant = NULL;
6077         static MonoMethod *get_native_variant_for_object = NULL;
6078
6079         if (!get_object_for_native_variant)
6080                 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
6081         g_assert (get_object_for_native_variant);
6082
6083         if (!get_native_variant_for_object)
6084                 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
6085         g_assert (get_native_variant_for_object);
6086
6087         switch (action) {
6088         case MARSHAL_ACTION_CONV_IN: {
6089                 conv_arg = mono_mb_add_local (mb, &mono_class_get_variant_class ()->byval_arg);
6090                 
6091                 if (t->byref)
6092                         *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
6093                 else
6094                         *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
6095
6096                 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
6097                         break;
6098
6099                 mono_mb_emit_ldarg (mb, argnum);
6100                 if (t->byref)
6101                         mono_mb_emit_byte(mb, CEE_LDIND_REF);
6102                 mono_mb_emit_ldloc_addr (mb, conv_arg);
6103                 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6104                 break;
6105         }
6106
6107         case MARSHAL_ACTION_CONV_OUT: {
6108                 static MonoMethod *variant_clear = NULL;
6109
6110                 if (!variant_clear)
6111                         variant_clear = mono_class_get_method_from_name (mono_class_get_variant_class (), "Clear", 0);
6112                 g_assert (variant_clear);
6113
6114
6115                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
6116                         mono_mb_emit_ldarg (mb, argnum);
6117                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6118                         mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6119                         mono_mb_emit_byte (mb, CEE_STIND_REF);
6120                 }
6121
6122                 mono_mb_emit_ldloc_addr (mb, conv_arg);
6123                 mono_mb_emit_managed_call (mb, variant_clear, NULL);
6124                 break;
6125         }
6126
6127         case MARSHAL_ACTION_PUSH:
6128                 if (t->byref)
6129                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6130                 else
6131                         mono_mb_emit_ldloc (mb, conv_arg);
6132                 break;
6133
6134         case MARSHAL_ACTION_CONV_RESULT: {
6135                 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6136                 mono_mb_emit_exception_marshal_directive (mb, msg);
6137                 break;
6138         }
6139
6140         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6141                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6142
6143                 if (t->byref)
6144                         *conv_arg_type = &mono_class_get_variant_class ()->this_arg;
6145                 else
6146                         *conv_arg_type = &mono_class_get_variant_class ()->byval_arg;
6147
6148                 if (t->byref && !(t->attrs & PARAM_ATTRIBUTE_IN) && t->attrs & PARAM_ATTRIBUTE_OUT)
6149                         break;
6150
6151                 if (t->byref)
6152                         mono_mb_emit_ldarg (mb, argnum);
6153                 else
6154                         mono_mb_emit_ldarg_addr (mb, argnum);
6155                 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6156                 mono_mb_emit_stloc (mb, conv_arg);
6157                 break;
6158         }
6159
6160         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6161                 if (t->byref && (t->attrs & PARAM_ATTRIBUTE_OUT || !(t->attrs & PARAM_ATTRIBUTE_IN))) {
6162                         mono_mb_emit_ldloc (mb, conv_arg);
6163                         mono_mb_emit_ldarg (mb, argnum);
6164                         mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6165                 }
6166                 break;
6167         }
6168
6169         case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6170                 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6171                 mono_mb_emit_exception_marshal_directive (mb, msg);
6172                 break;
6173         }
6174
6175         default:
6176                 g_assert_not_reached ();
6177         }
6178
6179         return conv_arg;
6180 }
6181
6182 #endif /* DISABLE_COM */
6183 #endif /* DISABLE_JIT */
6184
6185 static gboolean
6186 mono_pinvoke_is_unicode (MonoMethodPInvoke *piinfo)
6187 {
6188         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
6189         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
6190                 return FALSE;
6191         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
6192                 return TRUE;
6193         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
6194         default:
6195 #ifdef TARGET_WIN32
6196                 return TRUE;
6197 #else
6198                 return FALSE;
6199 #endif
6200         }
6201 }
6202
6203
6204 static int
6205 emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
6206                                         MonoMarshalSpec *spec, 
6207                                         int conv_arg, MonoType **conv_arg_type, 
6208                                         MarshalAction action)
6209 {
6210 #ifdef DISABLE_JIT
6211         switch (action) {
6212         case MARSHAL_ACTION_CONV_IN:
6213                 *conv_arg_type = &mono_defaults.object_class->byval_arg;
6214                 break;
6215         case MARSHAL_ACTION_MANAGED_CONV_IN:
6216                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6217                 break;
6218         }
6219 #else
6220         MonoMethodBuilder *mb = m->mb;
6221         MonoClass *klass = mono_class_from_mono_type (t);
6222         gboolean need_convert, need_free;
6223         MonoMarshalNative encoding;
6224
6225         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
6226
6227         switch (action) {
6228         case MARSHAL_ACTION_CONV_IN:
6229                 *conv_arg_type = &mono_defaults.object_class->byval_arg;
6230                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6231
6232                 if (klass->element_class->blittable) {
6233                         mono_mb_emit_ldarg (mb, argnum);
6234                         if (t->byref)
6235                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6236                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_ARRAY_LPARRAY, NULL));
6237                         mono_mb_emit_stloc (mb, conv_arg);
6238                 } else {
6239                         MonoClass *eklass;
6240                         guint32 label1, label2, label3;
6241                         int index_var, src_var, dest_ptr, esize;
6242                         MonoMarshalConv conv;
6243                         gboolean is_string = FALSE;
6244
6245                         dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6246
6247                         eklass = klass->element_class;
6248
6249                         if (eklass == mono_defaults.string_class) {
6250                                 is_string = TRUE;
6251                                 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6252                         }
6253                         else if (eklass == mono_defaults.stringbuilder_class) {
6254                                 is_string = TRUE;
6255                                 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6256                         }
6257                         else
6258                                 conv = MONO_MARSHAL_CONV_INVALID;
6259
6260                         if (is_string && conv == MONO_MARSHAL_CONV_INVALID) {
6261                                 char *msg = g_strdup_printf ("string/stringbuilder marshalling conversion %d not implemented", encoding);
6262                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6263                                 break;
6264                         }
6265
6266                         src_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6267                         mono_mb_emit_ldarg (mb, argnum);
6268                         if (t->byref)
6269                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6270                         mono_mb_emit_stloc (mb, src_var);
6271
6272                         /* Check null */
6273                         mono_mb_emit_ldloc (mb, src_var);
6274                         mono_mb_emit_stloc (mb, conv_arg);
6275                         mono_mb_emit_ldloc (mb, src_var);
6276                         label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6277
6278                         if (is_string)
6279                                 esize = sizeof (gpointer);
6280                         else if (eklass == mono_defaults.char_class) /*can't call mono_marshal_type_size since it causes all sorts of asserts*/
6281                                 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6282                         else
6283                                 esize = mono_class_native_size (eklass, NULL);
6284
6285                         /* allocate space for the native struct and store the address */
6286                         mono_mb_emit_icon (mb, esize);
6287                         mono_mb_emit_ldloc (mb, src_var);
6288                         mono_mb_emit_byte (mb, CEE_LDLEN);
6289
6290                         if (eklass == mono_defaults.string_class) {
6291                                 /* Make the array bigger for the terminating null */
6292                                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6293                                 mono_mb_emit_byte (mb, CEE_ADD);
6294                         }
6295                         mono_mb_emit_byte (mb, CEE_MUL);
6296                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6297                         mono_mb_emit_byte (mb, CEE_LOCALLOC);
6298                         mono_mb_emit_stloc (mb, conv_arg);
6299
6300                         mono_mb_emit_ldloc (mb, conv_arg);
6301                         mono_mb_emit_stloc (mb, dest_ptr);
6302
6303                         /* Emit marshalling loop */
6304                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
6305                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6306                         mono_mb_emit_stloc (mb, index_var);
6307                         label2 = mono_mb_get_label (mb);
6308                         mono_mb_emit_ldloc (mb, index_var);
6309                         mono_mb_emit_ldloc (mb, src_var);
6310                         mono_mb_emit_byte (mb, CEE_LDLEN);
6311                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
6312
6313                         /* Emit marshalling code */
6314
6315                         if (is_string) {
6316                                 int stind_op;
6317                                 mono_mb_emit_ldloc (mb, dest_ptr);
6318                                 mono_mb_emit_ldloc (mb, src_var);
6319                                 mono_mb_emit_ldloc (mb, index_var);
6320                                 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6321                                 mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
6322                                 mono_mb_emit_byte (mb, stind_op);
6323                         } else {
6324                                 /* set the src_ptr */
6325                                 mono_mb_emit_ldloc (mb, src_var);
6326                                 mono_mb_emit_ldloc (mb, index_var);
6327                                 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6328                                 mono_mb_emit_stloc (mb, 0);
6329
6330                                 /* set dst_ptr */
6331                                 mono_mb_emit_ldloc (mb, dest_ptr);
6332                                 mono_mb_emit_stloc (mb, 1);
6333
6334                                 /* emit valuetype conversion code */
6335                                 emit_struct_conv_full (mb, eklass, FALSE, eklass == mono_defaults.char_class ? encoding : (MonoMarshalNative)-1);
6336                         }
6337
6338                         mono_mb_emit_add_to_local (mb, index_var, 1);
6339                         mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6340                         
6341                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
6342
6343                         mono_mb_patch_branch (mb, label3);
6344
6345                         if (eklass == mono_defaults.string_class) {
6346                                 /* Null terminate */
6347                                 mono_mb_emit_ldloc (mb, dest_ptr);
6348                                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6349                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
6350                         }
6351
6352                         mono_mb_patch_branch (mb, label1);
6353                 }
6354
6355                 break;
6356
6357         case MARSHAL_ACTION_CONV_OUT:
6358                 /* Unicode character arrays are implicitly marshalled as [Out] under MS.NET */
6359                 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);
6360                 need_free = mono_marshal_need_free (&klass->element_class->byval_arg, 
6361                                                                                         m->piinfo, spec);
6362
6363                 if ((t->attrs & PARAM_ATTRIBUTE_OUT) && spec && spec->native == MONO_NATIVE_LPARRAY && spec->data.array_data.param_num != -1) {
6364                         int param_num = spec->data.array_data.param_num;
6365                         MonoType *param_type;
6366
6367                         param_type = m->sig->params [param_num];
6368
6369                         if (param_type->byref && param_type->type != MONO_TYPE_I4) {
6370                                 char *msg = g_strdup ("Not implemented.");
6371                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6372                                 break;
6373                         }
6374
6375                         if (t->byref ) {
6376                                 mono_mb_emit_ldarg (mb, argnum);
6377
6378                                 /* Create the managed array */
6379                                 mono_mb_emit_ldarg (mb, param_num);
6380                                 if (m->sig->params [param_num]->byref)
6381                                         // FIXME: Support other types
6382                                         mono_mb_emit_byte (mb, CEE_LDIND_I4);
6383                                 mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6384                                 mono_mb_emit_op (mb, CEE_NEWARR, klass->element_class);
6385                                 /* Store into argument */
6386                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
6387                         }
6388                 }
6389
6390                 if (need_convert || need_free) {
6391                         /* FIXME: Optimize blittable case */
6392                         MonoClass *eklass;
6393                         guint32 label1, label2, label3;
6394                         int index_var, src_ptr, loc, esize;
6395
6396                         eklass = klass->element_class;
6397                         if ((eklass == mono_defaults.stringbuilder_class) || (eklass == mono_defaults.string_class))
6398                                 esize = sizeof (gpointer);
6399                         else if (eklass == mono_defaults.char_class)
6400                                 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6401                         else
6402                                 esize = mono_class_native_size (eklass, NULL);
6403                         src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6404                         loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6405
6406                         /* Check null */
6407                         mono_mb_emit_ldarg (mb, argnum);
6408                         if (t->byref)
6409                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6410                         label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6411
6412                         mono_mb_emit_ldloc (mb, conv_arg);
6413                         mono_mb_emit_stloc (mb, src_ptr);
6414
6415                         /* Emit marshalling loop */
6416                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
6417                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6418                         mono_mb_emit_stloc (mb, index_var);
6419                         label2 = mono_mb_get_label (mb);
6420                         mono_mb_emit_ldloc (mb, index_var);
6421                         mono_mb_emit_ldarg (mb, argnum);
6422                         if (t->byref)
6423                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6424                         mono_mb_emit_byte (mb, CEE_LDLEN);
6425                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
6426
6427                         /* Emit marshalling code */
6428
6429                         if (eklass == mono_defaults.stringbuilder_class) {
6430                                 gboolean need_free2;
6431                                 MonoMarshalConv conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free2);
6432
6433                                 g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6434
6435                                 /* dest */
6436                                 mono_mb_emit_ldarg (mb, argnum);
6437                                 if (t->byref)
6438                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6439                                 mono_mb_emit_ldloc (mb, index_var);
6440                                 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6441
6442                                 /* src */
6443                                 mono_mb_emit_ldloc (mb, src_ptr);
6444                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6445
6446                                 mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
6447
6448                                 if (need_free) {
6449                                         /* src */
6450                                         mono_mb_emit_ldloc (mb, src_ptr);
6451                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6452
6453                                         mono_mb_emit_icall (mb, mono_marshal_free);
6454                                 }
6455                         }
6456                         else if (eklass == mono_defaults.string_class) {
6457                                 if (need_free) {
6458                                         /* src */
6459                                         mono_mb_emit_ldloc (mb, src_ptr);
6460                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6461
6462                                         mono_mb_emit_icall (mb, mono_marshal_free);
6463                                 }
6464                         }
6465                         else {
6466                                 if (need_convert) {
6467                                         /* set the src_ptr */
6468                                         mono_mb_emit_ldloc (mb, src_ptr);
6469                                         mono_mb_emit_stloc (mb, 0);
6470
6471                                         /* set dst_ptr */
6472                                         mono_mb_emit_ldarg (mb, argnum);
6473                                         if (t->byref)
6474                                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6475                                         mono_mb_emit_ldloc (mb, index_var);
6476                                         mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6477                                         mono_mb_emit_stloc (mb, 1);
6478
6479                                         /* emit valuetype conversion code */
6480                                         emit_struct_conv_full (mb, eklass, TRUE, eklass == mono_defaults.char_class ? encoding : (MonoMarshalNative)-1);
6481                                 }
6482
6483                                 if (need_free) {
6484                                         mono_mb_emit_ldloc (mb, src_ptr);
6485                                         mono_mb_emit_stloc (mb, loc);
6486                                         mono_mb_emit_ldloc (mb, loc);
6487
6488                                         emit_struct_free (mb, eklass, loc);
6489                                 }
6490                         }
6491
6492                         mono_mb_emit_add_to_local (mb, index_var, 1);
6493                         mono_mb_emit_add_to_local (mb, src_ptr, esize);
6494
6495                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
6496
6497                         mono_mb_patch_branch (mb, label1);
6498                         mono_mb_patch_branch (mb, label3);
6499                 }
6500                 
6501                 if (klass->element_class->blittable) {
6502                         /* free memory allocated (if any) by MONO_MARSHAL_CONV_ARRAY_LPARRAY */
6503
6504                         mono_mb_emit_ldarg (mb, argnum);
6505                         if (t->byref)
6506                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6507                         mono_mb_emit_ldloc (mb, conv_arg);
6508                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_FREE_LPARRAY, NULL));
6509                 }
6510
6511                 break;
6512
6513         case MARSHAL_ACTION_PUSH:
6514                 if (t->byref)
6515                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6516                 else
6517                         mono_mb_emit_ldloc (mb, conv_arg);
6518                 break;
6519
6520         case MARSHAL_ACTION_CONV_RESULT:
6521                 /* fixme: we need conversions here */
6522                 mono_mb_emit_stloc (mb, 3);
6523                 break;
6524
6525         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6526                 MonoClass *eklass;
6527                 guint32 label1, label2, label3;
6528                 int index_var, src_ptr, esize, param_num, num_elem;
6529                 MonoMarshalConv conv;
6530                 gboolean is_string = FALSE;
6531                 
6532                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6533                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6534
6535                 if (t->byref) {
6536                         char *msg = g_strdup ("Byref array marshalling to managed code is not implemented.");
6537                         mono_mb_emit_exception_marshal_directive (mb, msg);
6538                         return conv_arg;
6539                 }
6540                 if (!spec) {
6541                         char *msg = g_strdup ("[MarshalAs] attribute required to marshal arrays to managed code.");
6542                         mono_mb_emit_exception_marshal_directive (mb, msg);
6543                         return conv_arg;
6544                 }                       
6545                 if (spec->native != MONO_NATIVE_LPARRAY) {
6546                         char *msg = g_strdup ("Non LPArray marshalling of arrays to managed code is not implemented.");
6547                         mono_mb_emit_exception_marshal_directive (mb, msg);
6548                         return conv_arg;                        
6549                 }
6550
6551                 /* FIXME: t is from the method which is wrapped, not the delegate type */
6552                 /* g_assert (t->attrs & PARAM_ATTRIBUTE_IN); */
6553
6554                 param_num = spec->data.array_data.param_num;
6555                 num_elem = spec->data.array_data.num_elem;
6556                 if (spec->data.array_data.elem_mult == 0)
6557                         /* param_num is not specified */
6558                         param_num = -1;
6559
6560                 if (param_num == -1) {
6561                         if (num_elem <= 0) {
6562                                 char *msg = g_strdup ("Either SizeConst or SizeParamIndex should be specified when marshalling arrays to managed code.");
6563                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6564                                 return conv_arg;
6565                         }
6566                 }
6567
6568                 /* FIXME: Optimize blittable case */
6569
6570                 eklass = klass->element_class;
6571                 if (eklass == mono_defaults.string_class) {
6572                         is_string = TRUE;
6573                         conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
6574                 }
6575                 else if (eklass == mono_defaults.stringbuilder_class) {
6576                         is_string = TRUE;
6577                         conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
6578                 }
6579                 else
6580                         conv = MONO_MARSHAL_CONV_INVALID;
6581
6582                 mono_marshal_load_type_info (eklass);
6583
6584                 if (is_string)
6585                         esize = sizeof (gpointer);
6586                 else
6587                         esize = mono_class_native_size (eklass, NULL);
6588                 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6589
6590                 mono_mb_emit_byte (mb, CEE_LDNULL);
6591                 mono_mb_emit_stloc (mb, conv_arg);
6592
6593                 /* Check param index */
6594                 if (param_num != -1) {
6595                         if (param_num >= m->sig->param_count) {
6596                                 char *msg = g_strdup ("Array size control parameter index is out of range.");
6597                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6598                                 return conv_arg;
6599                         }
6600                         switch (m->sig->params [param_num]->type) {
6601                         case MONO_TYPE_I1:
6602                         case MONO_TYPE_U1:
6603                         case MONO_TYPE_I2:
6604                         case MONO_TYPE_U2:
6605                         case MONO_TYPE_I4:
6606                         case MONO_TYPE_U4:
6607                         case MONO_TYPE_I:
6608                         case MONO_TYPE_U:
6609                         case MONO_TYPE_I8:
6610                         case MONO_TYPE_U8:
6611                                 break;
6612                         default: {
6613                                 char *msg = g_strdup ("Array size control parameter must be an integral type.");
6614                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6615                                 return conv_arg;
6616                         }
6617                         }
6618                 }
6619
6620                 /* Check null */
6621                 mono_mb_emit_ldarg (mb, argnum);
6622                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6623
6624                 mono_mb_emit_ldarg (mb, argnum);
6625                 mono_mb_emit_stloc (mb, src_ptr);
6626
6627                 /* Create managed array */
6628                 /* 
6629                  * The LPArray marshalling spec says that sometimes param_num starts 
6630                  * from 1, sometimes it starts from 0. But MS seems to allways start
6631                  * from 0.
6632                  */
6633
6634                 if (param_num == -1) {
6635                         mono_mb_emit_icon (mb, num_elem);
6636                 } else {
6637                         mono_mb_emit_ldarg (mb, param_num);
6638                         if (num_elem > 0) {
6639                                 mono_mb_emit_icon (mb, num_elem);
6640                                 mono_mb_emit_byte (mb, CEE_ADD);
6641                         }
6642                         mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6643                 }
6644
6645                 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
6646                 mono_mb_emit_stloc (mb, conv_arg);
6647
6648                 if (eklass->blittable) {
6649                         mono_mb_emit_ldloc (mb, conv_arg);
6650                         mono_mb_emit_byte (mb, CEE_CONV_I);
6651                         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6652                         mono_mb_emit_byte (mb, CEE_ADD);
6653                         mono_mb_emit_ldarg (mb, argnum);
6654                         mono_mb_emit_ldloc (mb, conv_arg);
6655                         mono_mb_emit_byte (mb, CEE_LDLEN);
6656                         mono_mb_emit_icon (mb, esize);
6657                         mono_mb_emit_byte (mb, CEE_MUL);
6658                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6659                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
6660                         break;
6661                 }
6662
6663                 /* Emit marshalling loop */
6664                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6665                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6666                 mono_mb_emit_stloc (mb, index_var);
6667                 label2 = mono_mb_get_label (mb);
6668                 mono_mb_emit_ldloc (mb, index_var);
6669                 mono_mb_emit_ldloc (mb, conv_arg);
6670                 mono_mb_emit_byte (mb, CEE_LDLEN);
6671                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6672
6673                 /* Emit marshalling code */
6674                 if (is_string) {
6675                         g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6676
6677                         mono_mb_emit_ldloc (mb, conv_arg);
6678                         mono_mb_emit_ldloc (mb, index_var);
6679
6680                         mono_mb_emit_ldloc (mb, src_ptr);
6681                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6682
6683                         mono_mb_emit_icall (mb, conv_to_icall (conv, NULL));
6684                         mono_mb_emit_byte (mb, CEE_STELEM_REF);
6685                 }
6686                 else {
6687                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6688                         mono_mb_emit_exception_marshal_directive (mb, msg);
6689                         return conv_arg;
6690                 }
6691
6692                 mono_mb_emit_add_to_local (mb, index_var, 1);
6693                 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6694
6695                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6696
6697                 mono_mb_patch_branch (mb, label1);
6698                 mono_mb_patch_branch (mb, label3);
6699                 
6700                 break;
6701         }
6702         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6703                 MonoClass *eklass;
6704                 guint32 label1, label2, label3;
6705                 int index_var, dest_ptr, esize, param_num, num_elem;
6706                 MonoMarshalConv conv;
6707                 gboolean is_string = FALSE;
6708
6709                 if (!spec)
6710                         /* Already handled in CONV_IN */
6711                         break;
6712                 
6713                 /* These are already checked in CONV_IN */
6714                 g_assert (!t->byref);
6715                 g_assert (spec->native == MONO_NATIVE_LPARRAY);
6716                 g_assert (t->attrs & PARAM_ATTRIBUTE_OUT);
6717
6718                 param_num = spec->data.array_data.param_num;
6719                 num_elem = spec->data.array_data.num_elem;
6720
6721                 if (spec->data.array_data.elem_mult == 0)
6722                         /* param_num is not specified */
6723                         param_num = -1;
6724
6725                 if (param_num == -1) {
6726                         if (num_elem <= 0) {
6727                                 g_assert_not_reached ();
6728                         }
6729                 }
6730
6731                 /* FIXME: Optimize blittable case */
6732
6733                 eklass = klass->element_class;
6734                 if (eklass == mono_defaults.string_class) {
6735                         is_string = TRUE;
6736                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6737                 }
6738                 else if (eklass == mono_defaults.stringbuilder_class) {
6739                         is_string = TRUE;
6740                         conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6741                 }
6742                 else
6743                         conv = MONO_MARSHAL_CONV_INVALID;
6744
6745                 mono_marshal_load_type_info (eklass);
6746
6747                 if (is_string)
6748                         esize = sizeof (gpointer);
6749                 else
6750                         esize = mono_class_native_size (eklass, NULL);
6751
6752                 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6753
6754                 /* Check null */
6755                 mono_mb_emit_ldloc (mb, conv_arg);
6756                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6757
6758                 mono_mb_emit_ldarg (mb, argnum);
6759                 mono_mb_emit_stloc (mb, dest_ptr);
6760
6761                 if (eklass->blittable) {
6762                         /* dest */
6763                         mono_mb_emit_ldarg (mb, argnum);
6764                         /* src */
6765                         mono_mb_emit_ldloc (mb, conv_arg);
6766                         mono_mb_emit_byte (mb, CEE_CONV_I);
6767                         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6768                         mono_mb_emit_byte (mb, CEE_ADD);
6769                         /* length */
6770                         mono_mb_emit_ldloc (mb, conv_arg);
6771                         mono_mb_emit_byte (mb, CEE_LDLEN);
6772                         mono_mb_emit_icon (mb, esize);
6773                         mono_mb_emit_byte (mb, CEE_MUL);
6774                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6775                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
6776                         break;
6777                 }
6778
6779                 /* Emit marshalling loop */
6780                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6781                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6782                 mono_mb_emit_stloc (mb, index_var);
6783                 label2 = mono_mb_get_label (mb);
6784                 mono_mb_emit_ldloc (mb, index_var);
6785                 mono_mb_emit_ldloc (mb, conv_arg);
6786                 mono_mb_emit_byte (mb, CEE_LDLEN);
6787                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6788
6789                 /* Emit marshalling code */
6790                 if (is_string) {
6791                         int stind_op;
6792                         g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6793
6794                         /* dest */
6795                         mono_mb_emit_ldloc (mb, dest_ptr);
6796
6797                         /* src */
6798                         mono_mb_emit_ldloc (mb, conv_arg);
6799                         mono_mb_emit_ldloc (mb, index_var);
6800
6801                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6802
6803                         mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
6804                         mono_mb_emit_byte (mb, stind_op);
6805                 }
6806                 else {
6807                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6808                         mono_mb_emit_exception_marshal_directive (mb, msg);
6809                         return conv_arg;
6810                 }
6811
6812                 mono_mb_emit_add_to_local (mb, index_var, 1);
6813                 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6814
6815                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6816
6817                 mono_mb_patch_branch (mb, label1);
6818                 mono_mb_patch_branch (mb, label3);
6819
6820                 break;
6821         }
6822         case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6823                 MonoClass *eklass;
6824                 guint32 label1, label2, label3;
6825                 int index_var, src, dest, esize;
6826                 MonoMarshalConv conv = MONO_MARSHAL_CONV_INVALID;
6827                 gboolean is_string = FALSE;
6828                 
6829                 g_assert (!t->byref);
6830
6831                 eklass = klass->element_class;
6832
6833                 mono_marshal_load_type_info (eklass);
6834
6835                 if (eklass == mono_defaults.string_class) {
6836                         is_string = TRUE;
6837                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6838                 }
6839                 else {
6840                         g_assert_not_reached ();
6841                 }
6842
6843                 if (is_string)
6844                         esize = sizeof (gpointer);
6845                 else if (eklass == mono_defaults.char_class)
6846                         esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6847                 else
6848                         esize = mono_class_native_size (eklass, NULL);
6849
6850                 src = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6851                 dest = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6852                         
6853                 mono_mb_emit_stloc (mb, src);
6854                 mono_mb_emit_ldloc (mb, src);
6855                 mono_mb_emit_stloc (mb, 3);
6856
6857                 /* Check for null */
6858                 mono_mb_emit_ldloc (mb, src);
6859                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6860
6861                 /* Allocate native array */
6862                 mono_mb_emit_icon (mb, esize);
6863                 mono_mb_emit_ldloc (mb, src);
6864                 mono_mb_emit_byte (mb, CEE_LDLEN);
6865
6866                 if (eklass == mono_defaults.string_class) {
6867                         /* Make the array bigger for the terminating null */
6868                         mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6869                         mono_mb_emit_byte (mb, CEE_ADD);
6870                 }
6871                 mono_mb_emit_byte (mb, CEE_MUL);
6872                 mono_mb_emit_icall (mb, ves_icall_marshal_alloc);
6873                 mono_mb_emit_stloc (mb, dest);
6874                 mono_mb_emit_ldloc (mb, dest);
6875                 mono_mb_emit_stloc (mb, 3);
6876
6877                 /* Emit marshalling loop */
6878                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6879                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6880                 mono_mb_emit_stloc (mb, index_var);
6881                 label2 = mono_mb_get_label (mb);
6882                 mono_mb_emit_ldloc (mb, index_var);
6883                 mono_mb_emit_ldloc (mb, src);
6884                 mono_mb_emit_byte (mb, CEE_LDLEN);
6885                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6886
6887                 /* Emit marshalling code */
6888                 if (is_string) {
6889                         int stind_op;
6890                         g_assert (conv != MONO_MARSHAL_CONV_INVALID);
6891
6892                         /* dest */
6893                         mono_mb_emit_ldloc (mb, dest);
6894
6895                         /* src */
6896                         mono_mb_emit_ldloc (mb, src);
6897                         mono_mb_emit_ldloc (mb, index_var);
6898
6899                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6900
6901                         mono_mb_emit_icall (mb, conv_to_icall (conv, &stind_op));
6902                         mono_mb_emit_byte (mb, stind_op);
6903                 }
6904                 else {
6905                         char *msg = g_strdup ("Marshalling of non-string arrays to managed code is not implemented.");
6906                         mono_mb_emit_exception_marshal_directive (mb, msg);
6907                         return conv_arg;
6908                 }
6909
6910                 mono_mb_emit_add_to_local (mb, index_var, 1);
6911                 mono_mb_emit_add_to_local (mb, dest, esize);
6912
6913                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6914
6915                 mono_mb_patch_branch (mb, label3);
6916                 mono_mb_patch_branch (mb, label1);
6917                 break;
6918         }
6919         default:
6920                 g_assert_not_reached ();
6921         }
6922 #endif
6923         return conv_arg;
6924 }
6925
6926 static MonoType*
6927 marshal_boolean_conv_in_get_local_type (MonoMarshalSpec *spec, guint8 *ldc_op /*out*/)
6928 {
6929         if (spec == NULL) {
6930                 return &mono_defaults.int32_class->byval_arg;
6931         } else {
6932                 switch (spec->native) {
6933                 case MONO_NATIVE_I1:
6934                 case MONO_NATIVE_U1:
6935                         return &mono_defaults.byte_class->byval_arg;
6936                 case MONO_NATIVE_VARIANTBOOL:
6937                         if (ldc_op) *ldc_op = CEE_LDC_I4_M1;
6938                         return &mono_defaults.int16_class->byval_arg;
6939                 case MONO_NATIVE_BOOLEAN:
6940                         return &mono_defaults.int32_class->byval_arg;
6941                 default:
6942                         g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
6943                         return &mono_defaults.int32_class->byval_arg;
6944                 }
6945         }
6946 }
6947
6948 static MonoClass*
6949 marshal_boolean_managed_conv_in_get_conv_arg_class (MonoMarshalSpec *spec, guint8 *ldop/*out*/)
6950 {
6951         MonoClass* conv_arg_class = mono_defaults.int32_class;
6952         if (spec) {
6953                 switch (spec->native) {
6954                 case MONO_NATIVE_I1:
6955                 case MONO_NATIVE_U1:
6956                         conv_arg_class = mono_defaults.byte_class;
6957                         if (ldop) *ldop = CEE_LDIND_I1;
6958                         break;
6959                 case MONO_NATIVE_VARIANTBOOL:
6960                         conv_arg_class = mono_defaults.int16_class;
6961                         if (ldop) *ldop = CEE_LDIND_I2;
6962                         break;
6963                 case MONO_NATIVE_BOOLEAN:
6964                         break;
6965                 default:
6966                         g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
6967                 }
6968         }
6969         return conv_arg_class;
6970 }
6971
6972 static int
6973 emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
6974                       MonoMarshalSpec *spec, 
6975                       int conv_arg, MonoType **conv_arg_type, 
6976                       MarshalAction action)
6977 {
6978 #ifdef DISABLE_JIT
6979         switch (action) {
6980         case MARSHAL_ACTION_CONV_IN:
6981                 if (t->byref)
6982                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
6983                 else
6984                         *conv_arg_type = marshal_boolean_conv_in_get_local_type (spec, NULL);
6985                 break;
6986
6987         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6988                 MonoClass* conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, NULL);
6989                 if (t->byref)
6990                         *conv_arg_type = &conv_arg_class->this_arg;
6991                 else
6992                         *conv_arg_type = &conv_arg_class->byval_arg;
6993                 break;
6994         }
6995
6996         }
6997 #else
6998         MonoMethodBuilder *mb = m->mb;
6999
7000         switch (action) {
7001         case MARSHAL_ACTION_CONV_IN: {
7002                 MonoType *local_type;
7003                 int label_false;
7004                 guint8 ldc_op = CEE_LDC_I4_1;
7005
7006                 local_type = marshal_boolean_conv_in_get_local_type (spec, &ldc_op);
7007                 if (t->byref)
7008                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
7009                 else
7010                         *conv_arg_type = local_type;
7011                 conv_arg = mono_mb_add_local (mb, local_type);
7012                 
7013                 mono_mb_emit_ldarg (mb, argnum);
7014                 if (t->byref)
7015                         mono_mb_emit_byte (mb, CEE_LDIND_I1);
7016                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7017                 mono_mb_emit_byte (mb, ldc_op);
7018                 mono_mb_emit_stloc (mb, conv_arg);
7019                 mono_mb_patch_branch (mb, label_false);
7020
7021                 break;
7022         }
7023
7024         case MARSHAL_ACTION_CONV_OUT:
7025         {
7026                 int label_false, label_end;
7027                 if (!t->byref)
7028                         break;
7029
7030                 mono_mb_emit_ldarg (mb, argnum);
7031                 mono_mb_emit_ldloc (mb, conv_arg);
7032                 
7033                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7034                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7035
7036                 label_end = mono_mb_emit_branch (mb, CEE_BR);
7037                 mono_mb_patch_branch (mb, label_false);
7038                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7039                 mono_mb_patch_branch (mb, label_end);
7040
7041                 mono_mb_emit_byte (mb, CEE_STIND_I1);
7042                 break;
7043         }
7044
7045         case MARSHAL_ACTION_PUSH:
7046                 if (t->byref)
7047                         mono_mb_emit_ldloc_addr (mb, conv_arg);
7048                 else if (conv_arg)
7049                         mono_mb_emit_ldloc (mb, conv_arg);
7050                 else
7051                         mono_mb_emit_ldarg (mb, argnum);
7052                 break;
7053
7054         case MARSHAL_ACTION_CONV_RESULT:
7055                 /* maybe we need to make sure that it fits within 8 bits */
7056                 mono_mb_emit_stloc (mb, 3);
7057                 break;
7058
7059         case MARSHAL_ACTION_MANAGED_CONV_IN: {
7060                 MonoClass* conv_arg_class = mono_defaults.int32_class;
7061                 guint8 ldop = CEE_LDIND_I4;
7062                 int label_null, label_false;
7063
7064                 conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, &ldop);
7065                 conv_arg = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7066
7067                 if (t->byref)
7068                         *conv_arg_type = &conv_arg_class->this_arg;
7069                 else
7070                         *conv_arg_type = &conv_arg_class->byval_arg;
7071
7072
7073                 mono_mb_emit_ldarg (mb, argnum);
7074                 
7075                 /* Check null */
7076                 if (t->byref) {
7077                         label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
7078                         mono_mb_emit_ldarg (mb, argnum);
7079                         mono_mb_emit_byte (mb, ldop);
7080                 } else
7081                         label_null = 0;
7082
7083                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7084                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7085                 mono_mb_emit_stloc (mb, conv_arg);
7086                 mono_mb_patch_branch (mb, label_false);
7087
7088                 if (t->byref) 
7089                         mono_mb_patch_branch (mb, label_null);
7090                 break;
7091         }
7092
7093         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
7094                 guint8 stop = CEE_STIND_I4;
7095                 guint8 ldc_op = CEE_LDC_I4_1;
7096                 int label_null,label_false, label_end;;
7097
7098                 if (!t->byref)
7099                         break;
7100                 if (spec) {
7101                         switch (spec->native) {
7102                         case MONO_NATIVE_I1:
7103                         case MONO_NATIVE_U1:
7104                                 stop = CEE_STIND_I1;
7105                                 break;
7106                         case MONO_NATIVE_VARIANTBOOL:
7107                                 stop = CEE_STIND_I2;
7108                                 ldc_op = CEE_LDC_I4_M1;
7109                                 break;
7110                         default:
7111                                 break;
7112                         }
7113                 }
7114                 
7115                 /* Check null */
7116                 mono_mb_emit_ldarg (mb, argnum);
7117                 label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
7118
7119                 mono_mb_emit_ldarg (mb, argnum);
7120                 mono_mb_emit_ldloc (mb, conv_arg);
7121
7122                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
7123                 mono_mb_emit_byte (mb, ldc_op);
7124                 label_end = mono_mb_emit_branch (mb, CEE_BR);
7125
7126                 mono_mb_patch_branch (mb, label_false);
7127                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7128                 mono_mb_patch_branch (mb, label_end);
7129
7130                 mono_mb_emit_byte (mb, stop);
7131                 mono_mb_patch_branch (mb, label_null);
7132                 break;
7133         }
7134
7135         default:
7136                 g_assert_not_reached ();
7137         }
7138 #endif
7139         return conv_arg;
7140 }
7141
7142 static int
7143 emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t, 
7144                   MonoMarshalSpec *spec, int conv_arg, 
7145                   MonoType **conv_arg_type, MarshalAction action)
7146 {
7147 #ifndef DISABLE_JIT
7148         MonoMethodBuilder *mb = m->mb;
7149
7150         switch (action) {
7151         case MARSHAL_ACTION_CONV_IN:
7152                 /* MS seems to allow this in some cases, ie. bxc #158 */
7153                 /*
7154                 if (MONO_TYPE_ISSTRUCT (t->data.type) && !mono_class_from_mono_type (t->data.type)->blittable) {
7155                         char *msg = g_strdup_printf ("Can not marshal 'parameter #%d': Pointers can not reference marshaled structures. Use byref instead.", argnum + 1);
7156                         mono_mb_emit_exception_marshal_directive (m->mb, msg);
7157                 }
7158                 */
7159                 break;
7160
7161         case MARSHAL_ACTION_PUSH:
7162                 mono_mb_emit_ldarg (mb, argnum);
7163                 break;
7164
7165         case MARSHAL_ACTION_CONV_RESULT:
7166                 /* no conversions necessary */
7167                 mono_mb_emit_stloc (mb, 3);
7168                 break;
7169
7170         default:
7171                 break;
7172         }
7173 #endif
7174         return conv_arg;
7175 }
7176
7177 static int
7178 emit_marshal_char (EmitMarshalContext *m, int argnum, MonoType *t, 
7179                    MonoMarshalSpec *spec, int conv_arg, 
7180                    MonoType **conv_arg_type, MarshalAction action)
7181 {
7182 #ifndef DISABLE_JIT
7183         MonoMethodBuilder *mb = m->mb;
7184
7185         switch (action) {
7186         case MARSHAL_ACTION_PUSH:
7187                 /* fixme: dont know how to marshal that. We cant simply
7188                  * convert it to a one byte UTF8 character, because an
7189                  * unicode character may need more that one byte in UTF8 */
7190                 mono_mb_emit_ldarg (mb, argnum);
7191                 break;
7192
7193         case MARSHAL_ACTION_CONV_RESULT:
7194                 /* fixme: we need conversions here */
7195                 mono_mb_emit_stloc (mb, 3);
7196                 break;
7197
7198         default:
7199                 break;
7200         }
7201 #endif
7202         return conv_arg;
7203 }
7204
7205 static int
7206 emit_marshal_scalar (EmitMarshalContext *m, int argnum, MonoType *t, 
7207                      MonoMarshalSpec *spec, int conv_arg, 
7208                      MonoType **conv_arg_type, MarshalAction action)
7209 {
7210 #ifndef DISABLE_JIT
7211         MonoMethodBuilder *mb = m->mb;
7212
7213         switch (action) {
7214         case MARSHAL_ACTION_PUSH:
7215                 mono_mb_emit_ldarg (mb, argnum);
7216                 break;
7217
7218         case MARSHAL_ACTION_CONV_RESULT:
7219                 /* no conversions necessary */
7220                 mono_mb_emit_stloc (mb, 3);
7221                 break;
7222
7223         default:
7224                 break;
7225         }
7226 #endif
7227         return conv_arg;
7228 }
7229
7230 static int
7231 emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t, 
7232               MonoMarshalSpec *spec, int conv_arg, 
7233               MonoType **conv_arg_type, MarshalAction action)
7234 {
7235         /* Ensure that we have marshalling info for this param */
7236         mono_marshal_load_type_info (mono_class_from_mono_type (t));
7237
7238         if (spec && spec->native == MONO_NATIVE_CUSTOM)
7239                 return emit_marshal_custom (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7240
7241         if (spec && spec->native == MONO_NATIVE_ASANY)
7242                 return emit_marshal_asany (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7243                         
7244         switch (t->type) {
7245         case MONO_TYPE_VALUETYPE:
7246                 if (t->data.klass == mono_defaults.handleref_class)
7247                         return emit_marshal_handleref (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7248                 
7249                 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7250         case MONO_TYPE_STRING:
7251                 return emit_marshal_string (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7252         case MONO_TYPE_CLASS:
7253         case MONO_TYPE_OBJECT:
7254 #if !defined(DISABLE_COM) && !defined(DISABLE_JIT)
7255                 if (spec && spec->native == MONO_NATIVE_STRUCT)
7256                         return emit_marshal_variant (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7257 #endif
7258
7259 #if !defined(DISABLE_COM)
7260                 if (spec && (spec->native == MONO_NATIVE_IUNKNOWN ||
7261                         spec->native == MONO_NATIVE_IDISPATCH ||
7262                         spec->native == MONO_NATIVE_INTERFACE))
7263                         return mono_cominterop_emit_marshal_com_interface (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7264                 if (spec && (spec->native == MONO_NATIVE_SAFEARRAY) && 
7265                         (spec->data.safearray_data.elem_type == MONO_VARIANT_VARIANT) && 
7266                         ((action == MARSHAL_ACTION_CONV_OUT) || (action == MARSHAL_ACTION_CONV_IN) || (action == MARSHAL_ACTION_PUSH)))
7267                         return mono_cominterop_emit_marshal_safearray (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7268 #endif
7269
7270                 if (mono_class_try_get_safehandle_class () != NULL && t->data.klass &&
7271                     mono_class_is_subclass_of (t->data.klass,  mono_class_try_get_safehandle_class (), FALSE))
7272                         return emit_marshal_safehandle (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7273                 
7274                 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7275         case MONO_TYPE_ARRAY:
7276         case MONO_TYPE_SZARRAY:
7277                 return emit_marshal_array (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7278         case MONO_TYPE_BOOLEAN:
7279                 return emit_marshal_boolean (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7280         case MONO_TYPE_PTR:
7281                 return emit_marshal_ptr (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7282         case MONO_TYPE_CHAR:
7283                 return emit_marshal_char (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7284         case MONO_TYPE_I1:
7285         case MONO_TYPE_U1:
7286         case MONO_TYPE_I2:
7287         case MONO_TYPE_U2:
7288         case MONO_TYPE_I4:
7289         case MONO_TYPE_U4:
7290         case MONO_TYPE_I:
7291         case MONO_TYPE_U:
7292         case MONO_TYPE_R4:
7293         case MONO_TYPE_R8:
7294         case MONO_TYPE_I8:
7295         case MONO_TYPE_U8:
7296         case MONO_TYPE_FNPTR:
7297                 return emit_marshal_scalar (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7298         case MONO_TYPE_GENERICINST:
7299                 if (mono_type_generic_inst_is_valuetype (t))
7300                         return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7301                 else
7302                         return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7303         default:
7304                 return conv_arg;
7305         }
7306 }
7307
7308 #ifndef DISABLE_JIT
7309 /**
7310  * mono_marshal_emit_native_wrapper:
7311  * @image: the image to use for looking up custom marshallers
7312  * @sig: The signature of the native function
7313  * @piinfo: Marshalling information
7314  * @mspecs: Marshalling information
7315  * @aot: whenever the created method will be compiled by the AOT compiler
7316  * @method: if non-NULL, the pinvoke method to call
7317  * @check_exceptions: Whenever to check for pending exceptions after the native call
7318  * @func_param: the function to call is passed as a boxed IntPtr as the first parameter
7319  *
7320  * generates IL code for the pinvoke wrapper, the generated code calls @func.
7321  */
7322 void
7323 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)
7324 {
7325         EmitMarshalContext m;
7326         MonoMethodSignature *csig;
7327         MonoClass *klass;
7328         int i, argnum, *tmp_locals;
7329         int type, param_shift = 0;
7330         int coop_gc_stack_dummy, coop_gc_var;
7331
7332         memset (&m, 0, sizeof (m));
7333         m.mb = mb;
7334         m.sig = sig;
7335         m.piinfo = piinfo;
7336
7337         /* we copy the signature, so that we can set pinvoke to 0 */
7338         if (func_param) {
7339                 /* The function address is passed as the first argument */
7340                 g_assert (!sig->hasthis);
7341                 param_shift += 1;
7342         }
7343         csig = mono_metadata_signature_dup_full (mb->method->klass->image, sig);
7344         csig->pinvoke = 1;
7345         m.csig = csig;
7346         m.image = image;
7347
7348         if (sig->hasthis)
7349                 param_shift += 1;
7350
7351         /* we allocate local for use with emit_struct_conv() */
7352         /* allocate local 0 (pointer) src_ptr */
7353         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7354         /* allocate local 1 (pointer) dst_ptr */
7355         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7356         /* allocate local 2 (boolean) delete_old */
7357         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7358
7359         /* delete_old = FALSE */
7360         mono_mb_emit_icon (mb, 0);
7361         mono_mb_emit_stloc (mb, 2);
7362
7363         if (!MONO_TYPE_IS_VOID (sig->ret)) {
7364                 /* allocate local 3 to store the return value */
7365                 mono_mb_add_local (mb, sig->ret);
7366         }
7367
7368         if (mono_threads_is_coop_enabled ()) {
7369                 /* local 4, dummy local used to get a stack address for suspend funcs */
7370                 coop_gc_stack_dummy = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7371                 /* local 5, the local to be used when calling the suspend funcs */
7372                 coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7373         }
7374
7375         /*
7376          * cookie = mono_threads_enter_gc_safe_region_unbalanced (ref dummy);
7377          *
7378          * ret = method (...);
7379          *
7380          * mono_threads_exit_gc_safe_region_unbalanced (cookie, ref dummy);
7381          *
7382          * <interrupt check>
7383          *
7384          * return ret;
7385          */
7386
7387         if (MONO_TYPE_ISSTRUCT (sig->ret))
7388                 m.vtaddr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7389
7390         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7391                 /* Return type custom marshaling */
7392                 /*
7393                  * Since we can't determine the return type of the unmanaged function,
7394                  * we assume it returns a pointer, and pass that pointer to
7395                  * MarshalNativeToManaged.
7396                  */
7397                 csig->ret = &mono_defaults.int_class->byval_arg;
7398         }
7399
7400         /* we first do all conversions */
7401         tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
7402         m.orig_conv_args = (int *)alloca (sizeof (int) * (sig->param_count + 1));
7403
7404         for (i = 0; i < sig->param_count; i ++) {
7405                 tmp_locals [i] = emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_CONV_IN);
7406         }
7407
7408         // In coop mode need to register blocking state during native call
7409         if (mono_threads_is_coop_enabled ()) {
7410                 // Perform an extra, early lookup of the function address, so any exceptions
7411                 // potentially resulting from the lookup occur before entering blocking mode.
7412                 if (!func_param && !MONO_CLASS_IS_IMPORT (mb->method->klass) && aot) {
7413                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7414                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7415                         mono_mb_emit_byte (mb, CEE_POP); // Result not needed yet
7416                 }
7417
7418                 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7419                 mono_mb_emit_icall (mb, mono_threads_enter_gc_safe_region_unbalanced);
7420                 mono_mb_emit_stloc (mb, coop_gc_var);
7421         }
7422
7423         /* push all arguments */
7424
7425         if (sig->hasthis)
7426                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7427
7428         for (i = 0; i < sig->param_count; i++) {
7429                 emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
7430         }                       
7431
7432         /* call the native method */
7433         if (func_param) {
7434                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7435                 mono_mb_emit_op (mb, CEE_UNBOX, mono_defaults.int_class);
7436                 mono_mb_emit_byte (mb, CEE_LDIND_I);
7437                 mono_mb_emit_calli (mb, csig);
7438         } else if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
7439 #ifndef DISABLE_COM
7440                 mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
7441 #else
7442                 g_assert_not_reached ();
7443 #endif
7444         } else {
7445                 if (aot) {
7446                         /* Reuse the ICALL_ADDR opcode for pinvokes too */
7447                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7448                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7449                         mono_mb_emit_calli (mb, csig);
7450                 } else {                        
7451                         mono_mb_emit_native_call (mb, csig, func);
7452                 }
7453         }
7454
7455         /* Set LastError if needed */
7456         if (piinfo->piflags & PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR) {
7457 #ifdef TARGET_WIN32
7458                 static MonoMethodSignature *get_last_error_sig = NULL;
7459                 if (!get_last_error_sig) {
7460                         get_last_error_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
7461                         get_last_error_sig->ret = &mono_defaults.int_class->byval_arg;
7462                         get_last_error_sig->pinvoke = 1;
7463                 }
7464
7465                 /*
7466                  * Have to call GetLastError () early and without a wrapper, since various runtime components could
7467                  * clobber its value.
7468                  */
7469                 mono_mb_emit_native_call (mb, get_last_error_sig, GetLastError);
7470                 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7471 #else
7472                 mono_mb_emit_icall (mb, mono_marshal_set_last_error);
7473 #endif
7474         }
7475
7476         if (MONO_TYPE_ISSTRUCT (sig->ret)) {
7477                 MonoClass *klass = mono_class_from_mono_type (sig->ret);
7478                 mono_class_init (klass);
7479                 if (!(((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) || klass->blittable)) {
7480                         /* This is used by emit_marshal_vtype (), but it needs to go right before the call */
7481                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7482                         mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
7483                         mono_mb_emit_stloc (mb, m.vtaddr_var);
7484                 }
7485         }
7486
7487         /* Unblock before converting the result, since that can involve calls into the runtime */
7488         if (mono_threads_is_coop_enabled ()) {
7489                 mono_mb_emit_ldloc (mb, coop_gc_var);
7490                 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7491                 mono_mb_emit_icall (mb, mono_threads_exit_gc_safe_region_unbalanced);
7492         }
7493
7494         /* convert the result */
7495         if (!sig->ret->byref) {
7496                 MonoMarshalSpec *spec = mspecs [0];
7497                 type = sig->ret->type;
7498
7499                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7500                         emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7501                 } else {
7502                 handle_enum:
7503                         switch (type) {
7504                         case MONO_TYPE_VOID:
7505                                 break;
7506                         case MONO_TYPE_VALUETYPE:
7507                                 klass = sig->ret->data.klass;
7508                                 if (klass->enumtype) {
7509                                         type = mono_class_enum_basetype (sig->ret->data.klass)->type;
7510                                         goto handle_enum;
7511                                 }
7512                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7513                                 break;
7514                         case MONO_TYPE_I1:
7515                         case MONO_TYPE_U1:
7516                         case MONO_TYPE_I2:
7517                         case MONO_TYPE_U2:
7518                         case MONO_TYPE_I4:
7519                         case MONO_TYPE_U4:
7520                         case MONO_TYPE_I:
7521                         case MONO_TYPE_U:
7522                         case MONO_TYPE_R4:
7523                         case MONO_TYPE_R8:
7524                         case MONO_TYPE_I8:
7525                         case MONO_TYPE_U8:
7526                         case MONO_TYPE_FNPTR:
7527                         case MONO_TYPE_STRING:
7528                         case MONO_TYPE_CLASS:
7529                         case MONO_TYPE_OBJECT:
7530                         case MONO_TYPE_BOOLEAN:
7531                         case MONO_TYPE_ARRAY:
7532                         case MONO_TYPE_SZARRAY:
7533                         case MONO_TYPE_CHAR:
7534                         case MONO_TYPE_PTR:
7535                         case MONO_TYPE_GENERICINST:
7536                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7537                                 break;
7538                         case MONO_TYPE_TYPEDBYREF:
7539                         default:
7540                                 g_warning ("return type 0x%02x unknown", sig->ret->type);       
7541                                 g_assert_not_reached ();
7542                         }
7543                 }
7544         } else {
7545                 mono_mb_emit_stloc (mb, 3);
7546         }
7547
7548         /* 
7549          * Need to call this after converting the result since MONO_VTADDR needs 
7550          * to be adjacent to the call instruction.
7551          */
7552         if (check_exceptions)
7553                 emit_thread_interrupt_checkpoint (mb);
7554
7555         /* we need to convert byref arguments back and free string arrays */
7556         for (i = 0; i < sig->param_count; i++) {
7557                 MonoType *t = sig->params [i];
7558                 MonoMarshalSpec *spec = mspecs [i + 1];
7559
7560                 argnum = i + param_shift;
7561
7562                 if (spec && ((spec->native == MONO_NATIVE_CUSTOM) || (spec->native == MONO_NATIVE_ASANY))) {
7563                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7564                         continue;
7565                 }
7566
7567                 switch (t->type) {
7568                 case MONO_TYPE_STRING:
7569                 case MONO_TYPE_VALUETYPE:
7570                 case MONO_TYPE_CLASS:
7571                 case MONO_TYPE_OBJECT:
7572                 case MONO_TYPE_SZARRAY:
7573                 case MONO_TYPE_BOOLEAN:
7574                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7575                         break;
7576                 default:
7577                         break;
7578                 }
7579         }
7580
7581         if (!MONO_TYPE_IS_VOID(sig->ret))
7582                 mono_mb_emit_ldloc (mb, 3);
7583
7584         mono_mb_emit_byte (mb, CEE_RET);
7585 }
7586 #endif /* DISABLE_JIT */
7587
7588 /**
7589  * mono_marshal_get_native_wrapper:
7590  * @method: The MonoMethod to wrap.
7591  * @check_exceptions: Whenever to check for pending exceptions
7592  *
7593  * generates IL code for the pinvoke wrapper (the generated method
7594  * calls the unmanaged code in piinfo->addr)
7595  */
7596 MonoMethod *
7597 mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
7598 {
7599         MonoMethodSignature *sig, *csig;
7600         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7601         MonoMethodBuilder *mb;
7602         MonoMarshalSpec **mspecs;
7603         MonoMethod *res;
7604         GHashTable *cache;
7605         gboolean pinvoke = FALSE;
7606         gpointer iter;
7607         int i;
7608         const char *exc_class = "MissingMethodException";
7609         const char *exc_arg = NULL;
7610         WrapperInfo *info;
7611
7612         g_assert (method != NULL);
7613         g_assert (mono_method_signature (method)->pinvoke);
7614
7615         GHashTable **cache_ptr;
7616
7617         if (aot) {
7618                 if (check_exceptions)
7619                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_check_cache;
7620                 else
7621                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_cache;
7622         } else {
7623                 if (check_exceptions)
7624                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_check_cache;
7625                 else
7626                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_cache;
7627         }
7628
7629         cache = get_cache (cache_ptr, mono_aligned_addr_hash, NULL);
7630
7631         if ((res = mono_marshal_find_in_cache (cache, method)))
7632                 return res;
7633
7634         if (MONO_CLASS_IS_IMPORT (method->klass)) {
7635                 /* The COM code is not AOT compatible, it calls mono_custom_attrs_get_attr_checked () */
7636                 if (aot)
7637                         return method;
7638 #ifndef DISABLE_COM
7639                 return mono_cominterop_get_native_wrapper (method);
7640 #else
7641                 g_assert_not_reached ();
7642 #endif
7643         }
7644
7645         sig = mono_method_signature (method);
7646
7647         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
7648             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7649                 pinvoke = TRUE;
7650
7651         if (!piinfo->addr) {
7652                 if (pinvoke) {
7653                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
7654                                 exc_arg = "Method contains unsupported native code";
7655                         else if (!aot)
7656                                 mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7657                 } else {
7658                         piinfo->addr = mono_lookup_internal_call (method);
7659                 }
7660         }
7661
7662         /* hack - redirect certain string constructors to CreateString */
7663         if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
7664                 g_assert (!pinvoke);
7665                 g_assert (method->string_ctor);
7666                 g_assert (sig->hasthis);
7667
7668                 /* CreateString returns a value */
7669                 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7670                 csig->ret = &mono_defaults.string_class->byval_arg;
7671                 csig->pinvoke = 0;
7672
7673                 iter = NULL;
7674                 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
7675                         if (!strcmp ("CreateString", res->name) &&
7676                                 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
7677                                 WrapperInfo *info;
7678
7679                                 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
7680                                 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
7681
7682                                 /* create a wrapper to preserve .ctor in stack trace */
7683                                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
7684
7685 #ifndef DISABLE_JIT
7686                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7687                                 for (i = 1; i <= csig->param_count; i++)
7688                                         mono_mb_emit_ldarg (mb, i);
7689                                 mono_mb_emit_managed_call (mb, res, NULL);
7690                                 mono_mb_emit_byte (mb, CEE_RET);
7691 #endif
7692
7693                                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRING_CTOR);
7694                                 info->d.string_ctor.method = method;
7695
7696                                 /* use native_wrapper_cache because internal calls are looked up there */
7697                                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7698                                                                                                          csig->param_count + 1, info, NULL);
7699                                 mono_mb_free (mb);
7700
7701                                 return res;
7702                         }
7703                 }
7704
7705                 /* exception will be thrown */
7706                 piinfo->addr = NULL;
7707                 g_warning ("cannot find CreateString for .ctor");
7708         }
7709
7710         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7711
7712         mb->method->save_lmf = 1;
7713
7714         /*
7715          * In AOT mode and embedding scenarios, it is possible that the icall is not
7716          * registered in the runtime doing the AOT compilation.
7717          */
7718         if (!piinfo->addr && !aot) {
7719 #ifndef DISABLE_JIT
7720                 mono_mb_emit_exception (mb, exc_class, exc_arg);
7721 #endif
7722                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7723                 info->d.managed_to_native.method = method;
7724
7725                 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7726                 csig->pinvoke = 0;
7727                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7728                                                                                          csig->param_count + 16, info, NULL);
7729                 mono_mb_free (mb);
7730
7731                 return res;
7732         }
7733
7734         /* internal calls: we simply push all arguments and call the method (no conversions) */
7735         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
7736                 if (sig->hasthis)
7737                         csig = mono_metadata_signature_dup_add_this (method->klass->image, sig, method->klass);
7738                 else
7739                         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7740
7741                 /* hack - string constructors returns a value */
7742                 if (method->string_ctor)
7743                         csig->ret = &mono_defaults.string_class->byval_arg;
7744
7745 #ifndef DISABLE_JIT
7746                 if (sig->hasthis) {
7747                         int pos;
7748
7749                         /*
7750                          * Add a null check since public icalls can be called with 'call' which
7751                          * does no such check.
7752                          */
7753                         mono_mb_emit_byte (mb, CEE_LDARG_0);                    
7754                         pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
7755                         mono_mb_emit_exception (mb, "NullReferenceException", NULL);
7756                         mono_mb_patch_branch (mb, pos);
7757
7758                         mono_mb_emit_byte (mb, CEE_LDARG_0);
7759                 }
7760
7761                 for (i = 0; i < sig->param_count; i++)
7762                         mono_mb_emit_ldarg (mb, i + sig->hasthis);
7763
7764                 if (aot) {
7765                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7766                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7767                         mono_mb_emit_calli (mb, csig);
7768                 } else {
7769                         g_assert (piinfo->addr);
7770                         mono_mb_emit_native_call (mb, csig, piinfo->addr);
7771                 }
7772                 if (check_exceptions)
7773                         emit_thread_interrupt_checkpoint (mb);
7774                 mono_mb_emit_byte (mb, CEE_RET);
7775 #endif
7776                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7777                 info->d.managed_to_native.method = method;
7778
7779                 csig = mono_metadata_signature_dup_full (method->klass->image, csig);
7780                 csig->pinvoke = 0;
7781                 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7782                                                                                          info, NULL);
7783
7784                 mono_mb_free (mb);
7785                 return res;
7786         }
7787
7788         g_assert (pinvoke);
7789         if (!aot)
7790                 g_assert (piinfo->addr);
7791
7792 #ifndef DISABLE_JIT
7793         mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
7794         mono_method_get_marshal_info (method, mspecs);
7795
7796         mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr, aot, check_exceptions, FALSE);
7797 #endif
7798         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PINVOKE);
7799         info->d.managed_to_native.method = method;
7800
7801         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7802         csig->pinvoke = 0;
7803         res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7804                                                                                  info, NULL);
7805         mono_mb_free (mb);
7806
7807 #ifndef DISABLE_JIT
7808         for (i = sig->param_count; i >= 0; i--)
7809                 if (mspecs [i])
7810                         mono_metadata_free_marshal_spec (mspecs [i]);
7811         g_free (mspecs);
7812 #endif
7813
7814         /* mono_method_print_code (res); */
7815
7816         return res;
7817 }
7818
7819 /**
7820  * mono_marshal_get_native_func_wrapper:
7821  * @image: The image to use for memory allocation and for looking up custom marshallers.
7822  * @sig: The signature of the function
7823  * @func: The native function to wrap
7824  *
7825  *   Returns a wrapper method around native functions, similar to the pinvoke
7826  * wrapper.
7827  */
7828 MonoMethod *
7829 mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig, 
7830                                                                           MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
7831 {
7832         MonoMethodSignature *csig;
7833
7834         SignaturePointerPair key, *new_key;
7835         MonoMethodBuilder *mb;
7836         MonoMethod *res;
7837         GHashTable *cache;
7838         gboolean found;
7839         char *name;
7840
7841         key.sig = sig;
7842         key.pointer = func;
7843
7844         // Generic types are not safe to place in MonoImage caches.
7845         g_assert (!sig->is_inflated);
7846
7847         cache = get_cache (&image->native_func_wrapper_cache, signature_pointer_pair_hash, signature_pointer_pair_equal);
7848         if ((res = mono_marshal_find_in_cache (cache, &key)))
7849                 return res;
7850
7851         name = g_strdup_printf ("wrapper_native_%p", func);
7852         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7853         mb->method->save_lmf = 1;
7854
7855 #ifndef DISABLE_JIT
7856         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE, FALSE);
7857 #endif
7858
7859         csig = mono_metadata_signature_dup_full (image, sig);
7860         csig->pinvoke = 0;
7861
7862         new_key = g_new (SignaturePointerPair,1);
7863         new_key->sig = csig;
7864         new_key->pointer = func;
7865
7866         res = mono_mb_create_and_cache_full (cache, new_key, mb, csig, csig->param_count + 16, NULL, &found);
7867         if (found)
7868                 g_free (new_key);
7869
7870         mono_mb_free (mb);
7871
7872         mono_marshal_set_wrapper_info (res, NULL);
7873
7874         return res;
7875 }
7876
7877 /*
7878  * The wrapper receives the native function as a boxed IntPtr as its 'this' argument. This is easier to support in
7879  * AOT.
7880  */
7881 MonoMethod*
7882 mono_marshal_get_native_func_wrapper_aot (MonoClass *klass)
7883 {
7884         MonoMethodSignature *sig, *csig;
7885         MonoMethodBuilder *mb;
7886         MonoMethod *res;
7887         GHashTable *cache;
7888         char *name;
7889         WrapperInfo *info;
7890         MonoMethodPInvoke mpiinfo;
7891         MonoMethodPInvoke *piinfo = &mpiinfo;
7892         MonoMarshalSpec **mspecs;
7893         MonoMethod *invoke = mono_get_delegate_invoke (klass);
7894         MonoImage *image = invoke->klass->image;
7895         int i;
7896
7897         // FIXME: include UnmanagedFunctionPointerAttribute info
7898
7899         /*
7900          * The wrapper is associated with the delegate type, to pick up the marshalling info etc.
7901          */
7902         cache = get_cache (&mono_method_get_wrapper_cache (invoke)->native_func_wrapper_aot_cache, mono_aligned_addr_hash, NULL);
7903
7904         if ((res = mono_marshal_find_in_cache (cache, invoke)))
7905                 return res;
7906
7907         memset (&mpiinfo, 0, sizeof (mpiinfo));
7908         parse_unmanaged_function_pointer_attr (klass, &mpiinfo);
7909
7910         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
7911         mono_method_get_marshal_info (invoke, mspecs);
7912         /* Freed below so don't alloc from mempool */
7913         sig = mono_metadata_signature_dup (mono_method_signature (invoke));
7914         sig->hasthis = 0;
7915
7916         name = g_strdup_printf ("wrapper_aot_native");
7917         mb = mono_mb_new (invoke->klass, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7918         mb->method->save_lmf = 1;
7919
7920 #ifndef DISABLE_JIT
7921         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, NULL, FALSE, TRUE, TRUE);
7922 #endif
7923
7924         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NATIVE_FUNC_AOT);
7925         info->d.managed_to_native.method = invoke;
7926
7927         g_assert (!sig->hasthis);
7928         csig = mono_metadata_signature_dup_add_this (image, sig, mono_defaults.object_class);
7929         csig->pinvoke = 0;
7930         res = mono_mb_create_and_cache_full (cache, invoke,
7931                                                                                  mb, csig, csig->param_count + 16,
7932                                                                                  info, NULL);
7933         mono_mb_free (mb);
7934
7935         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
7936                 if (mspecs [i])
7937                         mono_metadata_free_marshal_spec (mspecs [i]);
7938         g_free (mspecs);
7939         g_free (sig);
7940
7941         return res;
7942 }
7943
7944 /*
7945  * mono_marshal_emit_managed_wrapper:
7946  *
7947  *   Emit the body of a native-to-managed wrapper. INVOKE_SIG is the signature of
7948  * the delegate which wraps the managed method to be called. For closed delegates,
7949  * it could have fewer parameters than the method it wraps.
7950  * THIS_LOC is the memory location where the target of the delegate is stored.
7951  */
7952 void
7953 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, uint32_t target_handle)
7954 {
7955 #ifdef DISABLE_JIT
7956         MonoMethodSignature *sig, *csig;
7957         int i;
7958
7959         sig = m->sig;
7960         csig = m->csig;
7961
7962         /* we first do all conversions */
7963         for (i = 0; i < sig->param_count; i ++) {
7964                 MonoType *t = sig->params [i];
7965
7966                 switch (t->type) {
7967                 case MONO_TYPE_OBJECT:
7968                 case MONO_TYPE_CLASS:
7969                 case MONO_TYPE_VALUETYPE:
7970                 case MONO_TYPE_ARRAY:
7971                 case MONO_TYPE_SZARRAY:
7972                 case MONO_TYPE_STRING:
7973                 case MONO_TYPE_BOOLEAN:
7974                         emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
7975                 }
7976         }
7977
7978         if (!sig->ret->byref) {
7979                 switch (sig->ret->type) {
7980                 case MONO_TYPE_STRING:
7981                         csig->ret = &mono_defaults.int_class->byval_arg;
7982                         break;
7983                 default:
7984                         break;
7985                 }
7986         }
7987 #else
7988         MonoMethodSignature *sig, *csig;
7989         MonoExceptionClause *clauses, *clause_finally, *clause_catch;
7990         int i, *tmp_locals, ex_local, e_local, attach_cookie_local, attach_dummy_local;
7991         int leave_try_pos, leave_catch_pos, ex_m1_pos;
7992         gboolean closed = FALSE;
7993
7994         sig = m->sig;
7995         csig = m->csig;
7996
7997         /* allocate local 0 (pointer) src_ptr */
7998         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7999         /* allocate local 1 (pointer) dst_ptr */
8000         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8001         /* allocate local 2 (boolean) delete_old */
8002         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8003
8004         if (!sig->hasthis && sig->param_count != invoke_sig->param_count) {
8005                 /* Closed delegate */
8006                 g_assert (sig->param_count == invoke_sig->param_count + 1);
8007                 closed = TRUE;
8008                 /* Use a new signature without the first argument */
8009                 sig = mono_metadata_signature_dup (sig);
8010                 memmove (&sig->params [0], &sig->params [1], (sig->param_count - 1) * sizeof (MonoType*));
8011                 sig->param_count --;
8012         }
8013
8014         if (!MONO_TYPE_IS_VOID(sig->ret)) {
8015                 /* allocate local 3 to store the return value */
8016                 mono_mb_add_local (mb, sig->ret);
8017         }
8018
8019         if (MONO_TYPE_ISSTRUCT (sig->ret))
8020                 m->vtaddr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8021
8022         ex_local = mono_mb_add_local (mb, &mono_defaults.uint32_class->byval_arg);
8023         e_local = mono_mb_add_local (mb, &mono_defaults.exception_class->byval_arg);
8024
8025         attach_cookie_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8026         attach_dummy_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8027
8028         /*
8029          * guint32 ex = -1;
8030          * try {
8031          *   // does (STARTING|RUNNING|BLOCKING) -> RUNNING + set/switch domain
8032          *   mono_threads_attach_coop ();
8033          *
8034          *   <interrupt check>
8035          *
8036          *   ret = method (...);
8037          * } catch (Exception e) {
8038          *   ex = mono_gchandle_new (e, false);
8039          * } finally {
8040          *   // does RUNNING -> (RUNNING|BLOCKING) + unset/switch domain
8041          *   mono_threads_detach_coop ();
8042          *
8043          *   if (ex != -1)
8044          *     mono_marshal_ftnptr_eh_callback (ex);
8045          * }
8046          *
8047          * return ret;
8048          */
8049
8050         clauses = g_new0 (MonoExceptionClause, 2);
8051
8052         clause_catch = &clauses [0];
8053         clause_catch->flags = MONO_EXCEPTION_CLAUSE_NONE;
8054         clause_catch->data.catch_class = mono_defaults.exception_class;
8055
8056         clause_finally = &clauses [1];
8057         clause_finally->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
8058
8059         mono_mb_emit_icon (mb, 0);
8060         mono_mb_emit_stloc (mb, 2);
8061
8062         mono_mb_emit_icon (mb, -1);
8063         mono_mb_emit_byte (mb, CEE_CONV_U4);
8064         mono_mb_emit_stloc (mb, ex_local);
8065
8066         /* try { */
8067         clause_catch->try_offset = clause_finally->try_offset = mono_mb_get_label (mb);
8068
8069         if (!mono_threads_is_coop_enabled ()) {
8070                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8071                 mono_mb_emit_byte (mb, CEE_MONO_JIT_ATTACH);
8072         } else {
8073                 /* mono_threads_attach_coop (); */
8074                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8075                 mono_mb_emit_byte (mb, CEE_MONO_LDDOMAIN);
8076                 mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
8077                 mono_mb_emit_icall (mb, mono_threads_attach_coop);
8078                 mono_mb_emit_stloc (mb, attach_cookie_local);
8079         }
8080
8081         /* <interrupt check> */
8082         emit_thread_interrupt_checkpoint (mb);
8083
8084         /* we first do all conversions */
8085         tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
8086         for (i = 0; i < sig->param_count; i ++) {
8087                 MonoType *t = sig->params [i];
8088
8089                 switch (t->type) {
8090                 case MONO_TYPE_OBJECT:
8091                 case MONO_TYPE_CLASS:
8092                 case MONO_TYPE_VALUETYPE:
8093                 case MONO_TYPE_ARRAY:
8094                 case MONO_TYPE_SZARRAY:
8095                 case MONO_TYPE_STRING:
8096                 case MONO_TYPE_BOOLEAN:
8097                         tmp_locals [i] = emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
8098
8099                         break;
8100                 default:
8101                         tmp_locals [i] = 0;
8102                         break;
8103                 }
8104         }
8105
8106         if (sig->hasthis) {
8107                 if (target_handle) {
8108                         mono_mb_emit_icon (mb, (gint32)target_handle);
8109                         mono_mb_emit_icall (mb, mono_gchandle_get_target);
8110                 } else {
8111                         /* fixme: */
8112                         g_assert_not_reached ();
8113                 }
8114         } else if (closed) {
8115                 mono_mb_emit_icon (mb, (gint32)target_handle);
8116                 mono_mb_emit_icall (mb, mono_gchandle_get_target);
8117         }
8118
8119         for (i = 0; i < sig->param_count; i++) {
8120                 MonoType *t = sig->params [i];
8121
8122                 if (tmp_locals [i]) {
8123                         if (t->byref)
8124                                 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
8125                         else
8126                                 mono_mb_emit_ldloc (mb, tmp_locals [i]);
8127                 }
8128                 else
8129                         mono_mb_emit_ldarg (mb, i);
8130         }
8131
8132         /* ret = method (...) */
8133         mono_mb_emit_managed_call (mb, method, NULL);
8134
8135         if (MONO_TYPE_ISSTRUCT (sig->ret)) {
8136                 MonoClass *klass = mono_class_from_mono_type (sig->ret);
8137                 mono_class_init (klass);
8138                 if (!(((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) || klass->blittable)) {
8139                         /* This is used by emit_marshal_vtype (), but it needs to go right before the call */
8140                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8141                         mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
8142                         mono_mb_emit_stloc (mb, m->vtaddr_var);
8143                 }
8144         }
8145
8146         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
8147                 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8148         } else if (!sig->ret->byref) { 
8149                 switch (sig->ret->type) {
8150                 case MONO_TYPE_VOID:
8151                         break;
8152                 case MONO_TYPE_BOOLEAN:
8153                 case MONO_TYPE_I1:
8154                 case MONO_TYPE_U1:
8155                 case MONO_TYPE_CHAR:
8156                 case MONO_TYPE_I2:
8157                 case MONO_TYPE_U2:
8158                 case MONO_TYPE_I4:
8159                 case MONO_TYPE_U4:
8160                 case MONO_TYPE_I:
8161                 case MONO_TYPE_U:
8162                 case MONO_TYPE_PTR:
8163                 case MONO_TYPE_R4:
8164                 case MONO_TYPE_R8:
8165                 case MONO_TYPE_I8:
8166                 case MONO_TYPE_U8:
8167                 case MONO_TYPE_OBJECT:
8168                         mono_mb_emit_stloc (mb, 3);
8169                         break;
8170                 case MONO_TYPE_STRING:
8171                         csig->ret = &mono_defaults.int_class->byval_arg;
8172                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8173                         break;
8174                 case MONO_TYPE_VALUETYPE:
8175                 case MONO_TYPE_CLASS:
8176                 case MONO_TYPE_SZARRAY:
8177                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8178                         break;
8179                 default:
8180                         g_warning ("return type 0x%02x unknown", sig->ret->type);       
8181                         g_assert_not_reached ();
8182                 }
8183         } else {
8184                 mono_mb_emit_stloc (mb, 3);
8185         }
8186
8187         /* Convert byref arguments back */
8188         for (i = 0; i < sig->param_count; i ++) {
8189                 MonoType *t = sig->params [i];
8190                 MonoMarshalSpec *spec = mspecs [i + 1];
8191
8192                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
8193                         emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8194                 }
8195                 else if (t->byref) {
8196                         switch (t->type) {
8197                         case MONO_TYPE_CLASS:
8198                         case MONO_TYPE_VALUETYPE:
8199                         case MONO_TYPE_OBJECT:
8200                         case MONO_TYPE_STRING:
8201                         case MONO_TYPE_BOOLEAN:
8202                                 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8203                                 break;
8204                         default:
8205                                 break;
8206                         }
8207                 }
8208                 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
8209                         /* The [Out] information is encoded in the delegate signature */
8210                         switch (t->type) {
8211                         case MONO_TYPE_SZARRAY:
8212                         case MONO_TYPE_CLASS:
8213                         case MONO_TYPE_VALUETYPE:
8214                                 emit_marshal (m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8215                                 break;
8216                         default:
8217                                 g_assert_not_reached ();
8218                         }
8219                 }
8220         }
8221
8222         leave_try_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8223
8224         /* } [endtry] */
8225
8226         /* catch (Exception e) { */
8227         clause_catch->try_len = mono_mb_get_label (mb) - clause_catch->try_offset;
8228         clause_catch->handler_offset = mono_mb_get_label (mb);
8229
8230         mono_mb_emit_stloc (mb, e_local);
8231
8232         /* ex = mono_gchandle_new (e, false); */
8233         mono_mb_emit_ldloc (mb, e_local);
8234         mono_mb_emit_icon (mb, 0);
8235         mono_mb_emit_icall (mb, mono_gchandle_new);
8236         mono_mb_emit_stloc (mb, ex_local);
8237
8238         leave_catch_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8239
8240         /* } [endcatch] */
8241         clause_catch->handler_len = mono_mb_get_pos (mb) - clause_catch->handler_offset;
8242
8243         /* finally { */
8244         clause_finally->try_len = mono_mb_get_label (mb) - clause_finally->try_offset;
8245         clause_finally->handler_offset = mono_mb_get_label (mb);
8246
8247         if (!mono_threads_is_coop_enabled ()) {
8248                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8249                 mono_mb_emit_byte (mb, CEE_MONO_JIT_DETACH);
8250         } else {
8251                 /* mono_threads_detach_coop (); */
8252                 mono_mb_emit_ldloc (mb, attach_cookie_local);
8253                 mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
8254                 mono_mb_emit_icall (mb, mono_threads_detach_coop);
8255         }
8256
8257         /* if (ex != -1) */
8258         mono_mb_emit_ldloc (mb, ex_local);
8259         mono_mb_emit_icon (mb, -1);
8260         mono_mb_emit_byte (mb, CEE_CONV_U4);
8261         ex_m1_pos = mono_mb_emit_branch (mb, CEE_BEQ);
8262
8263         /* mono_marshal_ftnptr_eh_callback (ex) */
8264         mono_mb_emit_ldloc (mb, ex_local);
8265         mono_mb_emit_icall (mb, mono_marshal_ftnptr_eh_callback);
8266
8267         /* [ex == -1] */
8268         mono_mb_patch_branch (mb, ex_m1_pos);
8269
8270         mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8271
8272         /* } [endfinally] */
8273         clause_finally->handler_len = mono_mb_get_pos (mb) - clause_finally->handler_offset;
8274
8275         mono_mb_patch_branch (mb, leave_try_pos);
8276         mono_mb_patch_branch (mb, leave_catch_pos);
8277
8278         /* return ret; */
8279         if (m->retobj_var) {
8280                 mono_mb_emit_ldloc (mb, m->retobj_var);
8281                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8282                 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m->retobj_class);
8283         }
8284         else {
8285                 if (!MONO_TYPE_IS_VOID(sig->ret))
8286                         mono_mb_emit_ldloc (mb, 3);
8287                 mono_mb_emit_byte (mb, CEE_RET);
8288         }
8289
8290         mono_mb_set_clauses (mb, 2, clauses);
8291
8292         if (closed)
8293                 g_free (sig);
8294 #endif
8295 }
8296
8297 static void 
8298 mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *csig)
8299 {
8300         MonoMethodSignature *sig;
8301         int i;
8302
8303 #ifdef TARGET_WIN32
8304         /* 
8305          * Under windows, delegates passed to native code must use the STDCALL
8306          * calling convention.
8307          */
8308         csig->call_convention = MONO_CALL_STDCALL;
8309 #endif
8310
8311         sig = mono_method_signature (method);
8312
8313         /* Change default calling convention if needed */
8314         /* Why is this a modopt ? */
8315         if (sig->ret && sig->ret->num_mods) {
8316                 for (i = 0; i < sig->ret->num_mods; ++i) {
8317                         MonoError error;
8318                         MonoClass *cmod_class = mono_class_get_checked (method->klass->image, sig->ret->modifiers [i].token, &error);
8319                         g_assert (mono_error_ok (&error));
8320                         if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
8321                                 if (!strcmp (cmod_class->name, "CallConvCdecl"))
8322                                         csig->call_convention = MONO_CALL_C;
8323                                 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
8324                                         csig->call_convention = MONO_CALL_STDCALL;
8325                                 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
8326                                         csig->call_convention = MONO_CALL_FASTCALL;
8327                                 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
8328                                         csig->call_convention = MONO_CALL_THISCALL;
8329                         }
8330                 }
8331         }
8332 }
8333
8334 /*
8335  * generates IL code to call managed methods from unmanaged code 
8336  * If target_handle==0, the wrapper info will be a WrapperInfo structure.
8337  */
8338 MonoMethod *
8339 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle)
8340 {
8341         MonoError error;
8342         MonoMethodSignature *sig, *csig, *invoke_sig;
8343         MonoMethodBuilder *mb;
8344         MonoMethod *res, *invoke;
8345         MonoMarshalSpec **mspecs;
8346         MonoMethodPInvoke piinfo;
8347         GHashTable *cache;
8348         int i;
8349         EmitMarshalContext m;
8350
8351         g_assert (method != NULL);
8352         g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
8353
8354         /* 
8355          * FIXME: Should cache the method+delegate type pair, since the same method
8356          * could be called with different delegates, thus different marshalling
8357          * options.
8358          */
8359         cache = get_cache (&mono_method_get_wrapper_cache (method)->managed_wrapper_cache, mono_aligned_addr_hash, NULL);
8360
8361         if (!target_handle && (res = mono_marshal_find_in_cache (cache, method)))
8362                 return res;
8363
8364         invoke = mono_get_delegate_invoke (delegate_klass);
8365         invoke_sig = mono_method_signature (invoke);
8366
8367         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8368         mono_method_get_marshal_info (invoke, mspecs);
8369
8370         sig = mono_method_signature (method);
8371
8372         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8373
8374         /*the target gchandle must be the first entry after size and the wrapper itself.*/
8375         mono_mb_add_data (mb, GUINT_TO_POINTER (target_handle));
8376
8377         /* we copy the signature, so that we can modify it */
8378         if (target_handle)
8379                 /* Need to free this later */
8380                 csig = mono_metadata_signature_dup (invoke_sig);
8381         else
8382                 csig = mono_metadata_signature_dup_full (method->klass->image, invoke_sig);
8383         csig->hasthis = 0;
8384         csig->pinvoke = 1;
8385
8386         memset (&m, 0, sizeof (m));
8387         m.mb = mb;
8388         m.sig = sig;
8389         m.piinfo = NULL;
8390         m.retobj_var = 0;
8391         m.csig = csig;
8392         m.image = method->klass->image;
8393
8394         mono_marshal_set_callconv_from_modopt (invoke, csig);
8395
8396         /* The attribute is only available in Net 2.0 */
8397         if (mono_class_try_get_unmanaged_function_pointer_attribute_class ()) {
8398                 MonoCustomAttrInfo *cinfo;
8399                 MonoCustomAttrEntry *attr;
8400
8401                 /* 
8402                  * The pinvoke attributes are stored in a real custom attribute. Obtain the
8403                  * contents of the attribute without constructing it, as that might not be
8404                  * possible when running in cross-compiling mode.
8405                  */
8406                 cinfo = mono_custom_attrs_from_class_checked (delegate_klass, &error);
8407                 mono_error_assert_ok (&error);
8408                 attr = NULL;
8409                 if (cinfo) {
8410                         for (i = 0; i < cinfo->num_attrs; ++i) {
8411                                 MonoClass *ctor_class = cinfo->attrs [i].ctor->klass;
8412                                 if (mono_class_has_parent (ctor_class, mono_class_try_get_unmanaged_function_pointer_attribute_class ())) {
8413                                         attr = &cinfo->attrs [i];
8414                                         break;
8415                                 }
8416                         }
8417                 }
8418                 if (attr) {
8419                         MonoArray *typed_args, *named_args;
8420                         CattrNamedArg *arginfo;
8421                         MonoObject *o;
8422                         gint32 call_conv;
8423                         gint32 charset = 0;
8424                         MonoBoolean set_last_error = 0;
8425                         MonoError error;
8426
8427                         mono_reflection_create_custom_attr_data_args (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8428                         g_assert (mono_error_ok (&error));
8429                         g_assert (mono_array_length (typed_args) == 1);
8430
8431                         /* typed args */
8432                         o = mono_array_get (typed_args, MonoObject*, 0);
8433                         call_conv = *(gint32*)mono_object_unbox (o);
8434
8435                         /* named args */
8436                         for (i = 0; i < mono_array_length (named_args); ++i) {
8437                                 CattrNamedArg *narg = &arginfo [i];
8438
8439                                 o = mono_array_get (named_args, MonoObject*, i);
8440
8441                                 g_assert (narg->field);
8442                                 if (!strcmp (narg->field->name, "CharSet")) {
8443                                         charset = *(gint32*)mono_object_unbox (o);
8444                                 } else if (!strcmp (narg->field->name, "SetLastError")) {
8445                                         set_last_error = *(MonoBoolean*)mono_object_unbox (o);
8446                                 } else if (!strcmp (narg->field->name, "BestFitMapping")) {
8447                                         // best_fit_mapping = *(MonoBoolean*)mono_object_unbox (o);
8448                                 } else if (!strcmp (narg->field->name, "ThrowOnUnmappableChar")) {
8449                                         // throw_on_unmappable = *(MonoBoolean*)mono_object_unbox (o);
8450                                 } else {
8451                                         g_assert_not_reached ();
8452                                 }
8453                         }
8454
8455                         g_free (arginfo);
8456
8457                         memset (&piinfo, 0, sizeof (piinfo));
8458                         m.piinfo = &piinfo;
8459                         piinfo.piflags = (call_conv << 8) | (charset ? (charset - 1) * 2 : 1) | set_last_error;
8460
8461                         csig->call_convention = call_conv - 1;
8462                 }
8463
8464                 if (cinfo && !cinfo->cached)
8465                         mono_custom_attrs_free (cinfo);
8466         }
8467
8468         mono_marshal_emit_managed_wrapper (mb, invoke_sig, mspecs, &m, method, target_handle);
8469
8470         if (!target_handle) {
8471                 WrapperInfo *info;
8472
8473                 // FIXME: Associate it with the method+delegate_klass pair
8474                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8475                 info->d.native_to_managed.method = method;
8476                 info->d.native_to_managed.klass = delegate_klass;
8477
8478                 res = mono_mb_create_and_cache_full (cache, method,
8479                                                                                          mb, csig, sig->param_count + 16,
8480                                                                                          info, NULL);
8481         } else {
8482 #ifndef DISABLE_JIT
8483                 mb->dynamic = TRUE;
8484 #endif
8485                 res = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
8486         }
8487         mono_mb_free (mb);
8488
8489         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8490                 if (mspecs [i])
8491                         mono_metadata_free_marshal_spec (mspecs [i]);
8492         g_free (mspecs);
8493
8494         /* mono_method_print_code (res); */
8495
8496         return res;
8497 }
8498
8499 gpointer
8500 mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
8501 {
8502         MonoError error;
8503         MonoMethod *method;
8504         MonoMethodSignature *sig;
8505         MonoMethodBuilder *mb;
8506         int i, param_count;
8507
8508         g_assert (token);
8509
8510         method = mono_get_method_checked (image, token, NULL, NULL, &error);
8511         if (!method)
8512                 g_error ("Could not load vtfixup token 0x%x due to %s", token, mono_error_get_message (&error));
8513         g_assert (method);
8514
8515         if (type & (VTFIXUP_TYPE_FROM_UNMANAGED | VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN)) {
8516                 MonoMethodSignature *csig;
8517                 MonoMarshalSpec **mspecs;
8518                 EmitMarshalContext m;
8519
8520                 sig = mono_method_signature (method);
8521                 g_assert (!sig->hasthis);
8522
8523                 mspecs = g_new0 (MonoMarshalSpec*, sig->param_count + 1);
8524                 mono_method_get_marshal_info (method, mspecs);
8525
8526                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8527                 csig = mono_metadata_signature_dup_full (image, sig);
8528                 csig->hasthis = 0;
8529                 csig->pinvoke = 1;
8530
8531                 memset (&m, 0, sizeof (m));
8532                 m.mb = mb;
8533                 m.sig = sig;
8534                 m.piinfo = NULL;
8535                 m.retobj_var = 0;
8536                 m.csig = csig;
8537                 m.image = image;
8538
8539                 mono_marshal_set_callconv_from_modopt (method, csig);
8540
8541                 /* FIXME: Implement VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN. */
8542
8543                 mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, 0);
8544
8545 #ifndef DISABLE_JIT
8546                 mb->dynamic = TRUE;
8547 #endif
8548                 method = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
8549                 mono_mb_free (mb);
8550
8551                 for (i = sig->param_count; i >= 0; i--)
8552                         if (mspecs [i])
8553                                 mono_metadata_free_marshal_spec (mspecs [i]);
8554                 g_free (mspecs);
8555
8556                 gpointer compiled_ptr = mono_compile_method_checked (method, &error);
8557                 mono_error_assert_ok (&error);
8558                 return compiled_ptr;
8559         }
8560
8561         sig = mono_method_signature (method);
8562         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
8563
8564         param_count = sig->param_count + sig->hasthis;
8565 #ifndef DISABLE_JIT
8566         for (i = 0; i < param_count; i++)
8567                 mono_mb_emit_ldarg (mb, i);
8568
8569         if (type & VTFIXUP_TYPE_CALL_MOST_DERIVED)
8570                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
8571         else
8572                 mono_mb_emit_op (mb, CEE_CALL, method);
8573         mono_mb_emit_byte (mb, CEE_RET);
8574
8575         mb->dynamic = TRUE;
8576 #endif
8577
8578         method = mono_mb_create (mb, sig, param_count, NULL);
8579         mono_mb_free (mb);
8580
8581         gpointer compiled_ptr = mono_compile_method_checked (method, &error);
8582         mono_error_assert_ok (&error);
8583         return compiled_ptr;
8584 }
8585
8586 #ifndef DISABLE_JIT
8587
8588 /*
8589  * The code directly following this is the cache hit, value positive branch
8590  *
8591  * This function takes a new method builder with 0 locals and adds two locals
8592  * to create multiple out-branches and the fall through state of having the object
8593  * on the stack after a cache miss
8594  */
8595 static void
8596 generate_check_cache (int obj_arg_position, int class_arg_position, int cache_arg_position, // In-parameters
8597                                                                                         int *null_obj, int *cache_hit_neg, int *cache_hit_pos, // Out-parameters
8598                                                                                         MonoMethodBuilder *mb)
8599 {
8600         int cache_miss_pos;
8601
8602         /* allocate local 0 (pointer) obj_vtable */
8603         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8604         /* allocate local 1 (pointer) cached_vtable */
8605         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8606
8607         /*if (!obj)*/
8608         mono_mb_emit_ldarg (mb, obj_arg_position);
8609         *null_obj = mono_mb_emit_branch (mb, CEE_BRFALSE);
8610
8611         /*obj_vtable = obj->vtable;*/
8612         mono_mb_emit_ldarg (mb, obj_arg_position);
8613         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
8614         mono_mb_emit_byte (mb, CEE_LDIND_I);
8615         mono_mb_emit_stloc (mb, 0);
8616
8617         /* cached_vtable = *cache*/
8618         mono_mb_emit_ldarg (mb, cache_arg_position);
8619         mono_mb_emit_byte (mb, CEE_LDIND_I);
8620         mono_mb_emit_stloc (mb, 1);
8621
8622         mono_mb_emit_ldloc (mb, 1);
8623         mono_mb_emit_byte (mb, CEE_LDC_I4);
8624         mono_mb_emit_i4 (mb, ~0x1);
8625         mono_mb_emit_byte (mb, CEE_CONV_I);
8626         mono_mb_emit_byte (mb, CEE_AND);
8627         mono_mb_emit_ldloc (mb, 0);
8628         /*if ((cached_vtable & ~0x1)== obj_vtable)*/
8629         cache_miss_pos = mono_mb_emit_branch (mb, CEE_BNE_UN);
8630
8631         /*return (cached_vtable & 0x1) ? NULL : obj;*/
8632         mono_mb_emit_ldloc (mb, 1);
8633         mono_mb_emit_byte(mb, CEE_LDC_I4_1);
8634         mono_mb_emit_byte (mb, CEE_CONV_U);
8635         mono_mb_emit_byte (mb, CEE_AND);
8636         *cache_hit_neg = mono_mb_emit_branch (mb, CEE_BRTRUE);
8637         *cache_hit_pos = mono_mb_emit_branch (mb, CEE_BR);
8638
8639         // slow path
8640         mono_mb_patch_branch (mb, cache_miss_pos);
8641
8642         // if isinst
8643         mono_mb_emit_ldarg (mb, obj_arg_position);
8644         mono_mb_emit_ldarg (mb, class_arg_position);
8645         mono_mb_emit_ldarg (mb, cache_arg_position);
8646         mono_mb_emit_icall (mb, mono_marshal_isinst_with_cache);
8647 }
8648
8649 #endif /* DISABLE_JIT */
8650
8651 /*
8652  * This does the equivalent of mono_object_castclass_with_cache.
8653  */
8654 MonoMethod *
8655 mono_marshal_get_castclass_with_cache (void)
8656 {
8657         static MonoMethod *cached;
8658         MonoMethod *res;
8659         MonoMethodBuilder *mb;
8660         MonoMethodSignature *sig;
8661         int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos, invalid_cast_pos;
8662         WrapperInfo *info;
8663
8664         const int obj_arg_position = 0;
8665         const int class_arg_position = 1;
8666         const int cache_arg_position = 2;
8667
8668         if (cached)
8669                 return cached;
8670
8671         mb = mono_mb_new (mono_defaults.object_class, "__castclass_with_cache", MONO_WRAPPER_CASTCLASS);
8672         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8673         sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
8674         sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
8675         sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
8676         sig->ret = &mono_defaults.object_class->byval_arg;
8677         sig->pinvoke = 0;
8678
8679 #ifndef DISABLE_JIT
8680         generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
8681                                                                                                 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
8682         invalid_cast_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8683
8684         /*return obj;*/
8685         mono_mb_patch_branch (mb, positive_cache_hit_pos);
8686         mono_mb_emit_ldarg (mb, obj_arg_position);
8687         mono_mb_emit_byte (mb, CEE_RET);
8688
8689         /*fails*/
8690         mono_mb_patch_branch (mb, negative_cache_hit_pos);
8691         mono_mb_patch_branch (mb, invalid_cast_pos);
8692         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8693
8694         /*return null*/
8695         mono_mb_patch_branch (mb, return_null_pos);
8696         mono_mb_emit_byte (mb, CEE_LDNULL);
8697         mono_mb_emit_byte (mb, CEE_RET);
8698 #endif /* DISABLE_JIT */
8699
8700         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE);
8701         res = mono_mb_create (mb, sig, 8, info);
8702         STORE_STORE_FENCE;
8703
8704         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8705                 mono_free_method (res);
8706                 mono_metadata_free_method_signature (sig);
8707         }
8708         mono_mb_free (mb);
8709
8710         return cached;
8711 }
8712
8713 /* this is an icall */
8714 static MonoObject *
8715 mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *cache)
8716 {
8717         MonoError error;
8718         MonoObject *isinst = mono_object_isinst_checked (obj, klass, &error);
8719         if (mono_error_set_pending_exception (&error))
8720                 return NULL;
8721
8722 #ifndef DISABLE_REMOTING
8723         if (obj->vtable->klass == mono_defaults.transparent_proxy_class)
8724                 return isinst;
8725 #endif
8726
8727         uintptr_t cache_update = (uintptr_t)obj->vtable;
8728         if (!isinst)
8729                 cache_update = cache_update | 0x1;
8730
8731         *cache = cache_update;
8732
8733         return isinst;
8734 }
8735
8736 /*
8737  * This does the equivalent of mono_object_isinst_with_cache.
8738  */
8739 MonoMethod *
8740 mono_marshal_get_isinst_with_cache (void)
8741 {
8742         static MonoMethod *cached;
8743         MonoMethod *res;
8744         MonoMethodBuilder *mb;
8745         MonoMethodSignature *sig;
8746         int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos;
8747         WrapperInfo *info;
8748
8749         const int obj_arg_position = 0;
8750         const int class_arg_position = 1;
8751         const int cache_arg_position = 2;
8752
8753         if (cached)
8754                 return cached;
8755
8756         mb = mono_mb_new (mono_defaults.object_class, "__isinst_with_cache", MONO_WRAPPER_CASTCLASS);
8757         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8758         // The object
8759         sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
8760         // The class
8761         sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
8762         // The cache
8763         sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
8764         sig->ret = &mono_defaults.object_class->byval_arg;
8765         sig->pinvoke = 0;
8766
8767 #ifndef DISABLE_JIT
8768         generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
8769                 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
8770         // Return the object gotten via the slow path.
8771         mono_mb_emit_byte (mb, CEE_RET);
8772
8773         // return NULL;
8774         mono_mb_patch_branch (mb, negative_cache_hit_pos);
8775         mono_mb_patch_branch (mb, return_null_pos);
8776         mono_mb_emit_byte (mb, CEE_LDNULL);
8777         mono_mb_emit_byte (mb, CEE_RET);
8778
8779         // return obj
8780         mono_mb_patch_branch (mb, positive_cache_hit_pos);
8781         mono_mb_emit_ldarg (mb, obj_arg_position);
8782         mono_mb_emit_byte (mb, CEE_RET);
8783 #endif
8784
8785         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ISINST_WITH_CACHE);
8786         res = mono_mb_create (mb, sig, 8, info);
8787         STORE_STORE_FENCE;
8788
8789         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8790                 mono_free_method (res);
8791                 mono_metadata_free_method_signature (sig);
8792         }
8793         mono_mb_free (mb);
8794
8795         return cached;
8796 }
8797
8798 /*
8799  * mono_marshal_get_isinst:
8800  * @klass: the type of the field
8801  *
8802  * This method generates a function which can be used to check if an object is
8803  * an instance of the given type, icluding the case where the object is a proxy.
8804  * The generated function has the following signature:
8805  * MonoObject* __isinst_wrapper_ (MonoObject *obj)
8806  */
8807 MonoMethod *
8808 mono_marshal_get_isinst (MonoClass *klass)
8809 {
8810         static MonoMethodSignature *isint_sig = NULL;
8811         GHashTable *cache;
8812         MonoMethod *res;
8813         WrapperInfo *info;
8814         int pos_was_ok, pos_end;
8815 #ifndef DISABLE_REMOTING
8816         int pos_end2, pos_failed;
8817 #endif
8818         char *name;
8819         MonoMethodBuilder *mb;
8820
8821         cache = get_cache (&klass->image->isinst_cache, mono_aligned_addr_hash, NULL);
8822         if ((res = mono_marshal_find_in_cache (cache, klass)))
8823                 return res;
8824
8825         if (!isint_sig) {
8826                 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8827                 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
8828                 isint_sig->ret = &mono_defaults.object_class->byval_arg;
8829                 isint_sig->pinvoke = 0;
8830         }
8831         
8832         name = g_strdup_printf ("__isinst_wrapper_%s", klass->name); 
8833         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ISINST);
8834         g_free (name);
8835         
8836         mb->method->save_lmf = 1;
8837
8838 #ifndef DISABLE_JIT
8839         /* check if the object is a proxy that needs special cast */
8840         mono_mb_emit_ldarg (mb, 0);
8841         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8842         mono_mb_emit_op (mb, CEE_MONO_CISINST, klass);
8843
8844         /* The result of MONO_CISINST can be:
8845                 0) the type check succeeded
8846                 1) the type check did not succeed
8847                 2) a CanCastTo call is needed */
8848 #ifndef DISABLE_REMOTING
8849         mono_mb_emit_byte (mb, CEE_DUP);
8850         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8851
8852         mono_mb_emit_byte (mb, CEE_LDC_I4_2);
8853         pos_failed = mono_mb_emit_branch (mb, CEE_BNE_UN);
8854         
8855         /* get the real proxy from the transparent proxy*/
8856
8857         mono_mb_emit_ldarg (mb, 0);
8858         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8859         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8860         
8861         /* fail */
8862         
8863         mono_mb_patch_branch (mb, pos_failed);
8864         mono_mb_emit_byte (mb, CEE_LDNULL);
8865         pos_end2 = mono_mb_emit_branch (mb, CEE_BR);
8866         
8867         /* success */
8868         
8869         mono_mb_patch_branch (mb, pos_was_ok);
8870         mono_mb_emit_byte (mb, CEE_POP);
8871         mono_mb_emit_ldarg (mb, 0);
8872         
8873         /* the end */
8874         
8875         mono_mb_patch_branch (mb, pos_end);
8876         mono_mb_patch_branch (mb, pos_end2);
8877         mono_mb_emit_byte (mb, CEE_RET);
8878 #else
8879         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8880
8881         /* fail */
8882
8883         mono_mb_emit_byte (mb, CEE_LDNULL);
8884         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8885
8886         /* success */
8887
8888         mono_mb_patch_branch (mb, pos_was_ok);
8889         mono_mb_emit_ldarg (mb, 0);
8890
8891         /* the end */
8892
8893         mono_mb_patch_branch (mb, pos_end);
8894         mono_mb_emit_byte (mb, CEE_RET);
8895 #endif /* DISABLE_REMOTING */
8896 #endif /* DISABLE_JIT */
8897
8898         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8899         info->d.proxy.klass = klass;
8900         res = mono_mb_create_and_cache_full (cache, klass, mb, isint_sig, isint_sig->param_count + 16, info, NULL);
8901         mono_mb_free (mb);
8902
8903         return res;
8904 }
8905
8906 /*
8907  * mono_marshal_get_castclass:
8908  * @klass: the type of the field
8909  *
8910  * This method generates a function which can be used to cast an object to
8911  * an instance of the given type, icluding the case where the object is a proxy.
8912  * The generated function has the following signature:
8913  * MonoObject* __castclass_wrapper_ (MonoObject *obj)
8914  */
8915 MonoMethod *
8916 mono_marshal_get_castclass (MonoClass *klass)
8917 {
8918         static MonoMethodSignature *castclass_sig = NULL;
8919         GHashTable *cache;
8920         MonoMethod *res;
8921 #ifndef DISABLE_REMOTING
8922         int pos_was_ok, pos_was_ok2;
8923 #endif
8924         char *name;
8925         MonoMethodBuilder *mb;
8926         WrapperInfo *info;
8927
8928         cache = get_cache (&klass->image->castclass_cache, mono_aligned_addr_hash, NULL);
8929         if ((res = mono_marshal_find_in_cache (cache, klass)))
8930                 return res;
8931
8932         if (!castclass_sig) {
8933                 castclass_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8934                 castclass_sig->params [0] = &mono_defaults.object_class->byval_arg;
8935                 castclass_sig->ret = &mono_defaults.object_class->byval_arg;
8936                 castclass_sig->pinvoke = 0;
8937         }
8938         
8939         name = g_strdup_printf ("__castclass_wrapper_%s", klass->name); 
8940         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_CASTCLASS);
8941         g_free (name);
8942         
8943         mb->method->save_lmf = 1;
8944
8945 #ifndef DISABLE_JIT
8946         /* check if the object is a proxy that needs special cast */
8947         mono_mb_emit_ldarg (mb, 0);
8948         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8949         mono_mb_emit_op (mb, CEE_MONO_CCASTCLASS, klass);
8950
8951         /* The result of MONO_CCASTCLASS can be:
8952                 0) the cast is valid
8953                 1) cast of unknown proxy type
8954                 or an exception if the cast is is invalid
8955         */
8956 #ifndef DISABLE_REMOTING
8957         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8958
8959         /* get the real proxy from the transparent proxy*/
8960
8961         mono_mb_emit_ldarg (mb, 0);
8962         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8963         pos_was_ok2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
8964         
8965         /* fail */
8966         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8967         
8968         /* success */
8969         mono_mb_patch_branch (mb, pos_was_ok);
8970         mono_mb_patch_branch (mb, pos_was_ok2);
8971 #else
8972         /* MONO_CCASTCLASS leaves an int in the stack with the result, pop it. */
8973         mono_mb_emit_byte (mb, CEE_POP);
8974 #endif /* DISABLE_REMOTING */
8975
8976         mono_mb_emit_ldarg (mb, 0);
8977         
8978         /* the end */
8979         mono_mb_emit_byte (mb, CEE_RET);
8980 #endif /* DISABLE_JIT */
8981
8982         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8983
8984         res = mono_mb_create_and_cache_full (cache, klass, mb, castclass_sig, castclass_sig->param_count + 16,
8985                                                                                  info, NULL);
8986         mono_mb_free (mb);
8987
8988         return res;
8989 }
8990
8991 /**
8992  * mono_marshal_get_struct_to_ptr:
8993  * @klass:
8994  *
8995  * generates IL code for StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)
8996  */
8997 MonoMethod *
8998 mono_marshal_get_struct_to_ptr (MonoClass *klass)
8999 {
9000         MonoMethodBuilder *mb;
9001         static MonoMethod *stoptr = NULL;
9002         MonoMethod *res;
9003         WrapperInfo *info;
9004
9005         g_assert (klass != NULL);
9006
9007         mono_marshal_load_type_info (klass);
9008
9009         if (klass->marshal_info->str_to_ptr)
9010                 return klass->marshal_info->str_to_ptr;
9011
9012         if (!stoptr) 
9013                 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
9014         g_assert (stoptr);
9015
9016         mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
9017
9018 #ifndef DISABLE_JIT
9019         if (klass->blittable) {
9020                 mono_mb_emit_byte (mb, CEE_LDARG_1);
9021                 mono_mb_emit_byte (mb, CEE_LDARG_0);
9022                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9023                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
9024                 mono_mb_emit_byte (mb, CEE_PREFIX1);
9025                 mono_mb_emit_byte (mb, CEE_CPBLK);
9026         } else {
9027
9028                 /* allocate local 0 (pointer) src_ptr */
9029                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9030                 /* allocate local 1 (pointer) dst_ptr */
9031                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9032                 /* allocate local 2 (boolean) delete_old */
9033                 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9034                 mono_mb_emit_byte (mb, CEE_LDARG_2);
9035                 mono_mb_emit_stloc (mb, 2);
9036
9037                 /* initialize src_ptr to point to the start of object data */
9038                 mono_mb_emit_byte (mb, CEE_LDARG_0);
9039                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9040                 mono_mb_emit_stloc (mb, 0);
9041
9042                 /* initialize dst_ptr */
9043                 mono_mb_emit_byte (mb, CEE_LDARG_1);
9044                 mono_mb_emit_stloc (mb, 1);
9045
9046                 emit_struct_conv (mb, klass, FALSE);
9047         }
9048
9049         mono_mb_emit_byte (mb, CEE_RET);
9050 #endif
9051         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRUCTURE_TO_PTR);
9052         res = mono_mb_create (mb, mono_signature_no_pinvoke (stoptr), 0, info);
9053         mono_mb_free (mb);
9054
9055         mono_marshal_lock ();
9056         if (!klass->marshal_info->str_to_ptr)
9057                 klass->marshal_info->str_to_ptr = res;
9058         else
9059                 res = klass->marshal_info->str_to_ptr;
9060         mono_marshal_unlock ();
9061         return res;
9062 }
9063
9064 /**
9065  * mono_marshal_get_ptr_to_struct:
9066  * @klass:
9067  *
9068  * generates IL code for PtrToStructure (IntPtr src, object structure)
9069  */
9070 MonoMethod *
9071 mono_marshal_get_ptr_to_struct (MonoClass *klass)
9072 {
9073         MonoMethodBuilder *mb;
9074         static MonoMethodSignature *ptostr = NULL;
9075         MonoMethod *res;
9076         WrapperInfo *info;
9077
9078         g_assert (klass != NULL);
9079
9080         mono_marshal_load_type_info (klass);
9081
9082         if (klass->marshal_info->ptr_to_str)
9083                 return klass->marshal_info->ptr_to_str;
9084
9085         if (!ptostr) {
9086                 MonoMethodSignature *sig;
9087
9088                 /* Create the signature corresponding to
9089                           static void PtrToStructure (IntPtr ptr, object structure);
9090                    defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
9091                 sig = mono_create_icall_signature ("void ptr object");
9092                 sig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
9093                 sig->pinvoke = 0;
9094                 mono_memory_barrier ();
9095                 ptostr = sig;
9096         }
9097
9098         mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
9099
9100 #ifndef DISABLE_JIT
9101         if (klass->blittable) {
9102                 mono_mb_emit_byte (mb, CEE_LDARG_1);
9103                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9104                 mono_mb_emit_byte (mb, CEE_LDARG_0);
9105                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
9106                 mono_mb_emit_byte (mb, CEE_PREFIX1);
9107                 mono_mb_emit_byte (mb, CEE_CPBLK);
9108         } else {
9109
9110                 /* allocate local 0 (pointer) src_ptr */
9111                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9112                 /* allocate local 1 (pointer) dst_ptr */
9113                 mono_mb_add_local (mb, &klass->this_arg);
9114                 
9115                 /* initialize src_ptr to point to the start of object data */
9116                 mono_mb_emit_byte (mb, CEE_LDARG_0);
9117                 mono_mb_emit_stloc (mb, 0);
9118
9119                 /* initialize dst_ptr */
9120                 mono_mb_emit_byte (mb, CEE_LDARG_1);
9121                 mono_mb_emit_op (mb, CEE_UNBOX, klass);
9122                 mono_mb_emit_stloc (mb, 1);
9123
9124                 emit_struct_conv (mb, klass, TRUE);
9125         }
9126
9127         mono_mb_emit_byte (mb, CEE_RET);
9128 #endif
9129         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PTR_TO_STRUCTURE);
9130         res = mono_mb_create (mb, ptostr, 0, info);
9131         mono_mb_free (mb);
9132
9133         mono_marshal_lock ();
9134         if (!klass->marshal_info->ptr_to_str)
9135                 klass->marshal_info->ptr_to_str = res;
9136         else
9137                 res = klass->marshal_info->ptr_to_str;
9138         mono_marshal_unlock ();
9139         return res;
9140 }
9141
9142 /*
9143  * Return a dummy wrapper for METHOD which is called by synchronized wrappers.
9144  * This is used to avoid infinite recursion since it is hard to determine where to
9145  * replace a method with its synchronized wrapper, and where not.
9146  * The runtime should execute METHOD instead of the wrapper.
9147  */
9148 MonoMethod *
9149 mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
9150 {
9151         MonoMethodBuilder *mb;
9152         WrapperInfo *info;
9153         MonoMethodSignature *sig;
9154         MonoMethod *res;
9155         MonoGenericContext *ctx = NULL;
9156         MonoGenericContainer *container = NULL;
9157
9158         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9159                 ctx = &((MonoMethodInflated*)method)->context;
9160                 method = ((MonoMethodInflated*)method)->declaring;
9161                 container = mono_method_get_generic_container (method);
9162                 if (!container)
9163                         container = method->klass->generic_container;
9164                 g_assert (container);
9165         }
9166
9167         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
9168 #ifndef DISABLE_JIT
9169         mono_mb_emit_exception_full (mb, "System", "ExecutionEngineException", "Shouldn't be called.");
9170         mono_mb_emit_byte (mb, CEE_RET);
9171 #endif
9172         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9173
9174         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_SYNCHRONIZED_INNER);
9175         info->d.synchronized_inner.method = method;
9176         res = mono_mb_create (mb, sig, 0, info);
9177         mono_mb_free (mb);
9178         if (ctx) {
9179                 MonoError error;
9180                 res = mono_class_inflate_generic_method_checked (res, ctx, &error);
9181                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9182         }
9183         return res;
9184 }
9185
9186 /*
9187  * generates IL code for the synchronized wrapper: the generated method
9188  * calls METHOD while locking 'this' or the parent type.
9189  */
9190 MonoMethod *
9191 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
9192 {
9193         static MonoMethod *enter_method, *exit_method, *gettypefromhandle_method;
9194         MonoMethodSignature *sig;
9195         MonoExceptionClause *clause;
9196         MonoMethodBuilder *mb;
9197         MonoMethod *res;
9198         GHashTable *cache;
9199         WrapperInfo *info;
9200         int i, pos, pos2, this_local, taken_local, ret_local = 0;
9201         MonoGenericContext *ctx = NULL;
9202         MonoMethod *orig_method = NULL;
9203         MonoGenericContainer *container = NULL;
9204
9205         g_assert (method);
9206
9207         if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
9208                 return method;
9209
9210         /* FIXME: Support generic methods too */
9211         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9212                 orig_method = method;
9213                 ctx = &((MonoMethodInflated*)method)->context;
9214                 method = ((MonoMethodInflated*)method)->declaring;
9215                 container = mono_method_get_generic_container (method);
9216                 if (!container)
9217                         container = method->klass->generic_container;
9218                 g_assert (container);
9219         }
9220
9221         /*
9222          * Check cache
9223          */
9224         if (ctx) {
9225                 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9226                 res = check_generic_wrapper_cache (cache, orig_method, orig_method, method);
9227                 if (res)
9228                         return res;
9229         } else {
9230                 cache = get_cache (&method->klass->image->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9231                 if ((res = mono_marshal_find_in_cache (cache, method)))
9232                         return res;
9233         }
9234
9235         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9236         sig->pinvoke = 0;
9237
9238         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
9239
9240         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9241         info->d.synchronized.method = method;
9242
9243 #ifndef DISABLE_JIT
9244         mb->skip_visibility = 1;
9245         /* result */
9246         if (!MONO_TYPE_IS_VOID (sig->ret))
9247                 ret_local = mono_mb_add_local (mb, sig->ret);
9248 #endif
9249
9250         if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
9251                 mono_class_set_failure (method->klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
9252 #ifndef DISABLE_JIT
9253                 /* This will throw the type load exception when the wrapper is compiled */
9254                 mono_mb_emit_byte (mb, CEE_LDNULL);
9255                 mono_mb_emit_op (mb, CEE_ISINST, method->klass);
9256                 mono_mb_emit_byte (mb, CEE_POP);
9257
9258                 if (!MONO_TYPE_IS_VOID (sig->ret))
9259                         mono_mb_emit_ldloc (mb, ret_local);
9260                 mono_mb_emit_byte (mb, CEE_RET);
9261 #endif
9262
9263                 res = mono_mb_create_and_cache_full (cache, method,
9264                                                                                          mb, sig, sig->param_count + 16, info, NULL);
9265                 mono_mb_free (mb);
9266
9267                 return res;
9268         }
9269
9270 #ifndef DISABLE_JIT
9271         /* this */
9272         this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
9273         taken_local = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9274
9275         clause = (MonoExceptionClause *)mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
9276         clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
9277 #endif
9278
9279         mono_marshal_lock ();
9280
9281         if (!enter_method) {
9282                 MonoMethodDesc *desc;
9283
9284                 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
9285                 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9286                 g_assert (enter_method);
9287                 mono_method_desc_free (desc);
9288
9289                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
9290                 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9291                 g_assert (exit_method);
9292                 mono_method_desc_free (desc);
9293
9294                 desc = mono_method_desc_new ("Type:GetTypeFromHandle", FALSE);
9295                 gettypefromhandle_method = mono_method_desc_search_in_class (desc, mono_defaults.systemtype_class);
9296                 g_assert (gettypefromhandle_method);
9297                 mono_method_desc_free (desc);
9298         }
9299
9300         mono_marshal_unlock ();
9301
9302 #ifndef DISABLE_JIT
9303         /* Push this or the type object */
9304         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
9305                 /* We have special handling for this in the JIT */
9306                 int index = mono_mb_add_data (mb, method->klass);
9307                 mono_mb_add_data (mb, mono_defaults.typehandle_class);
9308                 mono_mb_emit_byte (mb, CEE_LDTOKEN);
9309                 mono_mb_emit_i4 (mb, index);
9310
9311                 mono_mb_emit_managed_call (mb, gettypefromhandle_method, NULL);
9312         }
9313         else
9314                 mono_mb_emit_ldarg (mb, 0);
9315         mono_mb_emit_stloc (mb, this_local);
9316
9317         /* Call Monitor::Enter() */
9318         mono_mb_emit_ldloc (mb, this_local);
9319         mono_mb_emit_ldloc_addr (mb, taken_local);
9320         mono_mb_emit_managed_call (mb, enter_method, NULL);
9321
9322         clause->try_offset = mono_mb_get_label (mb);
9323
9324         /* Call the method */
9325         if (sig->hasthis)
9326                 mono_mb_emit_ldarg (mb, 0);
9327         for (i = 0; i < sig->param_count; i++)
9328                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
9329
9330         if (ctx) {
9331                 MonoError error;
9332                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
9333                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9334         } else {
9335                 mono_mb_emit_managed_call (mb, method, NULL);
9336         }
9337
9338         if (!MONO_TYPE_IS_VOID (sig->ret))
9339                 mono_mb_emit_stloc (mb, ret_local);
9340
9341         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
9342
9343         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
9344         clause->handler_offset = mono_mb_get_label (mb);
9345
9346         /* Call Monitor::Exit() if needed */
9347         mono_mb_emit_ldloc (mb, taken_local);
9348         pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9349         mono_mb_emit_ldloc (mb, this_local);
9350         mono_mb_emit_managed_call (mb, exit_method, NULL);
9351         mono_mb_patch_branch (mb, pos2);
9352         mono_mb_emit_byte (mb, CEE_ENDFINALLY);
9353
9354         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
9355
9356         mono_mb_patch_branch (mb, pos);
9357         if (!MONO_TYPE_IS_VOID (sig->ret))
9358                 mono_mb_emit_ldloc (mb, ret_local);
9359         mono_mb_emit_byte (mb, CEE_RET);
9360
9361         mono_mb_set_clauses (mb, 1, clause);
9362 #endif
9363
9364         if (ctx) {
9365                 MonoMethod *def;
9366                 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
9367                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
9368         } else {
9369                 res = mono_mb_create_and_cache_full (cache, method,
9370                                                                                          mb, sig, sig->param_count + 16, info, NULL);
9371         }
9372         mono_mb_free (mb);
9373
9374         return res;     
9375 }
9376
9377
9378 /*
9379  * the returned method calls 'method' unboxing the this argument
9380  */
9381 MonoMethod *
9382 mono_marshal_get_unbox_wrapper (MonoMethod *method)
9383 {
9384         MonoMethodSignature *sig = mono_method_signature (method);
9385         int i;
9386         MonoMethodBuilder *mb;
9387         MonoMethod *res;
9388         GHashTable *cache;
9389         WrapperInfo *info;
9390
9391         cache = get_cache (&mono_method_get_wrapper_cache (method)->unbox_wrapper_cache, mono_aligned_addr_hash, NULL);
9392
9393         if ((res = mono_marshal_find_in_cache (cache, method)))
9394                 return res;
9395
9396         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
9397
9398         g_assert (sig->hasthis);
9399         
9400 #ifndef DISABLE_JIT
9401         mono_mb_emit_ldarg (mb, 0); 
9402         mono_mb_emit_icon (mb, sizeof (MonoObject));
9403         mono_mb_emit_byte (mb, CEE_ADD);
9404         for (i = 0; i < sig->param_count; ++i)
9405                 mono_mb_emit_ldarg (mb, i + 1);
9406         mono_mb_emit_managed_call (mb, method, NULL);
9407         mono_mb_emit_byte (mb, CEE_RET);
9408 #endif
9409
9410         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9411         info->d.unbox.method = method;
9412
9413         res = mono_mb_create_and_cache_full (cache, method,
9414                                                                                  mb, sig, sig->param_count + 16, info, NULL);
9415         mono_mb_free (mb);
9416
9417         /* mono_method_print_code (res); */
9418
9419         return res;     
9420 }
9421
9422 enum {
9423         STELEMREF_OBJECT, /*no check at all*/
9424         STELEMREF_SEALED_CLASS, /*check vtable->klass->element_type */
9425         STELEMREF_CLASS, /*only the klass->parents check*/
9426         STELEMREF_INTERFACE, /*interfaces without variant generic arguments. */
9427         STELEMREF_COMPLEX, /*arrays, MBR or types with variant generic args - go straight to icalls*/
9428         STELEMREF_KIND_COUNT
9429 };
9430
9431 static const char *strelemref_wrapper_name[] = {
9432         "object", "sealed_class", "class", "interface", "complex"
9433 };
9434
9435 static gboolean
9436 is_monomorphic_array (MonoClass *klass)
9437 {
9438         MonoClass *element_class;
9439         if (klass->rank != 1)
9440                 return FALSE;
9441
9442         element_class = klass->element_class;
9443         return (element_class->flags & TYPE_ATTRIBUTE_SEALED) || element_class->valuetype;
9444 }
9445
9446 static int
9447 get_virtual_stelemref_kind (MonoClass *element_class)
9448 {
9449         if (element_class == mono_defaults.object_class)
9450                 return STELEMREF_OBJECT;
9451         if (is_monomorphic_array (element_class))
9452                 return STELEMREF_SEALED_CLASS;
9453         /* Compressed interface bitmaps require code that is quite complex, so don't optimize for it. */
9454         if (MONO_CLASS_IS_INTERFACE (element_class) && !mono_class_has_variant_generic_params (element_class))
9455 #ifdef COMPRESSED_INTERFACE_BITMAP
9456                 return STELEMREF_COMPLEX;
9457 #else
9458                 return STELEMREF_INTERFACE;
9459 #endif
9460         /*Arrays are sealed but are covariant on their element type, We can't use any of the fast paths.*/
9461         if (mono_class_is_marshalbyref (element_class) || element_class->rank || mono_class_has_variant_generic_params (element_class))
9462                 return STELEMREF_COMPLEX;
9463         if (element_class->flags & TYPE_ATTRIBUTE_SEALED)
9464                 return STELEMREF_SEALED_CLASS;
9465         return STELEMREF_CLASS;
9466 }
9467
9468 #ifndef DISABLE_JIT
9469
9470 static void
9471 load_array_element_address (MonoMethodBuilder *mb)
9472 {
9473         mono_mb_emit_ldarg (mb, 0);
9474         mono_mb_emit_ldarg (mb, 1);
9475         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9476 }
9477
9478 static void
9479 load_array_class (MonoMethodBuilder *mb, int aklass)
9480 {
9481         mono_mb_emit_ldarg (mb, 0);
9482         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9483         mono_mb_emit_byte (mb, CEE_LDIND_I);
9484         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9485         mono_mb_emit_byte (mb, CEE_LDIND_I);
9486         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9487         mono_mb_emit_byte (mb, CEE_LDIND_I);
9488         mono_mb_emit_stloc (mb, aklass);
9489 }
9490
9491 static void
9492 load_value_class (MonoMethodBuilder *mb, int vklass)
9493 {
9494         mono_mb_emit_ldarg (mb, 2);
9495         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9496         mono_mb_emit_byte (mb, CEE_LDIND_I);
9497         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9498         mono_mb_emit_byte (mb, CEE_LDIND_I);
9499         mono_mb_emit_stloc (mb, vklass);
9500 }
9501 #endif
9502
9503 #if 0
9504 static void
9505 record_slot_vstore (MonoObject *array, size_t index, MonoObject *value)
9506 {
9507         char *name = mono_type_get_full_name (array->vtable->klass->element_class);
9508         printf ("slow vstore of %s\n", name);
9509         g_free (name);
9510 }
9511 #endif
9512
9513 /*
9514  * TODO:
9515  *      - Separate simple interfaces from variant interfaces or mbr types. This way we can avoid the icall for them.
9516  *      - Emit a (new) mono bytecode that produces OP_COND_EXC_NE_UN to raise ArrayTypeMismatch
9517  *      - Maybe mve some MonoClass field into the vtable to reduce the number of loads
9518  *      - Add a case for arrays of arrays.
9519  */
9520 static MonoMethod*
9521 get_virtual_stelemref_wrapper (int kind)
9522 {
9523         static MonoMethod *cached_methods [STELEMREF_KIND_COUNT] = { NULL }; /*object iface sealed regular*/
9524         static MonoMethodSignature *signature;
9525         MonoMethodBuilder *mb;
9526         MonoMethod *res;
9527         char *name;
9528         const char *param_names [16];
9529         guint32 b1, b2, b3;
9530         int aklass, vklass, vtable, uiid;
9531         int array_slot_addr;
9532         WrapperInfo *info;
9533
9534         if (cached_methods [kind])
9535                 return cached_methods [kind];
9536
9537         name = g_strdup_printf ("virt_stelemref_%s", strelemref_wrapper_name [kind]);
9538         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STELEMREF);
9539         g_free (name);
9540
9541         if (!signature) {
9542                 MonoMethodSignature *sig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
9543
9544                 /* void this::stelemref (size_t idx, void* value) */
9545                 sig->ret = &mono_defaults.void_class->byval_arg;
9546                 sig->hasthis = TRUE;
9547                 sig->params [0] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9548                 sig->params [1] = &mono_defaults.object_class->byval_arg;
9549                 signature = sig;
9550         }
9551
9552 #ifndef DISABLE_JIT
9553         param_names [0] = "index";
9554         param_names [1] = "value";
9555         mono_mb_set_param_names (mb, param_names);
9556
9557         /*For now simply call plain old stelemref*/
9558         switch (kind) {
9559         case STELEMREF_OBJECT:
9560                 /* ldelema (implicit bound check) */
9561                 load_array_element_address (mb);
9562                 /* do_store */
9563                 mono_mb_emit_ldarg (mb, 2);
9564                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9565                 mono_mb_emit_byte (mb, CEE_RET);
9566                 break;
9567
9568         case STELEMREF_COMPLEX:
9569                 /*
9570                 <ldelema (bound check)>
9571                 if (!value)
9572                         goto store;
9573                 if (!mono_object_isinst (value, aklass))
9574                         goto do_exception;
9575
9576                  do_store:
9577                          *array_slot_addr = value;
9578
9579                 do_exception:
9580                         throw new ArrayTypeMismatchException ();
9581                 */
9582
9583                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9584                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9585
9586 #if 0
9587                 {
9588                         /*Use this to debug/record stores that are going thru the slow path*/
9589                         MonoMethodSignature *csig;
9590                         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9591                         csig->ret = &mono_defaults.void_class->byval_arg;
9592                         csig->params [0] = &mono_defaults.object_class->byval_arg;
9593                         csig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9594                         csig->params [2] = &mono_defaults.object_class->byval_arg;
9595                         mono_mb_emit_ldarg (mb, 0);
9596                         mono_mb_emit_ldarg (mb, 1);
9597                         mono_mb_emit_ldarg (mb, 2);
9598                         mono_mb_emit_native_call (mb, csig, record_slot_vstore);
9599                 }
9600 #endif
9601
9602                 /* ldelema (implicit bound check) */
9603                 load_array_element_address (mb);
9604                 mono_mb_emit_stloc (mb, array_slot_addr);
9605
9606                 /* if (!value) goto do_store */
9607                 mono_mb_emit_ldarg (mb, 2);
9608                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9609
9610                 /* aklass = array->vtable->klass->element_class */
9611                 load_array_class (mb, aklass);
9612
9613                 /*if (mono_object_isinst (value, aklass)) */
9614                 mono_mb_emit_ldarg (mb, 2);
9615                 mono_mb_emit_ldloc (mb, aklass);
9616                 mono_mb_emit_icall (mb, mono_object_isinst_icall);
9617                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9618
9619                 /* do_store: */
9620                 mono_mb_patch_branch (mb, b1);
9621                 mono_mb_emit_ldloc (mb, array_slot_addr);
9622                 mono_mb_emit_ldarg (mb, 2);
9623                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9624                 mono_mb_emit_byte (mb, CEE_RET);
9625
9626                 /* do_exception: */
9627                 mono_mb_patch_branch (mb, b2);
9628
9629                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9630                 break;
9631
9632         case STELEMREF_SEALED_CLASS:
9633                 /*
9634                 <ldelema (bound check)>
9635                 if (!value)
9636                         goto store;
9637
9638                 aklass = array->vtable->klass->element_class;
9639                 vklass = value->vtable->klass;
9640
9641                 if (vklass != aklass)
9642                         goto do_exception;
9643
9644                 do_store:
9645                          *array_slot_addr = value;
9646
9647                 do_exception:
9648                         throw new ArrayTypeMismatchException ();
9649                 */
9650                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9651                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9652                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9653
9654
9655                 /* ldelema (implicit bound check) */
9656                 load_array_element_address (mb);
9657                 mono_mb_emit_stloc (mb, array_slot_addr);
9658
9659                 /* if (!value) goto do_store */
9660                 mono_mb_emit_ldarg (mb, 2);
9661                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9662
9663                 /* aklass = array->vtable->klass->element_class */
9664                 load_array_class (mb, aklass);
9665
9666                 /* vklass = value->vtable->klass */
9667                 load_value_class (mb, vklass);
9668
9669                 /*if (vklass != aklass) goto do_exception; */
9670                 mono_mb_emit_ldloc (mb, aklass);
9671                 mono_mb_emit_ldloc (mb, vklass);
9672                 b2 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9673
9674                 /* do_store: */
9675                 mono_mb_patch_branch (mb, b1);
9676                 mono_mb_emit_ldloc (mb, array_slot_addr);
9677                 mono_mb_emit_ldarg (mb, 2);
9678                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9679                 mono_mb_emit_byte (mb, CEE_RET);
9680
9681                 /* do_exception: */
9682                 mono_mb_patch_branch (mb, b2);
9683                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9684                 break;
9685
9686         case STELEMREF_CLASS:
9687                 /*
9688                 the method:
9689                 <ldelema (bound check)>
9690                 if (!value)
9691                         goto do_store;
9692
9693                 aklass = array->vtable->klass->element_class;
9694                 vklass = value->vtable->klass;
9695
9696                 if (vklass->idepth < aklass->idepth)
9697                         goto do_exception;
9698
9699                 if (vklass->supertypes [aklass->idepth - 1] != aklass)
9700                         goto do_exception;
9701
9702                 do_store:
9703                         *array_slot_addr = value;
9704                         return;
9705
9706                 long:
9707                         throw new ArrayTypeMismatchException ();
9708                 */
9709                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9710                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9711                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9712
9713                 /* ldelema (implicit bound check) */
9714                 load_array_element_address (mb);
9715                 mono_mb_emit_stloc (mb, array_slot_addr);
9716
9717                 /* if (!value) goto do_store */
9718                 mono_mb_emit_ldarg (mb, 2);
9719                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9720
9721                 /* aklass = array->vtable->klass->element_class */
9722                 load_array_class (mb, aklass);
9723
9724                 /* vklass = value->vtable->klass */
9725                 load_value_class (mb, vklass);
9726
9727                 /*if (mono_object_isinst (value, aklass)) */
9728                 mono_mb_emit_ldarg (mb, 2);
9729                 mono_mb_emit_ldloc (mb, aklass);
9730                 mono_mb_emit_icall (mb, mono_object_isinst_icall);
9731                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9732
9733                 /* if (vklass->idepth < aklass->idepth) goto failue */
9734                 mono_mb_emit_ldloc (mb, vklass);
9735                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9736                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9737
9738                 mono_mb_emit_ldloc (mb, aklass);
9739                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9740                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9741
9742                 b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
9743
9744                 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
9745                 mono_mb_emit_ldloc (mb, vklass);
9746                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
9747                 mono_mb_emit_byte (mb, CEE_LDIND_I);
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                 mono_mb_emit_icon (mb, 1);
9753                 mono_mb_emit_byte (mb, CEE_SUB);
9754                 mono_mb_emit_icon (mb, sizeof (void*));
9755                 mono_mb_emit_byte (mb, CEE_MUL);
9756                 mono_mb_emit_byte (mb, CEE_ADD);
9757                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9758
9759                 mono_mb_emit_ldloc (mb, aklass);
9760                 b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9761
9762                 /* do_store: */
9763                 mono_mb_patch_branch (mb, b1);
9764                 mono_mb_emit_ldloc (mb, array_slot_addr);
9765                 mono_mb_emit_ldarg (mb, 2);
9766                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9767                 mono_mb_emit_byte (mb, CEE_RET);
9768
9769                 /* do_exception: */
9770                 mono_mb_patch_branch (mb, b2);
9771                 mono_mb_patch_branch (mb, b3);
9772
9773                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9774                 break;
9775
9776         case STELEMREF_INTERFACE:
9777                 /*Mono *klass;
9778                 MonoVTable *vt;
9779                 unsigned uiid;
9780                 if (value == NULL)
9781                         goto store;
9782
9783                 klass = array->obj.vtable->klass->element_class;
9784                 vt = value->vtable;
9785                 uiid = klass->interface_id;
9786                 if (uiid > vt->max_interface_id)
9787                         goto exception;
9788                 if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7))))
9789                         goto exception;
9790                 store:
9791                         mono_array_setref (array, index, value);
9792                         return;
9793                 exception:
9794                         mono_raise_exception (mono_get_exception_array_type_mismatch ());*/
9795
9796                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9797                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9798                 vtable = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9799                 uiid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9800
9801                 /* ldelema (implicit bound check) */
9802                 load_array_element_address (mb);
9803                 mono_mb_emit_stloc (mb, array_slot_addr);
9804
9805                 /* if (!value) goto do_store */
9806                 mono_mb_emit_ldarg (mb, 2);
9807                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9808
9809                 /* klass = array->vtable->klass->element_class */
9810                 load_array_class (mb, aklass);
9811
9812                 /* vt = value->vtable */
9813                 mono_mb_emit_ldarg (mb, 2);
9814                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9815                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9816                 mono_mb_emit_stloc (mb, vtable);
9817
9818                 /* uiid = klass->interface_id; */
9819                 mono_mb_emit_ldloc (mb, aklass);
9820                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, interface_id));
9821                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9822                 mono_mb_emit_stloc (mb, uiid);
9823
9824                 /*if (uiid > vt->max_interface_id)*/
9825                 mono_mb_emit_ldloc (mb, uiid);
9826                 mono_mb_emit_ldloc (mb, vtable);
9827                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, max_interface_id));
9828                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9829                 b2 = mono_mb_emit_branch (mb, CEE_BGT_UN);
9830
9831                 /* if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7)))) */
9832
9833                 /*vt->interface_bitmap*/
9834                 mono_mb_emit_ldloc (mb, vtable);
9835                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, interface_bitmap));
9836                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9837
9838                 /*uiid >> 3*/
9839                 mono_mb_emit_ldloc (mb, uiid);
9840                 mono_mb_emit_icon (mb, 3);
9841                 mono_mb_emit_byte (mb, CEE_SHR_UN);
9842
9843                 /*vt->interface_bitmap [(uiid) >> 3]*/
9844                 mono_mb_emit_byte (mb, CEE_ADD); /*interface_bitmap is a guint8 array*/
9845                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
9846
9847                 /*(1 << ((uiid)&7)))*/
9848                 mono_mb_emit_icon (mb, 1);
9849                 mono_mb_emit_ldloc (mb, uiid);
9850                 mono_mb_emit_icon (mb, 7);
9851                 mono_mb_emit_byte (mb, CEE_AND);
9852                 mono_mb_emit_byte (mb, CEE_SHL);
9853
9854                 /*bitwise and the whole thing*/
9855                 mono_mb_emit_byte (mb, CEE_AND);
9856                 b3 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9857
9858                 /* do_store: */
9859                 mono_mb_patch_branch (mb, b1);
9860                 mono_mb_emit_ldloc (mb, array_slot_addr);
9861                 mono_mb_emit_ldarg (mb, 2);
9862                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9863                 mono_mb_emit_byte (mb, CEE_RET);
9864
9865                 /* do_exception: */
9866                 mono_mb_patch_branch (mb, b2);
9867                 mono_mb_patch_branch (mb, b3);
9868                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9869                 break;
9870
9871         default:
9872                 mono_mb_emit_ldarg (mb, 0);
9873                 mono_mb_emit_ldarg (mb, 1);
9874                 mono_mb_emit_ldarg (mb, 2);
9875                 mono_mb_emit_managed_call (mb, mono_marshal_get_stelemref (), NULL);
9876                 mono_mb_emit_byte (mb, CEE_RET);
9877                 g_assert (0);
9878         }
9879 #endif /* DISABLE_JIT */
9880         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_VIRTUAL_STELEMREF);
9881         info->d.virtual_stelemref.kind = kind;
9882         res = mono_mb_create (mb, signature, 4, info);
9883         res->flags |= METHOD_ATTRIBUTE_VIRTUAL;
9884
9885         mono_marshal_lock ();
9886         if (!cached_methods [kind]) {
9887                 cached_methods [kind] = res;
9888                 mono_marshal_unlock ();
9889         } else {
9890                 mono_marshal_unlock ();
9891                 mono_free_method (res);
9892         }
9893
9894         mono_mb_free (mb);
9895         return cached_methods [kind];
9896 }
9897
9898 MonoMethod*
9899 mono_marshal_get_virtual_stelemref (MonoClass *array_class)
9900 {
9901         int kind;
9902
9903         g_assert (array_class->rank == 1);
9904         kind = get_virtual_stelemref_kind (array_class->element_class);
9905
9906         return get_virtual_stelemref_wrapper (kind);
9907 }
9908
9909 MonoMethod**
9910 mono_marshal_get_virtual_stelemref_wrappers (int *nwrappers)
9911 {
9912         MonoMethod **res;
9913         int i;
9914
9915         *nwrappers = STELEMREF_KIND_COUNT;
9916         res = (MonoMethod **)g_malloc0 (STELEMREF_KIND_COUNT * sizeof (MonoMethod*));
9917         for (i = 0; i < STELEMREF_KIND_COUNT; ++i)
9918                 res [i] = get_virtual_stelemref_wrapper (i);
9919         return res;
9920 }
9921
9922 MonoMethod*
9923 mono_marshal_get_stelemref (void)
9924 {
9925         static MonoMethod* ret = NULL;
9926         MonoMethodSignature *sig;
9927         MonoMethodBuilder *mb;
9928         WrapperInfo *info;
9929         
9930         guint32 b1, b2, b3, b4;
9931         guint32 copy_pos;
9932         int aklass, vklass;
9933         int array_slot_addr;
9934         
9935         if (ret)
9936                 return ret;
9937         
9938         mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
9939         
9940
9941         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9942
9943         /* void stelemref (void* array, int idx, void* value) */
9944         sig->ret = &mono_defaults.void_class->byval_arg;
9945         sig->params [0] = &mono_defaults.object_class->byval_arg;
9946         sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9947         sig->params [2] = &mono_defaults.object_class->byval_arg;
9948
9949 #ifndef DISABLE_JIT
9950         aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9951         vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9952         array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9953         
9954         /*
9955         the method:
9956         <ldelema (bound check)>
9957         if (!value)
9958                 goto store;
9959         
9960         aklass = array->vtable->klass->element_class;
9961         vklass = value->vtable->klass;
9962         
9963         if (vklass->idepth < aklass->idepth)
9964                 goto long;
9965         
9966         if (vklass->supertypes [aklass->idepth - 1] != aklass)
9967                 goto long;
9968         
9969         store:
9970                 *array_slot_addr = value;
9971                 return;
9972         
9973         long:
9974                 if (mono_object_isinst (value, aklass))
9975                         goto store;
9976                 
9977                 throw new ArrayTypeMismatchException ();
9978         */
9979         
9980         /* ldelema (implicit bound check) */
9981         mono_mb_emit_ldarg (mb, 0);
9982         mono_mb_emit_ldarg (mb, 1);
9983         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9984         mono_mb_emit_stloc (mb, array_slot_addr);
9985                 
9986         /* if (!value) goto do_store */
9987         mono_mb_emit_ldarg (mb, 2);
9988         b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9989         
9990         /* aklass = array->vtable->klass->element_class */
9991         mono_mb_emit_ldarg (mb, 0);
9992         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9993         mono_mb_emit_byte (mb, CEE_LDIND_I);
9994         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9995         mono_mb_emit_byte (mb, CEE_LDIND_I);
9996         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9997         mono_mb_emit_byte (mb, CEE_LDIND_I);
9998         mono_mb_emit_stloc (mb, aklass);
9999         
10000         /* vklass = value->vtable->klass */
10001         mono_mb_emit_ldarg (mb, 2);
10002         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10003         mono_mb_emit_byte (mb, CEE_LDIND_I);
10004         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10005         mono_mb_emit_byte (mb, CEE_LDIND_I);
10006         mono_mb_emit_stloc (mb, vklass);
10007         
10008         /* if (vklass->idepth < aklass->idepth) goto failue */
10009         mono_mb_emit_ldloc (mb, vklass);
10010         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10011         mono_mb_emit_byte (mb, CEE_LDIND_U2);
10012         
10013         mono_mb_emit_ldloc (mb, aklass);
10014         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10015         mono_mb_emit_byte (mb, CEE_LDIND_U2);
10016         
10017         b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
10018         
10019         /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
10020         mono_mb_emit_ldloc (mb, vklass);
10021         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
10022         mono_mb_emit_byte (mb, CEE_LDIND_I);
10023         
10024         mono_mb_emit_ldloc (mb, aklass);
10025         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10026         mono_mb_emit_byte (mb, CEE_LDIND_U2);
10027         mono_mb_emit_icon (mb, 1);
10028         mono_mb_emit_byte (mb, CEE_SUB);
10029         mono_mb_emit_icon (mb, sizeof (void*));
10030         mono_mb_emit_byte (mb, CEE_MUL);
10031         mono_mb_emit_byte (mb, CEE_ADD);
10032         mono_mb_emit_byte (mb, CEE_LDIND_I);
10033         
10034         mono_mb_emit_ldloc (mb, aklass);
10035         
10036         b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10037         
10038         copy_pos = mono_mb_get_label (mb);
10039         /* do_store */
10040         mono_mb_patch_branch (mb, b1);
10041         mono_mb_emit_ldloc (mb, array_slot_addr);
10042         mono_mb_emit_ldarg (mb, 2);
10043         mono_mb_emit_byte (mb, CEE_STIND_REF);
10044         
10045         mono_mb_emit_byte (mb, CEE_RET);
10046         
10047         /* the hard way */
10048         mono_mb_patch_branch (mb, b2);
10049         mono_mb_patch_branch (mb, b3);
10050         
10051         mono_mb_emit_ldarg (mb, 2);
10052         mono_mb_emit_ldloc (mb, aklass);
10053         mono_mb_emit_icall (mb, mono_object_isinst_icall);
10054         
10055         b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
10056         mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
10057         mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10058         
10059         mono_mb_emit_byte (mb, CEE_RET);
10060 #endif
10061         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
10062         ret = mono_mb_create (mb, sig, 4, info);
10063         mono_mb_free (mb);
10064
10065         return ret;
10066 }
10067
10068 /*
10069  * mono_marshal_get_gsharedvt_in_wrapper:
10070  *
10071  *   This wrapper handles calls from normal code to gsharedvt code.
10072  */
10073 MonoMethod*
10074 mono_marshal_get_gsharedvt_in_wrapper (void)
10075 {
10076         static MonoMethod* ret = NULL;
10077         MonoMethodSignature *sig;
10078         MonoMethodBuilder *mb;
10079         WrapperInfo *info;
10080
10081         if (ret)
10082                 return ret;
10083         
10084         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_in", MONO_WRAPPER_UNKNOWN);
10085         
10086         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
10087         sig->ret = &mono_defaults.void_class->byval_arg;
10088
10089 #ifndef DISABLE_JIT
10090         /*
10091          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
10092          */
10093         mono_mb_emit_byte (mb, CEE_RET);
10094 #endif
10095         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_IN);
10096         ret = mono_mb_create (mb, sig, 4, info);
10097         mono_mb_free (mb);
10098
10099         return ret;
10100 }
10101
10102 /*
10103  * mono_marshal_get_gsharedvt_out_wrapper:
10104  *
10105  *   This wrapper handles calls from gsharedvt code to normal code.
10106  */
10107 MonoMethod*
10108 mono_marshal_get_gsharedvt_out_wrapper (void)
10109 {
10110         static MonoMethod* ret = NULL;
10111         MonoMethodSignature *sig;
10112         MonoMethodBuilder *mb;
10113         WrapperInfo *info;
10114
10115         if (ret)
10116                 return ret;
10117         
10118         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_out", MONO_WRAPPER_UNKNOWN);
10119         
10120         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
10121         sig->ret = &mono_defaults.void_class->byval_arg;
10122
10123 #ifndef DISABLE_JIT
10124         /*
10125          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
10126          */
10127         mono_mb_emit_byte (mb, CEE_RET);
10128 #endif
10129         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_OUT);
10130         ret = mono_mb_create (mb, sig, 4, info);
10131         mono_mb_free (mb);
10132
10133         return ret;
10134 }
10135
10136 typedef struct {
10137         int rank;
10138         int elem_size;
10139         MonoMethod *method;
10140 } ArrayElemAddr;
10141
10142 /* LOCKING: vars accessed under the marshal lock */
10143 static ArrayElemAddr *elem_addr_cache = NULL;
10144 static int elem_addr_cache_size = 0;
10145 static int elem_addr_cache_next = 0;
10146
10147 /**
10148  * mono_marshal_get_array_address:
10149  * @rank: rank of the array type
10150  * @elem_size: size in bytes of an element of an array.
10151  *
10152  * Returns a MonoMethod that implements the code to get the address
10153  * of an element in a multi-dimenasional array of @rank dimensions.
10154  * The returned method takes an array as the first argument and then
10155  * @rank indexes for the @rank dimensions.
10156  * If ELEM_SIZE is 0, read the array size from the array object.
10157  */
10158 MonoMethod*
10159 mono_marshal_get_array_address (int rank, int elem_size)
10160 {
10161         MonoMethod *ret;
10162         MonoMethodBuilder *mb;
10163         MonoMethodSignature *sig;
10164         WrapperInfo *info;
10165         char *name;
10166         int i, bounds, ind, realidx;
10167         int branch_pos, *branch_positions;
10168         int cached;
10169
10170         ret = NULL;
10171         mono_marshal_lock ();
10172         for (i = 0; i < elem_addr_cache_next; ++i) {
10173                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10174                         ret = elem_addr_cache [i].method;
10175                         break;
10176                 }
10177         }
10178         mono_marshal_unlock ();
10179         if (ret)
10180                 return ret;
10181
10182         branch_positions = g_new0 (int, rank);
10183
10184         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1 + rank);
10185
10186         /* void* address (void* array, int idx0, int idx1, int idx2, ...) */
10187         sig->ret = &mono_defaults.int_class->byval_arg;
10188         sig->params [0] = &mono_defaults.object_class->byval_arg;
10189         for (i = 0; i < rank; ++i) {
10190                 sig->params [i + 1] = &mono_defaults.int32_class->byval_arg;
10191         }
10192
10193         name = g_strdup_printf ("ElementAddr_%d", elem_size);
10194         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
10195         g_free (name);
10196         
10197 #ifndef DISABLE_JIT
10198         bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10199         ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10200         realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10201
10202         /* bounds = array->bounds; */
10203         mono_mb_emit_ldarg (mb, 0);
10204         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, bounds));
10205         mono_mb_emit_byte (mb, CEE_LDIND_I);
10206         mono_mb_emit_stloc (mb, bounds);
10207
10208         /* ind is the overall element index, realidx is the partial index in a single dimension */
10209         /* ind = idx0 - bounds [0].lower_bound */
10210         mono_mb_emit_ldarg (mb, 1);
10211         mono_mb_emit_ldloc (mb, bounds);
10212         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10213         mono_mb_emit_byte (mb, CEE_ADD);
10214         mono_mb_emit_byte (mb, CEE_LDIND_I4);
10215         mono_mb_emit_byte (mb, CEE_SUB);
10216         mono_mb_emit_stloc (mb, ind);
10217         /* if (ind >= bounds [0].length) goto exeception; */
10218         mono_mb_emit_ldloc (mb, ind);
10219         mono_mb_emit_ldloc (mb, bounds);
10220         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10221         mono_mb_emit_byte (mb, CEE_ADD);
10222         mono_mb_emit_byte (mb, CEE_LDIND_I4);
10223         /* note that we use unsigned comparison */
10224         branch_pos = mono_mb_emit_branch (mb, CEE_BGE_UN);
10225
10226         /* For large ranks (> 4?) use a loop n IL later to reduce code size.
10227          * We could also decide to ignore the passed elem_size and get it
10228          * from the array object, to reduce the number of methods we generate:
10229          * the additional cost is 3 memory loads and a non-immediate mul.
10230          */
10231         for (i = 1; i < rank; ++i) {
10232                 /* realidx = idxi - bounds [i].lower_bound */
10233                 mono_mb_emit_ldarg (mb, 1 + i);
10234                 mono_mb_emit_ldloc (mb, bounds);
10235                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10236                 mono_mb_emit_byte (mb, CEE_ADD);
10237                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10238                 mono_mb_emit_byte (mb, CEE_SUB);
10239                 mono_mb_emit_stloc (mb, realidx);
10240                 /* if (realidx >= bounds [i].length) goto exeception; */
10241                 mono_mb_emit_ldloc (mb, realidx);
10242                 mono_mb_emit_ldloc (mb, bounds);
10243                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10244                 mono_mb_emit_byte (mb, CEE_ADD);
10245                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10246                 branch_positions [i] = mono_mb_emit_branch (mb, CEE_BGE_UN);
10247                 /* ind = ind * bounds [i].length + realidx */
10248                 mono_mb_emit_ldloc (mb, ind);
10249                 mono_mb_emit_ldloc (mb, bounds);
10250                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10251                 mono_mb_emit_byte (mb, CEE_ADD);
10252                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10253                 mono_mb_emit_byte (mb, CEE_MUL);
10254                 mono_mb_emit_ldloc (mb, realidx);
10255                 mono_mb_emit_byte (mb, CEE_ADD);
10256                 mono_mb_emit_stloc (mb, ind);
10257         }
10258
10259         /* return array->vector + ind * element_size */
10260         mono_mb_emit_ldarg (mb, 0);
10261         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
10262         mono_mb_emit_ldloc (mb, ind);
10263         if (elem_size) {
10264                 mono_mb_emit_icon (mb, elem_size);
10265         } else {
10266                 /* Load arr->vtable->klass->sizes.element_class */
10267                 mono_mb_emit_ldarg (mb, 0);
10268                 mono_mb_emit_byte (mb, CEE_CONV_I);
10269                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10270                 mono_mb_emit_byte (mb, CEE_ADD);
10271                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10272                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10273                 mono_mb_emit_byte (mb, CEE_ADD);
10274                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10275                 /* sizes is an union, so this reads sizes.element_size */
10276                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
10277                 mono_mb_emit_byte (mb, CEE_ADD);
10278                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10279         }
10280                 mono_mb_emit_byte (mb, CEE_MUL);
10281         mono_mb_emit_byte (mb, CEE_ADD);
10282         mono_mb_emit_byte (mb, CEE_RET);
10283
10284         /* patch the branches to get here and throw */
10285         for (i = 1; i < rank; ++i) {
10286                 mono_mb_patch_branch (mb, branch_positions [i]);
10287         }
10288         mono_mb_patch_branch (mb, branch_pos);
10289         /* throw exception */
10290         mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
10291
10292         g_free (branch_positions);
10293 #endif /* DISABLE_JIT */
10294
10295         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ELEMENT_ADDR);
10296         info->d.element_addr.rank = rank;
10297         info->d.element_addr.elem_size = elem_size;
10298         ret = mono_mb_create (mb, sig, 4, info);
10299         mono_mb_free (mb);
10300
10301         /* cache the result */
10302         cached = 0;
10303         mono_marshal_lock ();
10304         for (i = 0; i < elem_addr_cache_next; ++i) {
10305                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10306                         /* FIXME: free ret */
10307                         ret = elem_addr_cache [i].method;
10308                         cached = TRUE;
10309                         break;
10310                 }
10311         }
10312         if (!cached) {
10313                 if (elem_addr_cache_next >= elem_addr_cache_size) {
10314                         int new_size = elem_addr_cache_size + 4;
10315                         ArrayElemAddr *new_array = g_new0 (ArrayElemAddr, new_size);
10316                         memcpy (new_array, elem_addr_cache, elem_addr_cache_size * sizeof (ArrayElemAddr));
10317                         g_free (elem_addr_cache);
10318                         elem_addr_cache = new_array;
10319                         elem_addr_cache_size = new_size;
10320                 }
10321                 elem_addr_cache [elem_addr_cache_next].rank = rank;
10322                 elem_addr_cache [elem_addr_cache_next].elem_size = elem_size;
10323                 elem_addr_cache [elem_addr_cache_next].method = ret;
10324                 elem_addr_cache_next ++;
10325         }
10326         mono_marshal_unlock ();
10327         return ret;
10328 }
10329
10330 /*
10331  * mono_marshal_get_array_accessor_wrapper:
10332  *
10333  *   Return a wrapper which just calls METHOD, which should be an Array Get/Set/Address method.
10334  */
10335 MonoMethod *
10336 mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
10337 {
10338         MonoMethodSignature *sig;
10339         MonoMethodBuilder *mb;
10340         MonoMethod *res;
10341         GHashTable *cache;
10342         int i;
10343         MonoGenericContext *ctx = NULL;
10344         MonoMethod *orig_method = NULL;
10345         MonoGenericContainer *container = NULL;
10346         WrapperInfo *info;
10347
10348         /*
10349          * These wrappers are needed to avoid the JIT replacing the calls to these methods with intrinsics
10350          * inside runtime invoke wrappers, thereby making the wrappers not unshareable.
10351          * FIXME: Use generic methods.
10352          */
10353         /*
10354          * Check cache
10355          */
10356         if (ctx) {
10357                 cache = NULL;
10358                 g_assert_not_reached ();
10359         } else {
10360                 cache = get_cache (&method->klass->image->array_accessor_cache, mono_aligned_addr_hash, NULL);
10361                 if ((res = mono_marshal_find_in_cache (cache, method)))
10362                         return res;
10363         }
10364
10365         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
10366         sig->pinvoke = 0;
10367
10368         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
10369
10370 #ifndef DISABLE_JIT
10371         /* Call the method */
10372         if (sig->hasthis)
10373                 mono_mb_emit_ldarg (mb, 0);
10374         for (i = 0; i < sig->param_count; i++)
10375                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
10376
10377         if (ctx) {
10378                 MonoError error;
10379                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
10380                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
10381         } else {
10382                 mono_mb_emit_managed_call (mb, method, NULL);
10383         }
10384         mono_mb_emit_byte (mb, CEE_RET);
10385 #endif
10386
10387         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ARRAY_ACCESSOR);
10388         info->d.array_accessor.method = method;
10389
10390         if (ctx) {
10391                 MonoMethod *def;
10392                 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
10393                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
10394         } else {
10395                 res = mono_mb_create_and_cache_full (cache, method,
10396                                                                                          mb, sig, sig->param_count + 16,
10397                                                                                          info, NULL);
10398         }
10399         mono_mb_free (mb);
10400
10401         return res;     
10402 }
10403
10404 void*
10405 mono_marshal_alloc (gulong size, MonoError *error)
10406 {
10407         gpointer res;
10408
10409         mono_error_init (error);
10410
10411 #ifdef HOST_WIN32
10412         res = CoTaskMemAlloc (size);
10413 #else
10414         res = g_try_malloc ((gulong)size);
10415         if (!res)
10416                 mono_error_set_out_of_memory (error, "Could not allocate %i bytes", size);
10417 #endif
10418         return res;
10419 }
10420
10421 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10422 static void*
10423 ves_icall_marshal_alloc (gulong size)
10424 {
10425         MonoError error;
10426         void *ret = mono_marshal_alloc (size, &error);
10427         if (!mono_error_ok (&error)) {
10428                 mono_error_set_pending_exception (&error);
10429                 return NULL;
10430         }
10431
10432         return ret;
10433 }
10434
10435 void
10436 mono_marshal_free (gpointer ptr)
10437 {
10438 #ifdef HOST_WIN32
10439         CoTaskMemFree (ptr);
10440 #else
10441         g_free (ptr);
10442 #endif
10443 }
10444
10445 void
10446 mono_marshal_free_array (gpointer *ptr, int size) 
10447 {
10448         int i;
10449
10450         if (!ptr)
10451                 return;
10452
10453         for (i = 0; i < size; i++)
10454                 if (ptr [i])
10455                         g_free (ptr [i]);
10456 }
10457
10458 void *
10459 mono_marshal_string_to_utf16 (MonoString *s)
10460 {
10461         return s ? mono_string_chars (s) : NULL;
10462 }
10463
10464 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10465 static void *
10466 mono_marshal_string_to_utf16_copy (MonoString *s)
10467 {
10468         if (s == NULL) {
10469                 return NULL;
10470         } else {
10471                 MonoError error;
10472                 gunichar2 *res = (gunichar2 *)mono_marshal_alloc ((mono_string_length (s) * 2) + 2, &error);
10473                 if (!mono_error_ok (&error)) {
10474                         mono_error_set_pending_exception (&error);
10475                         return NULL;
10476                 }
10477                 memcpy (res, mono_string_chars (s), mono_string_length (s) * 2);
10478                 res [mono_string_length (s)] = 0;
10479                 return res;
10480         }
10481 }
10482
10483 /**
10484  * mono_marshal_set_last_error:
10485  *
10486  * This function is invoked to set the last error value from a P/Invoke call
10487  * which has SetLastError set.
10488  */
10489 void
10490 mono_marshal_set_last_error (void)
10491 {
10492 #ifdef WIN32
10493         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
10494 #else
10495         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (errno));
10496 #endif
10497 }
10498
10499 static void
10500 mono_marshal_set_last_error_windows (int error)
10501 {
10502 #ifdef WIN32
10503         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (error));
10504 #endif
10505 }
10506
10507 void
10508 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
10509                                                                     gpointer dest, gint32 length)
10510 {
10511         int element_size;
10512         void *source_addr;
10513
10514         MONO_CHECK_ARG_NULL (src,);
10515         MONO_CHECK_ARG_NULL (dest,);
10516
10517         if (src->obj.vtable->klass->rank != 1) {
10518                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10519                 return;
10520         }
10521         if (start_index < 0) {
10522                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10523                 return;
10524         }
10525         if (length < 0) {
10526                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10527                 return;
10528         }
10529         if (start_index + length > mono_array_length (src)) {
10530                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10531                 return;
10532         }
10533
10534         element_size = mono_array_element_size (src->obj.vtable->klass);
10535
10536         /* no references should be involved */
10537         source_addr = mono_array_addr_with_size_fast (src, element_size, start_index);
10538
10539         memcpy (dest, source_addr, length * element_size);
10540 }
10541
10542 void
10543 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
10544                                                                       MonoArray *dest, gint32 length)
10545 {
10546         int element_size;
10547         void *dest_addr;
10548
10549         MONO_CHECK_ARG_NULL (src,);
10550         MONO_CHECK_ARG_NULL (dest,);
10551
10552         if (dest->obj.vtable->klass->rank != 1) {
10553                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10554                 return;
10555         }
10556         if (start_index < 0) {
10557                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10558                 return;
10559         }
10560         if (length < 0) {
10561                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10562                 return;
10563         }
10564         if (start_index + length > mono_array_length (dest)) {
10565                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10566                 return;
10567         }
10568         element_size = mono_array_element_size (dest->obj.vtable->klass);
10569           
10570         /* no references should be involved */
10571         dest_addr = mono_array_addr_with_size_fast (dest, element_size, start_index);
10572
10573         memcpy (dest_addr, src, length * element_size);
10574 }
10575
10576 MonoString *
10577 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr)
10578 {
10579         if (ptr == NULL)
10580                 return NULL;
10581         else
10582                 return mono_string_new (mono_domain_get (), ptr);
10583 }
10584
10585 MonoString *
10586 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
10587 {
10588         MonoError error;
10589         MonoString *result = NULL;
10590         mono_error_init (&error);
10591         if (ptr == NULL)
10592                 mono_error_set_argument_null (&error, "ptr", "");
10593         else
10594                 result = mono_string_new_len_checked (mono_domain_get (), ptr, len, &error);
10595         mono_error_set_pending_exception (&error);
10596         return result;
10597 }
10598
10599 MonoString *
10600 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
10601 {
10602         MonoError error;
10603         MonoString *res = NULL;
10604         MonoDomain *domain = mono_domain_get (); 
10605         int len = 0;
10606         guint16 *t = ptr;
10607
10608         if (ptr == NULL)
10609                 return NULL;
10610
10611         while (*t++)
10612                 len++;
10613
10614         res = mono_string_new_utf16_checked (domain, ptr, len, &error);
10615         if (!mono_error_ok (&error)) {
10616                 mono_error_set_pending_exception (&error);
10617                 return NULL;
10618         }
10619         return res;
10620 }
10621
10622 MonoString *
10623 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
10624 {
10625         MonoError error;
10626         MonoString *res = NULL;
10627         MonoDomain *domain = mono_domain_get (); 
10628
10629         mono_error_init (&error);
10630
10631         if (ptr == NULL) {
10632                 res = NULL;
10633                 mono_error_set_argument_null (&error, "ptr", "");
10634         } else {
10635                 res = mono_string_new_utf16_checked (domain, ptr, len, &error);
10636         }
10637
10638         if (!mono_error_ok (&error))
10639                 mono_error_set_pending_exception (&error);
10640         return res;
10641 }
10642
10643 guint32 
10644 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
10645 {
10646         return (GPOINTER_TO_INT (mono_native_tls_get_value (last_error_tls_id)));
10647 }
10648
10649 guint32 
10650 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionType *rtype)
10651 {
10652         MonoClass *klass;
10653         MonoType *type;
10654         guint32 layout;
10655
10656         MONO_CHECK_ARG_NULL (rtype, 0);
10657
10658         type = rtype->type;
10659         klass = mono_class_from_mono_type (type);
10660         if (!mono_class_init (klass)) {
10661                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10662                 return 0;
10663         }
10664
10665         layout = (klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK);
10666
10667         if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
10668                 return sizeof (gpointer);
10669         } else if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
10670                 gchar *msg;
10671                 MonoException *exc;
10672
10673                 msg = g_strdup_printf ("Type %s cannot be marshaled as an unmanaged structure.", klass->name);
10674                 exc = mono_get_exception_argument ("t", msg);
10675                 g_free (msg);
10676                 mono_set_pending_exception (exc);
10677                 return 0;
10678         }
10679
10680         return mono_class_native_size (klass, NULL);
10681 }
10682
10683 void
10684 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
10685 {
10686         MonoError error;
10687         MonoMethod *method;
10688         gpointer pa [3];
10689
10690         MONO_CHECK_ARG_NULL (obj,);
10691         MONO_CHECK_ARG_NULL (dst,);
10692
10693         method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
10694
10695         pa [0] = obj;
10696         pa [1] = &dst;
10697         pa [2] = &delete_old;
10698
10699         mono_runtime_invoke_checked (method, NULL, pa, &error);
10700         if (!mono_error_ok (&error))
10701                 mono_error_set_pending_exception (&error);
10702 }
10703
10704 static void
10705 ptr_to_structure (gpointer src, MonoObject *dst, MonoError *error)
10706 {
10707         MonoMethod *method;
10708         gpointer pa [2];
10709
10710         mono_error_init (error);
10711
10712         method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
10713
10714         pa [0] = &src;
10715         pa [1] = dst;
10716
10717         mono_runtime_invoke_checked (method, NULL, pa, error);
10718 }
10719
10720 void
10721 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
10722 {
10723         MonoType *t;
10724         MonoError error;
10725
10726         MONO_CHECK_ARG_NULL (src,);
10727         MONO_CHECK_ARG_NULL (dst,);
10728         
10729         t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
10730
10731         if (t->type == MONO_TYPE_VALUETYPE) {
10732                 MonoException *exc;
10733                 gchar *tmp;
10734
10735                 tmp = g_strdup_printf ("Destination is a boxed value type.");
10736                 exc = mono_get_exception_argument ("dst", tmp);
10737                 g_free (tmp);  
10738
10739                 mono_set_pending_exception (exc);
10740                 return;
10741         }
10742
10743         ptr_to_structure (src, dst, &error);
10744         if (!mono_error_ok (&error))
10745                 mono_error_set_pending_exception (&error);
10746 }
10747
10748 MonoObject *
10749 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
10750 {
10751         MonoError error;
10752         MonoClass *klass;
10753         MonoDomain *domain = mono_domain_get (); 
10754         MonoObject *res;
10755
10756         if (src == NULL)
10757                 return NULL;
10758         MONO_CHECK_ARG_NULL (type, NULL);
10759
10760         klass = mono_class_from_mono_type (type->type);
10761         if (!mono_class_init (klass)) {
10762                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10763                 return NULL;
10764         }
10765
10766         res = mono_object_new_checked (domain, klass, &error);
10767         if (!mono_error_ok (&error)) {
10768                 mono_error_set_pending_exception (&error);
10769                 return NULL;
10770         }
10771
10772         ptr_to_structure (src, res, &error);
10773         if (!mono_error_ok (&error)) {
10774                 mono_error_set_pending_exception (&error);
10775                 return NULL;
10776         }
10777
10778         return res;
10779 }
10780
10781 int
10782 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *type, MonoString *field_name)
10783 {
10784         MonoError error;
10785         MonoMarshalType *info;
10786         MonoClass *klass;
10787         char *fname;
10788         int match_index = -1;
10789         
10790         MONO_CHECK_ARG_NULL (type, 0);
10791         MONO_CHECK_ARG_NULL (field_name, 0);
10792
10793         fname = mono_string_to_utf8_checked (field_name, &error);
10794         if (mono_error_set_pending_exception (&error))
10795                 return 0;
10796         klass = mono_class_from_mono_type (type->type);
10797         if (!mono_class_init (klass)) {
10798                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10799                 return 0;
10800         }
10801
10802         while (klass && match_index == -1) {
10803                 MonoClassField* field;
10804                 int i = 0;
10805                 gpointer iter = NULL;
10806                 while ((field = mono_class_get_fields (klass, &iter))) {
10807                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10808                                 continue;
10809                         if (!strcmp (fname, mono_field_get_name (field))) {
10810                                 match_index = i;
10811                                 break;
10812                         }
10813                         i ++;
10814                 }
10815
10816                 if (match_index == -1)
10817                         klass = klass->parent;
10818         }
10819
10820         g_free (fname);
10821
10822         if(match_index == -1) {
10823                 MonoException* exc;
10824                 gchar *tmp;
10825
10826                 /* Get back original class instance */
10827                 klass = mono_class_from_mono_type (type->type);
10828
10829                 tmp = g_strdup_printf ("Field passed in is not a marshaled member of the type %s", klass->name);
10830                 exc = mono_get_exception_argument ("fieldName", tmp);
10831                 g_free (tmp);
10832  
10833                 mono_set_pending_exception ((MonoException*)exc);
10834                 return 0;
10835         }
10836
10837         info = mono_marshal_load_type_info (klass);     
10838         return info->fields [match_index].offset;
10839 }
10840
10841 gpointer
10842 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
10843 {
10844         MonoError error;
10845 #ifdef HOST_WIN32
10846         char* tres, *ret;
10847         size_t len;
10848         tres = mono_string_to_utf8_checked (string, &error);
10849         if (mono_error_set_pending_exception (&error))
10850                 return NULL;
10851         if (!tres)
10852                 return tres;
10853
10854         len = strlen (tres) + 1;
10855         ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len);
10856         memcpy (ret, tres, len);
10857         g_free (tres);
10858         return ret;
10859
10860 #else
10861         char *ret = mono_string_to_utf8_checked (string, &error);
10862         mono_error_set_pending_exception (&error);
10863         return ret;
10864 #endif
10865 }
10866
10867 gpointer
10868 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
10869 {
10870         if (string == NULL)
10871                 return NULL;
10872         else {
10873 #ifdef TARGET_WIN32
10874                 gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal 
10875                         ((mono_string_length (string) + 1) * 2);
10876 #else
10877                 gunichar2 *res = (gunichar2 *)g_malloc ((mono_string_length (string) + 1) * 2);
10878 #endif
10879                 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
10880                 res [mono_string_length (string)] = 0;
10881                 return res;
10882         }
10883 }
10884
10885 static void
10886 mono_struct_delete_old (MonoClass *klass, char *ptr)
10887 {
10888         MonoMarshalType *info;
10889         int i;
10890
10891         info = mono_marshal_load_type_info (klass);
10892
10893         for (i = 0; i < info->num_fields; i++) {
10894                 MonoMarshalConv conv;
10895                 MonoType *ftype = info->fields [i].field->type;
10896                 char *cpos;
10897
10898                 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
10899                         continue;
10900
10901                 mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, 
10902                                 klass->unicode, &conv);
10903                         
10904                 cpos = ptr + info->fields [i].offset;
10905
10906                 switch (conv) {
10907                 case MONO_MARSHAL_CONV_NONE:
10908                         if (MONO_TYPE_ISSTRUCT (ftype)) {
10909                                 mono_struct_delete_old (ftype->data.klass, cpos);
10910                                 continue;
10911                         }
10912                         break;
10913                 case MONO_MARSHAL_CONV_STR_LPWSTR:
10914                         /* We assume this field points inside a MonoString */
10915                         break;
10916                 case MONO_MARSHAL_CONV_STR_LPTSTR:
10917 #ifdef TARGET_WIN32
10918                         /* We assume this field points inside a MonoString 
10919                          * on Win32 */
10920                         break;
10921 #endif
10922                 case MONO_MARSHAL_CONV_STR_LPSTR:
10923                 case MONO_MARSHAL_CONV_STR_BSTR:
10924                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
10925                 case MONO_MARSHAL_CONV_STR_TBSTR:
10926                         mono_marshal_free (*(gpointer *)cpos);
10927                         break;
10928
10929                 default:
10930                         continue;
10931                 }
10932         }
10933 }
10934
10935 void
10936 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
10937 {
10938         MonoClass *klass;
10939
10940         MONO_CHECK_ARG_NULL (src,);
10941         MONO_CHECK_ARG_NULL (type,);
10942
10943         klass = mono_class_from_mono_type (type->type);
10944         if (!mono_class_init (klass)) {
10945                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10946                 return;
10947         }
10948
10949         mono_struct_delete_old (klass, (char *)src);
10950 }
10951
10952 void*
10953 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
10954 {
10955         gpointer res;
10956         size_t s = (size_t)size;
10957
10958         if (s == 0)
10959                 /* This returns a valid pointer for size 0 on MS.NET */
10960                 s = 4;
10961
10962 #ifdef HOST_WIN32
10963         res = GlobalAlloc (GMEM_FIXED, s);
10964 #else
10965         res = g_try_malloc (s);
10966 #endif
10967         if (!res) {
10968                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
10969                 return NULL;
10970         }
10971
10972         return res;
10973 }
10974
10975 gpointer
10976 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, gpointer size)
10977 {
10978         gpointer res;
10979         size_t s = (size_t)size;
10980
10981         if (ptr == NULL) {
10982                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
10983                 return NULL;
10984         }
10985
10986 #ifdef HOST_WIN32
10987         res = GlobalReAlloc (ptr, s, GMEM_MOVEABLE);
10988 #else
10989         res = g_try_realloc (ptr, s);
10990 #endif
10991         if (!res) {
10992                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
10993                 return NULL;
10994         }
10995
10996         return res;
10997 }
10998
10999 void
11000 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
11001 {
11002 #ifdef HOST_WIN32
11003         GlobalFree (ptr);
11004 #else
11005         g_free (ptr);
11006 #endif
11007 }
11008
11009 void*
11010 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
11011 {
11012         void *res;
11013
11014 #ifdef HOST_WIN32
11015         res = CoTaskMemAlloc (size);
11016 #else
11017         if ((gulong)size == 0)
11018                 /* This returns a valid pointer for size 0 on MS.NET */
11019                 size = 4;
11020
11021         res = g_try_malloc ((gulong)size);
11022 #endif
11023         if (!res) {
11024                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11025                 return NULL;
11026         }
11027         return res;
11028 }
11029
11030 void
11031 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
11032 {
11033 #ifdef HOST_WIN32
11034         CoTaskMemFree (ptr);
11035 #else
11036         g_free (ptr);
11037 #endif
11038 }
11039
11040 gpointer
11041 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
11042 {
11043         void *res;
11044
11045 #ifdef HOST_WIN32
11046         res = CoTaskMemRealloc (ptr, size);
11047 #else
11048         res = g_try_realloc (ptr, (gulong)size);
11049 #endif
11050         if (!res) {
11051                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11052                 return NULL;
11053         }
11054         return res;
11055 }
11056
11057 void*
11058 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
11059 {
11060         return mono_array_addr_with_size_fast (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
11061 }
11062
11063 MonoDelegate*
11064 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionType *type)
11065 {
11066         MonoClass *klass = mono_type_get_class (type->type);
11067         if (!mono_class_init (klass)) {
11068                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
11069                 return NULL;
11070         }
11071
11072         return mono_ftnptr_to_delegate (klass, ftn);
11073 }
11074
11075 gpointer
11076 ves_icall_System_Runtime_InteropServices_Marshal_GetFunctionPointerForDelegateInternal (MonoDelegate *delegate)
11077 {
11078         return mono_delegate_to_ftnptr (delegate);
11079 }
11080
11081 /**
11082  * mono_marshal_is_loading_type_info:
11083  *
11084  *  Return whenever mono_marshal_load_type_info () is being executed for KLASS by this
11085  * thread.
11086  */
11087 static gboolean
11088 mono_marshal_is_loading_type_info (MonoClass *klass)
11089 {
11090         GSList *loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11091
11092         return g_slist_find (loads_list, klass) != NULL;
11093 }
11094
11095 /**
11096  * mono_marshal_load_type_info:
11097  *
11098  *  Initialize klass->marshal_info using information from metadata. This function can
11099  * recursively call itself, and the caller is responsible to avoid that by calling 
11100  * mono_marshal_is_loading_type_info () beforehand.
11101  *
11102  * LOCKING: Acquires the loader lock.
11103  */
11104 MonoMarshalType *
11105 mono_marshal_load_type_info (MonoClass* klass)
11106 {
11107         int j, count = 0;
11108         guint32 native_size = 0, min_align = 1, packing;
11109         MonoMarshalType *info;
11110         MonoClassField* field;
11111         gpointer iter;
11112         guint32 layout;
11113         GSList *loads_list;
11114
11115         g_assert (klass != NULL);
11116
11117         if (klass->marshal_info)
11118                 return klass->marshal_info;
11119
11120         if (!klass->inited)
11121                 mono_class_init (klass);
11122
11123         if (klass->marshal_info)
11124                 return klass->marshal_info;
11125
11126         /*
11127          * This function can recursively call itself, so we keep the list of classes which are
11128          * under initialization in a TLS list.
11129          */
11130         g_assert (!mono_marshal_is_loading_type_info (klass));
11131         loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11132         loads_list = g_slist_prepend (loads_list, klass);
11133         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11134         
11135         iter = NULL;
11136         while ((field = mono_class_get_fields (klass, &iter))) {
11137                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11138                         continue;
11139                 if (mono_field_is_deleted (field))
11140                         continue;
11141                 count++;
11142         }
11143
11144         layout = klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
11145
11146         /* The mempool is protected by the loader lock */
11147         info = (MonoMarshalType *)mono_image_alloc0 (klass->image, MONO_SIZEOF_MARSHAL_TYPE + sizeof (MonoMarshalField) * count);
11148         info->num_fields = count;
11149         
11150         /* Try to find a size for this type in metadata */
11151         mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
11152
11153         if (klass->parent) {
11154                 int parent_size = mono_class_native_size (klass->parent, NULL);
11155
11156                 /* Add parent size to real size */
11157                 native_size += parent_size;
11158                 info->native_size = parent_size;
11159         }
11160
11161         packing = klass->packing_size ? klass->packing_size : 8;
11162         iter = NULL;
11163         j = 0;
11164         while ((field = mono_class_get_fields (klass, &iter))) {
11165                 int size;
11166                 guint32 align;
11167                 
11168                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11169                         continue;
11170
11171                 if (mono_field_is_deleted (field))
11172                         continue;
11173                 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
11174                         mono_metadata_field_info_with_mempool (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1, 
11175                                                   NULL, NULL, &info->fields [j].mspec);
11176
11177                 info->fields [j].field = field;
11178
11179                 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
11180                         (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
11181                         /* This field is a hack inserted by MCS to empty structures */
11182                         continue;
11183                 }
11184
11185                 switch (layout) {
11186                 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
11187                 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
11188                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
11189                                                        &align, TRUE, klass->unicode);
11190                         align = klass->packing_size ? MIN (klass->packing_size, align): align;
11191                         min_align = MAX (align, min_align);
11192                         info->fields [j].offset = info->native_size;
11193                         info->fields [j].offset += align - 1;
11194                         info->fields [j].offset &= ~(align - 1);
11195                         info->native_size = info->fields [j].offset + size;
11196                         break;
11197                 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
11198                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
11199                                                        &align, TRUE, klass->unicode);
11200                         min_align = MAX (align, min_align);
11201                         info->fields [j].offset = field->offset - sizeof (MonoObject);
11202                         info->native_size = MAX (info->native_size, info->fields [j].offset + size);
11203                         break;
11204                 }       
11205                 j++;
11206         }
11207
11208         if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
11209                 info->native_size = MAX (native_size, info->native_size);
11210                 /*
11211                  * If the provided Size is equal or larger than the calculated size, and there
11212                  * was no Pack attribute, we set min_align to 1 to avoid native_size being increased
11213                  */
11214                 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
11215                         if (native_size && native_size == info->native_size && klass->packing_size == 0)
11216                                 min_align = 1;
11217                         else
11218                                 min_align = MIN (min_align, packing);
11219                 }
11220         }
11221
11222         if (info->native_size & (min_align - 1)) {
11223                 info->native_size += min_align - 1;
11224                 info->native_size &= ~(min_align - 1);
11225         }
11226
11227         info->min_align = min_align;
11228
11229         /* Update the class's blittable info, if the layouts don't match */
11230         if (info->native_size != mono_class_value_size (klass, NULL))
11231                 klass->blittable = FALSE;
11232
11233         /* If this is an array type, ensure that we have element info */
11234         if (klass->rank && !mono_marshal_is_loading_type_info (klass->element_class)) {
11235                 mono_marshal_load_type_info (klass->element_class);
11236         }
11237
11238         loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11239         loads_list = g_slist_remove (loads_list, klass);
11240         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11241
11242         mono_marshal_lock ();
11243         if (!klass->marshal_info) {
11244                 /*We do double-checking locking on marshal_info */
11245                 mono_memory_barrier ();
11246                 klass->marshal_info = info;
11247         }
11248         mono_marshal_unlock ();
11249
11250         return klass->marshal_info;
11251 }
11252
11253 /**
11254  * mono_class_native_size:
11255  * @klass: a class 
11256  * 
11257  * Returns: the native size of an object instance (when marshaled 
11258  * to unmanaged code) 
11259  */
11260 gint32
11261 mono_class_native_size (MonoClass *klass, guint32 *align)
11262 {       
11263         if (!klass->marshal_info) {
11264                 if (mono_marshal_is_loading_type_info (klass)) {
11265                         if (align)
11266                                 *align = 0;
11267                         return 0;
11268                 } else {
11269                         mono_marshal_load_type_info (klass);
11270                 }
11271         }
11272
11273         if (align)
11274                 *align = klass->marshal_info->min_align;
11275
11276         return klass->marshal_info->native_size;
11277 }
11278
11279 /*
11280  * mono_type_native_stack_size:
11281  * @t: the type to return the size it uses on the stack
11282  *
11283  * Returns: the number of bytes required to hold an instance of this
11284  * type on the native stack
11285  */
11286 int
11287 mono_type_native_stack_size (MonoType *t, guint32 *align)
11288 {
11289         guint32 tmp;
11290
11291         g_assert (t != NULL);
11292
11293         if (!align)
11294                 align = &tmp;
11295
11296         if (t->byref) {
11297                 *align = sizeof (gpointer);
11298                 return sizeof (gpointer);
11299         }
11300
11301         switch (t->type){
11302         case MONO_TYPE_BOOLEAN:
11303         case MONO_TYPE_CHAR:
11304         case MONO_TYPE_I1:
11305         case MONO_TYPE_U1:
11306         case MONO_TYPE_I2:
11307         case MONO_TYPE_U2:
11308         case MONO_TYPE_I4:
11309         case MONO_TYPE_U4:
11310                 *align = 4;
11311                 return 4;
11312         case MONO_TYPE_I:
11313         case MONO_TYPE_U:
11314         case MONO_TYPE_STRING:
11315         case MONO_TYPE_OBJECT:
11316         case MONO_TYPE_CLASS:
11317         case MONO_TYPE_SZARRAY:
11318         case MONO_TYPE_PTR:
11319         case MONO_TYPE_FNPTR:
11320         case MONO_TYPE_ARRAY:
11321                 *align = sizeof (gpointer);
11322                 return sizeof (gpointer);
11323         case MONO_TYPE_R4:
11324                 *align = 4;
11325                 return 4;
11326         case MONO_TYPE_R8:
11327                 *align = MONO_ABI_ALIGNOF (double);
11328                 return 8;
11329         case MONO_TYPE_I8:
11330         case MONO_TYPE_U8:
11331                 *align = MONO_ABI_ALIGNOF (gint64);
11332                 return 8;
11333         case MONO_TYPE_GENERICINST:
11334                 if (!mono_type_generic_inst_is_valuetype (t)) {
11335                         *align = sizeof (gpointer);
11336                         return sizeof (gpointer);
11337                 } 
11338                 /* Fall through */
11339         case MONO_TYPE_TYPEDBYREF:
11340         case MONO_TYPE_VALUETYPE: {
11341                 guint32 size;
11342                 MonoClass *klass = mono_class_from_mono_type (t);
11343
11344                 if (klass->enumtype)
11345                         return mono_type_native_stack_size (mono_class_enum_basetype (klass), align);
11346                 else {
11347                         size = mono_class_native_size (klass, align);
11348                         *align = *align + 3;
11349                         *align &= ~3;
11350                         
11351                         size +=  3;
11352                         size &= ~3;
11353
11354                         return size;
11355                 }
11356         }
11357         default:
11358                 g_error ("type 0x%02x unknown", t->type);
11359         }
11360         return 0;
11361 }
11362
11363 gint32
11364 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
11365                         gboolean as_field, gboolean unicode)
11366 {
11367         MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
11368         MonoClass *klass;
11369
11370         switch (native_type) {
11371         case MONO_NATIVE_BOOLEAN:
11372                 *align = 4;
11373                 return 4;
11374         case MONO_NATIVE_I1:
11375         case MONO_NATIVE_U1:
11376                 *align = 1;
11377                 return 1;
11378         case MONO_NATIVE_I2:
11379         case MONO_NATIVE_U2:
11380         case MONO_NATIVE_VARIANTBOOL:
11381                 *align = 2;
11382                 return 2;
11383         case MONO_NATIVE_I4:
11384         case MONO_NATIVE_U4:
11385         case MONO_NATIVE_ERROR:
11386                 *align = 4;
11387                 return 4;
11388         case MONO_NATIVE_I8:
11389         case MONO_NATIVE_U8:
11390                 *align = MONO_ABI_ALIGNOF (gint64);
11391                 return 8;
11392         case MONO_NATIVE_R4:
11393                 *align = 4;
11394                 return 4;
11395         case MONO_NATIVE_R8:
11396                 *align = MONO_ABI_ALIGNOF (double);
11397                 return 8;
11398         case MONO_NATIVE_INT:
11399         case MONO_NATIVE_UINT:
11400         case MONO_NATIVE_LPSTR:
11401         case MONO_NATIVE_LPWSTR:
11402         case MONO_NATIVE_LPTSTR:
11403         case MONO_NATIVE_BSTR:
11404         case MONO_NATIVE_ANSIBSTR:
11405         case MONO_NATIVE_TBSTR:
11406         case MONO_NATIVE_LPARRAY:
11407         case MONO_NATIVE_SAFEARRAY:
11408         case MONO_NATIVE_IUNKNOWN:
11409         case MONO_NATIVE_IDISPATCH:
11410         case MONO_NATIVE_INTERFACE:
11411         case MONO_NATIVE_ASANY:
11412         case MONO_NATIVE_FUNC:
11413         case MONO_NATIVE_LPSTRUCT:
11414                 *align = MONO_ABI_ALIGNOF (gpointer);
11415                 return sizeof (gpointer);
11416         case MONO_NATIVE_STRUCT: 
11417                 klass = mono_class_from_mono_type (type);
11418                 if (klass == mono_defaults.object_class &&
11419                         (mspec && mspec->native == MONO_NATIVE_STRUCT)) {
11420                 *align = 16;
11421                 return 16;
11422                 }
11423                 return mono_class_native_size (klass, align);
11424         case MONO_NATIVE_BYVALTSTR: {
11425                 int esize = unicode ? 2: 1;
11426                 g_assert (mspec);
11427                 *align = esize;
11428                 return mspec->data.array_data.num_elem * esize;
11429         }
11430         case MONO_NATIVE_BYVALARRAY: {
11431                 // FIXME: Have to consider ArraySubType
11432                 int esize;
11433                 klass = mono_class_from_mono_type (type);
11434                 if (klass->element_class == mono_defaults.char_class) {
11435                         esize = unicode ? 2 : 1;
11436                         *align = esize;
11437                 } else {
11438                         esize = mono_class_native_size (klass->element_class, align);
11439                 }
11440                 g_assert (mspec);
11441                 return mspec->data.array_data.num_elem * esize;
11442         }
11443         case MONO_NATIVE_CUSTOM:
11444                 *align = sizeof (gpointer);
11445                 return sizeof (gpointer);
11446                 break;
11447         case MONO_NATIVE_CURRENCY:
11448         case MONO_NATIVE_VBBYREFSTR:
11449         default:
11450                 g_error ("native type %02x not implemented", native_type); 
11451                 break;
11452         }
11453         g_assert_not_reached ();
11454         return 0;
11455 }
11456
11457 /* This is a JIT icall, it sets the pending exception and return NULL on error */
11458 gpointer
11459 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
11460 {
11461         MonoError error;
11462         MonoType *t;
11463         MonoClass *klass;
11464
11465         if (o == NULL)
11466                 return NULL;
11467
11468         t = &o->vtable->klass->byval_arg;
11469         switch (t->type) {
11470         case MONO_TYPE_I4:
11471         case MONO_TYPE_U4:
11472         case MONO_TYPE_PTR:
11473         case MONO_TYPE_I1:
11474         case MONO_TYPE_U1:
11475         case MONO_TYPE_BOOLEAN:
11476         case MONO_TYPE_I2:
11477         case MONO_TYPE_U2:
11478         case MONO_TYPE_CHAR:
11479         case MONO_TYPE_I8:
11480         case MONO_TYPE_U8:
11481         case MONO_TYPE_R4:
11482         case MONO_TYPE_R8:
11483                 return mono_object_unbox (o);
11484                 break;
11485         case MONO_TYPE_STRING:
11486                 switch (string_encoding) {
11487                 case MONO_NATIVE_LPWSTR:
11488                         return mono_marshal_string_to_utf16_copy ((MonoString*)o);
11489                         break;
11490                 case MONO_NATIVE_LPSTR:
11491                         return mono_string_to_lpstr ((MonoString*)o);
11492                         break;
11493                 default:
11494                         g_warning ("marshaling conversion %d not implemented", string_encoding);
11495                         g_assert_not_reached ();
11496                 }
11497                 break;
11498         case MONO_TYPE_CLASS:
11499         case MONO_TYPE_VALUETYPE: {
11500                 MonoMethod *method;
11501                 gpointer pa [3];
11502                 gpointer res;
11503                 MonoBoolean delete_old = FALSE;
11504
11505                 klass = t->data.klass;
11506
11507                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
11508                         break;
11509
11510                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
11511                         klass->blittable || klass->enumtype))
11512                         return mono_object_unbox (o);
11513
11514                 res = mono_marshal_alloc (mono_class_native_size (klass, NULL), &error);
11515                 if (!mono_error_ok (&error)) {
11516                         mono_error_set_pending_exception (&error);
11517                         return NULL;
11518                 }
11519
11520                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11521                         method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
11522
11523                         pa [0] = o;
11524                         pa [1] = &res;
11525                         pa [2] = &delete_old;
11526
11527                         mono_runtime_invoke_checked (method, NULL, pa, &error);
11528                         if (!mono_error_ok (&error)) {
11529                                 mono_error_set_pending_exception (&error);
11530                                 return NULL;
11531                         }
11532                 }
11533
11534                 return res;
11535         }
11536         default:
11537                 break;
11538         }
11539         mono_set_pending_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
11540         return NULL;
11541 }
11542
11543 /* This is a JIT icall, it sets the pending exception */
11544 void
11545 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
11546 {
11547         MonoError error;
11548         MonoType *t;
11549         MonoClass *klass;
11550
11551         if (o == NULL)
11552                 return;
11553
11554         t = &o->vtable->klass->byval_arg;
11555         switch (t->type) {
11556         case MONO_TYPE_STRING:
11557                 switch (string_encoding) {
11558                 case MONO_NATIVE_LPWSTR:
11559                 case MONO_NATIVE_LPSTR:
11560                         mono_marshal_free (ptr);
11561                         break;
11562                 default:
11563                         g_warning ("marshaling conversion %d not implemented", string_encoding);
11564                         g_assert_not_reached ();
11565                 }
11566                 break;
11567         case MONO_TYPE_CLASS:
11568         case MONO_TYPE_VALUETYPE: {
11569                 klass = t->data.klass;
11570
11571                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
11572                                                                  klass->blittable || klass->enumtype))
11573                         break;
11574
11575                 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
11576                         MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
11577                         gpointer pa [2];
11578
11579                         pa [0] = &ptr;
11580                         pa [1] = o;
11581
11582                         mono_runtime_invoke_checked (method, NULL, pa, &error);
11583                         if (!mono_error_ok (&error)) {
11584                                 mono_error_set_pending_exception (&error);
11585                                 return;
11586                         }
11587                 }
11588
11589                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11590                         mono_struct_delete_old (klass, (char *)ptr);
11591                 }
11592
11593                 mono_marshal_free (ptr);
11594                 break;
11595         }
11596         default:
11597                 break;
11598         }
11599 }
11600
11601 MonoMethod *
11602 mono_marshal_get_generic_array_helper (MonoClass *klass, MonoClass *iface, gchar *name, MonoMethod *method)
11603 {
11604         MonoMethodSignature *sig, *csig;
11605         MonoMethodBuilder *mb;
11606         MonoMethod *res;
11607         WrapperInfo *info;
11608         int i;
11609
11610         mb = mono_mb_new_no_dup_name (klass, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
11611         mb->method->slot = -1;
11612
11613         mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
11614                 METHOD_ATTRIBUTE_NEW_SLOT | METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
11615
11616         sig = mono_method_signature (method);
11617         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
11618         csig->generic_param_count = 0;
11619
11620 #ifndef DISABLE_JIT
11621         mono_mb_emit_ldarg (mb, 0);
11622         for (i = 0; i < csig->param_count; i++)
11623                 mono_mb_emit_ldarg (mb, i + 1);
11624         mono_mb_emit_managed_call (mb, method, NULL);
11625         mono_mb_emit_byte (mb, CEE_RET);
11626
11627         /* We can corlib internal methods */
11628         mb->skip_visibility = TRUE;
11629 #endif
11630         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER);
11631         info->d.generic_array_helper.method = method;
11632         res = mono_mb_create (mb, csig, csig->param_count + 16, info);
11633
11634         mono_mb_free (mb);
11635
11636         return res;
11637 }
11638
11639 /*
11640  * The mono_win32_compat_* functions are implementations of inline
11641  * Windows kernel32 APIs, which are DllImport-able under MS.NET,
11642  * although not exported by kernel32.
11643  *
11644  * We map the appropiate kernel32 entries to these functions using
11645  * dllmaps declared in the global etc/mono/config.
11646  */
11647
11648 void
11649 mono_win32_compat_CopyMemory (gpointer dest, gconstpointer source, gsize length)
11650 {
11651         if (!dest || !source)
11652                 return;
11653
11654         memcpy (dest, source, length);
11655 }
11656
11657 void
11658 mono_win32_compat_FillMemory (gpointer dest, gsize length, guchar fill)
11659 {
11660         memset (dest, fill, length);
11661 }
11662
11663 void
11664 mono_win32_compat_MoveMemory (gpointer dest, gconstpointer source, gsize length)
11665 {
11666         if (!dest || !source)
11667                 return;
11668
11669         memmove (dest, source, length);
11670 }
11671
11672 void
11673 mono_win32_compat_ZeroMemory (gpointer dest, gsize length)
11674 {
11675         memset (dest, 0, length);
11676 }
11677
11678 void
11679 mono_marshal_find_nonzero_bit_offset (guint8 *buf, int len, int *byte_offset, guint8 *bitmask)
11680 {
11681         int i;
11682         guint8 byte;
11683
11684         for (i = 0; i < len; ++i)
11685                 if (buf [i])
11686                         break;
11687
11688         g_assert (i < len);
11689
11690         byte = buf [i];
11691         while (byte && !(byte & 1))
11692                 byte >>= 1;
11693         g_assert (byte == 1);
11694
11695         *byte_offset = i;
11696         *bitmask = buf [i];
11697 }
11698
11699 MonoMethod *
11700 mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
11701 {
11702         MonoMethodBuilder *mb;
11703         MonoMethodSignature *sig, *csig;
11704         MonoExceptionClause *clause;
11705         MonoImage *image;
11706         MonoClass *klass;
11707         GHashTable *cache;
11708         MonoMethod *res;
11709         int i, param_count, sig_size, pos_leave;
11710
11711         g_assert (method);
11712
11713         // FIXME: we need to store the exception into a MonoHandle
11714         g_assert (!mono_threads_is_coop_enabled ());
11715
11716         klass = method->klass;
11717         image = method->klass->image;
11718
11719         cache = get_cache (&mono_method_get_wrapper_cache (method)->thunk_invoke_cache, mono_aligned_addr_hash, NULL);
11720
11721         if ((res = mono_marshal_find_in_cache (cache, method)))
11722                 return res;
11723
11724         sig = mono_method_signature (method);
11725         mb = mono_mb_new (klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
11726
11727         /* add "this" and exception param */
11728         param_count = sig->param_count + sig->hasthis + 1;
11729
11730         /* dup & extend signature */
11731         csig = mono_metadata_signature_alloc (image, param_count);
11732         sig_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *);
11733         memcpy (csig, sig, sig_size);
11734         csig->param_count = param_count;
11735         csig->hasthis = 0;
11736         csig->pinvoke = 1;
11737         csig->call_convention = MONO_CALL_DEFAULT;
11738
11739         if (sig->hasthis) {
11740                 /* add "this" */
11741                 csig->params [0] = &klass->byval_arg;
11742                 /* move params up by one */
11743                 for (i = 0; i < sig->param_count; i++)
11744                         csig->params [i + 1] = sig->params [i];
11745         }
11746
11747         /* setup exception param as byref+[out] */
11748         csig->params [param_count - 1] = mono_metadata_type_dup (image,
11749                  &mono_defaults.exception_class->byval_arg);
11750         csig->params [param_count - 1]->byref = 1;
11751         csig->params [param_count - 1]->attrs = PARAM_ATTRIBUTE_OUT;
11752
11753         /* convert struct return to object */
11754         if (MONO_TYPE_ISSTRUCT (sig->ret))
11755                 csig->ret = &mono_defaults.object_class->byval_arg;
11756
11757 #ifndef DISABLE_JIT
11758         /* local 0 (temp for exception object) */
11759         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
11760
11761         /* local 1 (temp for result) */
11762         if (!MONO_TYPE_IS_VOID (sig->ret))
11763                 mono_mb_add_local (mb, sig->ret);
11764
11765         /* clear exception arg */
11766         mono_mb_emit_ldarg (mb, param_count - 1);
11767         mono_mb_emit_byte (mb, CEE_LDNULL);
11768         mono_mb_emit_byte (mb, CEE_STIND_REF);
11769
11770         /* try */
11771         clause = (MonoExceptionClause *)mono_image_alloc0 (image, sizeof (MonoExceptionClause));
11772         clause->try_offset = mono_mb_get_label (mb);
11773
11774         /* push method's args */
11775         for (i = 0; i < param_count - 1; i++) {
11776                 MonoType *type;
11777                 MonoClass *klass;
11778
11779                 mono_mb_emit_ldarg (mb, i);
11780
11781                 /* get the byval type of the param */
11782                 klass = mono_class_from_mono_type (csig->params [i]);
11783                 type = &klass->byval_arg;
11784
11785                 /* unbox struct args */
11786                 if (MONO_TYPE_ISSTRUCT (type)) {
11787                         mono_mb_emit_op (mb, CEE_UNBOX, klass);
11788
11789                         /* byref args & and the "this" arg must remain a ptr.
11790                            Otherwise make a copy of the value type */
11791                         if (!(csig->params [i]->byref || (i == 0 && sig->hasthis)))
11792                                 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
11793
11794                         csig->params [i] = &mono_defaults.object_class->byval_arg;
11795                 }
11796         }
11797
11798         /* call */
11799         if (method->flags & METHOD_ATTRIBUTE_VIRTUAL)
11800                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
11801         else
11802                 mono_mb_emit_op (mb, CEE_CALL, method);
11803
11804         /* save result at local 1 */
11805         if (!MONO_TYPE_IS_VOID (sig->ret))
11806                 mono_mb_emit_stloc (mb, 1);
11807
11808         pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
11809
11810         /* catch */
11811         clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
11812         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
11813         clause->data.catch_class = mono_defaults.object_class;
11814
11815         clause->handler_offset = mono_mb_get_label (mb);
11816
11817         /* store exception at local 0 */
11818         mono_mb_emit_stloc (mb, 0);
11819         mono_mb_emit_ldarg (mb, param_count - 1);
11820         mono_mb_emit_ldloc (mb, 0);
11821         mono_mb_emit_byte (mb, CEE_STIND_REF);
11822         mono_mb_emit_branch (mb, CEE_LEAVE);
11823
11824         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
11825
11826         mono_mb_set_clauses (mb, 1, clause);
11827
11828         mono_mb_patch_branch (mb, pos_leave);
11829         /* end-try */
11830
11831         if (!MONO_TYPE_IS_VOID (sig->ret)) {
11832                 mono_mb_emit_ldloc (mb, 1);
11833
11834                 /* box the return value */
11835                 if (MONO_TYPE_ISSTRUCT (sig->ret))
11836                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
11837         }
11838
11839         mono_mb_emit_byte (mb, CEE_RET);
11840 #endif
11841
11842         res = mono_mb_create_and_cache (cache, method, mb, csig, param_count + 16);
11843         mono_mb_free (mb);
11844
11845         return res;
11846 }
11847
11848 /*
11849  * mono_marshal_free_dynamic_wrappers:
11850  *
11851  *   Free wrappers of the dynamic method METHOD.
11852  */
11853 void
11854 mono_marshal_free_dynamic_wrappers (MonoMethod *method)
11855 {
11856         MonoImage *image = method->klass->image;
11857
11858         g_assert (method_is_dynamic (method));
11859
11860         /* This could be called during shutdown */
11861         if (marshal_mutex_initialized)
11862                 mono_marshal_lock ();
11863         /* 
11864          * FIXME: We currently leak the wrappers. Freeing them would be tricky as
11865          * they could be shared with other methods ?
11866          */
11867         if (image->wrapper_caches.runtime_invoke_direct_cache)
11868                 g_hash_table_remove (image->wrapper_caches.runtime_invoke_direct_cache, method);
11869         if (image->wrapper_caches.delegate_abstract_invoke_cache)
11870                 g_hash_table_foreach_remove (image->wrapper_caches.delegate_abstract_invoke_cache, signature_pointer_pair_matches_pointer, method);
11871         // FIXME: Need to clear the caches in other images as well
11872         if (image->delegate_bound_static_invoke_cache)
11873                 g_hash_table_remove (image->delegate_bound_static_invoke_cache, mono_method_signature (method));
11874
11875         if (marshal_mutex_initialized)
11876                 mono_marshal_unlock ();
11877 }
11878
11879 static void
11880 mono_marshal_ftnptr_eh_callback (guint32 gchandle)
11881 {
11882         g_assert (ftnptr_eh_callback);
11883         ftnptr_eh_callback (gchandle);
11884 }
11885
11886 static void
11887 ftnptr_eh_callback_default (guint32 gchandle)
11888 {
11889         MonoException *exc;
11890         gpointer stackdata;
11891
11892         g_assert (gchandle >= 0);
11893
11894         mono_threads_enter_gc_unsafe_region_unbalanced (&stackdata);
11895
11896         exc = (MonoException*) mono_gchandle_get_target (gchandle);
11897
11898         mono_gchandle_free (gchandle);
11899
11900         mono_raise_exception (exc);
11901 }
11902
11903 /*
11904  * mono_install_ftnptr_eh_callback:
11905  *
11906  *   Install a callback that should be called when there is a managed exception
11907  *   in a native-to-managed wrapper. This is mainly used by iOS to convert a
11908  *   managed exception to a native exception, to properly unwind the native
11909  *   stack; this native exception will then be converted back to a managed
11910  *   exception in their managed-to-native wrapper.
11911  */
11912 void
11913 mono_install_ftnptr_eh_callback (MonoFtnPtrEHCallback callback)
11914 {
11915         ftnptr_eh_callback = callback;
11916 }