Merge pull request #3349 from lambdageek/handle-icalls-in-jit
[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         /* if (delegates == null) */
3419         mono_mb_emit_ldloc (mb, local_delegates);
3420         pos2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
3421
3422         /* return target.<target_method|method_ptr> ( args .. ); */
3423
3424         /* target = d.target; */
3425         mono_mb_emit_ldarg (mb, 0);
3426         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, target));
3427         mono_mb_emit_byte (mb, CEE_LDIND_REF);
3428         mono_mb_emit_stloc (mb, local_target);
3429
3430         /*static methods with bound first arg can have null target and still be bound*/
3431         if (!static_method_with_first_arg_bound) {
3432                 /* if target != null */
3433                 mono_mb_emit_ldloc (mb, local_target);
3434                 pos0 = mono_mb_emit_branch (mb, CEE_BRFALSE);
3435
3436                 /* then call this->method_ptr nonstatic */
3437                 if (callvirt) {
3438                         // FIXME:
3439                         mono_mb_emit_exception_full (mb, "System", "NotImplementedException", "");
3440                 } else {
3441                         mono_mb_emit_ldloc (mb, local_target);
3442                         for (i = 0; i < sig->param_count; ++i)
3443                                 mono_mb_emit_ldarg (mb, i + 1);
3444                         mono_mb_emit_ldarg (mb, 0);
3445                         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, extra_arg));
3446                         mono_mb_emit_byte (mb, CEE_LDIND_I);
3447                         mono_mb_emit_ldarg (mb, 0);
3448                         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr));
3449                         mono_mb_emit_byte (mb, CEE_LDIND_I);
3450                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
3451                         mono_mb_emit_op (mb, CEE_MONO_CALLI_EXTRA_ARG, sig);
3452                         mono_mb_emit_byte (mb, CEE_RET);
3453                 }
3454         
3455                 /* else [target == null] call this->method_ptr static */
3456                 mono_mb_patch_branch (mb, pos0);
3457         }
3458
3459         if (callvirt) {
3460                 if (!closed_over_null) {
3461                         if (target_class->valuetype) {
3462                                 mono_mb_emit_ldarg (mb, 1);
3463                                 for (i = 1; i < sig->param_count; ++i)
3464                                         mono_mb_emit_ldarg (mb, i + 1);
3465                                 mono_mb_emit_op (mb, CEE_CALL, target_method);
3466                         } else {
3467                                 mono_mb_emit_ldarg (mb, 1);
3468                                 mono_mb_emit_op (mb, CEE_CASTCLASS, target_class);
3469                                 for (i = 1; i < sig->param_count; ++i)
3470                                         mono_mb_emit_ldarg (mb, i + 1);
3471                                 mono_mb_emit_op (mb, CEE_CALLVIRT, target_method);
3472                         }
3473                 } else {
3474                         mono_mb_emit_byte (mb, CEE_LDNULL);
3475                         for (i = 0; i < sig->param_count; ++i)
3476                                 mono_mb_emit_ldarg (mb, i + 1);
3477                         mono_mb_emit_op (mb, CEE_CALL, target_method);
3478                 }
3479         } else {
3480                 if (static_method_with_first_arg_bound) {
3481                         mono_mb_emit_ldloc (mb, local_target);
3482                         if (!MONO_TYPE_IS_REFERENCE (invoke_sig->params[0]))
3483                                 mono_mb_emit_op (mb, CEE_UNBOX_ANY, mono_class_from_mono_type (invoke_sig->params[0]));
3484                 }
3485                 for (i = 0; i < sig->param_count; ++i)
3486                         mono_mb_emit_ldarg (mb, i + 1);
3487                 mono_mb_emit_ldarg (mb, 0);
3488                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, extra_arg));
3489                 mono_mb_emit_byte (mb, CEE_LDIND_I);
3490                 mono_mb_emit_ldarg (mb, 0);
3491                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr));
3492                 mono_mb_emit_byte (mb, CEE_LDIND_I);
3493                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
3494                 mono_mb_emit_op (mb, CEE_MONO_CALLI_EXTRA_ARG, invoke_sig);
3495         }
3496
3497         mono_mb_emit_byte (mb, CEE_RET);
3498
3499         /* else [delegates != null] */
3500         mono_mb_patch_branch (mb, pos2);
3501
3502         /* len = delegates.Length; */
3503         mono_mb_emit_ldloc (mb, local_delegates);
3504         mono_mb_emit_byte (mb, CEE_LDLEN);
3505         mono_mb_emit_byte (mb, CEE_CONV_I4);
3506         mono_mb_emit_stloc (mb, local_len);
3507
3508         /* i = 0; */
3509         mono_mb_emit_icon (mb, 0);
3510         mono_mb_emit_stloc (mb, local_i);
3511
3512         pos1 = mono_mb_get_label (mb);
3513
3514         /* d = delegates [i]; */
3515         mono_mb_emit_ldloc (mb, local_delegates);
3516         mono_mb_emit_ldloc (mb, local_i);
3517         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
3518         mono_mb_emit_stloc (mb, local_d);
3519
3520         /* res = d.Invoke ( args .. ); */
3521         mono_mb_emit_ldloc (mb, local_d);
3522         for (i = 0; i < sig->param_count; i++)
3523                 mono_mb_emit_ldarg (mb, i + 1);
3524         if (!ctx) {
3525                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
3526         } else {
3527                 MonoError error;
3528                 mono_mb_emit_op (mb, CEE_CALLVIRT, mono_class_inflate_generic_method_checked (method, &container->context, &error));
3529                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3530         }
3531         if (!void_ret)
3532                 mono_mb_emit_stloc (mb, local_res);
3533
3534         /* i += 1 */
3535         mono_mb_emit_add_to_local (mb, local_i, 1);
3536
3537         /* i < l */
3538         mono_mb_emit_ldloc (mb, local_i);
3539         mono_mb_emit_ldloc (mb, local_len);
3540         mono_mb_emit_branch_label (mb, CEE_BLT, pos1);
3541
3542         /* return res */
3543         if (!void_ret)
3544                 mono_mb_emit_ldloc (mb, local_res);
3545         mono_mb_emit_byte (mb, CEE_RET);
3546
3547         mb->skip_visibility = 1;
3548 #endif /* DISABLE_JIT */
3549
3550         info = mono_wrapper_info_create (mb, subtype);
3551         info->d.delegate_invoke.method = method;
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  * mono_marshal_get_native_wrapper:
7607  * @method: The MonoMethod to wrap.
7608  * @check_exceptions: Whenever to check for pending exceptions
7609  *
7610  * generates IL code for the pinvoke wrapper (the generated method
7611  * calls the unmanaged code in piinfo->addr)
7612  */
7613 MonoMethod *
7614 mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
7615 {
7616         MonoMethodSignature *sig, *csig;
7617         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7618         MonoMethodBuilder *mb;
7619         MonoMarshalSpec **mspecs;
7620         MonoMethod *res;
7621         GHashTable *cache;
7622         gboolean pinvoke = FALSE;
7623         gpointer iter;
7624         int i;
7625         const char *exc_class = "MissingMethodException";
7626         const char *exc_arg = NULL;
7627         WrapperInfo *info;
7628
7629         g_assert (method != NULL);
7630         g_assert (mono_method_signature (method)->pinvoke);
7631
7632         GHashTable **cache_ptr;
7633
7634         if (aot) {
7635                 if (check_exceptions)
7636                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_check_cache;
7637                 else
7638                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_cache;
7639         } else {
7640                 if (check_exceptions)
7641                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_check_cache;
7642                 else
7643                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_cache;
7644         }
7645
7646         cache = get_cache (cache_ptr, mono_aligned_addr_hash, NULL);
7647
7648         if ((res = mono_marshal_find_in_cache (cache, method)))
7649                 return res;
7650
7651         if (MONO_CLASS_IS_IMPORT (method->klass)) {
7652                 /* The COM code is not AOT compatible, it calls mono_custom_attrs_get_attr_checked () */
7653                 if (aot)
7654                         return method;
7655 #ifndef DISABLE_COM
7656                 return mono_cominterop_get_native_wrapper (method);
7657 #else
7658                 g_assert_not_reached ();
7659 #endif
7660         }
7661
7662         sig = mono_method_signature (method);
7663
7664         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
7665             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7666                 pinvoke = TRUE;
7667
7668         if (!piinfo->addr) {
7669                 if (pinvoke) {
7670                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
7671                                 exc_arg = "Method contains unsupported native code";
7672                         else if (!aot)
7673                                 mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7674                 } else {
7675                         piinfo->addr = mono_lookup_internal_call (method);
7676                 }
7677         }
7678
7679         /* hack - redirect certain string constructors to CreateString */
7680         if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
7681                 g_assert (!pinvoke);
7682                 g_assert (method->string_ctor);
7683                 g_assert (sig->hasthis);
7684
7685                 /* CreateString returns a value */
7686                 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7687                 csig->ret = &mono_defaults.string_class->byval_arg;
7688                 csig->pinvoke = 0;
7689
7690                 iter = NULL;
7691                 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
7692                         if (!strcmp ("CreateString", res->name) &&
7693                                 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
7694                                 WrapperInfo *info;
7695
7696                                 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
7697                                 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
7698
7699                                 /* create a wrapper to preserve .ctor in stack trace */
7700                                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
7701
7702 #ifndef DISABLE_JIT
7703                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7704                                 for (i = 1; i <= csig->param_count; i++)
7705                                         mono_mb_emit_ldarg (mb, i);
7706                                 mono_mb_emit_managed_call (mb, res, NULL);
7707                                 mono_mb_emit_byte (mb, CEE_RET);
7708 #endif
7709
7710                                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRING_CTOR);
7711                                 info->d.string_ctor.method = method;
7712
7713                                 /* use native_wrapper_cache because internal calls are looked up there */
7714                                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7715                                                                                                          csig->param_count + 1, info, NULL);
7716                                 mono_mb_free (mb);
7717
7718                                 return res;
7719                         }
7720                 }
7721
7722                 /* exception will be thrown */
7723                 piinfo->addr = NULL;
7724                 g_warning ("cannot find CreateString for .ctor");
7725         }
7726
7727         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7728
7729         mb->method->save_lmf = 1;
7730
7731         /*
7732          * In AOT mode and embedding scenarios, it is possible that the icall is not
7733          * registered in the runtime doing the AOT compilation.
7734          */
7735         if (!piinfo->addr && !aot) {
7736 #ifndef DISABLE_JIT
7737                 mono_mb_emit_exception (mb, exc_class, exc_arg);
7738 #endif
7739                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7740                 info->d.managed_to_native.method = method;
7741
7742                 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7743                 csig->pinvoke = 0;
7744                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7745                                                                                          csig->param_count + 16, info, NULL);
7746                 mono_mb_free (mb);
7747
7748                 return res;
7749         }
7750
7751         /* internal calls: we simply push all arguments and call the method (no conversions) */
7752         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
7753                 if (sig->hasthis)
7754                         csig = mono_metadata_signature_dup_add_this (method->klass->image, sig, method->klass);
7755                 else
7756                         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7757
7758                 //printf ("%s\n", mono_method_full_name (method, 1));
7759
7760                 /* hack - string constructors returns a value */
7761                 if (method->string_ctor)
7762                         csig->ret = &mono_defaults.string_class->byval_arg;
7763
7764 #ifndef DISABLE_JIT
7765                 // FIXME:
7766                 MonoClass *handle_stack_mark_class;
7767                 MonoClass *error_class;
7768                 int thread_info_var = -1, stack_mark_var = -1, error_var = -1;
7769                 MonoMethodSignature *call_sig = csig;
7770                 gboolean uses_handles;
7771                 (void) mono_lookup_internal_call_full (method, &uses_handles);
7772
7773
7774                 /* If it uses handles and MonoError, it had better check exceptions */
7775                 g_assert (!uses_handles || check_exceptions);
7776
7777                 if (uses_handles) {
7778                         MonoMethodSignature *ret;
7779
7780                         /* Add a MonoError argument */
7781                         // FIXME: The stuff from mono_metadata_signature_dup_internal_with_padding ()
7782                         ret = mono_metadata_signature_alloc (method->klass->image, csig->param_count + 1);
7783
7784                         ret->param_count = csig->param_count + 1;
7785                         ret->ret = csig->ret;
7786                         for (int i = 0; i < csig->param_count; ++i) {
7787                                 // FIXME: TODO implement handle wrapping for out and inout params.
7788                                 g_assert (!mono_signature_param_is_out (csig, i));
7789                                 ret->params [i] = csig->params [i];
7790                         }
7791                         ret->params [csig->param_count] = &mono_get_intptr_class ()->byval_arg;
7792                         call_sig = ret;
7793                 }
7794
7795                 if (uses_handles) {
7796                         handle_stack_mark_class = mono_class_load_from_name (mono_get_corlib (), "Mono", "RuntimeStructs/HandleStackMark");
7797                         error_class = mono_class_load_from_name (mono_get_corlib (), "Mono", "RuntimeStructs/MonoError");
7798
7799                         thread_info_var = mono_mb_add_local (mb, &mono_get_intptr_class ()->byval_arg);
7800                         stack_mark_var = mono_mb_add_local (mb, &handle_stack_mark_class->byval_arg);
7801                         error_var = mono_mb_add_local (mb, &error_class->byval_arg);
7802
7803                         // FIXME: Change csig so it passes a handle not an objref
7804                 }
7805
7806                 if (sig->hasthis) {
7807                         int pos;
7808
7809                         /*
7810                          * Add a null check since public icalls can be called with 'call' which
7811                          * does no such check.
7812                          */
7813                         mono_mb_emit_byte (mb, CEE_LDARG_0);                    
7814                         pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
7815                         mono_mb_emit_exception (mb, "NullReferenceException", NULL);
7816                         mono_mb_patch_branch (mb, pos);
7817                 }
7818
7819                 if (uses_handles) {
7820                         mono_mb_emit_ldloc_addr (mb, stack_mark_var);
7821                         mono_mb_emit_ldloc_addr (mb, error_var);
7822                         mono_mb_emit_icall (mb, mono_icall_start);
7823                         mono_mb_emit_stloc (mb, thread_info_var);
7824
7825                         if (sig->hasthis) {
7826                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7827                                 mono_mb_emit_icall (mb, mono_handle_new);
7828                         }
7829                         for (i = 0; i < sig->param_count; i++) {
7830                                 mono_mb_emit_ldarg (mb, i + sig->hasthis);
7831                                 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
7832                                         mono_mb_emit_icall (mb, mono_handle_new);
7833                                 }
7834                         }
7835                         mono_mb_emit_ldloc_addr (mb, error_var);
7836                 } else {
7837                         if (sig->hasthis)
7838                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7839                         for (i = 0; i < sig->param_count; i++)
7840                                 mono_mb_emit_ldarg (mb, i + sig->hasthis);
7841                 }
7842
7843                 if (aot) {
7844                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7845                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7846                         mono_mb_emit_calli (mb, call_sig);
7847                 } else {
7848                         g_assert (piinfo->addr);
7849                         mono_mb_emit_native_call (mb, call_sig, piinfo->addr);
7850                 }
7851
7852                 if (uses_handles) {
7853                         if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7854                                 // if (ret != NULL_HANDLE) {
7855                                 //   ret = MONO_HANDLE_RAW(ret)
7856                                 // }
7857                                 mono_mb_emit_byte (mb, CEE_DUP);
7858                                 int pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
7859                                 mono_mb_emit_ldflda (mb, MONO_HANDLE_PAYLOAD_OFFSET (MonoObject));
7860                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
7861                                 mono_mb_patch_branch (mb, pos);
7862                         }
7863                         mono_mb_emit_ldloc (mb, thread_info_var);
7864                         mono_mb_emit_ldloc_addr (mb, stack_mark_var);
7865                         mono_mb_emit_ldloc_addr (mb, error_var);
7866                         mono_mb_emit_icall (mb, mono_icall_end);
7867                 }
7868
7869                 if (check_exceptions)
7870                         emit_thread_interrupt_checkpoint (mb);
7871                 mono_mb_emit_byte (mb, CEE_RET);
7872 #endif
7873                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7874                 info->d.managed_to_native.method = method;
7875
7876                 csig = mono_metadata_signature_dup_full (method->klass->image, csig);
7877                 csig->pinvoke = 0;
7878                 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7879                                                                                          info, NULL);
7880
7881                 mono_mb_free (mb);
7882                 return res;
7883         }
7884
7885         g_assert (pinvoke);
7886         if (!aot)
7887                 g_assert (piinfo->addr);
7888
7889 #ifndef DISABLE_JIT
7890         mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
7891         mono_method_get_marshal_info (method, mspecs);
7892
7893         mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr, aot, check_exceptions, FALSE);
7894 #endif
7895         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PINVOKE);
7896         info->d.managed_to_native.method = method;
7897
7898         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7899         csig->pinvoke = 0;
7900         res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7901                                                                                  info, NULL);
7902         mono_mb_free (mb);
7903
7904 #ifndef DISABLE_JIT
7905         for (i = sig->param_count; i >= 0; i--)
7906                 if (mspecs [i])
7907                         mono_metadata_free_marshal_spec (mspecs [i]);
7908         g_free (mspecs);
7909 #endif
7910
7911         /* mono_method_print_code (res); */
7912
7913         return res;
7914 }
7915
7916 /**
7917  * mono_marshal_get_native_func_wrapper:
7918  * @image: The image to use for memory allocation and for looking up custom marshallers.
7919  * @sig: The signature of the function
7920  * @func: The native function to wrap
7921  *
7922  *   Returns a wrapper method around native functions, similar to the pinvoke
7923  * wrapper.
7924  */
7925 MonoMethod *
7926 mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig, 
7927                                                                           MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
7928 {
7929         MonoMethodSignature *csig;
7930
7931         SignaturePointerPair key, *new_key;
7932         MonoMethodBuilder *mb;
7933         MonoMethod *res;
7934         GHashTable *cache;
7935         gboolean found;
7936         char *name;
7937
7938         key.sig = sig;
7939         key.pointer = func;
7940
7941         // Generic types are not safe to place in MonoImage caches.
7942         g_assert (!sig->is_inflated);
7943
7944         cache = get_cache (&image->native_func_wrapper_cache, signature_pointer_pair_hash, signature_pointer_pair_equal);
7945         if ((res = mono_marshal_find_in_cache (cache, &key)))
7946                 return res;
7947
7948         name = g_strdup_printf ("wrapper_native_%p", func);
7949         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7950         mb->method->save_lmf = 1;
7951
7952 #ifndef DISABLE_JIT
7953         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE, FALSE);
7954 #endif
7955
7956         csig = mono_metadata_signature_dup_full (image, sig);
7957         csig->pinvoke = 0;
7958
7959         new_key = g_new (SignaturePointerPair,1);
7960         new_key->sig = csig;
7961         new_key->pointer = func;
7962
7963         res = mono_mb_create_and_cache_full (cache, new_key, mb, csig, csig->param_count + 16, NULL, &found);
7964         if (found)
7965                 g_free (new_key);
7966
7967         mono_mb_free (mb);
7968
7969         mono_marshal_set_wrapper_info (res, NULL);
7970
7971         return res;
7972 }
7973
7974 /*
7975  * The wrapper receives the native function as a boxed IntPtr as its 'this' argument. This is easier to support in
7976  * AOT.
7977  */
7978 MonoMethod*
7979 mono_marshal_get_native_func_wrapper_aot (MonoClass *klass)
7980 {
7981         MonoMethodSignature *sig, *csig;
7982         MonoMethodBuilder *mb;
7983         MonoMethod *res;
7984         GHashTable *cache;
7985         char *name;
7986         WrapperInfo *info;
7987         MonoMethodPInvoke mpiinfo;
7988         MonoMethodPInvoke *piinfo = &mpiinfo;
7989         MonoMarshalSpec **mspecs;
7990         MonoMethod *invoke = mono_get_delegate_invoke (klass);
7991         MonoImage *image = invoke->klass->image;
7992         int i;
7993
7994         // FIXME: include UnmanagedFunctionPointerAttribute info
7995
7996         /*
7997          * The wrapper is associated with the delegate type, to pick up the marshalling info etc.
7998          */
7999         cache = get_cache (&mono_method_get_wrapper_cache (invoke)->native_func_wrapper_aot_cache, mono_aligned_addr_hash, NULL);
8000
8001         if ((res = mono_marshal_find_in_cache (cache, invoke)))
8002                 return res;
8003
8004         memset (&mpiinfo, 0, sizeof (mpiinfo));
8005         parse_unmanaged_function_pointer_attr (klass, &mpiinfo);
8006
8007         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8008         mono_method_get_marshal_info (invoke, mspecs);
8009         /* Freed below so don't alloc from mempool */
8010         sig = mono_metadata_signature_dup (mono_method_signature (invoke));
8011         sig->hasthis = 0;
8012
8013         name = g_strdup_printf ("wrapper_aot_native");
8014         mb = mono_mb_new (invoke->klass, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8015         mb->method->save_lmf = 1;
8016
8017 #ifndef DISABLE_JIT
8018         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, NULL, FALSE, TRUE, TRUE);
8019 #endif
8020
8021         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NATIVE_FUNC_AOT);
8022         info->d.managed_to_native.method = invoke;
8023
8024         g_assert (!sig->hasthis);
8025         csig = mono_metadata_signature_dup_add_this (image, sig, mono_defaults.object_class);
8026         csig->pinvoke = 0;
8027         res = mono_mb_create_and_cache_full (cache, invoke,
8028                                                                                  mb, csig, csig->param_count + 16,
8029                                                                                  info, NULL);
8030         mono_mb_free (mb);
8031
8032         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8033                 if (mspecs [i])
8034                         mono_metadata_free_marshal_spec (mspecs [i]);
8035         g_free (mspecs);
8036         g_free (sig);
8037
8038         return res;
8039 }
8040
8041 /*
8042  * mono_marshal_emit_managed_wrapper:
8043  *
8044  *   Emit the body of a native-to-managed wrapper. INVOKE_SIG is the signature of
8045  * the delegate which wraps the managed method to be called. For closed delegates,
8046  * it could have fewer parameters than the method it wraps.
8047  * THIS_LOC is the memory location where the target of the delegate is stored.
8048  */
8049 void
8050 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, uint32_t target_handle)
8051 {
8052 #ifdef DISABLE_JIT
8053         MonoMethodSignature *sig, *csig;
8054         int i;
8055
8056         sig = m->sig;
8057         csig = m->csig;
8058
8059         /* we first do all conversions */
8060         for (i = 0; i < sig->param_count; i ++) {
8061                 MonoType *t = sig->params [i];
8062
8063                 switch (t->type) {
8064                 case MONO_TYPE_OBJECT:
8065                 case MONO_TYPE_CLASS:
8066                 case MONO_TYPE_VALUETYPE:
8067                 case MONO_TYPE_ARRAY:
8068                 case MONO_TYPE_SZARRAY:
8069                 case MONO_TYPE_STRING:
8070                 case MONO_TYPE_BOOLEAN:
8071                         emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
8072                 }
8073         }
8074
8075         if (!sig->ret->byref) {
8076                 switch (sig->ret->type) {
8077                 case MONO_TYPE_STRING:
8078                         csig->ret = &mono_defaults.int_class->byval_arg;
8079                         break;
8080                 default:
8081                         break;
8082                 }
8083         }
8084 #else
8085         MonoMethodSignature *sig, *csig;
8086         MonoExceptionClause *clauses, *clause_finally, *clause_catch;
8087         int i, *tmp_locals, ex_local, e_local, attach_cookie_local, attach_dummy_local;
8088         int leave_try_pos, leave_catch_pos, ex_m1_pos;
8089         gboolean closed = FALSE;
8090
8091         sig = m->sig;
8092         csig = m->csig;
8093
8094         /* allocate local 0 (pointer) src_ptr */
8095         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8096         /* allocate local 1 (pointer) dst_ptr */
8097         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8098         /* allocate local 2 (boolean) delete_old */
8099         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8100
8101         if (!sig->hasthis && sig->param_count != invoke_sig->param_count) {
8102                 /* Closed delegate */
8103                 g_assert (sig->param_count == invoke_sig->param_count + 1);
8104                 closed = TRUE;
8105                 /* Use a new signature without the first argument */
8106                 sig = mono_metadata_signature_dup (sig);
8107                 memmove (&sig->params [0], &sig->params [1], (sig->param_count - 1) * sizeof (MonoType*));
8108                 sig->param_count --;
8109         }
8110
8111         if (!MONO_TYPE_IS_VOID(sig->ret)) {
8112                 /* allocate local 3 to store the return value */
8113                 mono_mb_add_local (mb, sig->ret);
8114         }
8115
8116         if (MONO_TYPE_ISSTRUCT (sig->ret))
8117                 m->vtaddr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8118
8119         ex_local = mono_mb_add_local (mb, &mono_defaults.uint32_class->byval_arg);
8120         e_local = mono_mb_add_local (mb, &mono_defaults.exception_class->byval_arg);
8121
8122         attach_cookie_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8123         attach_dummy_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8124
8125         /*
8126          * guint32 ex = -1;
8127          * try {
8128          *   // does (STARTING|RUNNING|BLOCKING) -> RUNNING + set/switch domain
8129          *   mono_threads_attach_coop ();
8130          *
8131          *   <interrupt check>
8132          *
8133          *   ret = method (...);
8134          * } catch (Exception e) {
8135          *   ex = mono_gchandle_new (e, false);
8136          * } finally {
8137          *   // does RUNNING -> (RUNNING|BLOCKING) + unset/switch domain
8138          *   mono_threads_detach_coop ();
8139          *
8140          *   if (ex != -1)
8141          *     mono_marshal_ftnptr_eh_callback (ex);
8142          * }
8143          *
8144          * return ret;
8145          */
8146
8147         clauses = g_new0 (MonoExceptionClause, 2);
8148
8149         clause_catch = &clauses [0];
8150         clause_catch->flags = MONO_EXCEPTION_CLAUSE_NONE;
8151         clause_catch->data.catch_class = mono_defaults.exception_class;
8152
8153         clause_finally = &clauses [1];
8154         clause_finally->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
8155
8156         mono_mb_emit_icon (mb, 0);
8157         mono_mb_emit_stloc (mb, 2);
8158
8159         mono_mb_emit_icon (mb, -1);
8160         mono_mb_emit_byte (mb, CEE_CONV_U4);
8161         mono_mb_emit_stloc (mb, ex_local);
8162
8163         /* try { */
8164         clause_catch->try_offset = clause_finally->try_offset = mono_mb_get_label (mb);
8165
8166         if (!mono_threads_is_coop_enabled ()) {
8167                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8168                 mono_mb_emit_byte (mb, CEE_MONO_JIT_ATTACH);
8169         } else {
8170                 /* mono_threads_attach_coop (); */
8171                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8172                 mono_mb_emit_byte (mb, CEE_MONO_LDDOMAIN);
8173                 mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
8174                 mono_mb_emit_icall (mb, mono_threads_attach_coop);
8175                 mono_mb_emit_stloc (mb, attach_cookie_local);
8176         }
8177
8178         /* <interrupt check> */
8179         emit_thread_interrupt_checkpoint (mb);
8180
8181         /* we first do all conversions */
8182         tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
8183         for (i = 0; i < sig->param_count; i ++) {
8184                 MonoType *t = sig->params [i];
8185
8186                 switch (t->type) {
8187                 case MONO_TYPE_OBJECT:
8188                 case MONO_TYPE_CLASS:
8189                 case MONO_TYPE_VALUETYPE:
8190                 case MONO_TYPE_ARRAY:
8191                 case MONO_TYPE_SZARRAY:
8192                 case MONO_TYPE_STRING:
8193                 case MONO_TYPE_BOOLEAN:
8194                         tmp_locals [i] = emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
8195
8196                         break;
8197                 default:
8198                         tmp_locals [i] = 0;
8199                         break;
8200                 }
8201         }
8202
8203         if (sig->hasthis) {
8204                 if (target_handle) {
8205                         mono_mb_emit_icon (mb, (gint32)target_handle);
8206                         mono_mb_emit_icall (mb, mono_gchandle_get_target);
8207                 } else {
8208                         /* fixme: */
8209                         g_assert_not_reached ();
8210                 }
8211         } else if (closed) {
8212                 mono_mb_emit_icon (mb, (gint32)target_handle);
8213                 mono_mb_emit_icall (mb, mono_gchandle_get_target);
8214         }
8215
8216         for (i = 0; i < sig->param_count; i++) {
8217                 MonoType *t = sig->params [i];
8218
8219                 if (tmp_locals [i]) {
8220                         if (t->byref)
8221                                 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
8222                         else
8223                                 mono_mb_emit_ldloc (mb, tmp_locals [i]);
8224                 }
8225                 else
8226                         mono_mb_emit_ldarg (mb, i);
8227         }
8228
8229         /* ret = method (...) */
8230         mono_mb_emit_managed_call (mb, method, NULL);
8231
8232         if (MONO_TYPE_ISSTRUCT (sig->ret)) {
8233                 MonoClass *klass = mono_class_from_mono_type (sig->ret);
8234                 mono_class_init (klass);
8235                 if (!(((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) || klass->blittable)) {
8236                         /* This is used by emit_marshal_vtype (), but it needs to go right before the call */
8237                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8238                         mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
8239                         mono_mb_emit_stloc (mb, m->vtaddr_var);
8240                 }
8241         }
8242
8243         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
8244                 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8245         } else if (!sig->ret->byref) { 
8246                 switch (sig->ret->type) {
8247                 case MONO_TYPE_VOID:
8248                         break;
8249                 case MONO_TYPE_BOOLEAN:
8250                 case MONO_TYPE_I1:
8251                 case MONO_TYPE_U1:
8252                 case MONO_TYPE_CHAR:
8253                 case MONO_TYPE_I2:
8254                 case MONO_TYPE_U2:
8255                 case MONO_TYPE_I4:
8256                 case MONO_TYPE_U4:
8257                 case MONO_TYPE_I:
8258                 case MONO_TYPE_U:
8259                 case MONO_TYPE_PTR:
8260                 case MONO_TYPE_R4:
8261                 case MONO_TYPE_R8:
8262                 case MONO_TYPE_I8:
8263                 case MONO_TYPE_U8:
8264                 case MONO_TYPE_OBJECT:
8265                         mono_mb_emit_stloc (mb, 3);
8266                         break;
8267                 case MONO_TYPE_STRING:
8268                         csig->ret = &mono_defaults.int_class->byval_arg;
8269                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8270                         break;
8271                 case MONO_TYPE_VALUETYPE:
8272                 case MONO_TYPE_CLASS:
8273                 case MONO_TYPE_SZARRAY:
8274                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8275                         break;
8276                 default:
8277                         g_warning ("return type 0x%02x unknown", sig->ret->type);       
8278                         g_assert_not_reached ();
8279                 }
8280         } else {
8281                 mono_mb_emit_stloc (mb, 3);
8282         }
8283
8284         /* Convert byref arguments back */
8285         for (i = 0; i < sig->param_count; i ++) {
8286                 MonoType *t = sig->params [i];
8287                 MonoMarshalSpec *spec = mspecs [i + 1];
8288
8289                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
8290                         emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8291                 }
8292                 else if (t->byref) {
8293                         switch (t->type) {
8294                         case MONO_TYPE_CLASS:
8295                         case MONO_TYPE_VALUETYPE:
8296                         case MONO_TYPE_OBJECT:
8297                         case MONO_TYPE_STRING:
8298                         case MONO_TYPE_BOOLEAN:
8299                                 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8300                                 break;
8301                         default:
8302                                 break;
8303                         }
8304                 }
8305                 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
8306                         /* The [Out] information is encoded in the delegate signature */
8307                         switch (t->type) {
8308                         case MONO_TYPE_SZARRAY:
8309                         case MONO_TYPE_CLASS:
8310                         case MONO_TYPE_VALUETYPE:
8311                                 emit_marshal (m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8312                                 break;
8313                         default:
8314                                 g_assert_not_reached ();
8315                         }
8316                 }
8317         }
8318
8319         leave_try_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8320
8321         /* } [endtry] */
8322
8323         /* catch (Exception e) { */
8324         clause_catch->try_len = mono_mb_get_label (mb) - clause_catch->try_offset;
8325         clause_catch->handler_offset = mono_mb_get_label (mb);
8326
8327         mono_mb_emit_stloc (mb, e_local);
8328
8329         /* ex = mono_gchandle_new (e, false); */
8330         mono_mb_emit_ldloc (mb, e_local);
8331         mono_mb_emit_icon (mb, 0);
8332         mono_mb_emit_icall (mb, mono_gchandle_new);
8333         mono_mb_emit_stloc (mb, ex_local);
8334
8335         leave_catch_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8336
8337         /* } [endcatch] */
8338         clause_catch->handler_len = mono_mb_get_pos (mb) - clause_catch->handler_offset;
8339
8340         /* finally { */
8341         clause_finally->try_len = mono_mb_get_label (mb) - clause_finally->try_offset;
8342         clause_finally->handler_offset = mono_mb_get_label (mb);
8343
8344         if (!mono_threads_is_coop_enabled ()) {
8345                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8346                 mono_mb_emit_byte (mb, CEE_MONO_JIT_DETACH);
8347         } else {
8348                 /* mono_threads_detach_coop (); */
8349                 mono_mb_emit_ldloc (mb, attach_cookie_local);
8350                 mono_mb_emit_ldloc_addr (mb, attach_dummy_local);
8351                 mono_mb_emit_icall (mb, mono_threads_detach_coop);
8352         }
8353
8354         /* if (ex != -1) */
8355         mono_mb_emit_ldloc (mb, ex_local);
8356         mono_mb_emit_icon (mb, -1);
8357         mono_mb_emit_byte (mb, CEE_CONV_U4);
8358         ex_m1_pos = mono_mb_emit_branch (mb, CEE_BEQ);
8359
8360         /* mono_marshal_ftnptr_eh_callback (ex) */
8361         mono_mb_emit_ldloc (mb, ex_local);
8362         mono_mb_emit_icall (mb, mono_marshal_ftnptr_eh_callback);
8363
8364         /* [ex == -1] */
8365         mono_mb_patch_branch (mb, ex_m1_pos);
8366
8367         mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8368
8369         /* } [endfinally] */
8370         clause_finally->handler_len = mono_mb_get_pos (mb) - clause_finally->handler_offset;
8371
8372         mono_mb_patch_branch (mb, leave_try_pos);
8373         mono_mb_patch_branch (mb, leave_catch_pos);
8374
8375         /* return ret; */
8376         if (m->retobj_var) {
8377                 mono_mb_emit_ldloc (mb, m->retobj_var);
8378                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8379                 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m->retobj_class);
8380         }
8381         else {
8382                 if (!MONO_TYPE_IS_VOID(sig->ret))
8383                         mono_mb_emit_ldloc (mb, 3);
8384                 mono_mb_emit_byte (mb, CEE_RET);
8385         }
8386
8387         mono_mb_set_clauses (mb, 2, clauses);
8388
8389         if (closed)
8390                 g_free (sig);
8391 #endif
8392 }
8393
8394 static void 
8395 mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *csig)
8396 {
8397         MonoMethodSignature *sig;
8398         int i;
8399
8400 #ifdef TARGET_WIN32
8401         /* 
8402          * Under windows, delegates passed to native code must use the STDCALL
8403          * calling convention.
8404          */
8405         csig->call_convention = MONO_CALL_STDCALL;
8406 #endif
8407
8408         sig = mono_method_signature (method);
8409
8410         /* Change default calling convention if needed */
8411         /* Why is this a modopt ? */
8412         if (sig->ret && sig->ret->num_mods) {
8413                 for (i = 0; i < sig->ret->num_mods; ++i) {
8414                         MonoError error;
8415                         MonoClass *cmod_class = mono_class_get_checked (method->klass->image, sig->ret->modifiers [i].token, &error);
8416                         g_assert (mono_error_ok (&error));
8417                         if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
8418                                 if (!strcmp (cmod_class->name, "CallConvCdecl"))
8419                                         csig->call_convention = MONO_CALL_C;
8420                                 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
8421                                         csig->call_convention = MONO_CALL_STDCALL;
8422                                 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
8423                                         csig->call_convention = MONO_CALL_FASTCALL;
8424                                 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
8425                                         csig->call_convention = MONO_CALL_THISCALL;
8426                         }
8427                 }
8428         }
8429 }
8430
8431 /*
8432  * generates IL code to call managed methods from unmanaged code 
8433  * If target_handle==0, the wrapper info will be a WrapperInfo structure.
8434  */
8435 MonoMethod *
8436 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle)
8437 {
8438         MonoError error;
8439         MonoMethodSignature *sig, *csig, *invoke_sig;
8440         MonoMethodBuilder *mb;
8441         MonoMethod *res, *invoke;
8442         MonoMarshalSpec **mspecs;
8443         MonoMethodPInvoke piinfo;
8444         GHashTable *cache;
8445         int i;
8446         EmitMarshalContext m;
8447
8448         g_assert (method != NULL);
8449         g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
8450
8451         /* 
8452          * FIXME: Should cache the method+delegate type pair, since the same method
8453          * could be called with different delegates, thus different marshalling
8454          * options.
8455          */
8456         cache = get_cache (&mono_method_get_wrapper_cache (method)->managed_wrapper_cache, mono_aligned_addr_hash, NULL);
8457
8458         if (!target_handle && (res = mono_marshal_find_in_cache (cache, method)))
8459                 return res;
8460
8461         invoke = mono_get_delegate_invoke (delegate_klass);
8462         invoke_sig = mono_method_signature (invoke);
8463
8464         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8465         mono_method_get_marshal_info (invoke, mspecs);
8466
8467         sig = mono_method_signature (method);
8468
8469         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8470
8471         /*the target gchandle must be the first entry after size and the wrapper itself.*/
8472         mono_mb_add_data (mb, GUINT_TO_POINTER (target_handle));
8473
8474         /* we copy the signature, so that we can modify it */
8475         if (target_handle)
8476                 /* Need to free this later */
8477                 csig = mono_metadata_signature_dup (invoke_sig);
8478         else
8479                 csig = mono_metadata_signature_dup_full (method->klass->image, invoke_sig);
8480         csig->hasthis = 0;
8481         csig->pinvoke = 1;
8482
8483         memset (&m, 0, sizeof (m));
8484         m.mb = mb;
8485         m.sig = sig;
8486         m.piinfo = NULL;
8487         m.retobj_var = 0;
8488         m.csig = csig;
8489         m.image = method->klass->image;
8490
8491         mono_marshal_set_callconv_from_modopt (invoke, csig);
8492
8493         /* The attribute is only available in Net 2.0 */
8494         if (mono_class_try_get_unmanaged_function_pointer_attribute_class ()) {
8495                 MonoCustomAttrInfo *cinfo;
8496                 MonoCustomAttrEntry *attr;
8497
8498                 /* 
8499                  * The pinvoke attributes are stored in a real custom attribute. Obtain the
8500                  * contents of the attribute without constructing it, as that might not be
8501                  * possible when running in cross-compiling mode.
8502                  */
8503                 cinfo = mono_custom_attrs_from_class_checked (delegate_klass, &error);
8504                 mono_error_assert_ok (&error);
8505                 attr = NULL;
8506                 if (cinfo) {
8507                         for (i = 0; i < cinfo->num_attrs; ++i) {
8508                                 MonoClass *ctor_class = cinfo->attrs [i].ctor->klass;
8509                                 if (mono_class_has_parent (ctor_class, mono_class_try_get_unmanaged_function_pointer_attribute_class ())) {
8510                                         attr = &cinfo->attrs [i];
8511                                         break;
8512                                 }
8513                         }
8514                 }
8515                 if (attr) {
8516                         MonoArray *typed_args, *named_args;
8517                         CattrNamedArg *arginfo;
8518                         MonoObject *o;
8519                         gint32 call_conv;
8520                         gint32 charset = 0;
8521                         MonoBoolean set_last_error = 0;
8522                         MonoError error;
8523
8524                         mono_reflection_create_custom_attr_data_args (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8525                         g_assert (mono_error_ok (&error));
8526                         g_assert (mono_array_length (typed_args) == 1);
8527
8528                         /* typed args */
8529                         o = mono_array_get (typed_args, MonoObject*, 0);
8530                         call_conv = *(gint32*)mono_object_unbox (o);
8531
8532                         /* named args */
8533                         for (i = 0; i < mono_array_length (named_args); ++i) {
8534                                 CattrNamedArg *narg = &arginfo [i];
8535
8536                                 o = mono_array_get (named_args, MonoObject*, i);
8537
8538                                 g_assert (narg->field);
8539                                 if (!strcmp (narg->field->name, "CharSet")) {
8540                                         charset = *(gint32*)mono_object_unbox (o);
8541                                 } else if (!strcmp (narg->field->name, "SetLastError")) {
8542                                         set_last_error = *(MonoBoolean*)mono_object_unbox (o);
8543                                 } else if (!strcmp (narg->field->name, "BestFitMapping")) {
8544                                         // best_fit_mapping = *(MonoBoolean*)mono_object_unbox (o);
8545                                 } else if (!strcmp (narg->field->name, "ThrowOnUnmappableChar")) {
8546                                         // throw_on_unmappable = *(MonoBoolean*)mono_object_unbox (o);
8547                                 } else {
8548                                         g_assert_not_reached ();
8549                                 }
8550                         }
8551
8552                         g_free (arginfo);
8553
8554                         memset (&piinfo, 0, sizeof (piinfo));
8555                         m.piinfo = &piinfo;
8556                         piinfo.piflags = (call_conv << 8) | (charset ? (charset - 1) * 2 : 1) | set_last_error;
8557
8558                         csig->call_convention = call_conv - 1;
8559                 }
8560
8561                 if (cinfo && !cinfo->cached)
8562                         mono_custom_attrs_free (cinfo);
8563         }
8564
8565         mono_marshal_emit_managed_wrapper (mb, invoke_sig, mspecs, &m, method, target_handle);
8566
8567         if (!target_handle) {
8568                 WrapperInfo *info;
8569
8570                 // FIXME: Associate it with the method+delegate_klass pair
8571                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8572                 info->d.native_to_managed.method = method;
8573                 info->d.native_to_managed.klass = delegate_klass;
8574
8575                 res = mono_mb_create_and_cache_full (cache, method,
8576                                                                                          mb, csig, sig->param_count + 16,
8577                                                                                          info, NULL);
8578         } else {
8579 #ifndef DISABLE_JIT
8580                 mb->dynamic = TRUE;
8581 #endif
8582                 res = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
8583         }
8584         mono_mb_free (mb);
8585
8586         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8587                 if (mspecs [i])
8588                         mono_metadata_free_marshal_spec (mspecs [i]);
8589         g_free (mspecs);
8590
8591         /* mono_method_print_code (res); */
8592
8593         return res;
8594 }
8595
8596 gpointer
8597 mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
8598 {
8599         MonoError error;
8600         MonoMethod *method;
8601         MonoMethodSignature *sig;
8602         MonoMethodBuilder *mb;
8603         int i, param_count;
8604
8605         g_assert (token);
8606
8607         method = mono_get_method_checked (image, token, NULL, NULL, &error);
8608         if (!method)
8609                 g_error ("Could not load vtfixup token 0x%x due to %s", token, mono_error_get_message (&error));
8610         g_assert (method);
8611
8612         if (type & (VTFIXUP_TYPE_FROM_UNMANAGED | VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN)) {
8613                 MonoMethodSignature *csig;
8614                 MonoMarshalSpec **mspecs;
8615                 EmitMarshalContext m;
8616
8617                 sig = mono_method_signature (method);
8618                 g_assert (!sig->hasthis);
8619
8620                 mspecs = g_new0 (MonoMarshalSpec*, sig->param_count + 1);
8621                 mono_method_get_marshal_info (method, mspecs);
8622
8623                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8624                 csig = mono_metadata_signature_dup_full (image, sig);
8625                 csig->hasthis = 0;
8626                 csig->pinvoke = 1;
8627
8628                 memset (&m, 0, sizeof (m));
8629                 m.mb = mb;
8630                 m.sig = sig;
8631                 m.piinfo = NULL;
8632                 m.retobj_var = 0;
8633                 m.csig = csig;
8634                 m.image = image;
8635
8636                 mono_marshal_set_callconv_from_modopt (method, csig);
8637
8638                 /* FIXME: Implement VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN. */
8639
8640                 mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, 0);
8641
8642 #ifndef DISABLE_JIT
8643                 mb->dynamic = TRUE;
8644 #endif
8645                 method = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
8646                 mono_mb_free (mb);
8647
8648                 for (i = sig->param_count; i >= 0; i--)
8649                         if (mspecs [i])
8650                                 mono_metadata_free_marshal_spec (mspecs [i]);
8651                 g_free (mspecs);
8652
8653                 gpointer compiled_ptr = mono_compile_method_checked (method, &error);
8654                 mono_error_assert_ok (&error);
8655                 return compiled_ptr;
8656         }
8657
8658         sig = mono_method_signature (method);
8659         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
8660
8661         param_count = sig->param_count + sig->hasthis;
8662 #ifndef DISABLE_JIT
8663         for (i = 0; i < param_count; i++)
8664                 mono_mb_emit_ldarg (mb, i);
8665
8666         if (type & VTFIXUP_TYPE_CALL_MOST_DERIVED)
8667                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
8668         else
8669                 mono_mb_emit_op (mb, CEE_CALL, method);
8670         mono_mb_emit_byte (mb, CEE_RET);
8671
8672         mb->dynamic = TRUE;
8673 #endif
8674
8675         method = mono_mb_create (mb, sig, param_count, NULL);
8676         mono_mb_free (mb);
8677
8678         gpointer compiled_ptr = mono_compile_method_checked (method, &error);
8679         mono_error_assert_ok (&error);
8680         return compiled_ptr;
8681 }
8682
8683 #ifndef DISABLE_JIT
8684
8685 /*
8686  * The code directly following this is the cache hit, value positive branch
8687  *
8688  * This function takes a new method builder with 0 locals and adds two locals
8689  * to create multiple out-branches and the fall through state of having the object
8690  * on the stack after a cache miss
8691  */
8692 static void
8693 generate_check_cache (int obj_arg_position, int class_arg_position, int cache_arg_position, // In-parameters
8694                                                                                         int *null_obj, int *cache_hit_neg, int *cache_hit_pos, // Out-parameters
8695                                                                                         MonoMethodBuilder *mb)
8696 {
8697         int cache_miss_pos;
8698
8699         /* allocate local 0 (pointer) obj_vtable */
8700         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8701         /* allocate local 1 (pointer) cached_vtable */
8702         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8703
8704         /*if (!obj)*/
8705         mono_mb_emit_ldarg (mb, obj_arg_position);
8706         *null_obj = mono_mb_emit_branch (mb, CEE_BRFALSE);
8707
8708         /*obj_vtable = obj->vtable;*/
8709         mono_mb_emit_ldarg (mb, obj_arg_position);
8710         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
8711         mono_mb_emit_byte (mb, CEE_LDIND_I);
8712         mono_mb_emit_stloc (mb, 0);
8713
8714         /* cached_vtable = *cache*/
8715         mono_mb_emit_ldarg (mb, cache_arg_position);
8716         mono_mb_emit_byte (mb, CEE_LDIND_I);
8717         mono_mb_emit_stloc (mb, 1);
8718
8719         mono_mb_emit_ldloc (mb, 1);
8720         mono_mb_emit_byte (mb, CEE_LDC_I4);
8721         mono_mb_emit_i4 (mb, ~0x1);
8722         mono_mb_emit_byte (mb, CEE_CONV_I);
8723         mono_mb_emit_byte (mb, CEE_AND);
8724         mono_mb_emit_ldloc (mb, 0);
8725         /*if ((cached_vtable & ~0x1)== obj_vtable)*/
8726         cache_miss_pos = mono_mb_emit_branch (mb, CEE_BNE_UN);
8727
8728         /*return (cached_vtable & 0x1) ? NULL : obj;*/
8729         mono_mb_emit_ldloc (mb, 1);
8730         mono_mb_emit_byte(mb, CEE_LDC_I4_1);
8731         mono_mb_emit_byte (mb, CEE_CONV_U);
8732         mono_mb_emit_byte (mb, CEE_AND);
8733         *cache_hit_neg = mono_mb_emit_branch (mb, CEE_BRTRUE);
8734         *cache_hit_pos = mono_mb_emit_branch (mb, CEE_BR);
8735
8736         // slow path
8737         mono_mb_patch_branch (mb, cache_miss_pos);
8738
8739         // if isinst
8740         mono_mb_emit_ldarg (mb, obj_arg_position);
8741         mono_mb_emit_ldarg (mb, class_arg_position);
8742         mono_mb_emit_ldarg (mb, cache_arg_position);
8743         mono_mb_emit_icall (mb, mono_marshal_isinst_with_cache);
8744 }
8745
8746 #endif /* DISABLE_JIT */
8747
8748 /*
8749  * This does the equivalent of mono_object_castclass_with_cache.
8750  */
8751 MonoMethod *
8752 mono_marshal_get_castclass_with_cache (void)
8753 {
8754         static MonoMethod *cached;
8755         MonoMethod *res;
8756         MonoMethodBuilder *mb;
8757         MonoMethodSignature *sig;
8758         int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos, invalid_cast_pos;
8759         WrapperInfo *info;
8760
8761         const int obj_arg_position = 0;
8762         const int class_arg_position = 1;
8763         const int cache_arg_position = 2;
8764
8765         if (cached)
8766                 return cached;
8767
8768         mb = mono_mb_new (mono_defaults.object_class, "__castclass_with_cache", MONO_WRAPPER_CASTCLASS);
8769         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8770         sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
8771         sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
8772         sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
8773         sig->ret = &mono_defaults.object_class->byval_arg;
8774         sig->pinvoke = 0;
8775
8776 #ifndef DISABLE_JIT
8777         generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
8778                                                                                                 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
8779         invalid_cast_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8780
8781         /*return obj;*/
8782         mono_mb_patch_branch (mb, positive_cache_hit_pos);
8783         mono_mb_emit_ldarg (mb, obj_arg_position);
8784         mono_mb_emit_byte (mb, CEE_RET);
8785
8786         /*fails*/
8787         mono_mb_patch_branch (mb, negative_cache_hit_pos);
8788         mono_mb_patch_branch (mb, invalid_cast_pos);
8789         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8790
8791         /*return null*/
8792         mono_mb_patch_branch (mb, return_null_pos);
8793         mono_mb_emit_byte (mb, CEE_LDNULL);
8794         mono_mb_emit_byte (mb, CEE_RET);
8795 #endif /* DISABLE_JIT */
8796
8797         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE);
8798         res = mono_mb_create (mb, sig, 8, info);
8799         STORE_STORE_FENCE;
8800
8801         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8802                 mono_free_method (res);
8803                 mono_metadata_free_method_signature (sig);
8804         }
8805         mono_mb_free (mb);
8806
8807         return cached;
8808 }
8809
8810 /* this is an icall */
8811 static MonoObject *
8812 mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *cache)
8813 {
8814         MonoError error;
8815         MonoObject *isinst = mono_object_isinst_checked (obj, klass, &error);
8816         if (mono_error_set_pending_exception (&error))
8817                 return NULL;
8818
8819 #ifndef DISABLE_REMOTING
8820         if (obj->vtable->klass == mono_defaults.transparent_proxy_class)
8821                 return isinst;
8822 #endif
8823
8824         uintptr_t cache_update = (uintptr_t)obj->vtable;
8825         if (!isinst)
8826                 cache_update = cache_update | 0x1;
8827
8828         *cache = cache_update;
8829
8830         return isinst;
8831 }
8832
8833 /*
8834  * This does the equivalent of mono_object_isinst_with_cache.
8835  */
8836 MonoMethod *
8837 mono_marshal_get_isinst_with_cache (void)
8838 {
8839         static MonoMethod *cached;
8840         MonoMethod *res;
8841         MonoMethodBuilder *mb;
8842         MonoMethodSignature *sig;
8843         int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos;
8844         WrapperInfo *info;
8845
8846         const int obj_arg_position = 0;
8847         const int class_arg_position = 1;
8848         const int cache_arg_position = 2;
8849
8850         if (cached)
8851                 return cached;
8852
8853         mb = mono_mb_new (mono_defaults.object_class, "__isinst_with_cache", MONO_WRAPPER_CASTCLASS);
8854         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8855         // The object
8856         sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
8857         // The class
8858         sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
8859         // The cache
8860         sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
8861         sig->ret = &mono_defaults.object_class->byval_arg;
8862         sig->pinvoke = 0;
8863
8864 #ifndef DISABLE_JIT
8865         generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
8866                 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
8867         // Return the object gotten via the slow path.
8868         mono_mb_emit_byte (mb, CEE_RET);
8869
8870         // return NULL;
8871         mono_mb_patch_branch (mb, negative_cache_hit_pos);
8872         mono_mb_patch_branch (mb, return_null_pos);
8873         mono_mb_emit_byte (mb, CEE_LDNULL);
8874         mono_mb_emit_byte (mb, CEE_RET);
8875
8876         // return obj
8877         mono_mb_patch_branch (mb, positive_cache_hit_pos);
8878         mono_mb_emit_ldarg (mb, obj_arg_position);
8879         mono_mb_emit_byte (mb, CEE_RET);
8880 #endif
8881
8882         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ISINST_WITH_CACHE);
8883         res = mono_mb_create (mb, sig, 8, info);
8884         STORE_STORE_FENCE;
8885
8886         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8887                 mono_free_method (res);
8888                 mono_metadata_free_method_signature (sig);
8889         }
8890         mono_mb_free (mb);
8891
8892         return cached;
8893 }
8894
8895 /*
8896  * mono_marshal_get_isinst:
8897  * @klass: the type of the field
8898  *
8899  * This method generates a function which can be used to check if an object is
8900  * an instance of the given type, icluding the case where the object is a proxy.
8901  * The generated function has the following signature:
8902  * MonoObject* __isinst_wrapper_ (MonoObject *obj)
8903  */
8904 MonoMethod *
8905 mono_marshal_get_isinst (MonoClass *klass)
8906 {
8907         static MonoMethodSignature *isint_sig = NULL;
8908         GHashTable *cache;
8909         MonoMethod *res;
8910         WrapperInfo *info;
8911         int pos_was_ok, pos_end;
8912 #ifndef DISABLE_REMOTING
8913         int pos_end2, pos_failed;
8914 #endif
8915         char *name;
8916         MonoMethodBuilder *mb;
8917
8918         cache = get_cache (&klass->image->isinst_cache, mono_aligned_addr_hash, NULL);
8919         if ((res = mono_marshal_find_in_cache (cache, klass)))
8920                 return res;
8921
8922         if (!isint_sig) {
8923                 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8924                 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
8925                 isint_sig->ret = &mono_defaults.object_class->byval_arg;
8926                 isint_sig->pinvoke = 0;
8927         }
8928         
8929         name = g_strdup_printf ("__isinst_wrapper_%s", klass->name); 
8930         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ISINST);
8931         g_free (name);
8932         
8933         mb->method->save_lmf = 1;
8934
8935 #ifndef DISABLE_JIT
8936         /* check if the object is a proxy that needs special cast */
8937         mono_mb_emit_ldarg (mb, 0);
8938         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8939         mono_mb_emit_op (mb, CEE_MONO_CISINST, klass);
8940
8941         /* The result of MONO_CISINST can be:
8942                 0) the type check succeeded
8943                 1) the type check did not succeed
8944                 2) a CanCastTo call is needed */
8945 #ifndef DISABLE_REMOTING
8946         mono_mb_emit_byte (mb, CEE_DUP);
8947         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8948
8949         mono_mb_emit_byte (mb, CEE_LDC_I4_2);
8950         pos_failed = mono_mb_emit_branch (mb, CEE_BNE_UN);
8951         
8952         /* get the real proxy from the transparent proxy*/
8953
8954         mono_mb_emit_ldarg (mb, 0);
8955         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8956         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8957         
8958         /* fail */
8959         
8960         mono_mb_patch_branch (mb, pos_failed);
8961         mono_mb_emit_byte (mb, CEE_LDNULL);
8962         pos_end2 = mono_mb_emit_branch (mb, CEE_BR);
8963         
8964         /* success */
8965         
8966         mono_mb_patch_branch (mb, pos_was_ok);
8967         mono_mb_emit_byte (mb, CEE_POP);
8968         mono_mb_emit_ldarg (mb, 0);
8969         
8970         /* the end */
8971         
8972         mono_mb_patch_branch (mb, pos_end);
8973         mono_mb_patch_branch (mb, pos_end2);
8974         mono_mb_emit_byte (mb, CEE_RET);
8975 #else
8976         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8977
8978         /* fail */
8979
8980         mono_mb_emit_byte (mb, CEE_LDNULL);
8981         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8982
8983         /* success */
8984
8985         mono_mb_patch_branch (mb, pos_was_ok);
8986         mono_mb_emit_ldarg (mb, 0);
8987
8988         /* the end */
8989
8990         mono_mb_patch_branch (mb, pos_end);
8991         mono_mb_emit_byte (mb, CEE_RET);
8992 #endif /* DISABLE_REMOTING */
8993 #endif /* DISABLE_JIT */
8994
8995         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8996         info->d.proxy.klass = klass;
8997         res = mono_mb_create_and_cache_full (cache, klass, mb, isint_sig, isint_sig->param_count + 16, info, NULL);
8998         mono_mb_free (mb);
8999
9000         return res;
9001 }
9002
9003 /*
9004  * mono_marshal_get_castclass:
9005  * @klass: the type of the field
9006  *
9007  * This method generates a function which can be used to cast an object to
9008  * an instance of the given type, icluding the case where the object is a proxy.
9009  * The generated function has the following signature:
9010  * MonoObject* __castclass_wrapper_ (MonoObject *obj)
9011  */
9012 MonoMethod *
9013 mono_marshal_get_castclass (MonoClass *klass)
9014 {
9015         static MonoMethodSignature *castclass_sig = NULL;
9016         GHashTable *cache;
9017         MonoMethod *res;
9018 #ifndef DISABLE_REMOTING
9019         int pos_was_ok, pos_was_ok2;
9020 #endif
9021         char *name;
9022         MonoMethodBuilder *mb;
9023         WrapperInfo *info;
9024
9025         cache = get_cache (&klass->image->castclass_cache, mono_aligned_addr_hash, NULL);
9026         if ((res = mono_marshal_find_in_cache (cache, klass)))
9027                 return res;
9028
9029         if (!castclass_sig) {
9030                 castclass_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
9031                 castclass_sig->params [0] = &mono_defaults.object_class->byval_arg;
9032                 castclass_sig->ret = &mono_defaults.object_class->byval_arg;
9033                 castclass_sig->pinvoke = 0;
9034         }
9035         
9036         name = g_strdup_printf ("__castclass_wrapper_%s", klass->name); 
9037         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_CASTCLASS);
9038         g_free (name);
9039         
9040         mb->method->save_lmf = 1;
9041
9042 #ifndef DISABLE_JIT
9043         /* check if the object is a proxy that needs special cast */
9044         mono_mb_emit_ldarg (mb, 0);
9045         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
9046         mono_mb_emit_op (mb, CEE_MONO_CCASTCLASS, klass);
9047
9048         /* The result of MONO_CCASTCLASS can be:
9049                 0) the cast is valid
9050                 1) cast of unknown proxy type
9051                 or an exception if the cast is is invalid
9052         */
9053 #ifndef DISABLE_REMOTING
9054         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
9055
9056         /* get the real proxy from the transparent proxy*/
9057
9058         mono_mb_emit_ldarg (mb, 0);
9059         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
9060         pos_was_ok2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
9061         
9062         /* fail */
9063         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
9064         
9065         /* success */
9066         mono_mb_patch_branch (mb, pos_was_ok);
9067         mono_mb_patch_branch (mb, pos_was_ok2);
9068 #else
9069         /* MONO_CCASTCLASS leaves an int in the stack with the result, pop it. */
9070         mono_mb_emit_byte (mb, CEE_POP);
9071 #endif /* DISABLE_REMOTING */
9072
9073         mono_mb_emit_ldarg (mb, 0);
9074         
9075         /* the end */
9076         mono_mb_emit_byte (mb, CEE_RET);
9077 #endif /* DISABLE_JIT */
9078
9079         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9080
9081         res = mono_mb_create_and_cache_full (cache, klass, mb, castclass_sig, castclass_sig->param_count + 16,
9082                                                                                  info, NULL);
9083         mono_mb_free (mb);
9084
9085         return res;
9086 }
9087
9088 /**
9089  * mono_marshal_get_struct_to_ptr:
9090  * @klass:
9091  *
9092  * generates IL code for StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)
9093  */
9094 MonoMethod *
9095 mono_marshal_get_struct_to_ptr (MonoClass *klass)
9096 {
9097         MonoMethodBuilder *mb;
9098         static MonoMethod *stoptr = NULL;
9099         MonoMethod *res;
9100         WrapperInfo *info;
9101
9102         g_assert (klass != NULL);
9103
9104         mono_marshal_load_type_info (klass);
9105
9106         if (klass->marshal_info->str_to_ptr)
9107                 return klass->marshal_info->str_to_ptr;
9108
9109         if (!stoptr) 
9110                 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
9111         g_assert (stoptr);
9112
9113         mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
9114
9115 #ifndef DISABLE_JIT
9116         if (klass->blittable) {
9117                 mono_mb_emit_byte (mb, CEE_LDARG_1);
9118                 mono_mb_emit_byte (mb, CEE_LDARG_0);
9119                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9120                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
9121                 mono_mb_emit_byte (mb, CEE_PREFIX1);
9122                 mono_mb_emit_byte (mb, CEE_CPBLK);
9123         } else {
9124
9125                 /* allocate local 0 (pointer) src_ptr */
9126                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9127                 /* allocate local 1 (pointer) dst_ptr */
9128                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9129                 /* allocate local 2 (boolean) delete_old */
9130                 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9131                 mono_mb_emit_byte (mb, CEE_LDARG_2);
9132                 mono_mb_emit_stloc (mb, 2);
9133
9134                 /* initialize src_ptr to point to the start of object data */
9135                 mono_mb_emit_byte (mb, CEE_LDARG_0);
9136                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9137                 mono_mb_emit_stloc (mb, 0);
9138
9139                 /* initialize dst_ptr */
9140                 mono_mb_emit_byte (mb, CEE_LDARG_1);
9141                 mono_mb_emit_stloc (mb, 1);
9142
9143                 emit_struct_conv (mb, klass, FALSE);
9144         }
9145
9146         mono_mb_emit_byte (mb, CEE_RET);
9147 #endif
9148         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRUCTURE_TO_PTR);
9149         res = mono_mb_create (mb, mono_signature_no_pinvoke (stoptr), 0, info);
9150         mono_mb_free (mb);
9151
9152         mono_marshal_lock ();
9153         if (!klass->marshal_info->str_to_ptr)
9154                 klass->marshal_info->str_to_ptr = res;
9155         else
9156                 res = klass->marshal_info->str_to_ptr;
9157         mono_marshal_unlock ();
9158         return res;
9159 }
9160
9161 /**
9162  * mono_marshal_get_ptr_to_struct:
9163  * @klass:
9164  *
9165  * generates IL code for PtrToStructure (IntPtr src, object structure)
9166  */
9167 MonoMethod *
9168 mono_marshal_get_ptr_to_struct (MonoClass *klass)
9169 {
9170         MonoMethodBuilder *mb;
9171         static MonoMethodSignature *ptostr = NULL;
9172         MonoMethod *res;
9173         WrapperInfo *info;
9174
9175         g_assert (klass != NULL);
9176
9177         mono_marshal_load_type_info (klass);
9178
9179         if (klass->marshal_info->ptr_to_str)
9180                 return klass->marshal_info->ptr_to_str;
9181
9182         if (!ptostr) {
9183                 MonoMethodSignature *sig;
9184
9185                 /* Create the signature corresponding to
9186                           static void PtrToStructure (IntPtr ptr, object structure);
9187                    defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
9188                 sig = mono_create_icall_signature ("void ptr object");
9189                 sig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
9190                 sig->pinvoke = 0;
9191                 mono_memory_barrier ();
9192                 ptostr = sig;
9193         }
9194
9195         mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
9196
9197 #ifndef DISABLE_JIT
9198         if (klass->blittable) {
9199                 mono_mb_emit_byte (mb, CEE_LDARG_1);
9200                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
9201                 mono_mb_emit_byte (mb, CEE_LDARG_0);
9202                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
9203                 mono_mb_emit_byte (mb, CEE_PREFIX1);
9204                 mono_mb_emit_byte (mb, CEE_CPBLK);
9205         } else {
9206
9207                 /* allocate local 0 (pointer) src_ptr */
9208                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9209                 /* allocate local 1 (pointer) dst_ptr */
9210                 mono_mb_add_local (mb, &klass->this_arg);
9211                 
9212                 /* initialize src_ptr to point to the start of object data */
9213                 mono_mb_emit_byte (mb, CEE_LDARG_0);
9214                 mono_mb_emit_stloc (mb, 0);
9215
9216                 /* initialize dst_ptr */
9217                 mono_mb_emit_byte (mb, CEE_LDARG_1);
9218                 mono_mb_emit_op (mb, CEE_UNBOX, klass);
9219                 mono_mb_emit_stloc (mb, 1);
9220
9221                 emit_struct_conv (mb, klass, TRUE);
9222         }
9223
9224         mono_mb_emit_byte (mb, CEE_RET);
9225 #endif
9226         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PTR_TO_STRUCTURE);
9227         res = mono_mb_create (mb, ptostr, 0, info);
9228         mono_mb_free (mb);
9229
9230         mono_marshal_lock ();
9231         if (!klass->marshal_info->ptr_to_str)
9232                 klass->marshal_info->ptr_to_str = res;
9233         else
9234                 res = klass->marshal_info->ptr_to_str;
9235         mono_marshal_unlock ();
9236         return res;
9237 }
9238
9239 /*
9240  * Return a dummy wrapper for METHOD which is called by synchronized wrappers.
9241  * This is used to avoid infinite recursion since it is hard to determine where to
9242  * replace a method with its synchronized wrapper, and where not.
9243  * The runtime should execute METHOD instead of the wrapper.
9244  */
9245 MonoMethod *
9246 mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
9247 {
9248         MonoMethodBuilder *mb;
9249         WrapperInfo *info;
9250         MonoMethodSignature *sig;
9251         MonoMethod *res;
9252         MonoGenericContext *ctx = NULL;
9253         MonoGenericContainer *container = NULL;
9254
9255         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9256                 ctx = &((MonoMethodInflated*)method)->context;
9257                 method = ((MonoMethodInflated*)method)->declaring;
9258                 container = mono_method_get_generic_container (method);
9259                 if (!container)
9260                         container = method->klass->generic_container;
9261                 g_assert (container);
9262         }
9263
9264         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
9265 #ifndef DISABLE_JIT
9266         mono_mb_emit_exception_full (mb, "System", "ExecutionEngineException", "Shouldn't be called.");
9267         mono_mb_emit_byte (mb, CEE_RET);
9268 #endif
9269         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9270
9271         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_SYNCHRONIZED_INNER);
9272         info->d.synchronized_inner.method = method;
9273         res = mono_mb_create (mb, sig, 0, info);
9274         mono_mb_free (mb);
9275         if (ctx) {
9276                 MonoError error;
9277                 res = mono_class_inflate_generic_method_checked (res, ctx, &error);
9278                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9279         }
9280         return res;
9281 }
9282
9283 /*
9284  * generates IL code for the synchronized wrapper: the generated method
9285  * calls METHOD while locking 'this' or the parent type.
9286  */
9287 MonoMethod *
9288 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
9289 {
9290         static MonoMethod *enter_method, *exit_method, *gettypefromhandle_method;
9291         MonoMethodSignature *sig;
9292         MonoExceptionClause *clause;
9293         MonoMethodBuilder *mb;
9294         MonoMethod *res;
9295         GHashTable *cache;
9296         WrapperInfo *info;
9297         int i, pos, pos2, this_local, taken_local, ret_local = 0;
9298         MonoGenericContext *ctx = NULL;
9299         MonoMethod *orig_method = NULL;
9300         MonoGenericContainer *container = NULL;
9301
9302         g_assert (method);
9303
9304         if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
9305                 return method;
9306
9307         /* FIXME: Support generic methods too */
9308         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9309                 orig_method = method;
9310                 ctx = &((MonoMethodInflated*)method)->context;
9311                 method = ((MonoMethodInflated*)method)->declaring;
9312                 container = mono_method_get_generic_container (method);
9313                 if (!container)
9314                         container = method->klass->generic_container;
9315                 g_assert (container);
9316         }
9317
9318         /*
9319          * Check cache
9320          */
9321         if (ctx) {
9322                 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9323                 res = check_generic_wrapper_cache (cache, orig_method, orig_method, method);
9324                 if (res)
9325                         return res;
9326         } else {
9327                 cache = get_cache (&method->klass->image->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9328                 if ((res = mono_marshal_find_in_cache (cache, method)))
9329                         return res;
9330         }
9331
9332         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9333         sig->pinvoke = 0;
9334
9335         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
9336
9337         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9338         info->d.synchronized.method = method;
9339
9340 #ifndef DISABLE_JIT
9341         mb->skip_visibility = 1;
9342         /* result */
9343         if (!MONO_TYPE_IS_VOID (sig->ret))
9344                 ret_local = mono_mb_add_local (mb, sig->ret);
9345 #endif
9346
9347         if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
9348                 mono_class_set_failure (method->klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
9349 #ifndef DISABLE_JIT
9350                 /* This will throw the type load exception when the wrapper is compiled */
9351                 mono_mb_emit_byte (mb, CEE_LDNULL);
9352                 mono_mb_emit_op (mb, CEE_ISINST, method->klass);
9353                 mono_mb_emit_byte (mb, CEE_POP);
9354
9355                 if (!MONO_TYPE_IS_VOID (sig->ret))
9356                         mono_mb_emit_ldloc (mb, ret_local);
9357                 mono_mb_emit_byte (mb, CEE_RET);
9358 #endif
9359
9360                 res = mono_mb_create_and_cache_full (cache, method,
9361                                                                                          mb, sig, sig->param_count + 16, info, NULL);
9362                 mono_mb_free (mb);
9363
9364                 return res;
9365         }
9366
9367 #ifndef DISABLE_JIT
9368         /* this */
9369         this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
9370         taken_local = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9371
9372         clause = (MonoExceptionClause *)mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
9373         clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
9374 #endif
9375
9376         mono_marshal_lock ();
9377
9378         if (!enter_method) {
9379                 MonoMethodDesc *desc;
9380
9381                 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
9382                 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9383                 g_assert (enter_method);
9384                 mono_method_desc_free (desc);
9385
9386                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
9387                 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9388                 g_assert (exit_method);
9389                 mono_method_desc_free (desc);
9390
9391                 desc = mono_method_desc_new ("Type:GetTypeFromHandle", FALSE);
9392                 gettypefromhandle_method = mono_method_desc_search_in_class (desc, mono_defaults.systemtype_class);
9393                 g_assert (gettypefromhandle_method);
9394                 mono_method_desc_free (desc);
9395         }
9396
9397         mono_marshal_unlock ();
9398
9399 #ifndef DISABLE_JIT
9400         /* Push this or the type object */
9401         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
9402                 /* We have special handling for this in the JIT */
9403                 int index = mono_mb_add_data (mb, method->klass);
9404                 mono_mb_add_data (mb, mono_defaults.typehandle_class);
9405                 mono_mb_emit_byte (mb, CEE_LDTOKEN);
9406                 mono_mb_emit_i4 (mb, index);
9407
9408                 mono_mb_emit_managed_call (mb, gettypefromhandle_method, NULL);
9409         }
9410         else
9411                 mono_mb_emit_ldarg (mb, 0);
9412         mono_mb_emit_stloc (mb, this_local);
9413
9414         /* Call Monitor::Enter() */
9415         mono_mb_emit_ldloc (mb, this_local);
9416         mono_mb_emit_ldloc_addr (mb, taken_local);
9417         mono_mb_emit_managed_call (mb, enter_method, NULL);
9418
9419         clause->try_offset = mono_mb_get_label (mb);
9420
9421         /* Call the method */
9422         if (sig->hasthis)
9423                 mono_mb_emit_ldarg (mb, 0);
9424         for (i = 0; i < sig->param_count; i++)
9425                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
9426
9427         if (ctx) {
9428                 MonoError error;
9429                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
9430                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9431         } else {
9432                 mono_mb_emit_managed_call (mb, method, NULL);
9433         }
9434
9435         if (!MONO_TYPE_IS_VOID (sig->ret))
9436                 mono_mb_emit_stloc (mb, ret_local);
9437
9438         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
9439
9440         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
9441         clause->handler_offset = mono_mb_get_label (mb);
9442
9443         /* Call Monitor::Exit() if needed */
9444         mono_mb_emit_ldloc (mb, taken_local);
9445         pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9446         mono_mb_emit_ldloc (mb, this_local);
9447         mono_mb_emit_managed_call (mb, exit_method, NULL);
9448         mono_mb_patch_branch (mb, pos2);
9449         mono_mb_emit_byte (mb, CEE_ENDFINALLY);
9450
9451         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
9452
9453         mono_mb_patch_branch (mb, pos);
9454         if (!MONO_TYPE_IS_VOID (sig->ret))
9455                 mono_mb_emit_ldloc (mb, ret_local);
9456         mono_mb_emit_byte (mb, CEE_RET);
9457
9458         mono_mb_set_clauses (mb, 1, clause);
9459 #endif
9460
9461         if (ctx) {
9462                 MonoMethod *def;
9463                 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
9464                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
9465         } else {
9466                 res = mono_mb_create_and_cache_full (cache, method,
9467                                                                                          mb, sig, sig->param_count + 16, info, NULL);
9468         }
9469         mono_mb_free (mb);
9470
9471         return res;     
9472 }
9473
9474
9475 /*
9476  * the returned method calls 'method' unboxing the this argument
9477  */
9478 MonoMethod *
9479 mono_marshal_get_unbox_wrapper (MonoMethod *method)
9480 {
9481         MonoMethodSignature *sig = mono_method_signature (method);
9482         int i;
9483         MonoMethodBuilder *mb;
9484         MonoMethod *res;
9485         GHashTable *cache;
9486         WrapperInfo *info;
9487
9488         cache = get_cache (&mono_method_get_wrapper_cache (method)->unbox_wrapper_cache, mono_aligned_addr_hash, NULL);
9489
9490         if ((res = mono_marshal_find_in_cache (cache, method)))
9491                 return res;
9492
9493         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
9494
9495         g_assert (sig->hasthis);
9496         
9497 #ifndef DISABLE_JIT
9498         mono_mb_emit_ldarg (mb, 0); 
9499         mono_mb_emit_icon (mb, sizeof (MonoObject));
9500         mono_mb_emit_byte (mb, CEE_ADD);
9501         for (i = 0; i < sig->param_count; ++i)
9502                 mono_mb_emit_ldarg (mb, i + 1);
9503         mono_mb_emit_managed_call (mb, method, NULL);
9504         mono_mb_emit_byte (mb, CEE_RET);
9505 #endif
9506
9507         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9508         info->d.unbox.method = method;
9509
9510         res = mono_mb_create_and_cache_full (cache, method,
9511                                                                                  mb, sig, sig->param_count + 16, info, NULL);
9512         mono_mb_free (mb);
9513
9514         /* mono_method_print_code (res); */
9515
9516         return res;     
9517 }
9518
9519 enum {
9520         STELEMREF_OBJECT, /*no check at all*/
9521         STELEMREF_SEALED_CLASS, /*check vtable->klass->element_type */
9522         STELEMREF_CLASS, /*only the klass->parents check*/
9523         STELEMREF_INTERFACE, /*interfaces without variant generic arguments. */
9524         STELEMREF_COMPLEX, /*arrays, MBR or types with variant generic args - go straight to icalls*/
9525         STELEMREF_KIND_COUNT
9526 };
9527
9528 static const char *strelemref_wrapper_name[] = {
9529         "object", "sealed_class", "class", "interface", "complex"
9530 };
9531
9532 static gboolean
9533 is_monomorphic_array (MonoClass *klass)
9534 {
9535         MonoClass *element_class;
9536         if (klass->rank != 1)
9537                 return FALSE;
9538
9539         element_class = klass->element_class;
9540         return (element_class->flags & TYPE_ATTRIBUTE_SEALED) || element_class->valuetype;
9541 }
9542
9543 static int
9544 get_virtual_stelemref_kind (MonoClass *element_class)
9545 {
9546         if (element_class == mono_defaults.object_class)
9547                 return STELEMREF_OBJECT;
9548         if (is_monomorphic_array (element_class))
9549                 return STELEMREF_SEALED_CLASS;
9550         /* Compressed interface bitmaps require code that is quite complex, so don't optimize for it. */
9551         if (MONO_CLASS_IS_INTERFACE (element_class) && !mono_class_has_variant_generic_params (element_class))
9552 #ifdef COMPRESSED_INTERFACE_BITMAP
9553                 return STELEMREF_COMPLEX;
9554 #else
9555                 return STELEMREF_INTERFACE;
9556 #endif
9557         /*Arrays are sealed but are covariant on their element type, We can't use any of the fast paths.*/
9558         if (mono_class_is_marshalbyref (element_class) || element_class->rank || mono_class_has_variant_generic_params (element_class))
9559                 return STELEMREF_COMPLEX;
9560         if (element_class->flags & TYPE_ATTRIBUTE_SEALED)
9561                 return STELEMREF_SEALED_CLASS;
9562         return STELEMREF_CLASS;
9563 }
9564
9565 #ifndef DISABLE_JIT
9566
9567 static void
9568 load_array_element_address (MonoMethodBuilder *mb)
9569 {
9570         mono_mb_emit_ldarg (mb, 0);
9571         mono_mb_emit_ldarg (mb, 1);
9572         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9573 }
9574
9575 static void
9576 load_array_class (MonoMethodBuilder *mb, int aklass)
9577 {
9578         mono_mb_emit_ldarg (mb, 0);
9579         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9580         mono_mb_emit_byte (mb, CEE_LDIND_I);
9581         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9582         mono_mb_emit_byte (mb, CEE_LDIND_I);
9583         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9584         mono_mb_emit_byte (mb, CEE_LDIND_I);
9585         mono_mb_emit_stloc (mb, aklass);
9586 }
9587
9588 static void
9589 load_value_class (MonoMethodBuilder *mb, int vklass)
9590 {
9591         mono_mb_emit_ldarg (mb, 2);
9592         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9593         mono_mb_emit_byte (mb, CEE_LDIND_I);
9594         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9595         mono_mb_emit_byte (mb, CEE_LDIND_I);
9596         mono_mb_emit_stloc (mb, vklass);
9597 }
9598 #endif
9599
9600 #if 0
9601 static void
9602 record_slot_vstore (MonoObject *array, size_t index, MonoObject *value)
9603 {
9604         char *name = mono_type_get_full_name (array->vtable->klass->element_class);
9605         printf ("slow vstore of %s\n", name);
9606         g_free (name);
9607 }
9608 #endif
9609
9610 /*
9611  * TODO:
9612  *      - Separate simple interfaces from variant interfaces or mbr types. This way we can avoid the icall for them.
9613  *      - Emit a (new) mono bytecode that produces OP_COND_EXC_NE_UN to raise ArrayTypeMismatch
9614  *      - Maybe mve some MonoClass field into the vtable to reduce the number of loads
9615  *      - Add a case for arrays of arrays.
9616  */
9617 static MonoMethod*
9618 get_virtual_stelemref_wrapper (int kind)
9619 {
9620         static MonoMethod *cached_methods [STELEMREF_KIND_COUNT] = { NULL }; /*object iface sealed regular*/
9621         static MonoMethodSignature *signature;
9622         MonoMethodBuilder *mb;
9623         MonoMethod *res;
9624         char *name;
9625         const char *param_names [16];
9626         guint32 b1, b2, b3, b4;
9627         int aklass, vklass, vtable, uiid;
9628         int array_slot_addr;
9629         WrapperInfo *info;
9630
9631         if (cached_methods [kind])
9632                 return cached_methods [kind];
9633
9634         name = g_strdup_printf ("virt_stelemref_%s", strelemref_wrapper_name [kind]);
9635         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STELEMREF);
9636         g_free (name);
9637
9638         if (!signature) {
9639                 MonoMethodSignature *sig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
9640
9641                 /* void this::stelemref (size_t idx, void* value) */
9642                 sig->ret = &mono_defaults.void_class->byval_arg;
9643                 sig->hasthis = TRUE;
9644                 sig->params [0] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9645                 sig->params [1] = &mono_defaults.object_class->byval_arg;
9646                 signature = sig;
9647         }
9648
9649 #ifndef DISABLE_JIT
9650         param_names [0] = "index";
9651         param_names [1] = "value";
9652         mono_mb_set_param_names (mb, param_names);
9653
9654         /*For now simply call plain old stelemref*/
9655         switch (kind) {
9656         case STELEMREF_OBJECT:
9657                 /* ldelema (implicit bound check) */
9658                 load_array_element_address (mb);
9659                 /* do_store */
9660                 mono_mb_emit_ldarg (mb, 2);
9661                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9662                 mono_mb_emit_byte (mb, CEE_RET);
9663                 break;
9664
9665         case STELEMREF_COMPLEX:
9666                 /*
9667                 <ldelema (bound check)>
9668                 if (!value)
9669                         goto store;
9670                 if (!mono_object_isinst (value, aklass))
9671                         goto do_exception;
9672
9673                  do_store:
9674                          *array_slot_addr = value;
9675
9676                 do_exception:
9677                         throw new ArrayTypeMismatchException ();
9678                 */
9679
9680                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9681                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9682
9683 #if 0
9684                 {
9685                         /*Use this to debug/record stores that are going thru the slow path*/
9686                         MonoMethodSignature *csig;
9687                         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9688                         csig->ret = &mono_defaults.void_class->byval_arg;
9689                         csig->params [0] = &mono_defaults.object_class->byval_arg;
9690                         csig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9691                         csig->params [2] = &mono_defaults.object_class->byval_arg;
9692                         mono_mb_emit_ldarg (mb, 0);
9693                         mono_mb_emit_ldarg (mb, 1);
9694                         mono_mb_emit_ldarg (mb, 2);
9695                         mono_mb_emit_native_call (mb, csig, record_slot_vstore);
9696                 }
9697 #endif
9698
9699                 /* ldelema (implicit bound check) */
9700                 load_array_element_address (mb);
9701                 mono_mb_emit_stloc (mb, array_slot_addr);
9702
9703                 /* if (!value) goto do_store */
9704                 mono_mb_emit_ldarg (mb, 2);
9705                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9706
9707                 /* aklass = array->vtable->klass->element_class */
9708                 load_array_class (mb, aklass);
9709
9710                 /*if (mono_object_isinst (value, aklass)) */
9711                 mono_mb_emit_ldarg (mb, 2);
9712                 mono_mb_emit_ldloc (mb, aklass);
9713                 mono_mb_emit_icall (mb, mono_object_isinst_icall);
9714                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9715
9716                 /* do_store: */
9717                 mono_mb_patch_branch (mb, b1);
9718                 mono_mb_emit_ldloc (mb, array_slot_addr);
9719                 mono_mb_emit_ldarg (mb, 2);
9720                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9721                 mono_mb_emit_byte (mb, CEE_RET);
9722
9723                 /* do_exception: */
9724                 mono_mb_patch_branch (mb, b2);
9725
9726                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9727                 break;
9728
9729         case STELEMREF_SEALED_CLASS:
9730                 /*
9731                 <ldelema (bound check)>
9732                 if (!value)
9733                         goto store;
9734
9735                 aklass = array->vtable->klass->element_class;
9736                 vklass = value->vtable->klass;
9737
9738                 if (vklass != aklass)
9739                         goto do_exception;
9740
9741                 do_store:
9742                          *array_slot_addr = value;
9743
9744                 do_exception:
9745                         throw new ArrayTypeMismatchException ();
9746                 */
9747                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9748                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9749                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9750
9751
9752                 /* ldelema (implicit bound check) */
9753                 load_array_element_address (mb);
9754                 mono_mb_emit_stloc (mb, array_slot_addr);
9755
9756                 /* if (!value) goto do_store */
9757                 mono_mb_emit_ldarg (mb, 2);
9758                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9759
9760                 /* aklass = array->vtable->klass->element_class */
9761                 load_array_class (mb, aklass);
9762
9763                 /* vklass = value->vtable->klass */
9764                 load_value_class (mb, vklass);
9765
9766                 /*if (vklass != aklass) goto do_exception; */
9767                 mono_mb_emit_ldloc (mb, aklass);
9768                 mono_mb_emit_ldloc (mb, vklass);
9769                 b2 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9770
9771                 /* do_store: */
9772                 mono_mb_patch_branch (mb, b1);
9773                 mono_mb_emit_ldloc (mb, array_slot_addr);
9774                 mono_mb_emit_ldarg (mb, 2);
9775                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9776                 mono_mb_emit_byte (mb, CEE_RET);
9777
9778                 /* do_exception: */
9779                 mono_mb_patch_branch (mb, b2);
9780                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9781                 break;
9782
9783         case STELEMREF_CLASS:
9784                 /*
9785                 the method:
9786                 <ldelema (bound check)>
9787                 if (!value)
9788                         goto do_store;
9789
9790                 aklass = array->vtable->klass->element_class;
9791                 vklass = value->vtable->klass;
9792
9793                 if (vklass->idepth < aklass->idepth)
9794                         goto do_exception;
9795
9796                 if (vklass->supertypes [aklass->idepth - 1] != aklass)
9797                         goto do_exception;
9798
9799                 do_store:
9800                         *array_slot_addr = value;
9801                         return;
9802
9803                 long:
9804                         throw new ArrayTypeMismatchException ();
9805                 */
9806                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9807                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9808                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9809
9810                 /* ldelema (implicit bound check) */
9811                 load_array_element_address (mb);
9812                 mono_mb_emit_stloc (mb, array_slot_addr);
9813
9814                 /* if (!value) goto do_store */
9815                 mono_mb_emit_ldarg (mb, 2);
9816                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9817
9818                 /* aklass = array->vtable->klass->element_class */
9819                 load_array_class (mb, aklass);
9820
9821                 /* vklass = value->vtable->klass */
9822                 load_value_class (mb, vklass);
9823
9824                 /*if (mono_object_isinst (value, aklass)) */
9825                 mono_mb_emit_ldarg (mb, 2);
9826                 mono_mb_emit_ldloc (mb, aklass);
9827                 mono_mb_emit_icall (mb, mono_object_isinst_icall);
9828                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9829
9830                 /* if (vklass->idepth < aklass->idepth) goto failue */
9831                 mono_mb_emit_ldloc (mb, vklass);
9832                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9833                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9834
9835                 mono_mb_emit_ldloc (mb, aklass);
9836                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9837                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9838
9839                 b3 = mono_mb_emit_branch (mb, CEE_BLT_UN);
9840
9841                 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
9842                 mono_mb_emit_ldloc (mb, vklass);
9843                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
9844                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9845
9846                 mono_mb_emit_ldloc (mb, aklass);
9847                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9848                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9849                 mono_mb_emit_icon (mb, 1);
9850                 mono_mb_emit_byte (mb, CEE_SUB);
9851                 mono_mb_emit_icon (mb, sizeof (void*));
9852                 mono_mb_emit_byte (mb, CEE_MUL);
9853                 mono_mb_emit_byte (mb, CEE_ADD);
9854                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9855
9856                 mono_mb_emit_ldloc (mb, aklass);
9857                 b4 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9858
9859                 /* do_store: */
9860                 mono_mb_patch_branch (mb, b1);
9861                 mono_mb_emit_ldloc (mb, array_slot_addr);
9862                 mono_mb_emit_ldarg (mb, 2);
9863                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9864                 mono_mb_emit_byte (mb, CEE_RET);
9865
9866                 /* do_exception: */
9867                 mono_mb_patch_branch (mb, b2);
9868                 mono_mb_patch_branch (mb, b3);
9869                 mono_mb_patch_branch (mb, b4);
9870
9871                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9872                 break;
9873
9874         case STELEMREF_INTERFACE:
9875                 /*Mono *klass;
9876                 MonoVTable *vt;
9877                 unsigned uiid;
9878                 if (value == NULL)
9879                         goto store;
9880
9881                 klass = array->obj.vtable->klass->element_class;
9882                 vt = value->vtable;
9883                 uiid = klass->interface_id;
9884                 if (uiid > vt->max_interface_id)
9885                         goto exception;
9886                 if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7))))
9887                         goto exception;
9888                 store:
9889                         mono_array_setref (array, index, value);
9890                         return;
9891                 exception:
9892                         mono_raise_exception (mono_get_exception_array_type_mismatch ());*/
9893
9894                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9895                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9896                 vtable = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9897                 uiid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9898
9899                 /* ldelema (implicit bound check) */
9900                 load_array_element_address (mb);
9901                 mono_mb_emit_stloc (mb, array_slot_addr);
9902
9903                 /* if (!value) goto do_store */
9904                 mono_mb_emit_ldarg (mb, 2);
9905                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9906
9907                 /* klass = array->vtable->klass->element_class */
9908                 load_array_class (mb, aklass);
9909
9910                 /* vt = value->vtable */
9911                 mono_mb_emit_ldarg (mb, 2);
9912                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9913                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9914                 mono_mb_emit_stloc (mb, vtable);
9915
9916                 /* uiid = klass->interface_id; */
9917                 mono_mb_emit_ldloc (mb, aklass);
9918                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, interface_id));
9919                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9920                 mono_mb_emit_stloc (mb, uiid);
9921
9922                 /*if (uiid > vt->max_interface_id)*/
9923                 mono_mb_emit_ldloc (mb, uiid);
9924                 mono_mb_emit_ldloc (mb, vtable);
9925                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, max_interface_id));
9926                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9927                 b2 = mono_mb_emit_branch (mb, CEE_BGT_UN);
9928
9929                 /* if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7)))) */
9930
9931                 /*vt->interface_bitmap*/
9932                 mono_mb_emit_ldloc (mb, vtable);
9933                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, interface_bitmap));
9934                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9935
9936                 /*uiid >> 3*/
9937                 mono_mb_emit_ldloc (mb, uiid);
9938                 mono_mb_emit_icon (mb, 3);
9939                 mono_mb_emit_byte (mb, CEE_SHR_UN);
9940
9941                 /*vt->interface_bitmap [(uiid) >> 3]*/
9942                 mono_mb_emit_byte (mb, CEE_ADD); /*interface_bitmap is a guint8 array*/
9943                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
9944
9945                 /*(1 << ((uiid)&7)))*/
9946                 mono_mb_emit_icon (mb, 1);
9947                 mono_mb_emit_ldloc (mb, uiid);
9948                 mono_mb_emit_icon (mb, 7);
9949                 mono_mb_emit_byte (mb, CEE_AND);
9950                 mono_mb_emit_byte (mb, CEE_SHL);
9951
9952                 /*bitwise and the whole thing*/
9953                 mono_mb_emit_byte (mb, CEE_AND);
9954                 b3 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9955
9956                 /* do_store: */
9957                 mono_mb_patch_branch (mb, b1);
9958                 mono_mb_emit_ldloc (mb, array_slot_addr);
9959                 mono_mb_emit_ldarg (mb, 2);
9960                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9961                 mono_mb_emit_byte (mb, CEE_RET);
9962
9963                 /* do_exception: */
9964                 mono_mb_patch_branch (mb, b2);
9965                 mono_mb_patch_branch (mb, b3);
9966                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9967                 break;
9968
9969         default:
9970                 mono_mb_emit_ldarg (mb, 0);
9971                 mono_mb_emit_ldarg (mb, 1);
9972                 mono_mb_emit_ldarg (mb, 2);
9973                 mono_mb_emit_managed_call (mb, mono_marshal_get_stelemref (), NULL);
9974                 mono_mb_emit_byte (mb, CEE_RET);
9975                 g_assert (0);
9976         }
9977 #endif /* DISABLE_JIT */
9978         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_VIRTUAL_STELEMREF);
9979         info->d.virtual_stelemref.kind = kind;
9980         res = mono_mb_create (mb, signature, 4, info);
9981         res->flags |= METHOD_ATTRIBUTE_VIRTUAL;
9982
9983         mono_marshal_lock ();
9984         if (!cached_methods [kind]) {
9985                 cached_methods [kind] = res;
9986                 mono_marshal_unlock ();
9987         } else {
9988                 mono_marshal_unlock ();
9989                 mono_free_method (res);
9990         }
9991
9992         mono_mb_free (mb);
9993         return cached_methods [kind];
9994 }
9995
9996 MonoMethod*
9997 mono_marshal_get_virtual_stelemref (MonoClass *array_class)
9998 {
9999         int kind;
10000
10001         g_assert (array_class->rank == 1);
10002         kind = get_virtual_stelemref_kind (array_class->element_class);
10003
10004         return get_virtual_stelemref_wrapper (kind);
10005 }
10006
10007 MonoMethod**
10008 mono_marshal_get_virtual_stelemref_wrappers (int *nwrappers)
10009 {
10010         MonoMethod **res;
10011         int i;
10012
10013         *nwrappers = STELEMREF_KIND_COUNT;
10014         res = (MonoMethod **)g_malloc0 (STELEMREF_KIND_COUNT * sizeof (MonoMethod*));
10015         for (i = 0; i < STELEMREF_KIND_COUNT; ++i)
10016                 res [i] = get_virtual_stelemref_wrapper (i);
10017         return res;
10018 }
10019
10020 MonoMethod*
10021 mono_marshal_get_stelemref (void)
10022 {
10023         static MonoMethod* ret = NULL;
10024         MonoMethodSignature *sig;
10025         MonoMethodBuilder *mb;
10026         WrapperInfo *info;
10027         
10028         guint32 b1, b2, b3, b4;
10029         guint32 copy_pos;
10030         int aklass, vklass;
10031         int array_slot_addr;
10032         
10033         if (ret)
10034                 return ret;
10035         
10036         mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
10037         
10038
10039         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
10040
10041         /* void stelemref (void* array, int idx, void* value) */
10042         sig->ret = &mono_defaults.void_class->byval_arg;
10043         sig->params [0] = &mono_defaults.object_class->byval_arg;
10044         sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
10045         sig->params [2] = &mono_defaults.object_class->byval_arg;
10046
10047 #ifndef DISABLE_JIT
10048         aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10049         vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10050         array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
10051         
10052         /*
10053         the method:
10054         <ldelema (bound check)>
10055         if (!value)
10056                 goto store;
10057         
10058         aklass = array->vtable->klass->element_class;
10059         vklass = value->vtable->klass;
10060         
10061         if (vklass->idepth < aklass->idepth)
10062                 goto long;
10063         
10064         if (vklass->supertypes [aklass->idepth - 1] != aklass)
10065                 goto long;
10066         
10067         store:
10068                 *array_slot_addr = value;
10069                 return;
10070         
10071         long:
10072                 if (mono_object_isinst (value, aklass))
10073                         goto store;
10074                 
10075                 throw new ArrayTypeMismatchException ();
10076         */
10077         
10078         /* ldelema (implicit bound check) */
10079         mono_mb_emit_ldarg (mb, 0);
10080         mono_mb_emit_ldarg (mb, 1);
10081         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
10082         mono_mb_emit_stloc (mb, array_slot_addr);
10083                 
10084         /* if (!value) goto do_store */
10085         mono_mb_emit_ldarg (mb, 2);
10086         b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
10087         
10088         /* aklass = array->vtable->klass->element_class */
10089         mono_mb_emit_ldarg (mb, 0);
10090         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10091         mono_mb_emit_byte (mb, CEE_LDIND_I);
10092         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10093         mono_mb_emit_byte (mb, CEE_LDIND_I);
10094         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
10095         mono_mb_emit_byte (mb, CEE_LDIND_I);
10096         mono_mb_emit_stloc (mb, aklass);
10097         
10098         /* vklass = value->vtable->klass */
10099         mono_mb_emit_ldarg (mb, 2);
10100         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10101         mono_mb_emit_byte (mb, CEE_LDIND_I);
10102         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10103         mono_mb_emit_byte (mb, CEE_LDIND_I);
10104         mono_mb_emit_stloc (mb, vklass);
10105         
10106         /* if (vklass->idepth < aklass->idepth) goto failue */
10107         mono_mb_emit_ldloc (mb, vklass);
10108         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10109         mono_mb_emit_byte (mb, CEE_LDIND_U2);
10110         
10111         mono_mb_emit_ldloc (mb, aklass);
10112         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10113         mono_mb_emit_byte (mb, CEE_LDIND_U2);
10114         
10115         b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
10116         
10117         /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
10118         mono_mb_emit_ldloc (mb, vklass);
10119         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
10120         mono_mb_emit_byte (mb, CEE_LDIND_I);
10121         
10122         mono_mb_emit_ldloc (mb, aklass);
10123         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
10124         mono_mb_emit_byte (mb, CEE_LDIND_U2);
10125         mono_mb_emit_icon (mb, 1);
10126         mono_mb_emit_byte (mb, CEE_SUB);
10127         mono_mb_emit_icon (mb, sizeof (void*));
10128         mono_mb_emit_byte (mb, CEE_MUL);
10129         mono_mb_emit_byte (mb, CEE_ADD);
10130         mono_mb_emit_byte (mb, CEE_LDIND_I);
10131         
10132         mono_mb_emit_ldloc (mb, aklass);
10133         
10134         b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
10135         
10136         copy_pos = mono_mb_get_label (mb);
10137         /* do_store */
10138         mono_mb_patch_branch (mb, b1);
10139         mono_mb_emit_ldloc (mb, array_slot_addr);
10140         mono_mb_emit_ldarg (mb, 2);
10141         mono_mb_emit_byte (mb, CEE_STIND_REF);
10142         
10143         mono_mb_emit_byte (mb, CEE_RET);
10144         
10145         /* the hard way */
10146         mono_mb_patch_branch (mb, b2);
10147         mono_mb_patch_branch (mb, b3);
10148         
10149         mono_mb_emit_ldarg (mb, 2);
10150         mono_mb_emit_ldloc (mb, aklass);
10151         mono_mb_emit_icall (mb, mono_object_isinst_icall);
10152         
10153         b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
10154         mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
10155         mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
10156         
10157         mono_mb_emit_byte (mb, CEE_RET);
10158 #endif
10159         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
10160         ret = mono_mb_create (mb, sig, 4, info);
10161         mono_mb_free (mb);
10162
10163         return ret;
10164 }
10165
10166 /*
10167  * mono_marshal_get_gsharedvt_in_wrapper:
10168  *
10169  *   This wrapper handles calls from normal code to gsharedvt code.
10170  */
10171 MonoMethod*
10172 mono_marshal_get_gsharedvt_in_wrapper (void)
10173 {
10174         static MonoMethod* ret = NULL;
10175         MonoMethodSignature *sig;
10176         MonoMethodBuilder *mb;
10177         WrapperInfo *info;
10178
10179         if (ret)
10180                 return ret;
10181         
10182         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_in", MONO_WRAPPER_UNKNOWN);
10183         
10184         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
10185         sig->ret = &mono_defaults.void_class->byval_arg;
10186
10187 #ifndef DISABLE_JIT
10188         /*
10189          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
10190          */
10191         mono_mb_emit_byte (mb, CEE_RET);
10192 #endif
10193         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_IN);
10194         ret = mono_mb_create (mb, sig, 4, info);
10195         mono_mb_free (mb);
10196
10197         return ret;
10198 }
10199
10200 /*
10201  * mono_marshal_get_gsharedvt_out_wrapper:
10202  *
10203  *   This wrapper handles calls from gsharedvt code to normal code.
10204  */
10205 MonoMethod*
10206 mono_marshal_get_gsharedvt_out_wrapper (void)
10207 {
10208         static MonoMethod* ret = NULL;
10209         MonoMethodSignature *sig;
10210         MonoMethodBuilder *mb;
10211         WrapperInfo *info;
10212
10213         if (ret)
10214                 return ret;
10215         
10216         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_out", MONO_WRAPPER_UNKNOWN);
10217         
10218         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
10219         sig->ret = &mono_defaults.void_class->byval_arg;
10220
10221 #ifndef DISABLE_JIT
10222         /*
10223          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
10224          */
10225         mono_mb_emit_byte (mb, CEE_RET);
10226 #endif
10227         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_OUT);
10228         ret = mono_mb_create (mb, sig, 4, info);
10229         mono_mb_free (mb);
10230
10231         return ret;
10232 }
10233
10234 typedef struct {
10235         int rank;
10236         int elem_size;
10237         MonoMethod *method;
10238 } ArrayElemAddr;
10239
10240 /* LOCKING: vars accessed under the marshal lock */
10241 static ArrayElemAddr *elem_addr_cache = NULL;
10242 static int elem_addr_cache_size = 0;
10243 static int elem_addr_cache_next = 0;
10244
10245 /**
10246  * mono_marshal_get_array_address:
10247  * @rank: rank of the array type
10248  * @elem_size: size in bytes of an element of an array.
10249  *
10250  * Returns a MonoMethod that implements the code to get the address
10251  * of an element in a multi-dimenasional array of @rank dimensions.
10252  * The returned method takes an array as the first argument and then
10253  * @rank indexes for the @rank dimensions.
10254  * If ELEM_SIZE is 0, read the array size from the array object.
10255  */
10256 MonoMethod*
10257 mono_marshal_get_array_address (int rank, int elem_size)
10258 {
10259         MonoMethod *ret;
10260         MonoMethodBuilder *mb;
10261         MonoMethodSignature *sig;
10262         WrapperInfo *info;
10263         char *name;
10264         int i, bounds, ind, realidx;
10265         int branch_pos, *branch_positions;
10266         int cached;
10267
10268         ret = NULL;
10269         mono_marshal_lock ();
10270         for (i = 0; i < elem_addr_cache_next; ++i) {
10271                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10272                         ret = elem_addr_cache [i].method;
10273                         break;
10274                 }
10275         }
10276         mono_marshal_unlock ();
10277         if (ret)
10278                 return ret;
10279
10280         branch_positions = g_new0 (int, rank);
10281
10282         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1 + rank);
10283
10284         /* void* address (void* array, int idx0, int idx1, int idx2, ...) */
10285         sig->ret = &mono_defaults.int_class->byval_arg;
10286         sig->params [0] = &mono_defaults.object_class->byval_arg;
10287         for (i = 0; i < rank; ++i) {
10288                 sig->params [i + 1] = &mono_defaults.int32_class->byval_arg;
10289         }
10290
10291         name = g_strdup_printf ("ElementAddr_%d", elem_size);
10292         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
10293         g_free (name);
10294         
10295 #ifndef DISABLE_JIT
10296         bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10297         ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10298         realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10299
10300         /* bounds = array->bounds; */
10301         mono_mb_emit_ldarg (mb, 0);
10302         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, bounds));
10303         mono_mb_emit_byte (mb, CEE_LDIND_I);
10304         mono_mb_emit_stloc (mb, bounds);
10305
10306         /* ind is the overall element index, realidx is the partial index in a single dimension */
10307         /* ind = idx0 - bounds [0].lower_bound */
10308         mono_mb_emit_ldarg (mb, 1);
10309         mono_mb_emit_ldloc (mb, bounds);
10310         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10311         mono_mb_emit_byte (mb, CEE_ADD);
10312         mono_mb_emit_byte (mb, CEE_LDIND_I4);
10313         mono_mb_emit_byte (mb, CEE_SUB);
10314         mono_mb_emit_stloc (mb, ind);
10315         /* if (ind >= bounds [0].length) goto exeception; */
10316         mono_mb_emit_ldloc (mb, ind);
10317         mono_mb_emit_ldloc (mb, bounds);
10318         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10319         mono_mb_emit_byte (mb, CEE_ADD);
10320         mono_mb_emit_byte (mb, CEE_LDIND_I4);
10321         /* note that we use unsigned comparison */
10322         branch_pos = mono_mb_emit_branch (mb, CEE_BGE_UN);
10323
10324         /* For large ranks (> 4?) use a loop n IL later to reduce code size.
10325          * We could also decide to ignore the passed elem_size and get it
10326          * from the array object, to reduce the number of methods we generate:
10327          * the additional cost is 3 memory loads and a non-immediate mul.
10328          */
10329         for (i = 1; i < rank; ++i) {
10330                 /* realidx = idxi - bounds [i].lower_bound */
10331                 mono_mb_emit_ldarg (mb, 1 + i);
10332                 mono_mb_emit_ldloc (mb, bounds);
10333                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10334                 mono_mb_emit_byte (mb, CEE_ADD);
10335                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10336                 mono_mb_emit_byte (mb, CEE_SUB);
10337                 mono_mb_emit_stloc (mb, realidx);
10338                 /* if (realidx >= bounds [i].length) goto exeception; */
10339                 mono_mb_emit_ldloc (mb, realidx);
10340                 mono_mb_emit_ldloc (mb, bounds);
10341                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10342                 mono_mb_emit_byte (mb, CEE_ADD);
10343                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10344                 branch_positions [i] = mono_mb_emit_branch (mb, CEE_BGE_UN);
10345                 /* ind = ind * bounds [i].length + realidx */
10346                 mono_mb_emit_ldloc (mb, ind);
10347                 mono_mb_emit_ldloc (mb, bounds);
10348                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10349                 mono_mb_emit_byte (mb, CEE_ADD);
10350                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10351                 mono_mb_emit_byte (mb, CEE_MUL);
10352                 mono_mb_emit_ldloc (mb, realidx);
10353                 mono_mb_emit_byte (mb, CEE_ADD);
10354                 mono_mb_emit_stloc (mb, ind);
10355         }
10356
10357         /* return array->vector + ind * element_size */
10358         mono_mb_emit_ldarg (mb, 0);
10359         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
10360         mono_mb_emit_ldloc (mb, ind);
10361         if (elem_size) {
10362                 mono_mb_emit_icon (mb, elem_size);
10363         } else {
10364                 /* Load arr->vtable->klass->sizes.element_class */
10365                 mono_mb_emit_ldarg (mb, 0);
10366                 mono_mb_emit_byte (mb, CEE_CONV_I);
10367                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10368                 mono_mb_emit_byte (mb, CEE_ADD);
10369                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10370                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10371                 mono_mb_emit_byte (mb, CEE_ADD);
10372                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10373                 /* sizes is an union, so this reads sizes.element_size */
10374                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
10375                 mono_mb_emit_byte (mb, CEE_ADD);
10376                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10377         }
10378                 mono_mb_emit_byte (mb, CEE_MUL);
10379         mono_mb_emit_byte (mb, CEE_ADD);
10380         mono_mb_emit_byte (mb, CEE_RET);
10381
10382         /* patch the branches to get here and throw */
10383         for (i = 1; i < rank; ++i) {
10384                 mono_mb_patch_branch (mb, branch_positions [i]);
10385         }
10386         mono_mb_patch_branch (mb, branch_pos);
10387         /* throw exception */
10388         mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
10389
10390         g_free (branch_positions);
10391 #endif /* DISABLE_JIT */
10392
10393         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ELEMENT_ADDR);
10394         info->d.element_addr.rank = rank;
10395         info->d.element_addr.elem_size = elem_size;
10396         ret = mono_mb_create (mb, sig, 4, info);
10397         mono_mb_free (mb);
10398
10399         /* cache the result */
10400         cached = 0;
10401         mono_marshal_lock ();
10402         for (i = 0; i < elem_addr_cache_next; ++i) {
10403                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10404                         /* FIXME: free ret */
10405                         ret = elem_addr_cache [i].method;
10406                         cached = TRUE;
10407                         break;
10408                 }
10409         }
10410         if (!cached) {
10411                 if (elem_addr_cache_next >= elem_addr_cache_size) {
10412                         int new_size = elem_addr_cache_size + 4;
10413                         ArrayElemAddr *new_array = g_new0 (ArrayElemAddr, new_size);
10414                         memcpy (new_array, elem_addr_cache, elem_addr_cache_size * sizeof (ArrayElemAddr));
10415                         g_free (elem_addr_cache);
10416                         elem_addr_cache = new_array;
10417                         elem_addr_cache_size = new_size;
10418                 }
10419                 elem_addr_cache [elem_addr_cache_next].rank = rank;
10420                 elem_addr_cache [elem_addr_cache_next].elem_size = elem_size;
10421                 elem_addr_cache [elem_addr_cache_next].method = ret;
10422                 elem_addr_cache_next ++;
10423         }
10424         mono_marshal_unlock ();
10425         return ret;
10426 }
10427
10428 /*
10429  * mono_marshal_get_array_accessor_wrapper:
10430  *
10431  *   Return a wrapper which just calls METHOD, which should be an Array Get/Set/Address method.
10432  */
10433 MonoMethod *
10434 mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
10435 {
10436         MonoMethodSignature *sig;
10437         MonoMethodBuilder *mb;
10438         MonoMethod *res;
10439         GHashTable *cache;
10440         int i;
10441         MonoGenericContext *ctx = NULL;
10442         MonoMethod *orig_method = NULL;
10443         MonoGenericContainer *container = NULL;
10444         WrapperInfo *info;
10445
10446         /*
10447          * These wrappers are needed to avoid the JIT replacing the calls to these methods with intrinsics
10448          * inside runtime invoke wrappers, thereby making the wrappers not unshareable.
10449          * FIXME: Use generic methods.
10450          */
10451         /*
10452          * Check cache
10453          */
10454         if (ctx) {
10455                 cache = NULL;
10456                 g_assert_not_reached ();
10457         } else {
10458                 cache = get_cache (&method->klass->image->array_accessor_cache, mono_aligned_addr_hash, NULL);
10459                 if ((res = mono_marshal_find_in_cache (cache, method)))
10460                         return res;
10461         }
10462
10463         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
10464         sig->pinvoke = 0;
10465
10466         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
10467
10468 #ifndef DISABLE_JIT
10469         /* Call the method */
10470         if (sig->hasthis)
10471                 mono_mb_emit_ldarg (mb, 0);
10472         for (i = 0; i < sig->param_count; i++)
10473                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
10474
10475         if (ctx) {
10476                 MonoError error;
10477                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
10478                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
10479         } else {
10480                 mono_mb_emit_managed_call (mb, method, NULL);
10481         }
10482         mono_mb_emit_byte (mb, CEE_RET);
10483 #endif
10484
10485         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ARRAY_ACCESSOR);
10486         info->d.array_accessor.method = method;
10487
10488         if (ctx) {
10489                 MonoMethod *def;
10490                 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
10491                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
10492         } else {
10493                 res = mono_mb_create_and_cache_full (cache, method,
10494                                                                                          mb, sig, sig->param_count + 16,
10495                                                                                          info, NULL);
10496         }
10497         mono_mb_free (mb);
10498
10499         return res;     
10500 }
10501
10502 void*
10503 mono_marshal_alloc (gulong size, MonoError *error)
10504 {
10505         gpointer res;
10506
10507         mono_error_init (error);
10508
10509 #ifdef HOST_WIN32
10510         res = CoTaskMemAlloc (size);
10511 #else
10512         res = g_try_malloc ((gulong)size);
10513         if (!res)
10514                 mono_error_set_out_of_memory (error, "Could not allocate %i bytes", size);
10515 #endif
10516         return res;
10517 }
10518
10519 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10520 static void*
10521 ves_icall_marshal_alloc (gulong size)
10522 {
10523         MonoError error;
10524         void *ret = mono_marshal_alloc (size, &error);
10525         if (!mono_error_ok (&error)) {
10526                 mono_error_set_pending_exception (&error);
10527                 return NULL;
10528         }
10529
10530         return ret;
10531 }
10532
10533 void
10534 mono_marshal_free (gpointer ptr)
10535 {
10536 #ifdef HOST_WIN32
10537         CoTaskMemFree (ptr);
10538 #else
10539         g_free (ptr);
10540 #endif
10541 }
10542
10543 void
10544 mono_marshal_free_array (gpointer *ptr, int size) 
10545 {
10546         int i;
10547
10548         if (!ptr)
10549                 return;
10550
10551         for (i = 0; i < size; i++)
10552                 if (ptr [i])
10553                         g_free (ptr [i]);
10554 }
10555
10556 void *
10557 mono_marshal_string_to_utf16 (MonoString *s)
10558 {
10559         return s ? mono_string_chars (s) : NULL;
10560 }
10561
10562 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10563 static void *
10564 mono_marshal_string_to_utf16_copy (MonoString *s)
10565 {
10566         if (s == NULL) {
10567                 return NULL;
10568         } else {
10569                 MonoError error;
10570                 gunichar2 *res = (gunichar2 *)mono_marshal_alloc ((mono_string_length (s) * 2) + 2, &error);
10571                 if (!mono_error_ok (&error)) {
10572                         mono_error_set_pending_exception (&error);
10573                         return NULL;
10574                 }
10575                 memcpy (res, mono_string_chars (s), mono_string_length (s) * 2);
10576                 res [mono_string_length (s)] = 0;
10577                 return res;
10578         }
10579 }
10580
10581 /**
10582  * mono_marshal_set_last_error:
10583  *
10584  * This function is invoked to set the last error value from a P/Invoke call
10585  * which has SetLastError set.
10586  */
10587 void
10588 mono_marshal_set_last_error (void)
10589 {
10590 #ifdef WIN32
10591         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
10592 #else
10593         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (errno));
10594 #endif
10595 }
10596
10597 static void
10598 mono_marshal_set_last_error_windows (int error)
10599 {
10600 #ifdef WIN32
10601         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (error));
10602 #endif
10603 }
10604
10605 void
10606 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
10607                                                                     gpointer dest, gint32 length)
10608 {
10609         int element_size;
10610         void *source_addr;
10611
10612         MONO_CHECK_ARG_NULL (src,);
10613         MONO_CHECK_ARG_NULL (dest,);
10614
10615         if (src->obj.vtable->klass->rank != 1) {
10616                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10617                 return;
10618         }
10619         if (start_index < 0) {
10620                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10621                 return;
10622         }
10623         if (length < 0) {
10624                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10625                 return;
10626         }
10627         if (start_index + length > mono_array_length (src)) {
10628                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10629                 return;
10630         }
10631
10632         element_size = mono_array_element_size (src->obj.vtable->klass);
10633
10634         /* no references should be involved */
10635         source_addr = mono_array_addr_with_size_fast (src, element_size, start_index);
10636
10637         memcpy (dest, source_addr, length * element_size);
10638 }
10639
10640 void
10641 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
10642                                                                       MonoArray *dest, gint32 length)
10643 {
10644         int element_size;
10645         void *dest_addr;
10646
10647         MONO_CHECK_ARG_NULL (src,);
10648         MONO_CHECK_ARG_NULL (dest,);
10649
10650         if (dest->obj.vtable->klass->rank != 1) {
10651                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10652                 return;
10653         }
10654         if (start_index < 0) {
10655                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10656                 return;
10657         }
10658         if (length < 0) {
10659                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10660                 return;
10661         }
10662         if (start_index + length > mono_array_length (dest)) {
10663                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10664                 return;
10665         }
10666         element_size = mono_array_element_size (dest->obj.vtable->klass);
10667           
10668         /* no references should be involved */
10669         dest_addr = mono_array_addr_with_size_fast (dest, element_size, start_index);
10670
10671         memcpy (dest_addr, src, length * element_size);
10672 }
10673
10674 MonoString *
10675 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr)
10676 {
10677         if (ptr == NULL)
10678                 return NULL;
10679         else
10680                 return mono_string_new (mono_domain_get (), ptr);
10681 }
10682
10683 MonoString *
10684 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
10685 {
10686         MonoError error;
10687         MonoString *result = NULL;
10688         mono_error_init (&error);
10689         if (ptr == NULL)
10690                 mono_error_set_argument_null (&error, "ptr", "");
10691         else
10692                 result = mono_string_new_len_checked (mono_domain_get (), ptr, len, &error);
10693         mono_error_set_pending_exception (&error);
10694         return result;
10695 }
10696
10697 MonoString *
10698 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
10699 {
10700         MonoError error;
10701         MonoString *res = NULL;
10702         MonoDomain *domain = mono_domain_get (); 
10703         int len = 0;
10704         guint16 *t = ptr;
10705
10706         if (ptr == NULL)
10707                 return NULL;
10708
10709         while (*t++)
10710                 len++;
10711
10712         res = mono_string_new_utf16_checked (domain, ptr, len, &error);
10713         if (!mono_error_ok (&error)) {
10714                 mono_error_set_pending_exception (&error);
10715                 return NULL;
10716         }
10717         return res;
10718 }
10719
10720 MonoString *
10721 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
10722 {
10723         MonoError error;
10724         MonoString *res = NULL;
10725         MonoDomain *domain = mono_domain_get (); 
10726
10727         mono_error_init (&error);
10728
10729         if (ptr == NULL) {
10730                 res = NULL;
10731                 mono_error_set_argument_null (&error, "ptr", "");
10732         } else {
10733                 res = mono_string_new_utf16_checked (domain, ptr, len, &error);
10734         }
10735
10736         if (!mono_error_ok (&error))
10737                 mono_error_set_pending_exception (&error);
10738         return res;
10739 }
10740
10741 guint32 
10742 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
10743 {
10744         return (GPOINTER_TO_INT (mono_native_tls_get_value (last_error_tls_id)));
10745 }
10746
10747 guint32 
10748 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionType *rtype)
10749 {
10750         MonoClass *klass;
10751         MonoType *type;
10752         guint32 layout;
10753
10754         MONO_CHECK_ARG_NULL (rtype, 0);
10755
10756         type = rtype->type;
10757         klass = mono_class_from_mono_type (type);
10758         if (!mono_class_init (klass)) {
10759                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10760                 return 0;
10761         }
10762
10763         layout = (klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK);
10764
10765         if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
10766                 return sizeof (gpointer);
10767         } else if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
10768                 gchar *msg;
10769                 MonoException *exc;
10770
10771                 msg = g_strdup_printf ("Type %s cannot be marshaled as an unmanaged structure.", klass->name);
10772                 exc = mono_get_exception_argument ("t", msg);
10773                 g_free (msg);
10774                 mono_set_pending_exception (exc);
10775                 return 0;
10776         }
10777
10778         return mono_class_native_size (klass, NULL);
10779 }
10780
10781 void
10782 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
10783 {
10784         MonoError error;
10785         MonoMethod *method;
10786         gpointer pa [3];
10787
10788         MONO_CHECK_ARG_NULL (obj,);
10789         MONO_CHECK_ARG_NULL (dst,);
10790
10791         method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
10792
10793         pa [0] = obj;
10794         pa [1] = &dst;
10795         pa [2] = &delete_old;
10796
10797         mono_runtime_invoke_checked (method, NULL, pa, &error);
10798         if (!mono_error_ok (&error))
10799                 mono_error_set_pending_exception (&error);
10800 }
10801
10802 static void
10803 ptr_to_structure (gpointer src, MonoObject *dst, MonoError *error)
10804 {
10805         MonoMethod *method;
10806         gpointer pa [2];
10807
10808         mono_error_init (error);
10809
10810         method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
10811
10812         pa [0] = &src;
10813         pa [1] = dst;
10814
10815         mono_runtime_invoke_checked (method, NULL, pa, error);
10816 }
10817
10818 void
10819 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
10820 {
10821         MonoType *t;
10822         MonoError error;
10823
10824         MONO_CHECK_ARG_NULL (src,);
10825         MONO_CHECK_ARG_NULL (dst,);
10826         
10827         t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
10828
10829         if (t->type == MONO_TYPE_VALUETYPE) {
10830                 MonoException *exc;
10831                 gchar *tmp;
10832
10833                 tmp = g_strdup_printf ("Destination is a boxed value type.");
10834                 exc = mono_get_exception_argument ("dst", tmp);
10835                 g_free (tmp);  
10836
10837                 mono_set_pending_exception (exc);
10838                 return;
10839         }
10840
10841         ptr_to_structure (src, dst, &error);
10842         if (!mono_error_ok (&error))
10843                 mono_error_set_pending_exception (&error);
10844 }
10845
10846 MonoObject *
10847 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
10848 {
10849         MonoError error;
10850         MonoClass *klass;
10851         MonoDomain *domain = mono_domain_get (); 
10852         MonoObject *res;
10853
10854         if (src == NULL)
10855                 return NULL;
10856         MONO_CHECK_ARG_NULL (type, NULL);
10857
10858         klass = mono_class_from_mono_type (type->type);
10859         if (!mono_class_init (klass)) {
10860                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10861                 return NULL;
10862         }
10863
10864         res = mono_object_new_checked (domain, klass, &error);
10865         if (!mono_error_ok (&error)) {
10866                 mono_error_set_pending_exception (&error);
10867                 return NULL;
10868         }
10869
10870         ptr_to_structure (src, res, &error);
10871         if (!mono_error_ok (&error)) {
10872                 mono_error_set_pending_exception (&error);
10873                 return NULL;
10874         }
10875
10876         return res;
10877 }
10878
10879 int
10880 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *type, MonoString *field_name)
10881 {
10882         MonoError error;
10883         MonoMarshalType *info;
10884         MonoClass *klass;
10885         char *fname;
10886         int match_index = -1;
10887         
10888         MONO_CHECK_ARG_NULL (type, 0);
10889         MONO_CHECK_ARG_NULL (field_name, 0);
10890
10891         fname = mono_string_to_utf8_checked (field_name, &error);
10892         if (mono_error_set_pending_exception (&error))
10893                 return 0;
10894         klass = mono_class_from_mono_type (type->type);
10895         if (!mono_class_init (klass)) {
10896                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10897                 return 0;
10898         }
10899
10900         while (klass && match_index == -1) {
10901                 MonoClassField* field;
10902                 int i = 0;
10903                 gpointer iter = NULL;
10904                 while ((field = mono_class_get_fields (klass, &iter))) {
10905                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10906                                 continue;
10907                         if (!strcmp (fname, mono_field_get_name (field))) {
10908                                 match_index = i;
10909                                 break;
10910                         }
10911                         i ++;
10912                 }
10913
10914                 if (match_index == -1)
10915                         klass = klass->parent;
10916         }
10917
10918         g_free (fname);
10919
10920         if(match_index == -1) {
10921                 MonoException* exc;
10922                 gchar *tmp;
10923
10924                 /* Get back original class instance */
10925                 klass = mono_class_from_mono_type (type->type);
10926
10927                 tmp = g_strdup_printf ("Field passed in is not a marshaled member of the type %s", klass->name);
10928                 exc = mono_get_exception_argument ("fieldName", tmp);
10929                 g_free (tmp);
10930  
10931                 mono_set_pending_exception ((MonoException*)exc);
10932                 return 0;
10933         }
10934
10935         info = mono_marshal_load_type_info (klass);     
10936         return info->fields [match_index].offset;
10937 }
10938
10939 gpointer
10940 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
10941 {
10942         MonoError error;
10943 #ifdef HOST_WIN32
10944         char* tres, *ret;
10945         size_t len;
10946         tres = mono_string_to_utf8_checked (string, &error);
10947         if (mono_error_set_pending_exception (&error))
10948                 return NULL;
10949         if (!tres)
10950                 return tres;
10951
10952         len = strlen (tres) + 1;
10953         ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len);
10954         memcpy (ret, tres, len);
10955         g_free (tres);
10956         return ret;
10957
10958 #else
10959         char *ret = mono_string_to_utf8_checked (string, &error);
10960         mono_error_set_pending_exception (&error);
10961         return ret;
10962 #endif
10963 }
10964
10965 gpointer
10966 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
10967 {
10968         if (string == NULL)
10969                 return NULL;
10970         else {
10971 #ifdef TARGET_WIN32
10972                 gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal 
10973                         ((mono_string_length (string) + 1) * 2);
10974 #else
10975                 gunichar2 *res = (gunichar2 *)g_malloc ((mono_string_length (string) + 1) * 2);
10976 #endif
10977                 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
10978                 res [mono_string_length (string)] = 0;
10979                 return res;
10980         }
10981 }
10982
10983 static void
10984 mono_struct_delete_old (MonoClass *klass, char *ptr)
10985 {
10986         MonoMarshalType *info;
10987         int i;
10988
10989         info = mono_marshal_load_type_info (klass);
10990
10991         for (i = 0; i < info->num_fields; i++) {
10992                 MonoMarshalConv conv;
10993                 MonoType *ftype = info->fields [i].field->type;
10994                 char *cpos;
10995
10996                 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
10997                         continue;
10998
10999                 mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, 
11000                                 klass->unicode, &conv);
11001                         
11002                 cpos = ptr + info->fields [i].offset;
11003
11004                 switch (conv) {
11005                 case MONO_MARSHAL_CONV_NONE:
11006                         if (MONO_TYPE_ISSTRUCT (ftype)) {
11007                                 mono_struct_delete_old (ftype->data.klass, cpos);
11008                                 continue;
11009                         }
11010                         break;
11011                 case MONO_MARSHAL_CONV_STR_LPWSTR:
11012                         /* We assume this field points inside a MonoString */
11013                         break;
11014                 case MONO_MARSHAL_CONV_STR_LPTSTR:
11015 #ifdef TARGET_WIN32
11016                         /* We assume this field points inside a MonoString 
11017                          * on Win32 */
11018                         break;
11019 #endif
11020                 case MONO_MARSHAL_CONV_STR_LPSTR:
11021                 case MONO_MARSHAL_CONV_STR_BSTR:
11022                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
11023                 case MONO_MARSHAL_CONV_STR_TBSTR:
11024                         mono_marshal_free (*(gpointer *)cpos);
11025                         break;
11026
11027                 default:
11028                         continue;
11029                 }
11030         }
11031 }
11032
11033 void
11034 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
11035 {
11036         MonoClass *klass;
11037
11038         MONO_CHECK_ARG_NULL (src,);
11039         MONO_CHECK_ARG_NULL (type,);
11040
11041         klass = mono_class_from_mono_type (type->type);
11042         if (!mono_class_init (klass)) {
11043                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
11044                 return;
11045         }
11046
11047         mono_struct_delete_old (klass, (char *)src);
11048 }
11049
11050 void*
11051 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
11052 {
11053         gpointer res;
11054         size_t s = (size_t)size;
11055
11056         if (s == 0)
11057                 /* This returns a valid pointer for size 0 on MS.NET */
11058                 s = 4;
11059
11060 #ifdef HOST_WIN32
11061         res = GlobalAlloc (GMEM_FIXED, s);
11062 #else
11063         res = g_try_malloc (s);
11064 #endif
11065         if (!res) {
11066                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11067                 return NULL;
11068         }
11069
11070         return res;
11071 }
11072
11073 gpointer
11074 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, gpointer size)
11075 {
11076         gpointer res;
11077         size_t s = (size_t)size;
11078
11079         if (ptr == NULL) {
11080                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11081                 return NULL;
11082         }
11083
11084 #ifdef HOST_WIN32
11085         res = GlobalReAlloc (ptr, s, GMEM_MOVEABLE);
11086 #else
11087         res = g_try_realloc (ptr, s);
11088 #endif
11089         if (!res) {
11090                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11091                 return NULL;
11092         }
11093
11094         return res;
11095 }
11096
11097 void
11098 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
11099 {
11100 #ifdef HOST_WIN32
11101         GlobalFree (ptr);
11102 #else
11103         g_free (ptr);
11104 #endif
11105 }
11106
11107 void*
11108 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
11109 {
11110         void *res;
11111
11112 #ifdef HOST_WIN32
11113         res = CoTaskMemAlloc (size);
11114 #else
11115         if ((gulong)size == 0)
11116                 /* This returns a valid pointer for size 0 on MS.NET */
11117                 size = 4;
11118
11119         res = g_try_malloc ((gulong)size);
11120 #endif
11121         if (!res) {
11122                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11123                 return NULL;
11124         }
11125         return res;
11126 }
11127
11128 void
11129 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
11130 {
11131 #ifdef HOST_WIN32
11132         CoTaskMemFree (ptr);
11133 #else
11134         g_free (ptr);
11135 #endif
11136 }
11137
11138 gpointer
11139 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
11140 {
11141         void *res;
11142
11143 #ifdef HOST_WIN32
11144         res = CoTaskMemRealloc (ptr, size);
11145 #else
11146         res = g_try_realloc (ptr, (gulong)size);
11147 #endif
11148         if (!res) {
11149                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
11150                 return NULL;
11151         }
11152         return res;
11153 }
11154
11155 void*
11156 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
11157 {
11158         return mono_array_addr_with_size_fast (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
11159 }
11160
11161 MonoDelegate*
11162 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionType *type)
11163 {
11164         MonoClass *klass = mono_type_get_class (type->type);
11165         if (!mono_class_init (klass)) {
11166                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
11167                 return NULL;
11168         }
11169
11170         return mono_ftnptr_to_delegate (klass, ftn);
11171 }
11172
11173 gpointer
11174 ves_icall_System_Runtime_InteropServices_Marshal_GetFunctionPointerForDelegateInternal (MonoDelegate *delegate)
11175 {
11176         return mono_delegate_to_ftnptr (delegate);
11177 }
11178
11179 /**
11180  * mono_marshal_is_loading_type_info:
11181  *
11182  *  Return whenever mono_marshal_load_type_info () is being executed for KLASS by this
11183  * thread.
11184  */
11185 static gboolean
11186 mono_marshal_is_loading_type_info (MonoClass *klass)
11187 {
11188         GSList *loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11189
11190         return g_slist_find (loads_list, klass) != NULL;
11191 }
11192
11193 /**
11194  * mono_marshal_load_type_info:
11195  *
11196  *  Initialize klass->marshal_info using information from metadata. This function can
11197  * recursively call itself, and the caller is responsible to avoid that by calling 
11198  * mono_marshal_is_loading_type_info () beforehand.
11199  *
11200  * LOCKING: Acquires the loader lock.
11201  */
11202 MonoMarshalType *
11203 mono_marshal_load_type_info (MonoClass* klass)
11204 {
11205         int j, count = 0;
11206         guint32 native_size = 0, min_align = 1, packing;
11207         MonoMarshalType *info;
11208         MonoClassField* field;
11209         gpointer iter;
11210         guint32 layout;
11211         GSList *loads_list;
11212
11213         g_assert (klass != NULL);
11214
11215         if (klass->marshal_info)
11216                 return klass->marshal_info;
11217
11218         if (!klass->inited)
11219                 mono_class_init (klass);
11220
11221         if (klass->marshal_info)
11222                 return klass->marshal_info;
11223
11224         /*
11225          * This function can recursively call itself, so we keep the list of classes which are
11226          * under initialization in a TLS list.
11227          */
11228         g_assert (!mono_marshal_is_loading_type_info (klass));
11229         loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11230         loads_list = g_slist_prepend (loads_list, klass);
11231         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11232         
11233         iter = NULL;
11234         while ((field = mono_class_get_fields (klass, &iter))) {
11235                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11236                         continue;
11237                 if (mono_field_is_deleted (field))
11238                         continue;
11239                 count++;
11240         }
11241
11242         layout = klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
11243
11244         /* The mempool is protected by the loader lock */
11245         info = (MonoMarshalType *)mono_image_alloc0 (klass->image, MONO_SIZEOF_MARSHAL_TYPE + sizeof (MonoMarshalField) * count);
11246         info->num_fields = count;
11247         
11248         /* Try to find a size for this type in metadata */
11249         mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
11250
11251         if (klass->parent) {
11252                 int parent_size = mono_class_native_size (klass->parent, NULL);
11253
11254                 /* Add parent size to real size */
11255                 native_size += parent_size;
11256                 info->native_size = parent_size;
11257         }
11258
11259         packing = klass->packing_size ? klass->packing_size : 8;
11260         iter = NULL;
11261         j = 0;
11262         while ((field = mono_class_get_fields (klass, &iter))) {
11263                 int size;
11264                 guint32 align;
11265                 
11266                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
11267                         continue;
11268
11269                 if (mono_field_is_deleted (field))
11270                         continue;
11271                 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
11272                         mono_metadata_field_info_with_mempool (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1, 
11273                                                   NULL, NULL, &info->fields [j].mspec);
11274
11275                 info->fields [j].field = field;
11276
11277                 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
11278                         (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
11279                         /* This field is a hack inserted by MCS to empty structures */
11280                         continue;
11281                 }
11282
11283                 switch (layout) {
11284                 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
11285                 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
11286                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
11287                                                        &align, TRUE, klass->unicode);
11288                         align = klass->packing_size ? MIN (klass->packing_size, align): align;
11289                         min_align = MAX (align, min_align);
11290                         info->fields [j].offset = info->native_size;
11291                         info->fields [j].offset += align - 1;
11292                         info->fields [j].offset &= ~(align - 1);
11293                         info->native_size = info->fields [j].offset + size;
11294                         break;
11295                 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
11296                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
11297                                                        &align, TRUE, klass->unicode);
11298                         min_align = MAX (align, min_align);
11299                         info->fields [j].offset = field->offset - sizeof (MonoObject);
11300                         info->native_size = MAX (info->native_size, info->fields [j].offset + size);
11301                         break;
11302                 }       
11303                 j++;
11304         }
11305
11306         if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
11307                 info->native_size = MAX (native_size, info->native_size);
11308                 /*
11309                  * If the provided Size is equal or larger than the calculated size, and there
11310                  * was no Pack attribute, we set min_align to 1 to avoid native_size being increased
11311                  */
11312                 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
11313                         if (native_size && native_size == info->native_size && klass->packing_size == 0)
11314                                 min_align = 1;
11315                         else
11316                                 min_align = MIN (min_align, packing);
11317                 }
11318         }
11319
11320         if (info->native_size & (min_align - 1)) {
11321                 info->native_size += min_align - 1;
11322                 info->native_size &= ~(min_align - 1);
11323         }
11324
11325         info->min_align = min_align;
11326
11327         /* Update the class's blittable info, if the layouts don't match */
11328         if (info->native_size != mono_class_value_size (klass, NULL))
11329                 klass->blittable = FALSE;
11330
11331         /* If this is an array type, ensure that we have element info */
11332         if (klass->rank && !mono_marshal_is_loading_type_info (klass->element_class)) {
11333                 mono_marshal_load_type_info (klass->element_class);
11334         }
11335
11336         loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11337         loads_list = g_slist_remove (loads_list, klass);
11338         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11339
11340         mono_marshal_lock ();
11341         if (!klass->marshal_info) {
11342                 /*We do double-checking locking on marshal_info */
11343                 mono_memory_barrier ();
11344                 klass->marshal_info = info;
11345         }
11346         mono_marshal_unlock ();
11347
11348         return klass->marshal_info;
11349 }
11350
11351 /**
11352  * mono_class_native_size:
11353  * @klass: a class 
11354  * 
11355  * Returns: the native size of an object instance (when marshaled 
11356  * to unmanaged code) 
11357  */
11358 gint32
11359 mono_class_native_size (MonoClass *klass, guint32 *align)
11360 {       
11361         if (!klass->marshal_info) {
11362                 if (mono_marshal_is_loading_type_info (klass)) {
11363                         if (align)
11364                                 *align = 0;
11365                         return 0;
11366                 } else {
11367                         mono_marshal_load_type_info (klass);
11368                 }
11369         }
11370
11371         if (align)
11372                 *align = klass->marshal_info->min_align;
11373
11374         return klass->marshal_info->native_size;
11375 }
11376
11377 /*
11378  * mono_type_native_stack_size:
11379  * @t: the type to return the size it uses on the stack
11380  *
11381  * Returns: the number of bytes required to hold an instance of this
11382  * type on the native stack
11383  */
11384 int
11385 mono_type_native_stack_size (MonoType *t, guint32 *align)
11386 {
11387         guint32 tmp;
11388
11389         g_assert (t != NULL);
11390
11391         if (!align)
11392                 align = &tmp;
11393
11394         if (t->byref) {
11395                 *align = sizeof (gpointer);
11396                 return sizeof (gpointer);
11397         }
11398
11399         switch (t->type){
11400         case MONO_TYPE_BOOLEAN:
11401         case MONO_TYPE_CHAR:
11402         case MONO_TYPE_I1:
11403         case MONO_TYPE_U1:
11404         case MONO_TYPE_I2:
11405         case MONO_TYPE_U2:
11406         case MONO_TYPE_I4:
11407         case MONO_TYPE_U4:
11408                 *align = 4;
11409                 return 4;
11410         case MONO_TYPE_I:
11411         case MONO_TYPE_U:
11412         case MONO_TYPE_STRING:
11413         case MONO_TYPE_OBJECT:
11414         case MONO_TYPE_CLASS:
11415         case MONO_TYPE_SZARRAY:
11416         case MONO_TYPE_PTR:
11417         case MONO_TYPE_FNPTR:
11418         case MONO_TYPE_ARRAY:
11419                 *align = sizeof (gpointer);
11420                 return sizeof (gpointer);
11421         case MONO_TYPE_R4:
11422                 *align = 4;
11423                 return 4;
11424         case MONO_TYPE_R8:
11425                 *align = MONO_ABI_ALIGNOF (double);
11426                 return 8;
11427         case MONO_TYPE_I8:
11428         case MONO_TYPE_U8:
11429                 *align = MONO_ABI_ALIGNOF (gint64);
11430                 return 8;
11431         case MONO_TYPE_GENERICINST:
11432                 if (!mono_type_generic_inst_is_valuetype (t)) {
11433                         *align = sizeof (gpointer);
11434                         return sizeof (gpointer);
11435                 } 
11436                 /* Fall through */
11437         case MONO_TYPE_TYPEDBYREF:
11438         case MONO_TYPE_VALUETYPE: {
11439                 guint32 size;
11440                 MonoClass *klass = mono_class_from_mono_type (t);
11441
11442                 if (klass->enumtype)
11443                         return mono_type_native_stack_size (mono_class_enum_basetype (klass), align);
11444                 else {
11445                         size = mono_class_native_size (klass, align);
11446                         *align = *align + 3;
11447                         *align &= ~3;
11448                         
11449                         size +=  3;
11450                         size &= ~3;
11451
11452                         return size;
11453                 }
11454         }
11455         default:
11456                 g_error ("type 0x%02x unknown", t->type);
11457         }
11458         return 0;
11459 }
11460
11461 gint32
11462 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
11463                         gboolean as_field, gboolean unicode)
11464 {
11465         MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
11466         MonoClass *klass;
11467
11468         switch (native_type) {
11469         case MONO_NATIVE_BOOLEAN:
11470                 *align = 4;
11471                 return 4;
11472         case MONO_NATIVE_I1:
11473         case MONO_NATIVE_U1:
11474                 *align = 1;
11475                 return 1;
11476         case MONO_NATIVE_I2:
11477         case MONO_NATIVE_U2:
11478         case MONO_NATIVE_VARIANTBOOL:
11479                 *align = 2;
11480                 return 2;
11481         case MONO_NATIVE_I4:
11482         case MONO_NATIVE_U4:
11483         case MONO_NATIVE_ERROR:
11484                 *align = 4;
11485                 return 4;
11486         case MONO_NATIVE_I8:
11487         case MONO_NATIVE_U8:
11488                 *align = MONO_ABI_ALIGNOF (gint64);
11489                 return 8;
11490         case MONO_NATIVE_R4:
11491                 *align = 4;
11492                 return 4;
11493         case MONO_NATIVE_R8:
11494                 *align = MONO_ABI_ALIGNOF (double);
11495                 return 8;
11496         case MONO_NATIVE_INT:
11497         case MONO_NATIVE_UINT:
11498         case MONO_NATIVE_LPSTR:
11499         case MONO_NATIVE_LPWSTR:
11500         case MONO_NATIVE_LPTSTR:
11501         case MONO_NATIVE_BSTR:
11502         case MONO_NATIVE_ANSIBSTR:
11503         case MONO_NATIVE_TBSTR:
11504         case MONO_NATIVE_LPARRAY:
11505         case MONO_NATIVE_SAFEARRAY:
11506         case MONO_NATIVE_IUNKNOWN:
11507         case MONO_NATIVE_IDISPATCH:
11508         case MONO_NATIVE_INTERFACE:
11509         case MONO_NATIVE_ASANY:
11510         case MONO_NATIVE_FUNC:
11511         case MONO_NATIVE_LPSTRUCT:
11512                 *align = MONO_ABI_ALIGNOF (gpointer);
11513                 return sizeof (gpointer);
11514         case MONO_NATIVE_STRUCT: 
11515                 klass = mono_class_from_mono_type (type);
11516                 if (klass == mono_defaults.object_class &&
11517                         (mspec && mspec->native == MONO_NATIVE_STRUCT)) {
11518                 *align = 16;
11519                 return 16;
11520                 }
11521                 return mono_class_native_size (klass, align);
11522         case MONO_NATIVE_BYVALTSTR: {
11523                 int esize = unicode ? 2: 1;
11524                 g_assert (mspec);
11525                 *align = esize;
11526                 return mspec->data.array_data.num_elem * esize;
11527         }
11528         case MONO_NATIVE_BYVALARRAY: {
11529                 // FIXME: Have to consider ArraySubType
11530                 int esize;
11531                 klass = mono_class_from_mono_type (type);
11532                 if (klass->element_class == mono_defaults.char_class) {
11533                         esize = unicode ? 2 : 1;
11534                         *align = esize;
11535                 } else {
11536                         esize = mono_class_native_size (klass->element_class, align);
11537                 }
11538                 g_assert (mspec);
11539                 return mspec->data.array_data.num_elem * esize;
11540         }
11541         case MONO_NATIVE_CUSTOM:
11542                 *align = sizeof (gpointer);
11543                 return sizeof (gpointer);
11544                 break;
11545         case MONO_NATIVE_CURRENCY:
11546         case MONO_NATIVE_VBBYREFSTR:
11547         default:
11548                 g_error ("native type %02x not implemented", native_type); 
11549                 break;
11550         }
11551         g_assert_not_reached ();
11552         return 0;
11553 }
11554
11555 /* This is a JIT icall, it sets the pending exception and return NULL on error */
11556 gpointer
11557 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
11558 {
11559         MonoError error;
11560         MonoType *t;
11561         MonoClass *klass;
11562
11563         if (o == NULL)
11564                 return NULL;
11565
11566         t = &o->vtable->klass->byval_arg;
11567         switch (t->type) {
11568         case MONO_TYPE_I4:
11569         case MONO_TYPE_U4:
11570         case MONO_TYPE_PTR:
11571         case MONO_TYPE_I1:
11572         case MONO_TYPE_U1:
11573         case MONO_TYPE_BOOLEAN:
11574         case MONO_TYPE_I2:
11575         case MONO_TYPE_U2:
11576         case MONO_TYPE_CHAR:
11577         case MONO_TYPE_I8:
11578         case MONO_TYPE_U8:
11579         case MONO_TYPE_R4:
11580         case MONO_TYPE_R8:
11581                 return mono_object_unbox (o);
11582                 break;
11583         case MONO_TYPE_STRING:
11584                 switch (string_encoding) {
11585                 case MONO_NATIVE_LPWSTR:
11586                         return mono_marshal_string_to_utf16_copy ((MonoString*)o);
11587                         break;
11588                 case MONO_NATIVE_LPSTR:
11589                         return mono_string_to_lpstr ((MonoString*)o);
11590                         break;
11591                 default:
11592                         g_warning ("marshaling conversion %d not implemented", string_encoding);
11593                         g_assert_not_reached ();
11594                 }
11595                 break;
11596         case MONO_TYPE_CLASS:
11597         case MONO_TYPE_VALUETYPE: {
11598                 MonoMethod *method;
11599                 gpointer pa [3];
11600                 gpointer res;
11601                 MonoBoolean delete_old = FALSE;
11602
11603                 klass = t->data.klass;
11604
11605                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
11606                         break;
11607
11608                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
11609                         klass->blittable || klass->enumtype))
11610                         return mono_object_unbox (o);
11611
11612                 res = mono_marshal_alloc (mono_class_native_size (klass, NULL), &error);
11613                 if (!mono_error_ok (&error)) {
11614                         mono_error_set_pending_exception (&error);
11615                         return NULL;
11616                 }
11617
11618                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11619                         method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
11620
11621                         pa [0] = o;
11622                         pa [1] = &res;
11623                         pa [2] = &delete_old;
11624
11625                         mono_runtime_invoke_checked (method, NULL, pa, &error);
11626                         if (!mono_error_ok (&error)) {
11627                                 mono_error_set_pending_exception (&error);
11628                                 return NULL;
11629                         }
11630                 }
11631
11632                 return res;
11633         }
11634         default:
11635                 break;
11636         }
11637         mono_set_pending_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
11638         return NULL;
11639 }
11640
11641 /* This is a JIT icall, it sets the pending exception */
11642 void
11643 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
11644 {
11645         MonoError error;
11646         MonoType *t;
11647         MonoClass *klass;
11648
11649         if (o == NULL)
11650                 return;
11651
11652         t = &o->vtable->klass->byval_arg;
11653         switch (t->type) {
11654         case MONO_TYPE_STRING:
11655                 switch (string_encoding) {
11656                 case MONO_NATIVE_LPWSTR:
11657                 case MONO_NATIVE_LPSTR:
11658                         mono_marshal_free (ptr);
11659                         break;
11660                 default:
11661                         g_warning ("marshaling conversion %d not implemented", string_encoding);
11662                         g_assert_not_reached ();
11663                 }
11664                 break;
11665         case MONO_TYPE_CLASS:
11666         case MONO_TYPE_VALUETYPE: {
11667                 klass = t->data.klass;
11668
11669                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
11670                                                                  klass->blittable || klass->enumtype))
11671                         break;
11672
11673                 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
11674                         MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
11675                         gpointer pa [2];
11676
11677                         pa [0] = &ptr;
11678                         pa [1] = o;
11679
11680                         mono_runtime_invoke_checked (method, NULL, pa, &error);
11681                         if (!mono_error_ok (&error)) {
11682                                 mono_error_set_pending_exception (&error);
11683                                 return;
11684                         }
11685                 }
11686
11687                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11688                         mono_struct_delete_old (klass, (char *)ptr);
11689                 }
11690
11691                 mono_marshal_free (ptr);
11692                 break;
11693         }
11694         default:
11695                 break;
11696         }
11697 }
11698
11699 MonoMethod *
11700 mono_marshal_get_generic_array_helper (MonoClass *klass, MonoClass *iface, gchar *name, MonoMethod *method)
11701 {
11702         MonoMethodSignature *sig, *csig;
11703         MonoMethodBuilder *mb;
11704         MonoMethod *res;
11705         WrapperInfo *info;
11706         int i;
11707
11708         mb = mono_mb_new_no_dup_name (klass, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
11709         mb->method->slot = -1;
11710
11711         mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
11712                 METHOD_ATTRIBUTE_NEW_SLOT | METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
11713
11714         sig = mono_method_signature (method);
11715         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
11716         csig->generic_param_count = 0;
11717
11718 #ifndef DISABLE_JIT
11719         mono_mb_emit_ldarg (mb, 0);
11720         for (i = 0; i < csig->param_count; i++)
11721                 mono_mb_emit_ldarg (mb, i + 1);
11722         mono_mb_emit_managed_call (mb, method, NULL);
11723         mono_mb_emit_byte (mb, CEE_RET);
11724
11725         /* We can corlib internal methods */
11726         mb->skip_visibility = TRUE;
11727 #endif
11728         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER);
11729         info->d.generic_array_helper.method = method;
11730         res = mono_mb_create (mb, csig, csig->param_count + 16, info);
11731
11732         mono_mb_free (mb);
11733
11734         return res;
11735 }
11736
11737 /*
11738  * The mono_win32_compat_* functions are implementations of inline
11739  * Windows kernel32 APIs, which are DllImport-able under MS.NET,
11740  * although not exported by kernel32.
11741  *
11742  * We map the appropiate kernel32 entries to these functions using
11743  * dllmaps declared in the global etc/mono/config.
11744  */
11745
11746 void
11747 mono_win32_compat_CopyMemory (gpointer dest, gconstpointer source, gsize length)
11748 {
11749         if (!dest || !source)
11750                 return;
11751
11752         memcpy (dest, source, length);
11753 }
11754
11755 void
11756 mono_win32_compat_FillMemory (gpointer dest, gsize length, guchar fill)
11757 {
11758         memset (dest, fill, length);
11759 }
11760
11761 void
11762 mono_win32_compat_MoveMemory (gpointer dest, gconstpointer source, gsize length)
11763 {
11764         if (!dest || !source)
11765                 return;
11766
11767         memmove (dest, source, length);
11768 }
11769
11770 void
11771 mono_win32_compat_ZeroMemory (gpointer dest, gsize length)
11772 {
11773         memset (dest, 0, length);
11774 }
11775
11776 void
11777 mono_marshal_find_nonzero_bit_offset (guint8 *buf, int len, int *byte_offset, guint8 *bitmask)
11778 {
11779         int i;
11780         guint8 byte;
11781
11782         for (i = 0; i < len; ++i)
11783                 if (buf [i])
11784                         break;
11785
11786         g_assert (i < len);
11787
11788         byte = buf [i];
11789         while (byte && !(byte & 1))
11790                 byte >>= 1;
11791         g_assert (byte == 1);
11792
11793         *byte_offset = i;
11794         *bitmask = buf [i];
11795 }
11796
11797 MonoMethod *
11798 mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
11799 {
11800         MonoMethodBuilder *mb;
11801         MonoMethodSignature *sig, *csig;
11802         MonoExceptionClause *clause;
11803         MonoImage *image;
11804         MonoClass *klass;
11805         GHashTable *cache;
11806         MonoMethod *res;
11807         int i, param_count, sig_size, pos_leave;
11808
11809         g_assert (method);
11810
11811         // FIXME: we need to store the exception into a MonoHandle
11812         g_assert (!mono_threads_is_coop_enabled ());
11813
11814         klass = method->klass;
11815         image = method->klass->image;
11816
11817         cache = get_cache (&mono_method_get_wrapper_cache (method)->thunk_invoke_cache, mono_aligned_addr_hash, NULL);
11818
11819         if ((res = mono_marshal_find_in_cache (cache, method)))
11820                 return res;
11821
11822         sig = mono_method_signature (method);
11823         mb = mono_mb_new (klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
11824
11825         /* add "this" and exception param */
11826         param_count = sig->param_count + sig->hasthis + 1;
11827
11828         /* dup & extend signature */
11829         csig = mono_metadata_signature_alloc (image, param_count);
11830         sig_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *);
11831         memcpy (csig, sig, sig_size);
11832         csig->param_count = param_count;
11833         csig->hasthis = 0;
11834         csig->pinvoke = 1;
11835         csig->call_convention = MONO_CALL_DEFAULT;
11836
11837         if (sig->hasthis) {
11838                 /* add "this" */
11839                 csig->params [0] = &klass->byval_arg;
11840                 /* move params up by one */
11841                 for (i = 0; i < sig->param_count; i++)
11842                         csig->params [i + 1] = sig->params [i];
11843         }
11844
11845         /* setup exception param as byref+[out] */
11846         csig->params [param_count - 1] = mono_metadata_type_dup (image,
11847                  &mono_defaults.exception_class->byval_arg);
11848         csig->params [param_count - 1]->byref = 1;
11849         csig->params [param_count - 1]->attrs = PARAM_ATTRIBUTE_OUT;
11850
11851         /* convert struct return to object */
11852         if (MONO_TYPE_ISSTRUCT (sig->ret))
11853                 csig->ret = &mono_defaults.object_class->byval_arg;
11854
11855 #ifndef DISABLE_JIT
11856         /* local 0 (temp for exception object) */
11857         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
11858
11859         /* local 1 (temp for result) */
11860         if (!MONO_TYPE_IS_VOID (sig->ret))
11861                 mono_mb_add_local (mb, sig->ret);
11862
11863         /* clear exception arg */
11864         mono_mb_emit_ldarg (mb, param_count - 1);
11865         mono_mb_emit_byte (mb, CEE_LDNULL);
11866         mono_mb_emit_byte (mb, CEE_STIND_REF);
11867
11868         /* try */
11869         clause = (MonoExceptionClause *)mono_image_alloc0 (image, sizeof (MonoExceptionClause));
11870         clause->try_offset = mono_mb_get_label (mb);
11871
11872         /* push method's args */
11873         for (i = 0; i < param_count - 1; i++) {
11874                 MonoType *type;
11875                 MonoClass *klass;
11876
11877                 mono_mb_emit_ldarg (mb, i);
11878
11879                 /* get the byval type of the param */
11880                 klass = mono_class_from_mono_type (csig->params [i]);
11881                 type = &klass->byval_arg;
11882
11883                 /* unbox struct args */
11884                 if (MONO_TYPE_ISSTRUCT (type)) {
11885                         mono_mb_emit_op (mb, CEE_UNBOX, klass);
11886
11887                         /* byref args & and the "this" arg must remain a ptr.
11888                            Otherwise make a copy of the value type */
11889                         if (!(csig->params [i]->byref || (i == 0 && sig->hasthis)))
11890                                 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
11891
11892                         csig->params [i] = &mono_defaults.object_class->byval_arg;
11893                 }
11894         }
11895
11896         /* call */
11897         if (method->flags & METHOD_ATTRIBUTE_VIRTUAL)
11898                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
11899         else
11900                 mono_mb_emit_op (mb, CEE_CALL, method);
11901
11902         /* save result at local 1 */
11903         if (!MONO_TYPE_IS_VOID (sig->ret))
11904                 mono_mb_emit_stloc (mb, 1);
11905
11906         pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
11907
11908         /* catch */
11909         clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
11910         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
11911         clause->data.catch_class = mono_defaults.object_class;
11912
11913         clause->handler_offset = mono_mb_get_label (mb);
11914
11915         /* store exception at local 0 */
11916         mono_mb_emit_stloc (mb, 0);
11917         mono_mb_emit_ldarg (mb, param_count - 1);
11918         mono_mb_emit_ldloc (mb, 0);
11919         mono_mb_emit_byte (mb, CEE_STIND_REF);
11920         mono_mb_emit_branch (mb, CEE_LEAVE);
11921
11922         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
11923
11924         mono_mb_set_clauses (mb, 1, clause);
11925
11926         mono_mb_patch_branch (mb, pos_leave);
11927         /* end-try */
11928
11929         if (!MONO_TYPE_IS_VOID (sig->ret)) {
11930                 mono_mb_emit_ldloc (mb, 1);
11931
11932                 /* box the return value */
11933                 if (MONO_TYPE_ISSTRUCT (sig->ret))
11934                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
11935         }
11936
11937         mono_mb_emit_byte (mb, CEE_RET);
11938 #endif
11939
11940         res = mono_mb_create_and_cache (cache, method, mb, csig, param_count + 16);
11941         mono_mb_free (mb);
11942
11943         return res;
11944 }
11945
11946 /*
11947  * mono_marshal_free_dynamic_wrappers:
11948  *
11949  *   Free wrappers of the dynamic method METHOD.
11950  */
11951 void
11952 mono_marshal_free_dynamic_wrappers (MonoMethod *method)
11953 {
11954         MonoImage *image = method->klass->image;
11955
11956         g_assert (method_is_dynamic (method));
11957
11958         /* This could be called during shutdown */
11959         if (marshal_mutex_initialized)
11960                 mono_marshal_lock ();
11961         /* 
11962          * FIXME: We currently leak the wrappers. Freeing them would be tricky as
11963          * they could be shared with other methods ?
11964          */
11965         if (image->wrapper_caches.runtime_invoke_direct_cache)
11966                 g_hash_table_remove (image->wrapper_caches.runtime_invoke_direct_cache, method);
11967         if (image->wrapper_caches.delegate_abstract_invoke_cache)
11968                 g_hash_table_foreach_remove (image->wrapper_caches.delegate_abstract_invoke_cache, signature_pointer_pair_matches_pointer, method);
11969         // FIXME: Need to clear the caches in other images as well
11970         if (image->delegate_bound_static_invoke_cache)
11971                 g_hash_table_remove (image->delegate_bound_static_invoke_cache, mono_method_signature (method));
11972
11973         if (marshal_mutex_initialized)
11974                 mono_marshal_unlock ();
11975 }
11976
11977 static void
11978 mono_marshal_ftnptr_eh_callback (guint32 gchandle)
11979 {
11980         g_assert (ftnptr_eh_callback);
11981         ftnptr_eh_callback (gchandle);
11982 }
11983
11984 static void
11985 ftnptr_eh_callback_default (guint32 gchandle)
11986 {
11987         MonoException *exc;
11988         gpointer stackdata;
11989
11990         mono_threads_enter_gc_unsafe_region_unbalanced (&stackdata);
11991
11992         exc = (MonoException*) mono_gchandle_get_target (gchandle);
11993
11994         mono_gchandle_free (gchandle);
11995
11996         mono_raise_exception (exc);
11997 }
11998
11999 /*
12000  * mono_install_ftnptr_eh_callback:
12001  *
12002  *   Install a callback that should be called when there is a managed exception
12003  *   in a native-to-managed wrapper. This is mainly used by iOS to convert a
12004  *   managed exception to a native exception, to properly unwind the native
12005  *   stack; this native exception will then be converted back to a managed
12006  *   exception in their managed-to-native wrapper.
12007  */
12008 void
12009 mono_install_ftnptr_eh_callback (MonoFtnPtrEHCallback callback)
12010 {
12011         ftnptr_eh_callback = callback;
12012 }
12013
12014 static MonoThreadInfo*
12015 mono_icall_start (HandleStackMark *stackmark, MonoError *error)
12016 {
12017         MonoThreadInfo *info = mono_thread_info_current ();
12018
12019         mono_stack_mark_init (info, stackmark);
12020         mono_error_init (error);
12021         return info;
12022 }
12023
12024 static void
12025 mono_icall_end (MonoThreadInfo *info, HandleStackMark *stackmark, MonoError *error)
12026 {
12027         mono_stack_mark_pop (info, stackmark);
12028         mono_error_set_pending_exception (error);
12029 }