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