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