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