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