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