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