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