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