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