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