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