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