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