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