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