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