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