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