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