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