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