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