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