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