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