Merge pull request #2707 from lambdageek/dev/monoerror-mono_image_load_module_dynamic
[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                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
4952                 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
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                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
5033                 mono_mb_emit_byte (mb, CEE_MONO_VTADDR);
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         int i, argnum, *tmp_locals;
7227         int type, param_shift = 0;
7228         static MonoMethodSignature *get_last_error_sig = NULL;
7229         int coop_gc_stack_dummy, coop_gc_var;
7230
7231         memset (&m, 0, sizeof (m));
7232         m.mb = mb;
7233         m.sig = sig;
7234         m.piinfo = piinfo;
7235
7236         /* we copy the signature, so that we can set pinvoke to 0 */
7237         if (func_param) {
7238                 /* The function address is passed as the first argument */
7239                 g_assert (!sig->hasthis);
7240                 param_shift += 1;
7241         }
7242         csig = mono_metadata_signature_dup_full (mb->method->klass->image, sig);
7243         csig->pinvoke = 1;
7244         m.csig = csig;
7245         m.image = image;
7246
7247         if (sig->hasthis)
7248                 param_shift += 1;
7249
7250         /* we allocate local for use with emit_struct_conv() */
7251         /* allocate local 0 (pointer) src_ptr */
7252         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7253         /* allocate local 1 (pointer) dst_ptr */
7254         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7255         /* allocate local 2 (boolean) delete_old */
7256         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7257
7258         /* delete_old = FALSE */
7259         mono_mb_emit_icon (mb, 0);
7260         mono_mb_emit_stloc (mb, 2);
7261
7262         if (!MONO_TYPE_IS_VOID(sig->ret)) {
7263                 /* allocate local 3 to store the return value */
7264                 mono_mb_add_local (mb, sig->ret);
7265         }
7266
7267         if (mono_threads_is_coop_enabled ()) {
7268                 /* local 4, dummy local used to get a stack address for suspend funcs */
7269                 coop_gc_stack_dummy = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7270                 /* local 5, the local to be used when calling the suspend funcs */
7271                 coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7272         }
7273
7274         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7275                 /* Return type custom marshaling */
7276                 /*
7277                  * Since we can't determine the return type of the unmanaged function,
7278                  * we assume it returns a pointer, and pass that pointer to
7279                  * MarshalNativeToManaged.
7280                  */
7281                 csig->ret = &mono_defaults.int_class->byval_arg;
7282         }
7283
7284         /* we first do all conversions */
7285         tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
7286         m.orig_conv_args = (int *)alloca (sizeof (int) * (sig->param_count + 1));
7287
7288         for (i = 0; i < sig->param_count; i ++) {
7289                 tmp_locals [i] = emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_CONV_IN);
7290         }
7291
7292         /* push all arguments */
7293
7294         if (sig->hasthis)
7295                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7296
7297         for (i = 0; i < sig->param_count; i++) {
7298                 emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
7299         }                       
7300
7301         if (mono_threads_is_coop_enabled ()) {
7302                 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7303                 mono_mb_emit_icall (mb, mono_threads_prepare_blocking);
7304                 mono_mb_emit_stloc (mb, coop_gc_var);
7305         }
7306
7307         /* call the native method */
7308         if (func_param) {
7309                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7310                 mono_mb_emit_op (mb, CEE_UNBOX, mono_defaults.int_class);
7311                 mono_mb_emit_byte (mb, CEE_LDIND_I);
7312                 mono_mb_emit_calli (mb, csig);
7313         } else if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
7314 #ifndef DISABLE_COM
7315                 mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
7316 #else
7317                 g_assert_not_reached ();
7318 #endif
7319         }
7320         else {
7321                 if (aot) {
7322                         /* Reuse the ICALL_ADDR opcode for pinvokes too */
7323                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7324                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7325                         mono_mb_emit_calli (mb, csig);
7326                 } else {                        
7327                         mono_mb_emit_native_call (mb, csig, func);
7328                 }
7329         }
7330
7331         /* Set LastError if needed */
7332         if (piinfo->piflags & PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR) {
7333                 if (!get_last_error_sig) {
7334                         get_last_error_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
7335                         get_last_error_sig->ret = &mono_defaults.int_class->byval_arg;
7336                         get_last_error_sig->pinvoke = 1;
7337                 }
7338
7339 #ifdef TARGET_WIN32
7340                 /* 
7341                  * Have to call GetLastError () early and without a wrapper, since various runtime components could
7342                  * clobber its value.
7343                  */
7344                 mono_mb_emit_native_call (mb, get_last_error_sig, GetLastError);
7345                 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7346 #else
7347                 mono_mb_emit_icall (mb, mono_marshal_set_last_error);
7348 #endif
7349         }               
7350
7351         if (mono_threads_is_coop_enabled ()) {
7352                 mono_mb_emit_ldloc (mb, coop_gc_var);
7353                 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7354                 mono_mb_emit_icall (mb, mono_threads_finish_blocking);
7355         }
7356
7357         /* convert the result */
7358         if (!sig->ret->byref) {
7359                 MonoMarshalSpec *spec = mspecs [0];
7360                 type = sig->ret->type;
7361
7362                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7363                         emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7364                 } else {
7365
7366                 handle_enum:
7367                         switch (type) {
7368                         case MONO_TYPE_VOID:
7369                                 break;
7370                         case MONO_TYPE_VALUETYPE:
7371                                 klass = sig->ret->data.klass;
7372                                 if (klass->enumtype) {
7373                                         type = mono_class_enum_basetype (sig->ret->data.klass)->type;
7374                                         goto handle_enum;
7375                                 }
7376                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7377                                 break;
7378                         case MONO_TYPE_I1:
7379                         case MONO_TYPE_U1:
7380                         case MONO_TYPE_I2:
7381                         case MONO_TYPE_U2:
7382                         case MONO_TYPE_I4:
7383                         case MONO_TYPE_U4:
7384                         case MONO_TYPE_I:
7385                         case MONO_TYPE_U:
7386                         case MONO_TYPE_R4:
7387                         case MONO_TYPE_R8:
7388                         case MONO_TYPE_I8:
7389                         case MONO_TYPE_U8:
7390                         case MONO_TYPE_FNPTR:
7391                         case MONO_TYPE_STRING:
7392                         case MONO_TYPE_CLASS:
7393                         case MONO_TYPE_OBJECT:
7394                         case MONO_TYPE_BOOLEAN:
7395                         case MONO_TYPE_ARRAY:
7396                         case MONO_TYPE_SZARRAY:
7397                         case MONO_TYPE_CHAR:
7398                         case MONO_TYPE_PTR:
7399                         case MONO_TYPE_GENERICINST:
7400                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7401                                 break;
7402                         case MONO_TYPE_TYPEDBYREF:
7403                         default:
7404                                 g_warning ("return type 0x%02x unknown", sig->ret->type);       
7405                                 g_assert_not_reached ();
7406                         }
7407                 }
7408         } else {
7409                 mono_mb_emit_stloc (mb, 3);
7410         }
7411
7412         /* 
7413          * Need to call this after converting the result since MONO_VTADDR needs 
7414          * to be adjacent to the call instruction.
7415          */
7416         if (check_exceptions)
7417                 emit_thread_interrupt_checkpoint (mb);
7418
7419         /* we need to convert byref arguments back and free string arrays */
7420         for (i = 0; i < sig->param_count; i++) {
7421                 MonoType *t = sig->params [i];
7422                 MonoMarshalSpec *spec = mspecs [i + 1];
7423
7424                 argnum = i + param_shift;
7425
7426                 if (spec && ((spec->native == MONO_NATIVE_CUSTOM) || (spec->native == MONO_NATIVE_ASANY))) {
7427                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7428                         continue;
7429                 }
7430
7431                 switch (t->type) {
7432                 case MONO_TYPE_STRING:
7433                 case MONO_TYPE_VALUETYPE:
7434                 case MONO_TYPE_CLASS:
7435                 case MONO_TYPE_OBJECT:
7436                 case MONO_TYPE_SZARRAY:
7437                 case MONO_TYPE_BOOLEAN:
7438                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7439                         break;
7440                 default:
7441                         break;
7442                 }
7443         }
7444
7445         if (!MONO_TYPE_IS_VOID(sig->ret))
7446                 mono_mb_emit_ldloc (mb, 3);
7447
7448         mono_mb_emit_byte (mb, CEE_RET);
7449 }
7450 #endif /* DISABLE_JIT */
7451
7452 /**
7453  * mono_marshal_get_native_wrapper:
7454  * @method: The MonoMethod to wrap.
7455  * @check_exceptions: Whenever to check for pending exceptions
7456  *
7457  * generates IL code for the pinvoke wrapper (the generated method
7458  * calls the unmanaged code in piinfo->addr)
7459  * The wrapper info for the wrapper is a WrapperInfo structure.
7460  */
7461 MonoMethod *
7462 mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
7463 {
7464         MonoMethodSignature *sig, *csig;
7465         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7466         MonoMethodBuilder *mb;
7467         MonoMarshalSpec **mspecs;
7468         MonoMethod *res;
7469         GHashTable *cache;
7470         gboolean pinvoke = FALSE;
7471         gpointer iter;
7472         int i;
7473         const char *exc_class = "MissingMethodException";
7474         const char *exc_arg = NULL;
7475         WrapperInfo *info;
7476
7477         g_assert (method != NULL);
7478         g_assert (mono_method_signature (method)->pinvoke);
7479
7480         GHashTable **cache_ptr;
7481
7482         if (aot) {
7483                 if (check_exceptions)
7484                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_check_cache;
7485                 else
7486                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_cache;
7487         } else {
7488                 if (check_exceptions)
7489                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_check_cache;
7490                 else
7491                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_cache;
7492         }
7493
7494         cache = get_cache (cache_ptr, mono_aligned_addr_hash, NULL);
7495
7496         if ((res = mono_marshal_find_in_cache (cache, method)))
7497                 return res;
7498
7499         if (MONO_CLASS_IS_IMPORT (method->klass)) {
7500                 /* The COM code is not AOT compatible, it calls mono_custom_attrs_get_attr_checked () */
7501                 if (aot)
7502                         return method;
7503 #ifndef DISABLE_COM
7504                 return mono_cominterop_get_native_wrapper (method);
7505 #else
7506                 g_assert_not_reached ();
7507 #endif
7508         }
7509
7510         sig = mono_method_signature (method);
7511
7512         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
7513             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7514                 pinvoke = TRUE;
7515
7516         if (!piinfo->addr) {
7517                 if (pinvoke) {
7518                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
7519                                 exc_arg = "Method contains unsupported native code";
7520                         else if (!aot)
7521                                 mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7522                 } else {
7523                         piinfo->addr = mono_lookup_internal_call (method);
7524                 }
7525         }
7526
7527         /* hack - redirect certain string constructors to CreateString */
7528         if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
7529                 g_assert (!pinvoke);
7530                 g_assert (method->string_ctor);
7531                 g_assert (sig->hasthis);
7532
7533                 /* CreateString returns a value */
7534                 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7535                 csig->ret = &mono_defaults.string_class->byval_arg;
7536                 csig->pinvoke = 0;
7537
7538                 iter = NULL;
7539                 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
7540                         if (!strcmp ("CreateString", res->name) &&
7541                                 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
7542                                 WrapperInfo *info;
7543
7544                                 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
7545                                 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
7546
7547                                 /* create a wrapper to preserve .ctor in stack trace */
7548                                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
7549
7550 #ifndef DISABLE_JIT
7551                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7552                                 for (i = 1; i <= csig->param_count; i++)
7553                                         mono_mb_emit_ldarg (mb, i);
7554                                 mono_mb_emit_managed_call (mb, res, NULL);
7555                                 mono_mb_emit_byte (mb, CEE_RET);
7556 #endif
7557
7558                                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRING_CTOR);
7559                                 info->d.string_ctor.method = method;
7560
7561                                 /* use native_wrapper_cache because internal calls are looked up there */
7562                                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7563                                                                                                          csig->param_count + 1, info, NULL);
7564                                 mono_mb_free (mb);
7565
7566                                 return res;
7567                         }
7568                 }
7569
7570                 /* exception will be thrown */
7571                 piinfo->addr = NULL;
7572                 g_warning ("cannot find CreateString for .ctor");
7573         }
7574
7575         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7576
7577         mb->method->save_lmf = 1;
7578
7579         /*
7580          * In AOT mode and embedding scenarios, it is possible that the icall is not
7581          * registered in the runtime doing the AOT compilation.
7582          */
7583         if (!piinfo->addr && !aot) {
7584 #ifndef DISABLE_JIT
7585                 mono_mb_emit_exception (mb, exc_class, exc_arg);
7586 #endif
7587                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7588                 info->d.managed_to_native.method = method;
7589
7590                 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7591                 csig->pinvoke = 0;
7592                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7593                                                                                          csig->param_count + 16, info, NULL);
7594                 mono_mb_free (mb);
7595
7596                 return res;
7597         }
7598
7599         /* internal calls: we simply push all arguments and call the method (no conversions) */
7600         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
7601                 if (sig->hasthis)
7602                         csig = mono_metadata_signature_dup_add_this (method->klass->image, sig, method->klass);
7603                 else
7604                         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7605
7606                 /* hack - string constructors returns a value */
7607                 if (method->string_ctor)
7608                         csig->ret = &mono_defaults.string_class->byval_arg;
7609
7610 #ifndef DISABLE_JIT
7611                 if (sig->hasthis) {
7612                         int pos;
7613
7614                         /*
7615                          * Add a null check since public icalls can be called with 'call' which
7616                          * does no such check.
7617                          */
7618                         mono_mb_emit_byte (mb, CEE_LDARG_0);                    
7619                         pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
7620                         mono_mb_emit_exception (mb, "NullReferenceException", NULL);
7621                         mono_mb_patch_branch (mb, pos);
7622
7623                         mono_mb_emit_byte (mb, CEE_LDARG_0);
7624                 }
7625
7626                 for (i = 0; i < sig->param_count; i++)
7627                         mono_mb_emit_ldarg (mb, i + sig->hasthis);
7628
7629                 if (aot) {
7630                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7631                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7632                         mono_mb_emit_calli (mb, csig);
7633                 } else {
7634                         g_assert (piinfo->addr);
7635                         mono_mb_emit_native_call (mb, csig, piinfo->addr);
7636                 }
7637                 if (check_exceptions)
7638                         emit_thread_interrupt_checkpoint (mb);
7639                 mono_mb_emit_byte (mb, CEE_RET);
7640 #endif
7641                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7642                 info->d.managed_to_native.method = method;
7643
7644                 csig = mono_metadata_signature_dup_full (method->klass->image, csig);
7645                 csig->pinvoke = 0;
7646                 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7647                                                                                          info, NULL);
7648
7649                 mono_mb_free (mb);
7650                 return res;
7651         }
7652
7653         g_assert (pinvoke);
7654         if (!aot)
7655                 g_assert (piinfo->addr);
7656
7657 #ifndef DISABLE_JIT
7658         mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
7659         mono_method_get_marshal_info (method, mspecs);
7660
7661         mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr, aot, check_exceptions, FALSE);
7662 #endif
7663         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PINVOKE);
7664         info->d.managed_to_native.method = method;
7665
7666         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7667         csig->pinvoke = 0;
7668         res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7669                                                                                  info, NULL);
7670         mono_mb_free (mb);
7671
7672 #ifndef DISABLE_JIT
7673         for (i = sig->param_count; i >= 0; i--)
7674                 if (mspecs [i])
7675                         mono_metadata_free_marshal_spec (mspecs [i]);
7676         g_free (mspecs);
7677 #endif
7678
7679         /* mono_method_print_code (res); */
7680
7681         return res;
7682 }
7683
7684 /**
7685  * mono_marshal_get_native_func_wrapper:
7686  * @image: The image to use for memory allocation and for looking up custom marshallers.
7687  * @sig: The signature of the function
7688  * @func: The native function to wrap
7689  *
7690  *   Returns a wrapper method around native functions, similar to the pinvoke
7691  * wrapper.
7692  */
7693 MonoMethod *
7694 mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig, 
7695                                                                           MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
7696 {
7697         MonoMethodSignature *csig;
7698
7699         SignaturePointerPair key, *new_key;
7700         MonoMethodBuilder *mb;
7701         MonoMethod *res;
7702         GHashTable *cache;
7703         gboolean found;
7704         char *name;
7705
7706         key.sig = sig;
7707         key.pointer = func;
7708
7709         // Generic types are not safe to place in MonoImage caches.
7710         g_assert (!sig->is_inflated);
7711
7712         cache = get_cache (&image->native_func_wrapper_cache, signature_pointer_pair_hash, signature_pointer_pair_equal);
7713         if ((res = mono_marshal_find_in_cache (cache, &key)))
7714                 return res;
7715
7716         name = g_strdup_printf ("wrapper_native_%p", func);
7717         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7718         mb->method->save_lmf = 1;
7719
7720 #ifndef DISABLE_JIT
7721         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE, FALSE);
7722 #endif
7723
7724         csig = mono_metadata_signature_dup_full (image, sig);
7725         csig->pinvoke = 0;
7726
7727         new_key = g_new (SignaturePointerPair,1);
7728         new_key->sig = csig;
7729         new_key->pointer = func;
7730
7731         res = mono_mb_create_and_cache_full (cache, new_key, mb, csig, csig->param_count + 16, NULL, &found);
7732         if (found)
7733                 g_free (new_key);
7734
7735         mono_mb_free (mb);
7736
7737         mono_marshal_set_wrapper_info (res, NULL);
7738
7739         return res;
7740 }
7741
7742 /*
7743  * The wrapper receives the native function as a boxed IntPtr as its 'this' argument. This is easier to support in
7744  * AOT.
7745  */
7746 MonoMethod*
7747 mono_marshal_get_native_func_wrapper_aot (MonoClass *klass)
7748 {
7749         MonoMethodSignature *sig, *csig;
7750         MonoMethodBuilder *mb;
7751         MonoMethod *res;
7752         GHashTable *cache;
7753         char *name;
7754         WrapperInfo *info;
7755         MonoMethodPInvoke mpiinfo;
7756         MonoMethodPInvoke *piinfo = &mpiinfo;
7757         MonoMarshalSpec **mspecs;
7758         MonoMethod *invoke = mono_get_delegate_invoke (klass);
7759         MonoImage *image = invoke->klass->image;
7760         int i;
7761
7762         // FIXME: include UnmanagedFunctionPointerAttribute info
7763
7764         /*
7765          * The wrapper is associated with the delegate type, to pick up the marshalling info etc.
7766          */
7767         cache = get_cache (&mono_method_get_wrapper_cache (invoke)->native_func_wrapper_aot_cache, mono_aligned_addr_hash, NULL);
7768
7769         if ((res = mono_marshal_find_in_cache (cache, invoke)))
7770                 return res;
7771
7772         memset (&mpiinfo, 0, sizeof (mpiinfo));
7773         parse_unmanaged_function_pointer_attr (klass, &mpiinfo);
7774
7775         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
7776         mono_method_get_marshal_info (invoke, mspecs);
7777         /* Freed below so don't alloc from mempool */
7778         sig = mono_metadata_signature_dup (mono_method_signature (invoke));
7779         sig->hasthis = 0;
7780
7781         name = g_strdup_printf ("wrapper_aot_native");
7782         mb = mono_mb_new (invoke->klass, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7783         mb->method->save_lmf = 1;
7784
7785 #ifndef DISABLE_JIT
7786         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, NULL, FALSE, TRUE, TRUE);
7787 #endif
7788
7789         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NATIVE_FUNC_AOT);
7790         info->d.managed_to_native.method = invoke;
7791
7792         g_assert (!sig->hasthis);
7793         csig = mono_metadata_signature_dup_add_this (image, sig, mono_defaults.object_class);
7794         csig->pinvoke = 0;
7795         res = mono_mb_create_and_cache_full (cache, invoke,
7796                                                                                  mb, csig, csig->param_count + 16,
7797                                                                                  info, NULL);
7798         mono_mb_free (mb);
7799
7800         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
7801                 if (mspecs [i])
7802                         mono_metadata_free_marshal_spec (mspecs [i]);
7803         g_free (mspecs);
7804         g_free (sig);
7805
7806         return res;
7807 }
7808
7809 /*
7810  * mono_marshal_emit_managed_wrapper:
7811  *
7812  *   Emit the body of a native-to-managed wrapper. INVOKE_SIG is the signature of
7813  * the delegate which wraps the managed method to be called. For closed delegates,
7814  * it could have fewer parameters than the method it wraps.
7815  * THIS_LOC is the memory location where the target of the delegate is stored.
7816  */
7817 void
7818 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, uint32_t target_handle)
7819 {
7820 #ifdef DISABLE_JIT
7821         MonoMethodSignature *sig, *csig;
7822         int i;
7823
7824         sig = m->sig;
7825         csig = m->csig;
7826
7827         /* we first do all conversions */
7828         for (i = 0; i < sig->param_count; i ++) {
7829                 MonoType *t = sig->params [i];
7830
7831                 switch (t->type) {
7832                 case MONO_TYPE_OBJECT:
7833                 case MONO_TYPE_CLASS:
7834                 case MONO_TYPE_VALUETYPE:
7835                 case MONO_TYPE_ARRAY:
7836                 case MONO_TYPE_SZARRAY:
7837                 case MONO_TYPE_STRING:
7838                 case MONO_TYPE_BOOLEAN:
7839                         emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
7840                 }
7841         }
7842
7843         if (!sig->ret->byref) {
7844                 switch (sig->ret->type) {
7845                 case MONO_TYPE_STRING:
7846                         csig->ret = &mono_defaults.int_class->byval_arg;
7847                         break;
7848                 default:
7849                         break;
7850                 }
7851         }
7852 #else
7853         MonoMethodSignature *sig, *csig;
7854         MonoExceptionClause *clause;
7855         int i, *tmp_locals;
7856         int leave_pos;
7857         gboolean closed = FALSE;
7858
7859         sig = m->sig;
7860         csig = m->csig;
7861
7862         /* allocate local 0 (pointer) src_ptr */
7863         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7864         /* allocate local 1 (pointer) dst_ptr */
7865         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7866         /* allocate local 2 (boolean) delete_old */
7867         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7868
7869         if (!sig->hasthis && sig->param_count != invoke_sig->param_count) {
7870                 /* Closed delegate */
7871                 g_assert (sig->param_count == invoke_sig->param_count + 1);
7872                 closed = TRUE;
7873                 /* Use a new signature without the first argument */
7874                 sig = mono_metadata_signature_dup (sig);
7875                 memmove (&sig->params [0], &sig->params [1], (sig->param_count - 1) * sizeof (MonoType*));
7876                 sig->param_count --;
7877         }
7878
7879         if (!MONO_TYPE_IS_VOID(sig->ret)) {
7880                 /* allocate local 3 to store the return value */
7881                 mono_mb_add_local (mb, sig->ret);
7882         }
7883
7884         /*
7885          * try {
7886          *   mono_jit_attach ();
7887          *
7888          *   <interrupt check>
7889          *
7890          *   ret = method (...);
7891          * } finally {
7892          *   mono_jit_detach ();
7893          * }
7894          *
7895          * return ret;
7896          */
7897
7898         if (mono_threads_is_coop_enabled ()) {
7899                 clause = g_new0 (MonoExceptionClause, 1);
7900                 clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
7901         }
7902
7903         mono_mb_emit_icon (mb, 0);
7904         mono_mb_emit_stloc (mb, 2);
7905
7906         if (mono_threads_is_coop_enabled ()) {
7907                 /* try { */
7908                 clause->try_offset = mono_mb_get_label (mb);
7909         }
7910
7911         /*
7912          * Might need to attach the thread to the JIT or change the
7913          * domain for the callback.
7914          *
7915          * Also does the (STARTING|BLOCKING|RUNNING) -> RUNNING thread state transtion
7916          *
7917          * mono_jit_attach ();
7918          */
7919         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7920         mono_mb_emit_byte (mb, CEE_MONO_JIT_ATTACH);
7921
7922         /* <interrupt check> */
7923         emit_thread_interrupt_checkpoint (mb);
7924
7925         /* we first do all conversions */
7926         tmp_locals = (int *)alloca (sizeof (int) * sig->param_count);
7927         for (i = 0; i < sig->param_count; i ++) {
7928                 MonoType *t = sig->params [i];
7929
7930                 switch (t->type) {
7931                 case MONO_TYPE_OBJECT:
7932                 case MONO_TYPE_CLASS:
7933                 case MONO_TYPE_VALUETYPE:
7934                 case MONO_TYPE_ARRAY:
7935                 case MONO_TYPE_SZARRAY:
7936                 case MONO_TYPE_STRING:
7937                 case MONO_TYPE_BOOLEAN:
7938                         tmp_locals [i] = emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
7939
7940                         break;
7941                 default:
7942                         tmp_locals [i] = 0;
7943                         break;
7944                 }
7945         }
7946
7947         if (sig->hasthis) {
7948                 if (target_handle) {
7949                         mono_mb_emit_icon (mb, (gint32)target_handle);
7950                         mono_mb_emit_icall (mb, mono_gchandle_get_target);
7951                 } else {
7952                         /* fixme: */
7953                         g_assert_not_reached ();
7954                 }
7955         } else if (closed) {
7956                 mono_mb_emit_icon (mb, (gint32)target_handle);
7957                 mono_mb_emit_icall (mb, mono_gchandle_get_target);
7958         }
7959
7960         for (i = 0; i < sig->param_count; i++) {
7961                 MonoType *t = sig->params [i];
7962
7963                 if (tmp_locals [i]) {
7964                         if (t->byref)
7965                                 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
7966                         else
7967                                 mono_mb_emit_ldloc (mb, tmp_locals [i]);
7968                 }
7969                 else
7970                         mono_mb_emit_ldarg (mb, i);
7971         }
7972
7973         /* ret = method (...) */
7974         mono_mb_emit_managed_call (mb, method, NULL);
7975
7976         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7977                 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7978         } else if (!sig->ret->byref) { 
7979                 switch (sig->ret->type) {
7980                 case MONO_TYPE_VOID:
7981                         break;
7982                 case MONO_TYPE_BOOLEAN:
7983                 case MONO_TYPE_I1:
7984                 case MONO_TYPE_U1:
7985                 case MONO_TYPE_CHAR:
7986                 case MONO_TYPE_I2:
7987                 case MONO_TYPE_U2:
7988                 case MONO_TYPE_I4:
7989                 case MONO_TYPE_U4:
7990                 case MONO_TYPE_I:
7991                 case MONO_TYPE_U:
7992                 case MONO_TYPE_PTR:
7993                 case MONO_TYPE_R4:
7994                 case MONO_TYPE_R8:
7995                 case MONO_TYPE_I8:
7996                 case MONO_TYPE_U8:
7997                 case MONO_TYPE_OBJECT:
7998                         mono_mb_emit_stloc (mb, 3);
7999                         break;
8000                 case MONO_TYPE_STRING:
8001                         csig->ret = &mono_defaults.int_class->byval_arg;
8002                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8003                         break;
8004                 case MONO_TYPE_VALUETYPE:
8005                 case MONO_TYPE_CLASS:
8006                 case MONO_TYPE_SZARRAY:
8007                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8008                         break;
8009                 default:
8010                         g_warning ("return type 0x%02x unknown", sig->ret->type);       
8011                         g_assert_not_reached ();
8012                 }
8013         } else {
8014                 mono_mb_emit_stloc (mb, 3);
8015         }
8016
8017         /* Convert byref arguments back */
8018         for (i = 0; i < sig->param_count; i ++) {
8019                 MonoType *t = sig->params [i];
8020                 MonoMarshalSpec *spec = mspecs [i + 1];
8021
8022                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
8023                         emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8024                 }
8025                 else if (t->byref) {
8026                         switch (t->type) {
8027                         case MONO_TYPE_CLASS:
8028                         case MONO_TYPE_VALUETYPE:
8029                         case MONO_TYPE_OBJECT:
8030                         case MONO_TYPE_STRING:
8031                         case MONO_TYPE_BOOLEAN:
8032                                 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8033                                 break;
8034                         default:
8035                                 break;
8036                         }
8037                 }
8038                 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
8039                         /* The [Out] information is encoded in the delegate signature */
8040                         switch (t->type) {
8041                         case MONO_TYPE_SZARRAY:
8042                         case MONO_TYPE_CLASS:
8043                         case MONO_TYPE_VALUETYPE:
8044                                 emit_marshal (m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8045                                 break;
8046                         default:
8047                                 g_assert_not_reached ();
8048                         }
8049                 }
8050         }
8051
8052         if (mono_threads_is_coop_enabled ()) {
8053                 leave_pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8054
8055                 /* } finally { */
8056                 clause->try_len = mono_mb_get_label (mb) - clause->try_offset;
8057                 clause->handler_offset = mono_mb_get_label (mb);
8058         }
8059
8060         /*
8061          * Also does the RUNNING -> (BLOCKING|RUNNING) thread state transition
8062          *
8063          * mono_jit_detach ();
8064          */
8065         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8066         mono_mb_emit_byte (mb, CEE_MONO_JIT_DETACH);
8067
8068         if (mono_threads_is_coop_enabled ()) {
8069                 mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8070
8071                 /* } [endfinally] */
8072                 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
8073
8074                 mono_mb_patch_branch (mb, leave_pos);
8075         }
8076
8077         /* return ret; */
8078         if (m->retobj_var) {
8079                 mono_mb_emit_ldloc (mb, m->retobj_var);
8080                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8081                 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m->retobj_class);
8082         }
8083         else {
8084                 if (!MONO_TYPE_IS_VOID(sig->ret))
8085                         mono_mb_emit_ldloc (mb, 3);
8086                 mono_mb_emit_byte (mb, CEE_RET);
8087         }
8088
8089         if (mono_threads_is_coop_enabled ()) {
8090                 mono_mb_set_clauses (mb, 1, clause);
8091         }
8092
8093         if (closed)
8094                 g_free (sig);
8095 #endif
8096 }
8097
8098 static void 
8099 mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *csig)
8100 {
8101         MonoMethodSignature *sig;
8102         int i;
8103
8104 #ifdef TARGET_WIN32
8105         /* 
8106          * Under windows, delegates passed to native code must use the STDCALL
8107          * calling convention.
8108          */
8109         csig->call_convention = MONO_CALL_STDCALL;
8110 #endif
8111
8112         sig = mono_method_signature (method);
8113
8114         /* Change default calling convention if needed */
8115         /* Why is this a modopt ? */
8116         if (sig->ret && sig->ret->num_mods) {
8117                 for (i = 0; i < sig->ret->num_mods; ++i) {
8118                         MonoError error;
8119                         MonoClass *cmod_class = mono_class_get_checked (method->klass->image, sig->ret->modifiers [i].token, &error);
8120                         g_assert (mono_error_ok (&error));
8121                         if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
8122                                 if (!strcmp (cmod_class->name, "CallConvCdecl"))
8123                                         csig->call_convention = MONO_CALL_C;
8124                                 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
8125                                         csig->call_convention = MONO_CALL_STDCALL;
8126                                 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
8127                                         csig->call_convention = MONO_CALL_FASTCALL;
8128                                 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
8129                                         csig->call_convention = MONO_CALL_THISCALL;
8130                         }
8131                 }
8132         }
8133 }
8134
8135 /*
8136  * generates IL code to call managed methods from unmanaged code 
8137  * If target_handle==0, the wrapper info will be a WrapperInfo structure.
8138  */
8139 MonoMethod *
8140 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle)
8141 {
8142         MonoError error;
8143         MonoMethodSignature *sig, *csig, *invoke_sig;
8144         MonoMethodBuilder *mb;
8145         MonoMethod *res, *invoke;
8146         MonoMarshalSpec **mspecs;
8147         MonoMethodPInvoke piinfo;
8148         GHashTable *cache;
8149         int i;
8150         EmitMarshalContext m;
8151
8152         g_assert (method != NULL);
8153         g_assert (!mono_method_signature (method)->pinvoke);
8154
8155         /* 
8156          * FIXME: Should cache the method+delegate type pair, since the same method
8157          * could be called with different delegates, thus different marshalling
8158          * options.
8159          */
8160         cache = get_cache (&mono_method_get_wrapper_cache (method)->managed_wrapper_cache, mono_aligned_addr_hash, NULL);
8161
8162         if (!target_handle && (res = mono_marshal_find_in_cache (cache, method)))
8163                 return res;
8164
8165         invoke = mono_get_delegate_invoke (delegate_klass);
8166         invoke_sig = mono_method_signature (invoke);
8167
8168         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8169         mono_method_get_marshal_info (invoke, mspecs);
8170
8171         sig = mono_method_signature (method);
8172
8173         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8174
8175         /*the target gchandle must be the first entry after size and the wrapper itself.*/
8176         mono_mb_add_data (mb, GUINT_TO_POINTER (target_handle));
8177
8178         /* we copy the signature, so that we can modify it */
8179         if (target_handle)
8180                 /* Need to free this later */
8181                 csig = mono_metadata_signature_dup (invoke_sig);
8182         else
8183                 csig = mono_metadata_signature_dup_full (method->klass->image, invoke_sig);
8184         csig->hasthis = 0;
8185         csig->pinvoke = 1;
8186
8187         memset (&m, 0, sizeof (m));
8188         m.mb = mb;
8189         m.sig = sig;
8190         m.piinfo = NULL;
8191         m.retobj_var = 0;
8192         m.csig = csig;
8193         m.image = method->klass->image;
8194
8195         mono_marshal_set_callconv_from_modopt (invoke, csig);
8196
8197         /* The attribute is only available in Net 2.0 */
8198         if (mono_class_try_get_unmanaged_function_pointer_attribute_class ()) {
8199                 MonoCustomAttrInfo *cinfo;
8200                 MonoCustomAttrEntry *attr;
8201
8202                 /* 
8203                  * The pinvoke attributes are stored in a real custom attribute. Obtain the
8204                  * contents of the attribute without constructing it, as that might not be
8205                  * possible when running in cross-compiling mode.
8206                  */
8207                 cinfo = mono_custom_attrs_from_class_checked (delegate_klass, &error);
8208                 mono_error_assert_ok (&error);
8209                 attr = NULL;
8210                 if (cinfo) {
8211                         for (i = 0; i < cinfo->num_attrs; ++i) {
8212                                 MonoClass *ctor_class = cinfo->attrs [i].ctor->klass;
8213                                 if (mono_class_has_parent (ctor_class, mono_class_try_get_unmanaged_function_pointer_attribute_class ())) {
8214                                         attr = &cinfo->attrs [i];
8215                                         break;
8216                                 }
8217                         }
8218                 }
8219                 if (attr) {
8220                         MonoArray *typed_args, *named_args;
8221                         CattrNamedArg *arginfo;
8222                         MonoObject *o;
8223                         gint32 call_conv;
8224                         gint32 charset = 0;
8225                         MonoBoolean set_last_error = 0;
8226                         MonoError error;
8227
8228                         mono_reflection_create_custom_attr_data_args (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8229                         g_assert (mono_error_ok (&error));
8230                         g_assert (mono_array_length (typed_args) == 1);
8231
8232                         /* typed args */
8233                         o = mono_array_get (typed_args, MonoObject*, 0);
8234                         call_conv = *(gint32*)mono_object_unbox (o);
8235
8236                         /* named args */
8237                         for (i = 0; i < mono_array_length (named_args); ++i) {
8238                                 CattrNamedArg *narg = &arginfo [i];
8239
8240                                 o = mono_array_get (named_args, MonoObject*, i);
8241
8242                                 g_assert (narg->field);
8243                                 if (!strcmp (narg->field->name, "CharSet")) {
8244                                         charset = *(gint32*)mono_object_unbox (o);
8245                                 } else if (!strcmp (narg->field->name, "SetLastError")) {
8246                                         set_last_error = *(MonoBoolean*)mono_object_unbox (o);
8247                                 } else if (!strcmp (narg->field->name, "BestFitMapping")) {
8248                                         // best_fit_mapping = *(MonoBoolean*)mono_object_unbox (o);
8249                                 } else if (!strcmp (narg->field->name, "ThrowOnUnmappableChar")) {
8250                                         // throw_on_unmappable = *(MonoBoolean*)mono_object_unbox (o);
8251                                 } else {
8252                                         g_assert_not_reached ();
8253                                 }
8254                         }
8255
8256                         g_free (arginfo);
8257
8258                         memset (&piinfo, 0, sizeof (piinfo));
8259                         m.piinfo = &piinfo;
8260                         piinfo.piflags = (call_conv << 8) | (charset ? (charset - 1) * 2 : 1) | set_last_error;
8261
8262                         csig->call_convention = call_conv - 1;
8263                 }
8264
8265                 if (cinfo && !cinfo->cached)
8266                         mono_custom_attrs_free (cinfo);
8267         }
8268
8269         mono_marshal_emit_managed_wrapper (mb, invoke_sig, mspecs, &m, method, target_handle);
8270
8271         if (!target_handle) {
8272                 WrapperInfo *info;
8273
8274                 // FIXME: Associate it with the method+delegate_klass pair
8275                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8276                 info->d.native_to_managed.method = method;
8277                 info->d.native_to_managed.klass = delegate_klass;
8278
8279                 res = mono_mb_create_and_cache_full (cache, method,
8280                                                                                          mb, csig, sig->param_count + 16,
8281                                                                                          info, NULL);
8282         } else {
8283 #ifndef DISABLE_JIT
8284                 mb->dynamic = TRUE;
8285 #endif
8286                 res = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
8287         }
8288         mono_mb_free (mb);
8289
8290         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8291                 if (mspecs [i])
8292                         mono_metadata_free_marshal_spec (mspecs [i]);
8293         g_free (mspecs);
8294
8295         /* mono_method_print_code (res); */
8296
8297         return res;
8298 }
8299
8300 gpointer
8301 mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
8302 {
8303         MonoError error;
8304         MonoMethod *method;
8305         MonoMethodSignature *sig;
8306         MonoMethodBuilder *mb;
8307         int i, param_count;
8308
8309         g_assert (token);
8310
8311         method = mono_get_method_checked (image, token, NULL, NULL, &error);
8312         if (!method)
8313                 g_error ("Could not load vtfixup token 0x%x due to %s", token, mono_error_get_message (&error));
8314         g_assert (method);
8315
8316         if (type & (VTFIXUP_TYPE_FROM_UNMANAGED | VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN)) {
8317                 MonoMethodSignature *csig;
8318                 MonoMarshalSpec **mspecs;
8319                 EmitMarshalContext m;
8320
8321                 sig = mono_method_signature (method);
8322                 g_assert (!sig->hasthis);
8323
8324                 mspecs = g_new0 (MonoMarshalSpec*, sig->param_count + 1);
8325                 mono_method_get_marshal_info (method, mspecs);
8326
8327                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8328                 csig = mono_metadata_signature_dup_full (image, sig);
8329                 csig->hasthis = 0;
8330                 csig->pinvoke = 1;
8331
8332                 memset (&m, 0, sizeof (m));
8333                 m.mb = mb;
8334                 m.sig = sig;
8335                 m.piinfo = NULL;
8336                 m.retobj_var = 0;
8337                 m.csig = csig;
8338                 m.image = image;
8339
8340                 mono_marshal_set_callconv_from_modopt (method, csig);
8341
8342                 /* FIXME: Implement VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN. */
8343
8344                 mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, 0);
8345
8346 #ifndef DISABLE_JIT
8347                 mb->dynamic = TRUE;
8348 #endif
8349                 method = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
8350                 mono_mb_free (mb);
8351
8352                 for (i = sig->param_count; i >= 0; i--)
8353                         if (mspecs [i])
8354                                 mono_metadata_free_marshal_spec (mspecs [i]);
8355                 g_free (mspecs);
8356
8357                 return mono_compile_method (method);
8358         }
8359
8360         sig = mono_method_signature (method);
8361         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
8362
8363         param_count = sig->param_count + sig->hasthis;
8364 #ifndef DISABLE_JIT
8365         for (i = 0; i < param_count; i++)
8366                 mono_mb_emit_ldarg (mb, i);
8367
8368         if (type & VTFIXUP_TYPE_CALL_MOST_DERIVED)
8369                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
8370         else
8371                 mono_mb_emit_op (mb, CEE_CALL, method);
8372         mono_mb_emit_byte (mb, CEE_RET);
8373
8374         mb->dynamic = TRUE;
8375 #endif
8376
8377         method = mono_mb_create (mb, sig, param_count, NULL);
8378         mono_mb_free (mb);
8379
8380         return mono_compile_method (method);
8381 }
8382
8383 #ifndef DISABLE_JIT
8384
8385 /*
8386  * The code directly following this is the cache hit, value positive branch
8387  *
8388  * This function takes a new method builder with 0 locals and adds two locals
8389  * to create multiple out-branches and the fall through state of having the object
8390  * on the stack after a cache miss
8391  */
8392 static void
8393 generate_check_cache (int obj_arg_position, int class_arg_position, int cache_arg_position, // In-parameters
8394                                                                                         int *null_obj, int *cache_hit_neg, int *cache_hit_pos, // Out-parameters
8395                                                                                         MonoMethodBuilder *mb)
8396 {
8397         int cache_miss_pos;
8398
8399         /* allocate local 0 (pointer) obj_vtable */
8400         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8401         /* allocate local 1 (pointer) cached_vtable */
8402         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8403
8404         /*if (!obj)*/
8405         mono_mb_emit_ldarg (mb, obj_arg_position);
8406         *null_obj = mono_mb_emit_branch (mb, CEE_BRFALSE);
8407
8408         /*obj_vtable = obj->vtable;*/
8409         mono_mb_emit_ldarg (mb, obj_arg_position);
8410         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
8411         mono_mb_emit_byte (mb, CEE_LDIND_I);
8412         mono_mb_emit_stloc (mb, 0);
8413
8414         /* cached_vtable = *cache*/
8415         mono_mb_emit_ldarg (mb, cache_arg_position);
8416         mono_mb_emit_byte (mb, CEE_LDIND_I);
8417         mono_mb_emit_stloc (mb, 1);
8418
8419         mono_mb_emit_ldloc (mb, 1);
8420         mono_mb_emit_byte (mb, CEE_LDC_I4);
8421         mono_mb_emit_i4 (mb, ~0x1);
8422         mono_mb_emit_byte (mb, CEE_CONV_I);
8423         mono_mb_emit_byte (mb, CEE_AND);
8424         mono_mb_emit_ldloc (mb, 0);
8425         /*if ((cached_vtable & ~0x1)== obj_vtable)*/
8426         cache_miss_pos = mono_mb_emit_branch (mb, CEE_BNE_UN);
8427
8428         /*return (cached_vtable & 0x1) ? NULL : obj;*/
8429         mono_mb_emit_ldloc (mb, 1);
8430         mono_mb_emit_byte(mb, CEE_LDC_I4_1);
8431         mono_mb_emit_byte (mb, CEE_CONV_U);
8432         mono_mb_emit_byte (mb, CEE_AND);
8433         *cache_hit_neg = mono_mb_emit_branch (mb, CEE_BRTRUE);
8434         *cache_hit_pos = mono_mb_emit_branch (mb, CEE_BR);
8435
8436         // slow path
8437         mono_mb_patch_branch (mb, cache_miss_pos);
8438
8439         // if isinst
8440         mono_mb_emit_ldarg (mb, obj_arg_position);
8441         mono_mb_emit_ldarg (mb, class_arg_position);
8442         mono_mb_emit_ldarg (mb, cache_arg_position);
8443         mono_mb_emit_icall (mb, mono_marshal_isinst_with_cache);
8444 }
8445
8446 #endif /* DISABLE_JIT */
8447
8448 /*
8449  * This does the equivalent of mono_object_castclass_with_cache.
8450  * The wrapper info for the wrapper is a WrapperInfo structure.
8451  */
8452 MonoMethod *
8453 mono_marshal_get_castclass_with_cache (void)
8454 {
8455         static MonoMethod *cached;
8456         MonoMethod *res;
8457         MonoMethodBuilder *mb;
8458         MonoMethodSignature *sig;
8459         int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos, invalid_cast_pos;
8460         WrapperInfo *info;
8461
8462         const int obj_arg_position = 0;
8463         const int class_arg_position = 1;
8464         const int cache_arg_position = 2;
8465
8466         if (cached)
8467                 return cached;
8468
8469         mb = mono_mb_new (mono_defaults.object_class, "__castclass_with_cache", MONO_WRAPPER_CASTCLASS);
8470         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8471         sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
8472         sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
8473         sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
8474         sig->ret = &mono_defaults.object_class->byval_arg;
8475         sig->pinvoke = 0;
8476
8477 #ifndef DISABLE_JIT
8478         generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
8479                                                                                                 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
8480         invalid_cast_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8481
8482         /*return obj;*/
8483         mono_mb_patch_branch (mb, positive_cache_hit_pos);
8484         mono_mb_emit_ldarg (mb, obj_arg_position);
8485         mono_mb_emit_byte (mb, CEE_RET);
8486
8487         /*fails*/
8488         mono_mb_patch_branch (mb, negative_cache_hit_pos);
8489         mono_mb_patch_branch (mb, invalid_cast_pos);
8490         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8491
8492         /*return null*/
8493         mono_mb_patch_branch (mb, return_null_pos);
8494         mono_mb_emit_byte (mb, CEE_LDNULL);
8495         mono_mb_emit_byte (mb, CEE_RET);
8496 #endif /* DISABLE_JIT */
8497
8498         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE);
8499         res = mono_mb_create (mb, sig, 8, info);
8500         STORE_STORE_FENCE;
8501
8502         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8503                 mono_free_method (res);
8504                 mono_metadata_free_method_signature (sig);
8505         }
8506         mono_mb_free (mb);
8507
8508         return cached;
8509 }
8510
8511 static MonoObject *
8512 mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *cache)
8513 {
8514         MonoObject *isinst = mono_object_isinst (obj, klass);
8515
8516 #ifndef DISABLE_REMOTING
8517         if (obj->vtable->klass == mono_defaults.transparent_proxy_class)
8518                 return isinst;
8519 #endif
8520
8521         uintptr_t cache_update = (uintptr_t)obj->vtable;
8522         if (!isinst)
8523                 cache_update = cache_update | 0x1;
8524
8525         *cache = cache_update;
8526
8527         return isinst;
8528 }
8529
8530 /*
8531  * This does the equivalent of mono_object_isinst_with_cache.
8532  * The wrapper info for the wrapper is a WrapperInfo structure.
8533  */
8534 MonoMethod *
8535 mono_marshal_get_isinst_with_cache (void)
8536 {
8537         static MonoMethod *cached;
8538         MonoMethod *res;
8539         MonoMethodBuilder *mb;
8540         MonoMethodSignature *sig;
8541         int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos;
8542         WrapperInfo *info;
8543
8544         const int obj_arg_position = 0;
8545         const int class_arg_position = 1;
8546         const int cache_arg_position = 2;
8547
8548         if (cached)
8549                 return cached;
8550
8551         mb = mono_mb_new (mono_defaults.object_class, "__isinst_with_cache", MONO_WRAPPER_CASTCLASS);
8552         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8553         // The object
8554         sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
8555         // The class
8556         sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
8557         // The cache
8558         sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
8559         sig->ret = &mono_defaults.object_class->byval_arg;
8560         sig->pinvoke = 0;
8561
8562 #ifndef DISABLE_JIT
8563         generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
8564                 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
8565         // Return the object gotten via the slow path.
8566         mono_mb_emit_byte (mb, CEE_RET);
8567
8568         // return NULL;
8569         mono_mb_patch_branch (mb, negative_cache_hit_pos);
8570         mono_mb_patch_branch (mb, return_null_pos);
8571         mono_mb_emit_byte (mb, CEE_LDNULL);
8572         mono_mb_emit_byte (mb, CEE_RET);
8573
8574         // return obj
8575         mono_mb_patch_branch (mb, positive_cache_hit_pos);
8576         mono_mb_emit_ldarg (mb, 0);
8577         mono_mb_emit_byte (mb, CEE_RET);
8578 #endif
8579
8580         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ISINST_WITH_CACHE);
8581         res = mono_mb_create (mb, sig, 8, info);
8582         STORE_STORE_FENCE;
8583
8584         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8585                 mono_free_method (res);
8586                 mono_metadata_free_method_signature (sig);
8587         }
8588         mono_mb_free (mb);
8589
8590         return cached;
8591 }
8592
8593 /*
8594  * mono_marshal_get_isinst:
8595  * @klass: the type of the field
8596  *
8597  * This method generates a function which can be used to check if an object is
8598  * an instance of the given type, icluding the case where the object is a proxy.
8599  * The generated function has the following signature:
8600  * MonoObject* __isinst_wrapper_ (MonoObject *obj)
8601  */
8602 MonoMethod *
8603 mono_marshal_get_isinst (MonoClass *klass)
8604 {
8605         static MonoMethodSignature *isint_sig = NULL;
8606         GHashTable *cache;
8607         MonoMethod *res;
8608         WrapperInfo *info;
8609         int pos_was_ok, pos_end;
8610 #ifndef DISABLE_REMOTING
8611         int pos_end2, pos_failed;
8612 #endif
8613         char *name;
8614         MonoMethodBuilder *mb;
8615
8616         cache = get_cache (&klass->image->isinst_cache, mono_aligned_addr_hash, NULL);
8617         if ((res = mono_marshal_find_in_cache (cache, klass)))
8618                 return res;
8619
8620         if (!isint_sig) {
8621                 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8622                 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
8623                 isint_sig->ret = &mono_defaults.object_class->byval_arg;
8624                 isint_sig->pinvoke = 0;
8625         }
8626         
8627         name = g_strdup_printf ("__isinst_wrapper_%s", klass->name); 
8628         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ISINST);
8629         g_free (name);
8630         
8631         mb->method->save_lmf = 1;
8632
8633 #ifndef DISABLE_JIT
8634         /* check if the object is a proxy that needs special cast */
8635         mono_mb_emit_ldarg (mb, 0);
8636         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8637         mono_mb_emit_op (mb, CEE_MONO_CISINST, klass);
8638
8639         /* The result of MONO_CISINST can be:
8640                 0) the type check succeeded
8641                 1) the type check did not succeed
8642                 2) a CanCastTo call is needed */
8643 #ifndef DISABLE_REMOTING
8644         mono_mb_emit_byte (mb, CEE_DUP);
8645         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8646
8647         mono_mb_emit_byte (mb, CEE_LDC_I4_2);
8648         pos_failed = mono_mb_emit_branch (mb, CEE_BNE_UN);
8649         
8650         /* get the real proxy from the transparent proxy*/
8651
8652         mono_mb_emit_ldarg (mb, 0);
8653         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8654         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8655         
8656         /* fail */
8657         
8658         mono_mb_patch_branch (mb, pos_failed);
8659         mono_mb_emit_byte (mb, CEE_LDNULL);
8660         pos_end2 = mono_mb_emit_branch (mb, CEE_BR);
8661         
8662         /* success */
8663         
8664         mono_mb_patch_branch (mb, pos_was_ok);
8665         mono_mb_emit_byte (mb, CEE_POP);
8666         mono_mb_emit_ldarg (mb, 0);
8667         
8668         /* the end */
8669         
8670         mono_mb_patch_branch (mb, pos_end);
8671         mono_mb_patch_branch (mb, pos_end2);
8672         mono_mb_emit_byte (mb, CEE_RET);
8673 #else
8674         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8675
8676         /* fail */
8677
8678         mono_mb_emit_byte (mb, CEE_LDNULL);
8679         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8680
8681         /* success */
8682
8683         mono_mb_patch_branch (mb, pos_was_ok);
8684         mono_mb_emit_ldarg (mb, 0);
8685
8686         /* the end */
8687
8688         mono_mb_patch_branch (mb, pos_end);
8689         mono_mb_emit_byte (mb, CEE_RET);
8690 #endif /* DISABLE_REMOTING */
8691 #endif /* DISABLE_JIT */
8692
8693         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8694         info->d.proxy.klass = klass;
8695         res = mono_mb_create_and_cache_full (cache, klass, mb, isint_sig, isint_sig->param_count + 16, info, NULL);
8696         mono_mb_free (mb);
8697
8698         return res;
8699 }
8700
8701 /*
8702  * mono_marshal_get_castclass:
8703  * @klass: the type of the field
8704  *
8705  * This method generates a function which can be used to cast an object to
8706  * an instance of the given type, icluding the case where the object is a proxy.
8707  * The generated function has the following signature:
8708  * MonoObject* __castclass_wrapper_ (MonoObject *obj)
8709  * The wrapper info for the wrapper is a WrapperInfo structure.
8710  */
8711 MonoMethod *
8712 mono_marshal_get_castclass (MonoClass *klass)
8713 {
8714         static MonoMethodSignature *castclass_sig = NULL;
8715         GHashTable *cache;
8716         MonoMethod *res;
8717 #ifndef DISABLE_REMOTING
8718         int pos_was_ok, pos_was_ok2;
8719 #endif
8720         char *name;
8721         MonoMethodBuilder *mb;
8722         WrapperInfo *info;
8723
8724         cache = get_cache (&klass->image->castclass_cache, mono_aligned_addr_hash, NULL);
8725         if ((res = mono_marshal_find_in_cache (cache, klass)))
8726                 return res;
8727
8728         if (!castclass_sig) {
8729                 castclass_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8730                 castclass_sig->params [0] = &mono_defaults.object_class->byval_arg;
8731                 castclass_sig->ret = &mono_defaults.object_class->byval_arg;
8732                 castclass_sig->pinvoke = 0;
8733         }
8734         
8735         name = g_strdup_printf ("__castclass_wrapper_%s", klass->name); 
8736         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_CASTCLASS);
8737         g_free (name);
8738         
8739         mb->method->save_lmf = 1;
8740
8741 #ifndef DISABLE_JIT
8742         /* check if the object is a proxy that needs special cast */
8743         mono_mb_emit_ldarg (mb, 0);
8744         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8745         mono_mb_emit_op (mb, CEE_MONO_CCASTCLASS, klass);
8746
8747         /* The result of MONO_CCASTCLASS can be:
8748                 0) the cast is valid
8749                 1) cast of unknown proxy type
8750                 or an exception if the cast is is invalid
8751         */
8752 #ifndef DISABLE_REMOTING
8753         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8754
8755         /* get the real proxy from the transparent proxy*/
8756
8757         mono_mb_emit_ldarg (mb, 0);
8758         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8759         pos_was_ok2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
8760         
8761         /* fail */
8762         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8763         
8764         /* success */
8765         mono_mb_patch_branch (mb, pos_was_ok);
8766         mono_mb_patch_branch (mb, pos_was_ok2);
8767 #else
8768         /* MONO_CCASTCLASS leaves an int in the stack with the result, pop it. */
8769         mono_mb_emit_byte (mb, CEE_POP);
8770 #endif /* DISABLE_REMOTING */
8771
8772         mono_mb_emit_ldarg (mb, 0);
8773         
8774         /* the end */
8775         mono_mb_emit_byte (mb, CEE_RET);
8776 #endif /* DISABLE_JIT */
8777
8778         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8779
8780         res = mono_mb_create_and_cache_full (cache, klass, mb, castclass_sig, castclass_sig->param_count + 16,
8781                                                                                  info, NULL);
8782         mono_mb_free (mb);
8783
8784         return res;
8785 }
8786
8787 /**
8788  * mono_marshal_get_struct_to_ptr:
8789  * @klass:
8790  *
8791  * generates IL code for StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)
8792  * The wrapper info for the wrapper is a WrapperInfo structure.
8793  */
8794 MonoMethod *
8795 mono_marshal_get_struct_to_ptr (MonoClass *klass)
8796 {
8797         MonoMethodBuilder *mb;
8798         static MonoMethod *stoptr = NULL;
8799         MonoMethod *res;
8800         WrapperInfo *info;
8801
8802         g_assert (klass != NULL);
8803
8804         mono_marshal_load_type_info (klass);
8805
8806         if (klass->marshal_info->str_to_ptr)
8807                 return klass->marshal_info->str_to_ptr;
8808
8809         if (!stoptr) 
8810                 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
8811         g_assert (stoptr);
8812
8813         mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
8814
8815 #ifndef DISABLE_JIT
8816         if (klass->blittable) {
8817                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8818                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8819                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8820                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8821                 mono_mb_emit_byte (mb, CEE_PREFIX1);
8822                 mono_mb_emit_byte (mb, CEE_CPBLK);
8823         } else {
8824
8825                 /* allocate local 0 (pointer) src_ptr */
8826                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8827                 /* allocate local 1 (pointer) dst_ptr */
8828                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8829                 /* allocate local 2 (boolean) delete_old */
8830                 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8831                 mono_mb_emit_byte (mb, CEE_LDARG_2);
8832                 mono_mb_emit_stloc (mb, 2);
8833
8834                 /* initialize src_ptr to point to the start of object data */
8835                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8836                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8837                 mono_mb_emit_stloc (mb, 0);
8838
8839                 /* initialize dst_ptr */
8840                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8841                 mono_mb_emit_stloc (mb, 1);
8842
8843                 emit_struct_conv (mb, klass, FALSE);
8844         }
8845
8846         mono_mb_emit_byte (mb, CEE_RET);
8847 #endif
8848         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRUCTURE_TO_PTR);
8849         res = mono_mb_create (mb, mono_signature_no_pinvoke (stoptr), 0, info);
8850         mono_mb_free (mb);
8851
8852         mono_marshal_lock ();
8853         if (!klass->marshal_info->str_to_ptr)
8854                 klass->marshal_info->str_to_ptr = res;
8855         else
8856                 res = klass->marshal_info->str_to_ptr;
8857         mono_marshal_unlock ();
8858         return res;
8859 }
8860
8861 /**
8862  * mono_marshal_get_ptr_to_struct:
8863  * @klass:
8864  *
8865  * generates IL code for PtrToStructure (IntPtr src, object structure)
8866  * The wrapper info for the wrapper is a WrapperInfo structure.
8867  */
8868 MonoMethod *
8869 mono_marshal_get_ptr_to_struct (MonoClass *klass)
8870 {
8871         MonoMethodBuilder *mb;
8872         static MonoMethodSignature *ptostr = NULL;
8873         MonoMethod *res;
8874         WrapperInfo *info;
8875
8876         g_assert (klass != NULL);
8877
8878         mono_marshal_load_type_info (klass);
8879
8880         if (klass->marshal_info->ptr_to_str)
8881                 return klass->marshal_info->ptr_to_str;
8882
8883         if (!ptostr) {
8884                 MonoMethodSignature *sig;
8885
8886                 /* Create the signature corresponding to
8887                           static void PtrToStructure (IntPtr ptr, object structure);
8888                    defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
8889                 sig = mono_create_icall_signature ("void ptr object");
8890                 sig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
8891                 sig->pinvoke = 0;
8892                 mono_memory_barrier ();
8893                 ptostr = sig;
8894         }
8895
8896         mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
8897
8898 #ifndef DISABLE_JIT
8899         if (klass->blittable) {
8900                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8901                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8902                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8903                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8904                 mono_mb_emit_byte (mb, CEE_PREFIX1);
8905                 mono_mb_emit_byte (mb, CEE_CPBLK);
8906         } else {
8907
8908                 /* allocate local 0 (pointer) src_ptr */
8909                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8910                 /* allocate local 1 (pointer) dst_ptr */
8911                 mono_mb_add_local (mb, &klass->this_arg);
8912                 
8913                 /* initialize src_ptr to point to the start of object data */
8914                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8915                 mono_mb_emit_stloc (mb, 0);
8916
8917                 /* initialize dst_ptr */
8918                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8919                 mono_mb_emit_op (mb, CEE_UNBOX, klass);
8920                 mono_mb_emit_stloc (mb, 1);
8921
8922                 emit_struct_conv (mb, klass, TRUE);
8923         }
8924
8925         mono_mb_emit_byte (mb, CEE_RET);
8926 #endif
8927         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PTR_TO_STRUCTURE);
8928         res = mono_mb_create (mb, ptostr, 0, info);
8929         mono_mb_free (mb);
8930
8931         mono_marshal_lock ();
8932         if (!klass->marshal_info->ptr_to_str)
8933                 klass->marshal_info->ptr_to_str = res;
8934         else
8935                 res = klass->marshal_info->ptr_to_str;
8936         mono_marshal_unlock ();
8937         return res;
8938 }
8939
8940 /*
8941  * Return a dummy wrapper for METHOD which is called by synchronized wrappers.
8942  * This is used to avoid infinite recursion since it is hard to determine where to
8943  * replace a method with its synchronized wrapper, and where not.
8944  * The runtime should execute METHOD instead of the wrapper.
8945  * The wrapper info for the wrapper is a WrapperInfo structure.
8946  */
8947 MonoMethod *
8948 mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
8949 {
8950         MonoMethodBuilder *mb;
8951         WrapperInfo *info;
8952         MonoMethodSignature *sig;
8953         MonoMethod *res;
8954         MonoGenericContext *ctx = NULL;
8955         MonoGenericContainer *container = NULL;
8956
8957         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
8958                 ctx = &((MonoMethodInflated*)method)->context;
8959                 method = ((MonoMethodInflated*)method)->declaring;
8960                 container = mono_method_get_generic_container (method);
8961                 if (!container)
8962                         container = method->klass->generic_container;
8963                 g_assert (container);
8964         }
8965
8966         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
8967 #ifndef DISABLE_JIT
8968         mono_mb_emit_exception_full (mb, "System", "ExecutionEngineException", "Shouldn't be called.");
8969         mono_mb_emit_byte (mb, CEE_RET);
8970 #endif
8971         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
8972
8973         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_SYNCHRONIZED_INNER);
8974         info->d.synchronized_inner.method = method;
8975         res = mono_mb_create (mb, sig, 0, info);
8976         mono_mb_free (mb);
8977         if (ctx) {
8978                 MonoError error;
8979                 res = mono_class_inflate_generic_method_checked (res, ctx, &error);
8980                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8981         }
8982         return res;
8983 }
8984
8985 /*
8986  * generates IL code for the synchronized wrapper: the generated method
8987  * calls METHOD while locking 'this' or the parent type.
8988  */
8989 MonoMethod *
8990 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
8991 {
8992         static MonoMethod *enter_method, *exit_method, *gettypefromhandle_method;
8993         MonoMethodSignature *sig;
8994         MonoExceptionClause *clause;
8995         MonoMethodBuilder *mb;
8996         MonoMethod *res;
8997         GHashTable *cache;
8998         WrapperInfo *info;
8999         int i, pos, pos2, this_local, taken_local, ret_local = 0;
9000         MonoGenericContext *ctx = NULL;
9001         MonoMethod *orig_method = NULL;
9002         MonoGenericContainer *container = NULL;
9003
9004         g_assert (method);
9005
9006         if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
9007                 return method;
9008
9009         /* FIXME: Support generic methods too */
9010         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
9011                 orig_method = method;
9012                 ctx = &((MonoMethodInflated*)method)->context;
9013                 method = ((MonoMethodInflated*)method)->declaring;
9014                 container = mono_method_get_generic_container (method);
9015                 if (!container)
9016                         container = method->klass->generic_container;
9017                 g_assert (container);
9018         }
9019
9020         /*
9021          * Check cache
9022          */
9023         if (ctx) {
9024                 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9025                 res = check_generic_wrapper_cache (cache, orig_method, orig_method, method);
9026                 if (res)
9027                         return res;
9028         } else {
9029                 cache = get_cache (&method->klass->image->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
9030                 if ((res = mono_marshal_find_in_cache (cache, method)))
9031                         return res;
9032         }
9033
9034         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9035         sig->pinvoke = 0;
9036
9037         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
9038
9039         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9040         info->d.synchronized.method = method;
9041
9042 #ifndef DISABLE_JIT
9043         mb->skip_visibility = 1;
9044         /* result */
9045         if (!MONO_TYPE_IS_VOID (sig->ret))
9046                 ret_local = mono_mb_add_local (mb, sig->ret);
9047 #endif
9048
9049         if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
9050                 mono_class_set_failure (method->klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
9051 #ifndef DISABLE_JIT
9052                 /* This will throw the type load exception when the wrapper is compiled */
9053                 mono_mb_emit_byte (mb, CEE_LDNULL);
9054                 mono_mb_emit_op (mb, CEE_ISINST, method->klass);
9055                 mono_mb_emit_byte (mb, CEE_POP);
9056
9057                 if (!MONO_TYPE_IS_VOID (sig->ret))
9058                         mono_mb_emit_ldloc (mb, ret_local);
9059                 mono_mb_emit_byte (mb, CEE_RET);
9060 #endif
9061
9062                 res = mono_mb_create_and_cache_full (cache, method,
9063                                                                                          mb, sig, sig->param_count + 16, info, NULL);
9064                 mono_mb_free (mb);
9065
9066                 return res;
9067         }
9068
9069 #ifndef DISABLE_JIT
9070         /* this */
9071         this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
9072         taken_local = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
9073
9074         clause = (MonoExceptionClause *)mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
9075         clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
9076 #endif
9077
9078         mono_marshal_lock ();
9079
9080         if (!enter_method) {
9081                 MonoMethodDesc *desc;
9082
9083                 desc = mono_method_desc_new ("Monitor:enter_with_atomic_var(object,bool&)", FALSE);
9084                 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9085                 g_assert (enter_method);
9086                 mono_method_desc_free (desc);
9087
9088                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
9089                 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
9090                 g_assert (exit_method);
9091                 mono_method_desc_free (desc);
9092
9093                 desc = mono_method_desc_new ("Type:GetTypeFromHandle", FALSE);
9094                 gettypefromhandle_method = mono_method_desc_search_in_class (desc, mono_defaults.systemtype_class);
9095                 g_assert (gettypefromhandle_method);
9096                 mono_method_desc_free (desc);
9097         }
9098
9099         mono_marshal_unlock ();
9100
9101 #ifndef DISABLE_JIT
9102         /* Push this or the type object */
9103         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
9104                 /* We have special handling for this in the JIT */
9105                 int index = mono_mb_add_data (mb, method->klass);
9106                 mono_mb_add_data (mb, mono_defaults.typehandle_class);
9107                 mono_mb_emit_byte (mb, CEE_LDTOKEN);
9108                 mono_mb_emit_i4 (mb, index);
9109
9110                 mono_mb_emit_managed_call (mb, gettypefromhandle_method, NULL);
9111         }
9112         else
9113                 mono_mb_emit_ldarg (mb, 0);
9114         mono_mb_emit_stloc (mb, this_local);
9115
9116         /* Call Monitor::Enter() */
9117         mono_mb_emit_ldloc (mb, this_local);
9118         mono_mb_emit_ldloc_addr (mb, taken_local);
9119         mono_mb_emit_managed_call (mb, enter_method, NULL);
9120
9121         clause->try_offset = mono_mb_get_label (mb);
9122
9123         /* Call the method */
9124         if (sig->hasthis)
9125                 mono_mb_emit_ldarg (mb, 0);
9126         for (i = 0; i < sig->param_count; i++)
9127                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
9128
9129         if (ctx) {
9130                 MonoError error;
9131                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
9132                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9133         } else {
9134                 mono_mb_emit_managed_call (mb, method, NULL);
9135         }
9136
9137         if (!MONO_TYPE_IS_VOID (sig->ret))
9138                 mono_mb_emit_stloc (mb, ret_local);
9139
9140         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
9141
9142         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
9143         clause->handler_offset = mono_mb_get_label (mb);
9144
9145         /* Call Monitor::Exit() if needed */
9146         mono_mb_emit_ldloc (mb, taken_local);
9147         pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9148         mono_mb_emit_ldloc (mb, this_local);
9149         mono_mb_emit_managed_call (mb, exit_method, NULL);
9150         mono_mb_patch_branch (mb, pos2);
9151         mono_mb_emit_byte (mb, CEE_ENDFINALLY);
9152
9153         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
9154
9155         mono_mb_patch_branch (mb, pos);
9156         if (!MONO_TYPE_IS_VOID (sig->ret))
9157                 mono_mb_emit_ldloc (mb, ret_local);
9158         mono_mb_emit_byte (mb, CEE_RET);
9159
9160         mono_mb_set_clauses (mb, 1, clause);
9161 #endif
9162
9163         if (ctx) {
9164                 MonoMethod *def;
9165                 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
9166                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
9167         } else {
9168                 res = mono_mb_create_and_cache_full (cache, method,
9169                                                                                          mb, sig, sig->param_count + 16, info, NULL);
9170         }
9171         mono_mb_free (mb);
9172
9173         return res;     
9174 }
9175
9176
9177 /*
9178  * the returned method calls 'method' unboxing the this argument
9179  */
9180 MonoMethod *
9181 mono_marshal_get_unbox_wrapper (MonoMethod *method)
9182 {
9183         MonoMethodSignature *sig = mono_method_signature (method);
9184         int i;
9185         MonoMethodBuilder *mb;
9186         MonoMethod *res;
9187         GHashTable *cache;
9188         WrapperInfo *info;
9189
9190         cache = get_cache (&mono_method_get_wrapper_cache (method)->unbox_wrapper_cache, mono_aligned_addr_hash, NULL);
9191
9192         if ((res = mono_marshal_find_in_cache (cache, method)))
9193                 return res;
9194
9195         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
9196
9197         g_assert (sig->hasthis);
9198         
9199 #ifndef DISABLE_JIT
9200         mono_mb_emit_ldarg (mb, 0); 
9201         mono_mb_emit_icon (mb, sizeof (MonoObject));
9202         mono_mb_emit_byte (mb, CEE_ADD);
9203         for (i = 0; i < sig->param_count; ++i)
9204                 mono_mb_emit_ldarg (mb, i + 1);
9205         mono_mb_emit_managed_call (mb, method, NULL);
9206         mono_mb_emit_byte (mb, CEE_RET);
9207 #endif
9208
9209         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9210         info->d.unbox.method = method;
9211
9212         res = mono_mb_create_and_cache_full (cache, method,
9213                                                                                  mb, sig, sig->param_count + 16, info, NULL);
9214         mono_mb_free (mb);
9215
9216         /* mono_method_print_code (res); */
9217
9218         return res;     
9219 }
9220
9221 enum {
9222         STELEMREF_OBJECT, /*no check at all*/
9223         STELEMREF_SEALED_CLASS, /*check vtable->klass->element_type */
9224         STELEMREF_CLASS, /*only the klass->parents check*/
9225         STELEMREF_INTERFACE, /*interfaces without variant generic arguments. */
9226         STELEMREF_COMPLEX, /*arrays, MBR or types with variant generic args - go straight to icalls*/
9227         STELEMREF_KIND_COUNT
9228 };
9229
9230 static const char *strelemref_wrapper_name[] = {
9231         "object", "sealed_class", "class", "interface", "complex"
9232 };
9233
9234 static gboolean
9235 is_monomorphic_array (MonoClass *klass)
9236 {
9237         MonoClass *element_class;
9238         if (klass->rank != 1)
9239                 return FALSE;
9240
9241         element_class = klass->element_class;
9242         return (element_class->flags & TYPE_ATTRIBUTE_SEALED) || element_class->valuetype;
9243 }
9244
9245 static int
9246 get_virtual_stelemref_kind (MonoClass *element_class)
9247 {
9248         if (element_class == mono_defaults.object_class)
9249                 return STELEMREF_OBJECT;
9250         if (is_monomorphic_array (element_class))
9251                 return STELEMREF_SEALED_CLASS;
9252         /* Compressed interface bitmaps require code that is quite complex, so don't optimize for it. */
9253         if (MONO_CLASS_IS_INTERFACE (element_class) && !mono_class_has_variant_generic_params (element_class))
9254 #ifdef COMPRESSED_INTERFACE_BITMAP
9255                 return STELEMREF_COMPLEX;
9256 #else
9257                 return STELEMREF_INTERFACE;
9258 #endif
9259         /*Arrays are sealed but are covariant on their element type, We can't use any of the fast paths.*/
9260         if (mono_class_is_marshalbyref (element_class) || element_class->rank || mono_class_has_variant_generic_params (element_class))
9261                 return STELEMREF_COMPLEX;
9262         if (element_class->flags & TYPE_ATTRIBUTE_SEALED)
9263                 return STELEMREF_SEALED_CLASS;
9264         return STELEMREF_CLASS;
9265 }
9266
9267 #ifndef DISABLE_JIT
9268
9269 static void
9270 load_array_element_address (MonoMethodBuilder *mb)
9271 {
9272         mono_mb_emit_ldarg (mb, 0);
9273         mono_mb_emit_ldarg (mb, 1);
9274         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9275 }
9276
9277 static void
9278 load_array_class (MonoMethodBuilder *mb, int aklass)
9279 {
9280         mono_mb_emit_ldarg (mb, 0);
9281         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9282         mono_mb_emit_byte (mb, CEE_LDIND_I);
9283         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9284         mono_mb_emit_byte (mb, CEE_LDIND_I);
9285         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9286         mono_mb_emit_byte (mb, CEE_LDIND_I);
9287         mono_mb_emit_stloc (mb, aklass);
9288 }
9289
9290 static void
9291 load_value_class (MonoMethodBuilder *mb, int vklass)
9292 {
9293         mono_mb_emit_ldarg (mb, 2);
9294         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9295         mono_mb_emit_byte (mb, CEE_LDIND_I);
9296         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9297         mono_mb_emit_byte (mb, CEE_LDIND_I);
9298         mono_mb_emit_stloc (mb, vklass);
9299 }
9300 #endif
9301
9302 #if 0
9303 static void
9304 record_slot_vstore (MonoObject *array, size_t index, MonoObject *value)
9305 {
9306         char *name = mono_type_get_full_name (array->vtable->klass->element_class);
9307         printf ("slow vstore of %s\n", name);
9308         g_free (name);
9309 }
9310 #endif
9311
9312 /*
9313  * The wrapper info for the wrapper is a WrapperInfo structure.
9314  *
9315  * TODO:
9316  *      - Separate simple interfaces from variant interfaces or mbr types. This way we can avoid the icall for them.
9317  *      - Emit a (new) mono bytecode that produces OP_COND_EXC_NE_UN to raise ArrayTypeMismatch
9318  *      - Maybe mve some MonoClass field into the vtable to reduce the number of loads
9319  *      - Add a case for arrays of arrays.
9320  */
9321 static MonoMethod*
9322 get_virtual_stelemref_wrapper (int kind)
9323 {
9324         static MonoMethod *cached_methods [STELEMREF_KIND_COUNT] = { NULL }; /*object iface sealed regular*/
9325         static MonoMethodSignature *signature;
9326         MonoMethodBuilder *mb;
9327         MonoMethod *res;
9328         char *name;
9329         const char *param_names [16];
9330         guint32 b1, b2, b3;
9331         int aklass, vklass, vtable, uiid;
9332         int array_slot_addr;
9333         WrapperInfo *info;
9334
9335         if (cached_methods [kind])
9336                 return cached_methods [kind];
9337
9338         name = g_strdup_printf ("virt_stelemref_%s", strelemref_wrapper_name [kind]);
9339         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STELEMREF);
9340         g_free (name);
9341
9342         if (!signature) {
9343                 MonoMethodSignature *sig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
9344
9345                 /* void this::stelemref (size_t idx, void* value) */
9346                 sig->ret = &mono_defaults.void_class->byval_arg;
9347                 sig->hasthis = TRUE;
9348                 sig->params [0] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9349                 sig->params [1] = &mono_defaults.object_class->byval_arg;
9350                 signature = sig;
9351         }
9352
9353 #ifndef DISABLE_JIT
9354         param_names [0] = "index";
9355         param_names [1] = "value";
9356         mono_mb_set_param_names (mb, param_names);
9357
9358         /*For now simply call plain old stelemref*/
9359         switch (kind) {
9360         case STELEMREF_OBJECT:
9361                 /* ldelema (implicit bound check) */
9362                 load_array_element_address (mb);
9363                 /* do_store */
9364                 mono_mb_emit_ldarg (mb, 2);
9365                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9366                 mono_mb_emit_byte (mb, CEE_RET);
9367                 break;
9368
9369         case STELEMREF_COMPLEX:
9370                 /*
9371                 <ldelema (bound check)>
9372                 if (!value)
9373                         goto store;
9374                 if (!mono_object_isinst (value, aklass))
9375                         goto do_exception;
9376
9377                  do_store:
9378                          *array_slot_addr = value;
9379
9380                 do_exception:
9381                         throw new ArrayTypeMismatchException ();
9382                 */
9383
9384                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9385                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9386
9387 #if 0
9388                 {
9389                         /*Use this to debug/record stores that are going thru the slow path*/
9390                         MonoMethodSignature *csig;
9391                         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9392                         csig->ret = &mono_defaults.void_class->byval_arg;
9393                         csig->params [0] = &mono_defaults.object_class->byval_arg;
9394                         csig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9395                         csig->params [2] = &mono_defaults.object_class->byval_arg;
9396                         mono_mb_emit_ldarg (mb, 0);
9397                         mono_mb_emit_ldarg (mb, 1);
9398                         mono_mb_emit_ldarg (mb, 2);
9399                         mono_mb_emit_native_call (mb, csig, record_slot_vstore);
9400                 }
9401 #endif
9402
9403                 /* ldelema (implicit bound check) */
9404                 load_array_element_address (mb);
9405                 mono_mb_emit_stloc (mb, array_slot_addr);
9406
9407                 /* if (!value) goto do_store */
9408                 mono_mb_emit_ldarg (mb, 2);
9409                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9410
9411                 /* aklass = array->vtable->klass->element_class */
9412                 load_array_class (mb, aklass);
9413
9414                 /*if (mono_object_isinst (value, aklass)) */
9415                 mono_mb_emit_ldarg (mb, 2);
9416                 mono_mb_emit_ldloc (mb, aklass);
9417                 mono_mb_emit_icall (mb, mono_object_isinst);
9418                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9419
9420                 /* do_store: */
9421                 mono_mb_patch_branch (mb, b1);
9422                 mono_mb_emit_ldloc (mb, array_slot_addr);
9423                 mono_mb_emit_ldarg (mb, 2);
9424                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9425                 mono_mb_emit_byte (mb, CEE_RET);
9426
9427                 /* do_exception: */
9428                 mono_mb_patch_branch (mb, b2);
9429
9430                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9431                 break;
9432
9433         case STELEMREF_SEALED_CLASS:
9434                 /*
9435                 <ldelema (bound check)>
9436                 if (!value)
9437                         goto store;
9438
9439                 aklass = array->vtable->klass->element_class;
9440                 vklass = value->vtable->klass;
9441
9442                 if (vklass != aklass)
9443                         goto do_exception;
9444
9445                 do_store:
9446                          *array_slot_addr = value;
9447
9448                 do_exception:
9449                         throw new ArrayTypeMismatchException ();
9450                 */
9451                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9452                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9453                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9454
9455
9456                 /* ldelema (implicit bound check) */
9457                 load_array_element_address (mb);
9458                 mono_mb_emit_stloc (mb, array_slot_addr);
9459
9460                 /* if (!value) goto do_store */
9461                 mono_mb_emit_ldarg (mb, 2);
9462                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9463
9464                 /* aklass = array->vtable->klass->element_class */
9465                 load_array_class (mb, aklass);
9466
9467                 /* vklass = value->vtable->klass */
9468                 load_value_class (mb, vklass);
9469
9470                 /*if (vklass != aklass) goto do_exception; */
9471                 mono_mb_emit_ldloc (mb, aklass);
9472                 mono_mb_emit_ldloc (mb, vklass);
9473                 b2 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9474
9475                 /* do_store: */
9476                 mono_mb_patch_branch (mb, b1);
9477                 mono_mb_emit_ldloc (mb, array_slot_addr);
9478                 mono_mb_emit_ldarg (mb, 2);
9479                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9480                 mono_mb_emit_byte (mb, CEE_RET);
9481
9482                 /* do_exception: */
9483                 mono_mb_patch_branch (mb, b2);
9484                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9485                 break;
9486
9487         case STELEMREF_CLASS:
9488                 /*
9489                 the method:
9490                 <ldelema (bound check)>
9491                 if (!value)
9492                         goto do_store;
9493
9494                 aklass = array->vtable->klass->element_class;
9495                 vklass = value->vtable->klass;
9496
9497                 if (vklass->idepth < aklass->idepth)
9498                         goto do_exception;
9499
9500                 if (vklass->supertypes [aklass->idepth - 1] != aklass)
9501                         goto do_exception;
9502
9503                 do_store:
9504                         *array_slot_addr = value;
9505                         return;
9506
9507                 long:
9508                         throw new ArrayTypeMismatchException ();
9509                 */
9510                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9511                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9512                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9513
9514                 /* ldelema (implicit bound check) */
9515                 load_array_element_address (mb);
9516                 mono_mb_emit_stloc (mb, array_slot_addr);
9517
9518                 /* if (!value) goto do_store */
9519                 mono_mb_emit_ldarg (mb, 2);
9520                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9521
9522                 /* aklass = array->vtable->klass->element_class */
9523                 load_array_class (mb, aklass);
9524
9525                 /* vklass = value->vtable->klass */
9526                 load_value_class (mb, vklass);
9527
9528                 /*if (mono_object_isinst (value, aklass)) */
9529                 mono_mb_emit_ldarg (mb, 2);
9530                 mono_mb_emit_ldloc (mb, aklass);
9531                 mono_mb_emit_icall (mb, mono_object_isinst);
9532                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9533
9534                 /* if (vklass->idepth < aklass->idepth) goto failue */
9535                 mono_mb_emit_ldloc (mb, vklass);
9536                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9537                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9538
9539                 mono_mb_emit_ldloc (mb, aklass);
9540                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9541                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9542
9543                 b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
9544
9545                 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
9546                 mono_mb_emit_ldloc (mb, vklass);
9547                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
9548                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9549
9550                 mono_mb_emit_ldloc (mb, aklass);
9551                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9552                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9553                 mono_mb_emit_icon (mb, 1);
9554                 mono_mb_emit_byte (mb, CEE_SUB);
9555                 mono_mb_emit_icon (mb, sizeof (void*));
9556                 mono_mb_emit_byte (mb, CEE_MUL);
9557                 mono_mb_emit_byte (mb, CEE_ADD);
9558                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9559
9560                 mono_mb_emit_ldloc (mb, aklass);
9561                 b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9562
9563                 /* do_store: */
9564                 mono_mb_patch_branch (mb, b1);
9565                 mono_mb_emit_ldloc (mb, array_slot_addr);
9566                 mono_mb_emit_ldarg (mb, 2);
9567                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9568                 mono_mb_emit_byte (mb, CEE_RET);
9569
9570                 /* do_exception: */
9571                 mono_mb_patch_branch (mb, b2);
9572                 mono_mb_patch_branch (mb, b3);
9573
9574                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9575                 break;
9576
9577         case STELEMREF_INTERFACE:
9578                 /*Mono *klass;
9579                 MonoVTable *vt;
9580                 unsigned uiid;
9581                 if (value == NULL)
9582                         goto store;
9583
9584                 klass = array->obj.vtable->klass->element_class;
9585                 vt = value->vtable;
9586                 uiid = klass->interface_id;
9587                 if (uiid > vt->max_interface_id)
9588                         goto exception;
9589                 if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7))))
9590                         goto exception;
9591                 store:
9592                         mono_array_setref (array, index, value);
9593                         return;
9594                 exception:
9595                         mono_raise_exception (mono_get_exception_array_type_mismatch ());*/
9596
9597                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9598                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9599                 vtable = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9600                 uiid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9601
9602                 /* ldelema (implicit bound check) */
9603                 load_array_element_address (mb);
9604                 mono_mb_emit_stloc (mb, array_slot_addr);
9605
9606                 /* if (!value) goto do_store */
9607                 mono_mb_emit_ldarg (mb, 2);
9608                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9609
9610                 /* klass = array->vtable->klass->element_class */
9611                 load_array_class (mb, aklass);
9612
9613                 /* vt = value->vtable */
9614                 mono_mb_emit_ldarg (mb, 2);
9615                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9616                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9617                 mono_mb_emit_stloc (mb, vtable);
9618
9619                 /* uiid = klass->interface_id; */
9620                 mono_mb_emit_ldloc (mb, aklass);
9621                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, interface_id));
9622                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9623                 mono_mb_emit_stloc (mb, uiid);
9624
9625                 /*if (uiid > vt->max_interface_id)*/
9626                 mono_mb_emit_ldloc (mb, uiid);
9627                 mono_mb_emit_ldloc (mb, vtable);
9628                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, max_interface_id));
9629                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9630                 b2 = mono_mb_emit_branch (mb, CEE_BGT_UN);
9631
9632                 /* if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7)))) */
9633
9634                 /*vt->interface_bitmap*/
9635                 mono_mb_emit_ldloc (mb, vtable);
9636                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, interface_bitmap));
9637                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9638
9639                 /*uiid >> 3*/
9640                 mono_mb_emit_ldloc (mb, uiid);
9641                 mono_mb_emit_icon (mb, 3);
9642                 mono_mb_emit_byte (mb, CEE_SHR_UN);
9643
9644                 /*vt->interface_bitmap [(uiid) >> 3]*/
9645                 mono_mb_emit_byte (mb, CEE_ADD); /*interface_bitmap is a guint8 array*/
9646                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
9647
9648                 /*(1 << ((uiid)&7)))*/
9649                 mono_mb_emit_icon (mb, 1);
9650                 mono_mb_emit_ldloc (mb, uiid);
9651                 mono_mb_emit_icon (mb, 7);
9652                 mono_mb_emit_byte (mb, CEE_AND);
9653                 mono_mb_emit_byte (mb, CEE_SHL);
9654
9655                 /*bitwise and the whole thing*/
9656                 mono_mb_emit_byte (mb, CEE_AND);
9657                 b3 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9658
9659                 /* do_store: */
9660                 mono_mb_patch_branch (mb, b1);
9661                 mono_mb_emit_ldloc (mb, array_slot_addr);
9662                 mono_mb_emit_ldarg (mb, 2);
9663                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9664                 mono_mb_emit_byte (mb, CEE_RET);
9665
9666                 /* do_exception: */
9667                 mono_mb_patch_branch (mb, b2);
9668                 mono_mb_patch_branch (mb, b3);
9669                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9670                 break;
9671
9672         default:
9673                 mono_mb_emit_ldarg (mb, 0);
9674                 mono_mb_emit_ldarg (mb, 1);
9675                 mono_mb_emit_ldarg (mb, 2);
9676                 mono_mb_emit_managed_call (mb, mono_marshal_get_stelemref (), NULL);
9677                 mono_mb_emit_byte (mb, CEE_RET);
9678                 g_assert (0);
9679         }
9680 #endif /* DISABLE_JIT */
9681         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_VIRTUAL_STELEMREF);
9682         info->d.virtual_stelemref.kind = kind;
9683         res = mono_mb_create (mb, signature, 4, info);
9684         res->flags |= METHOD_ATTRIBUTE_VIRTUAL;
9685
9686         mono_marshal_lock ();
9687         if (!cached_methods [kind]) {
9688                 cached_methods [kind] = res;
9689                 mono_marshal_unlock ();
9690         } else {
9691                 mono_marshal_unlock ();
9692                 mono_free_method (res);
9693         }
9694
9695         mono_mb_free (mb);
9696         return cached_methods [kind];
9697 }
9698
9699 MonoMethod*
9700 mono_marshal_get_virtual_stelemref (MonoClass *array_class)
9701 {
9702         int kind;
9703
9704         g_assert (array_class->rank == 1);
9705         kind = get_virtual_stelemref_kind (array_class->element_class);
9706
9707         return get_virtual_stelemref_wrapper (kind);
9708 }
9709
9710 MonoMethod**
9711 mono_marshal_get_virtual_stelemref_wrappers (int *nwrappers)
9712 {
9713         MonoMethod **res;
9714         int i;
9715
9716         *nwrappers = STELEMREF_KIND_COUNT;
9717         res = (MonoMethod **)g_malloc0 (STELEMREF_KIND_COUNT * sizeof (MonoMethod*));
9718         for (i = 0; i < STELEMREF_KIND_COUNT; ++i)
9719                 res [i] = get_virtual_stelemref_wrapper (i);
9720         return res;
9721 }
9722
9723 /*
9724  * The wrapper info for the wrapper is a WrapperInfo structure.
9725  */
9726 MonoMethod*
9727 mono_marshal_get_stelemref (void)
9728 {
9729         static MonoMethod* ret = NULL;
9730         MonoMethodSignature *sig;
9731         MonoMethodBuilder *mb;
9732         WrapperInfo *info;
9733         
9734         guint32 b1, b2, b3, b4;
9735         guint32 copy_pos;
9736         int aklass, vklass;
9737         int array_slot_addr;
9738         
9739         if (ret)
9740                 return ret;
9741         
9742         mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
9743         
9744
9745         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9746
9747         /* void stelemref (void* array, int idx, void* value) */
9748         sig->ret = &mono_defaults.void_class->byval_arg;
9749         sig->params [0] = &mono_defaults.object_class->byval_arg;
9750         sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9751         sig->params [2] = &mono_defaults.object_class->byval_arg;
9752
9753 #ifndef DISABLE_JIT
9754         aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9755         vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9756         array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9757         
9758         /*
9759         the method:
9760         <ldelema (bound check)>
9761         if (!value)
9762                 goto store;
9763         
9764         aklass = array->vtable->klass->element_class;
9765         vklass = value->vtable->klass;
9766         
9767         if (vklass->idepth < aklass->idepth)
9768                 goto long;
9769         
9770         if (vklass->supertypes [aklass->idepth - 1] != aklass)
9771                 goto long;
9772         
9773         store:
9774                 *array_slot_addr = value;
9775                 return;
9776         
9777         long:
9778                 if (mono_object_isinst (value, aklass))
9779                         goto store;
9780                 
9781                 throw new ArrayTypeMismatchException ();
9782         */
9783         
9784         /* ldelema (implicit bound check) */
9785         mono_mb_emit_ldarg (mb, 0);
9786         mono_mb_emit_ldarg (mb, 1);
9787         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9788         mono_mb_emit_stloc (mb, array_slot_addr);
9789                 
9790         /* if (!value) goto do_store */
9791         mono_mb_emit_ldarg (mb, 2);
9792         b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9793         
9794         /* aklass = array->vtable->klass->element_class */
9795         mono_mb_emit_ldarg (mb, 0);
9796         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9797         mono_mb_emit_byte (mb, CEE_LDIND_I);
9798         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9799         mono_mb_emit_byte (mb, CEE_LDIND_I);
9800         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9801         mono_mb_emit_byte (mb, CEE_LDIND_I);
9802         mono_mb_emit_stloc (mb, aklass);
9803         
9804         /* vklass = value->vtable->klass */
9805         mono_mb_emit_ldarg (mb, 2);
9806         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9807         mono_mb_emit_byte (mb, CEE_LDIND_I);
9808         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9809         mono_mb_emit_byte (mb, CEE_LDIND_I);
9810         mono_mb_emit_stloc (mb, vklass);
9811         
9812         /* if (vklass->idepth < aklass->idepth) goto failue */
9813         mono_mb_emit_ldloc (mb, vklass);
9814         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9815         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9816         
9817         mono_mb_emit_ldloc (mb, aklass);
9818         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9819         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9820         
9821         b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
9822         
9823         /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
9824         mono_mb_emit_ldloc (mb, vklass);
9825         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
9826         mono_mb_emit_byte (mb, CEE_LDIND_I);
9827         
9828         mono_mb_emit_ldloc (mb, aklass);
9829         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9830         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9831         mono_mb_emit_icon (mb, 1);
9832         mono_mb_emit_byte (mb, CEE_SUB);
9833         mono_mb_emit_icon (mb, sizeof (void*));
9834         mono_mb_emit_byte (mb, CEE_MUL);
9835         mono_mb_emit_byte (mb, CEE_ADD);
9836         mono_mb_emit_byte (mb, CEE_LDIND_I);
9837         
9838         mono_mb_emit_ldloc (mb, aklass);
9839         
9840         b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9841         
9842         copy_pos = mono_mb_get_label (mb);
9843         /* do_store */
9844         mono_mb_patch_branch (mb, b1);
9845         mono_mb_emit_ldloc (mb, array_slot_addr);
9846         mono_mb_emit_ldarg (mb, 2);
9847         mono_mb_emit_byte (mb, CEE_STIND_REF);
9848         
9849         mono_mb_emit_byte (mb, CEE_RET);
9850         
9851         /* the hard way */
9852         mono_mb_patch_branch (mb, b2);
9853         mono_mb_patch_branch (mb, b3);
9854         
9855         mono_mb_emit_ldarg (mb, 2);
9856         mono_mb_emit_ldloc (mb, aklass);
9857         mono_mb_emit_icall (mb, mono_object_isinst);
9858         
9859         b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
9860         mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
9861         mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9862         
9863         mono_mb_emit_byte (mb, CEE_RET);
9864 #endif
9865         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9866         ret = mono_mb_create (mb, sig, 4, info);
9867         mono_mb_free (mb);
9868
9869         return ret;
9870 }
9871
9872 /*
9873  * mono_marshal_get_gsharedvt_in_wrapper:
9874  *
9875  *   This wrapper handles calls from normal code to gsharedvt code.
9876  *
9877  * The wrapper info for the wrapper is a WrapperInfo structure.
9878  */
9879 MonoMethod*
9880 mono_marshal_get_gsharedvt_in_wrapper (void)
9881 {
9882         static MonoMethod* ret = NULL;
9883         MonoMethodSignature *sig;
9884         MonoMethodBuilder *mb;
9885         WrapperInfo *info;
9886
9887         if (ret)
9888                 return ret;
9889         
9890         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_in", MONO_WRAPPER_UNKNOWN);
9891         
9892         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
9893         sig->ret = &mono_defaults.void_class->byval_arg;
9894
9895 #ifndef DISABLE_JIT
9896         /*
9897          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
9898          */
9899         mono_mb_emit_byte (mb, CEE_RET);
9900 #endif
9901         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_IN);
9902         ret = mono_mb_create (mb, sig, 4, info);
9903         mono_mb_free (mb);
9904
9905         return ret;
9906 }
9907
9908 /*
9909  * mono_marshal_get_gsharedvt_out_wrapper:
9910  *
9911  *   This wrapper handles calls from gsharedvt code to normal code.
9912  *
9913  * The wrapper info for the wrapper is a WrapperInfo structure.
9914  */
9915 MonoMethod*
9916 mono_marshal_get_gsharedvt_out_wrapper (void)
9917 {
9918         static MonoMethod* ret = NULL;
9919         MonoMethodSignature *sig;
9920         MonoMethodBuilder *mb;
9921         WrapperInfo *info;
9922
9923         if (ret)
9924                 return ret;
9925         
9926         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_out", MONO_WRAPPER_UNKNOWN);
9927         
9928         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
9929         sig->ret = &mono_defaults.void_class->byval_arg;
9930
9931 #ifndef DISABLE_JIT
9932         /*
9933          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
9934          */
9935         mono_mb_emit_byte (mb, CEE_RET);
9936 #endif
9937         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_OUT);
9938         ret = mono_mb_create (mb, sig, 4, info);
9939         mono_mb_free (mb);
9940
9941         return ret;
9942 }
9943
9944 typedef struct {
9945         int rank;
9946         int elem_size;
9947         MonoMethod *method;
9948 } ArrayElemAddr;
9949
9950 /* LOCKING: vars accessed under the marshal lock */
9951 static ArrayElemAddr *elem_addr_cache = NULL;
9952 static int elem_addr_cache_size = 0;
9953 static int elem_addr_cache_next = 0;
9954
9955 /**
9956  * mono_marshal_get_array_address:
9957  * @rank: rank of the array type
9958  * @elem_size: size in bytes of an element of an array.
9959  *
9960  * Returns a MonoMethod that implements the code to get the address
9961  * of an element in a multi-dimenasional array of @rank dimensions.
9962  * The returned method takes an array as the first argument and then
9963  * @rank indexes for the @rank dimensions.
9964  * If ELEM_SIZE is 0, read the array size from the array object.
9965  */
9966 MonoMethod*
9967 mono_marshal_get_array_address (int rank, int elem_size)
9968 {
9969         MonoMethod *ret;
9970         MonoMethodBuilder *mb;
9971         MonoMethodSignature *sig;
9972         WrapperInfo *info;
9973         char *name;
9974         int i, bounds, ind, realidx;
9975         int branch_pos, *branch_positions;
9976         int cached;
9977
9978         ret = NULL;
9979         mono_marshal_lock ();
9980         for (i = 0; i < elem_addr_cache_next; ++i) {
9981                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
9982                         ret = elem_addr_cache [i].method;
9983                         break;
9984                 }
9985         }
9986         mono_marshal_unlock ();
9987         if (ret)
9988                 return ret;
9989
9990         branch_positions = g_new0 (int, rank);
9991
9992         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1 + rank);
9993
9994         /* void* address (void* array, int idx0, int idx1, int idx2, ...) */
9995         sig->ret = &mono_defaults.int_class->byval_arg;
9996         sig->params [0] = &mono_defaults.object_class->byval_arg;
9997         for (i = 0; i < rank; ++i) {
9998                 sig->params [i + 1] = &mono_defaults.int32_class->byval_arg;
9999         }
10000
10001         name = g_strdup_printf ("ElementAddr_%d", elem_size);
10002         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
10003         g_free (name);
10004         
10005 #ifndef DISABLE_JIT
10006         bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
10007         ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10008         realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
10009
10010         /* bounds = array->bounds; */
10011         mono_mb_emit_ldarg (mb, 0);
10012         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, bounds));
10013         mono_mb_emit_byte (mb, CEE_LDIND_I);
10014         mono_mb_emit_stloc (mb, bounds);
10015
10016         /* ind is the overall element index, realidx is the partial index in a single dimension */
10017         /* ind = idx0 - bounds [0].lower_bound */
10018         mono_mb_emit_ldarg (mb, 1);
10019         mono_mb_emit_ldloc (mb, bounds);
10020         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10021         mono_mb_emit_byte (mb, CEE_ADD);
10022         mono_mb_emit_byte (mb, CEE_LDIND_I4);
10023         mono_mb_emit_byte (mb, CEE_SUB);
10024         mono_mb_emit_stloc (mb, ind);
10025         /* if (ind >= bounds [0].length) goto exeception; */
10026         mono_mb_emit_ldloc (mb, ind);
10027         mono_mb_emit_ldloc (mb, bounds);
10028         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10029         mono_mb_emit_byte (mb, CEE_ADD);
10030         mono_mb_emit_byte (mb, CEE_LDIND_I4);
10031         /* note that we use unsigned comparison */
10032         branch_pos = mono_mb_emit_branch (mb, CEE_BGE_UN);
10033
10034         /* For large ranks (> 4?) use a loop n IL later to reduce code size.
10035          * We could also decide to ignore the passed elem_size and get it
10036          * from the array object, to reduce the number of methods we generate:
10037          * the additional cost is 3 memory loads and a non-immediate mul.
10038          */
10039         for (i = 1; i < rank; ++i) {
10040                 /* realidx = idxi - bounds [i].lower_bound */
10041                 mono_mb_emit_ldarg (mb, 1 + i);
10042                 mono_mb_emit_ldloc (mb, bounds);
10043                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
10044                 mono_mb_emit_byte (mb, CEE_ADD);
10045                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10046                 mono_mb_emit_byte (mb, CEE_SUB);
10047                 mono_mb_emit_stloc (mb, realidx);
10048                 /* if (realidx >= bounds [i].length) goto exeception; */
10049                 mono_mb_emit_ldloc (mb, realidx);
10050                 mono_mb_emit_ldloc (mb, bounds);
10051                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10052                 mono_mb_emit_byte (mb, CEE_ADD);
10053                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10054                 branch_positions [i] = mono_mb_emit_branch (mb, CEE_BGE_UN);
10055                 /* ind = ind * bounds [i].length + realidx */
10056                 mono_mb_emit_ldloc (mb, ind);
10057                 mono_mb_emit_ldloc (mb, bounds);
10058                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
10059                 mono_mb_emit_byte (mb, CEE_ADD);
10060                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10061                 mono_mb_emit_byte (mb, CEE_MUL);
10062                 mono_mb_emit_ldloc (mb, realidx);
10063                 mono_mb_emit_byte (mb, CEE_ADD);
10064                 mono_mb_emit_stloc (mb, ind);
10065         }
10066
10067         /* return array->vector + ind * element_size */
10068         mono_mb_emit_ldarg (mb, 0);
10069         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
10070         mono_mb_emit_ldloc (mb, ind);
10071         if (elem_size) {
10072                 mono_mb_emit_icon (mb, elem_size);
10073         } else {
10074                 /* Load arr->vtable->klass->sizes.element_class */
10075                 mono_mb_emit_ldarg (mb, 0);
10076                 mono_mb_emit_byte (mb, CEE_CONV_I);
10077                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
10078                 mono_mb_emit_byte (mb, CEE_ADD);
10079                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10080                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
10081                 mono_mb_emit_byte (mb, CEE_ADD);
10082                 mono_mb_emit_byte (mb, CEE_LDIND_I);
10083                 /* sizes is an union, so this reads sizes.element_size */
10084                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
10085                 mono_mb_emit_byte (mb, CEE_ADD);
10086                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
10087         }
10088                 mono_mb_emit_byte (mb, CEE_MUL);
10089         mono_mb_emit_byte (mb, CEE_ADD);
10090         mono_mb_emit_byte (mb, CEE_RET);
10091
10092         /* patch the branches to get here and throw */
10093         for (i = 1; i < rank; ++i) {
10094                 mono_mb_patch_branch (mb, branch_positions [i]);
10095         }
10096         mono_mb_patch_branch (mb, branch_pos);
10097         /* throw exception */
10098         mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
10099
10100         g_free (branch_positions);
10101 #endif /* DISABLE_JIT */
10102
10103         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ELEMENT_ADDR);
10104         info->d.element_addr.rank = rank;
10105         info->d.element_addr.elem_size = elem_size;
10106         ret = mono_mb_create (mb, sig, 4, info);
10107         mono_mb_free (mb);
10108
10109         /* cache the result */
10110         cached = 0;
10111         mono_marshal_lock ();
10112         for (i = 0; i < elem_addr_cache_next; ++i) {
10113                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
10114                         /* FIXME: free ret */
10115                         ret = elem_addr_cache [i].method;
10116                         cached = TRUE;
10117                         break;
10118                 }
10119         }
10120         if (!cached) {
10121                 if (elem_addr_cache_next >= elem_addr_cache_size) {
10122                         int new_size = elem_addr_cache_size + 4;
10123                         ArrayElemAddr *new_array = g_new0 (ArrayElemAddr, new_size);
10124                         memcpy (new_array, elem_addr_cache, elem_addr_cache_size * sizeof (ArrayElemAddr));
10125                         g_free (elem_addr_cache);
10126                         elem_addr_cache = new_array;
10127                         elem_addr_cache_size = new_size;
10128                 }
10129                 elem_addr_cache [elem_addr_cache_next].rank = rank;
10130                 elem_addr_cache [elem_addr_cache_next].elem_size = elem_size;
10131                 elem_addr_cache [elem_addr_cache_next].method = ret;
10132                 elem_addr_cache_next ++;
10133         }
10134         mono_marshal_unlock ();
10135         return ret;
10136 }
10137
10138 /*
10139  * mono_marshal_get_array_accessor_wrapper:
10140  *
10141  *   Return a wrapper which just calls METHOD, which should be an Array Get/Set/Address method.
10142  */
10143 MonoMethod *
10144 mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
10145 {
10146         MonoMethodSignature *sig;
10147         MonoMethodBuilder *mb;
10148         MonoMethod *res;
10149         GHashTable *cache;
10150         int i;
10151         MonoGenericContext *ctx = NULL;
10152         MonoMethod *orig_method = NULL;
10153         MonoGenericContainer *container = NULL;
10154         WrapperInfo *info;
10155
10156         /*
10157          * These wrappers are needed to avoid the JIT replacing the calls to these methods with intrinsics
10158          * inside runtime invoke wrappers, thereby making the wrappers not unshareable.
10159          * FIXME: Use generic methods.
10160          */
10161         /*
10162          * Check cache
10163          */
10164         if (ctx) {
10165                 cache = NULL;
10166                 g_assert_not_reached ();
10167         } else {
10168                 cache = get_cache (&method->klass->image->array_accessor_cache, mono_aligned_addr_hash, NULL);
10169                 if ((res = mono_marshal_find_in_cache (cache, method)))
10170                         return res;
10171         }
10172
10173         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
10174         sig->pinvoke = 0;
10175
10176         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
10177
10178 #ifndef DISABLE_JIT
10179         /* Call the method */
10180         if (sig->hasthis)
10181                 mono_mb_emit_ldarg (mb, 0);
10182         for (i = 0; i < sig->param_count; i++)
10183                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
10184
10185         if (ctx) {
10186                 MonoError error;
10187                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
10188                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
10189         } else {
10190                 mono_mb_emit_managed_call (mb, method, NULL);
10191         }
10192         mono_mb_emit_byte (mb, CEE_RET);
10193 #endif
10194
10195         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ARRAY_ACCESSOR);
10196         info->d.array_accessor.method = method;
10197
10198         if (ctx) {
10199                 MonoMethod *def;
10200                 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
10201                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
10202         } else {
10203                 res = mono_mb_create_and_cache_full (cache, method,
10204                                                                                          mb, sig, sig->param_count + 16,
10205                                                                                          info, NULL);
10206         }
10207         mono_mb_free (mb);
10208
10209         return res;     
10210 }
10211
10212 void*
10213 mono_marshal_alloc (gulong size, MonoError *error)
10214 {
10215         gpointer res;
10216
10217         mono_error_init (error);
10218
10219 #ifdef HOST_WIN32
10220         res = CoTaskMemAlloc (size);
10221 #else
10222         res = g_try_malloc ((gulong)size);
10223         if (!res)
10224                 mono_error_set_out_of_memory (error, "Could not allocate %i bytes", size);
10225 #endif
10226         return res;
10227 }
10228
10229 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10230 static void*
10231 ves_icall_marshal_alloc (gulong size)
10232 {
10233         MonoError error;
10234         void *ret = mono_marshal_alloc (size, &error);
10235         if (!mono_error_ok (&error)) {
10236                 mono_error_set_pending_exception (&error);
10237                 return NULL;
10238         }
10239
10240         return ret;
10241 }
10242
10243 void
10244 mono_marshal_free (gpointer ptr)
10245 {
10246 #ifdef HOST_WIN32
10247         CoTaskMemFree (ptr);
10248 #else
10249         g_free (ptr);
10250 #endif
10251 }
10252
10253 void
10254 mono_marshal_free_array (gpointer *ptr, int size) 
10255 {
10256         int i;
10257
10258         if (!ptr)
10259                 return;
10260
10261         for (i = 0; i < size; i++)
10262                 if (ptr [i])
10263                         g_free (ptr [i]);
10264 }
10265
10266 void *
10267 mono_marshal_string_to_utf16 (MonoString *s)
10268 {
10269         return s ? mono_string_chars (s) : NULL;
10270 }
10271
10272 /* This is a JIT icall, it sets the pending exception and returns NULL on error. */
10273 static void *
10274 mono_marshal_string_to_utf16_copy (MonoString *s)
10275 {
10276         if (s == NULL) {
10277                 return NULL;
10278         } else {
10279                 MonoError error;
10280                 gunichar2 *res = (gunichar2 *)mono_marshal_alloc ((mono_string_length (s) * 2) + 2, &error);
10281                 if (!mono_error_ok (&error)) {
10282                         mono_error_set_pending_exception (&error);
10283                         return NULL;
10284                 }
10285                 memcpy (res, mono_string_chars (s), mono_string_length (s) * 2);
10286                 res [mono_string_length (s)] = 0;
10287                 return res;
10288         }
10289 }
10290
10291 /**
10292  * mono_marshal_set_last_error:
10293  *
10294  * This function is invoked to set the last error value from a P/Invoke call
10295  * which has SetLastError set.
10296  */
10297 void
10298 mono_marshal_set_last_error (void)
10299 {
10300 #ifdef WIN32
10301         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
10302 #else
10303         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (errno));
10304 #endif
10305 }
10306
10307 static void
10308 mono_marshal_set_last_error_windows (int error)
10309 {
10310 #ifdef WIN32
10311         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (error));
10312 #endif
10313 }
10314
10315 void
10316 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
10317                                                                     gpointer dest, gint32 length)
10318 {
10319         int element_size;
10320         void *source_addr;
10321
10322         MONO_CHECK_ARG_NULL (src,);
10323         MONO_CHECK_ARG_NULL (dest,);
10324
10325         if (src->obj.vtable->klass->rank != 1) {
10326                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10327                 return;
10328         }
10329         if (start_index < 0) {
10330                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10331                 return;
10332         }
10333         if (length < 0) {
10334                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10335                 return;
10336         }
10337         if (start_index + length > mono_array_length (src)) {
10338                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10339                 return;
10340         }
10341
10342         element_size = mono_array_element_size (src->obj.vtable->klass);
10343
10344         /* no references should be involved */
10345         source_addr = mono_array_addr_with_size_fast (src, element_size, start_index);
10346
10347         memcpy (dest, source_addr, length * element_size);
10348 }
10349
10350 void
10351 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
10352                                                                       MonoArray *dest, gint32 length)
10353 {
10354         int element_size;
10355         void *dest_addr;
10356
10357         MONO_CHECK_ARG_NULL (src,);
10358         MONO_CHECK_ARG_NULL (dest,);
10359
10360         if (dest->obj.vtable->klass->rank != 1) {
10361                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10362                 return;
10363         }
10364         if (start_index < 0) {
10365                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10366                 return;
10367         }
10368         if (length < 0) {
10369                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10370                 return;
10371         }
10372         if (start_index + length > mono_array_length (dest)) {
10373                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10374                 return;
10375         }
10376         element_size = mono_array_element_size (dest->obj.vtable->klass);
10377           
10378         /* no references should be involved */
10379         dest_addr = mono_array_addr_with_size_fast (dest, element_size, start_index);
10380
10381         memcpy (dest_addr, src, length * element_size);
10382 }
10383
10384 MonoString *
10385 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr)
10386 {
10387         if (ptr == NULL)
10388                 return NULL;
10389         else
10390                 return mono_string_new (mono_domain_get (), ptr);
10391 }
10392
10393 MonoString *
10394 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
10395 {
10396         if (ptr == NULL) {
10397                 mono_set_pending_exception (mono_get_exception_argument_null ("ptr"));
10398                 return NULL;
10399         } else {
10400                 return mono_string_new_len (mono_domain_get (), ptr, len);
10401         }
10402 }
10403
10404 MonoString *
10405 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
10406 {
10407         MonoError error;
10408         MonoString *res = NULL;
10409         MonoDomain *domain = mono_domain_get (); 
10410         int len = 0;
10411         guint16 *t = ptr;
10412
10413         if (ptr == NULL)
10414                 return NULL;
10415
10416         while (*t++)
10417                 len++;
10418
10419         res = mono_string_new_utf16_checked (domain, ptr, len, &error);
10420         if (!mono_error_ok (&error)) {
10421                 mono_error_set_pending_exception (&error);
10422                 return NULL;
10423         }
10424         return res;
10425 }
10426
10427 MonoString *
10428 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
10429 {
10430         MonoError error;
10431         MonoString *res = NULL;
10432         MonoDomain *domain = mono_domain_get (); 
10433
10434         mono_error_init (&error);
10435
10436         if (ptr == NULL) {
10437                 res = NULL;
10438                 mono_error_set_argument_null (&error, "ptr", "");
10439         } else {
10440                 res = mono_string_new_utf16_checked (domain, ptr, len, &error);
10441         }
10442
10443         if (!mono_error_ok (&error))
10444                 mono_error_set_pending_exception (&error);
10445         return res;
10446 }
10447
10448 guint32 
10449 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
10450 {
10451         return (GPOINTER_TO_INT (mono_native_tls_get_value (last_error_tls_id)));
10452 }
10453
10454 guint32 
10455 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionType *rtype)
10456 {
10457         MonoClass *klass;
10458         MonoType *type;
10459         guint32 layout;
10460
10461         MONO_CHECK_ARG_NULL (rtype, 0);
10462
10463         type = rtype->type;
10464         klass = mono_class_from_mono_type (type);
10465         if (!mono_class_init (klass)) {
10466                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10467                 return 0;
10468         }
10469
10470         layout = (klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK);
10471
10472         if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
10473                 return sizeof (gpointer);
10474         } else if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
10475                 gchar *msg;
10476                 MonoException *exc;
10477
10478                 msg = g_strdup_printf ("Type %s cannot be marshaled as an unmanaged structure.", klass->name);
10479                 exc = mono_get_exception_argument ("t", msg);
10480                 g_free (msg);
10481                 mono_set_pending_exception (exc);
10482                 return 0;
10483         }
10484
10485         return mono_class_native_size (klass, NULL);
10486 }
10487
10488 void
10489 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
10490 {
10491         MonoError error;
10492         MonoMethod *method;
10493         gpointer pa [3];
10494
10495         MONO_CHECK_ARG_NULL (obj,);
10496         MONO_CHECK_ARG_NULL (dst,);
10497
10498         method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
10499
10500         pa [0] = obj;
10501         pa [1] = &dst;
10502         pa [2] = &delete_old;
10503
10504         mono_runtime_invoke_checked (method, NULL, pa, &error);
10505         if (!mono_error_ok (&error))
10506                 mono_error_set_pending_exception (&error);
10507 }
10508
10509 static void
10510 ptr_to_structure (gpointer src, MonoObject *dst, MonoError *error)
10511 {
10512         MonoMethod *method;
10513         gpointer pa [2];
10514
10515         mono_error_init (error);
10516
10517         method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
10518
10519         pa [0] = &src;
10520         pa [1] = dst;
10521
10522         mono_runtime_invoke_checked (method, NULL, pa, error);
10523 }
10524
10525 void
10526 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
10527 {
10528         MonoType *t;
10529         MonoError error;
10530
10531         MONO_CHECK_ARG_NULL (src,);
10532         MONO_CHECK_ARG_NULL (dst,);
10533         
10534         t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
10535
10536         if (t->type == MONO_TYPE_VALUETYPE) {
10537                 MonoException *exc;
10538                 gchar *tmp;
10539
10540                 tmp = g_strdup_printf ("Destination is a boxed value type.");
10541                 exc = mono_get_exception_argument ("dst", tmp);
10542                 g_free (tmp);  
10543
10544                 mono_set_pending_exception (exc);
10545                 return;
10546         }
10547
10548         ptr_to_structure (src, dst, &error);
10549         if (!mono_error_ok (&error))
10550                 mono_error_set_pending_exception (&error);
10551 }
10552
10553 MonoObject *
10554 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
10555 {
10556         MonoError error;
10557         MonoClass *klass;
10558         MonoDomain *domain = mono_domain_get (); 
10559         MonoObject *res;
10560
10561         if (src == NULL)
10562                 return NULL;
10563         MONO_CHECK_ARG_NULL (type, NULL);
10564
10565         klass = mono_class_from_mono_type (type->type);
10566         if (!mono_class_init (klass)) {
10567                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10568                 return NULL;
10569         }
10570
10571         res = mono_object_new_checked (domain, klass, &error);
10572         if (!mono_error_ok (&error)) {
10573                 mono_error_set_pending_exception (&error);
10574                 return NULL;
10575         }
10576
10577         ptr_to_structure (src, res, &error);
10578         if (!mono_error_ok (&error)) {
10579                 mono_error_set_pending_exception (&error);
10580                 return NULL;
10581         }
10582
10583         return res;
10584 }
10585
10586 int
10587 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *type, MonoString *field_name)
10588 {
10589         MonoMarshalType *info;
10590         MonoClass *klass;
10591         char *fname;
10592         int match_index = -1;
10593         
10594         MONO_CHECK_ARG_NULL (type, 0);
10595         MONO_CHECK_ARG_NULL (field_name, 0);
10596
10597         fname = mono_string_to_utf8 (field_name);
10598         klass = mono_class_from_mono_type (type->type);
10599         if (!mono_class_init (klass)) {
10600                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10601                 return 0;
10602         }
10603
10604         while (klass && match_index == -1) {
10605                 MonoClassField* field;
10606                 int i = 0;
10607                 gpointer iter = NULL;
10608                 while ((field = mono_class_get_fields (klass, &iter))) {
10609                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10610                                 continue;
10611                         if (!strcmp (fname, mono_field_get_name (field))) {
10612                                 match_index = i;
10613                                 break;
10614                         }
10615                         i ++;
10616                 }
10617
10618                 if (match_index == -1)
10619                         klass = klass->parent;
10620         }
10621
10622         g_free (fname);
10623
10624         if(match_index == -1) {
10625                 MonoException* exc;
10626                 gchar *tmp;
10627
10628                 /* Get back original class instance */
10629                 klass = mono_class_from_mono_type (type->type);
10630
10631                 tmp = g_strdup_printf ("Field passed in is not a marshaled member of the type %s", klass->name);
10632                 exc = mono_get_exception_argument ("fieldName", tmp);
10633                 g_free (tmp);
10634  
10635                 mono_set_pending_exception ((MonoException*)exc);
10636                 return 0;
10637         }
10638
10639         info = mono_marshal_load_type_info (klass);     
10640         return info->fields [match_index].offset;
10641 }
10642
10643 gpointer
10644 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
10645 {
10646 #ifdef HOST_WIN32
10647         char* tres, *ret;
10648         size_t len;
10649         tres = mono_string_to_utf8 (string);
10650         if (!tres)
10651                 return tres;
10652
10653         len = strlen (tres) + 1;
10654         ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len);
10655         memcpy (ret, tres, len);
10656         g_free (tres);
10657         return ret;
10658
10659 #else
10660         return mono_string_to_utf8 (string);
10661 #endif
10662 }
10663
10664 gpointer
10665 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
10666 {
10667         if (string == NULL)
10668                 return NULL;
10669         else {
10670 #ifdef TARGET_WIN32
10671                 gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal 
10672                         ((mono_string_length (string) + 1) * 2);
10673 #else
10674                 gunichar2 *res = (gunichar2 *)g_malloc ((mono_string_length (string) + 1) * 2);
10675 #endif
10676                 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
10677                 res [mono_string_length (string)] = 0;
10678                 return res;
10679         }
10680 }
10681
10682 static void
10683 mono_struct_delete_old (MonoClass *klass, char *ptr)
10684 {
10685         MonoMarshalType *info;
10686         int i;
10687
10688         info = mono_marshal_load_type_info (klass);
10689
10690         for (i = 0; i < info->num_fields; i++) {
10691                 MonoMarshalConv conv;
10692                 MonoType *ftype = info->fields [i].field->type;
10693                 char *cpos;
10694
10695                 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
10696                         continue;
10697
10698                 mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, 
10699                                 klass->unicode, &conv);
10700                         
10701                 cpos = ptr + info->fields [i].offset;
10702
10703                 switch (conv) {
10704                 case MONO_MARSHAL_CONV_NONE:
10705                         if (MONO_TYPE_ISSTRUCT (ftype)) {
10706                                 mono_struct_delete_old (ftype->data.klass, cpos);
10707                                 continue;
10708                         }
10709                         break;
10710                 case MONO_MARSHAL_CONV_STR_LPWSTR:
10711                         /* We assume this field points inside a MonoString */
10712                         break;
10713                 case MONO_MARSHAL_CONV_STR_LPTSTR:
10714 #ifdef TARGET_WIN32
10715                         /* We assume this field points inside a MonoString 
10716                          * on Win32 */
10717                         break;
10718 #endif
10719                 case MONO_MARSHAL_CONV_STR_LPSTR:
10720                 case MONO_MARSHAL_CONV_STR_BSTR:
10721                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
10722                 case MONO_MARSHAL_CONV_STR_TBSTR:
10723                         mono_marshal_free (*(gpointer *)cpos);
10724                         break;
10725
10726                 default:
10727                         continue;
10728                 }
10729         }
10730 }
10731
10732 void
10733 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
10734 {
10735         MonoClass *klass;
10736
10737         MONO_CHECK_ARG_NULL (src,);
10738         MONO_CHECK_ARG_NULL (type,);
10739
10740         klass = mono_class_from_mono_type (type->type);
10741         if (!mono_class_init (klass)) {
10742                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10743                 return;
10744         }
10745
10746         mono_struct_delete_old (klass, (char *)src);
10747 }
10748
10749 void*
10750 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
10751 {
10752         gpointer res;
10753         size_t s = (size_t)size;
10754
10755         if (s == 0)
10756                 /* This returns a valid pointer for size 0 on MS.NET */
10757                 s = 4;
10758
10759 #ifdef HOST_WIN32
10760         res = GlobalAlloc (GMEM_FIXED, s);
10761 #else
10762         res = g_try_malloc (s);
10763 #endif
10764         if (!res) {
10765                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
10766                 return NULL;
10767         }
10768
10769         return res;
10770 }
10771
10772 gpointer
10773 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, gpointer size)
10774 {
10775         gpointer res;
10776         size_t s = (size_t)size;
10777
10778         if (ptr == NULL) {
10779                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
10780                 return NULL;
10781         }
10782
10783 #ifdef HOST_WIN32
10784         res = GlobalReAlloc (ptr, s, GMEM_MOVEABLE);
10785 #else
10786         res = g_try_realloc (ptr, s);
10787 #endif
10788         if (!res) {
10789                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
10790                 return NULL;
10791         }
10792
10793         return res;
10794 }
10795
10796 void
10797 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
10798 {
10799 #ifdef HOST_WIN32
10800         GlobalFree (ptr);
10801 #else
10802         g_free (ptr);
10803 #endif
10804 }
10805
10806 void*
10807 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
10808 {
10809         void *res;
10810
10811 #ifdef HOST_WIN32
10812         res = CoTaskMemAlloc (size);
10813 #else
10814         if ((gulong)size == 0)
10815                 /* This returns a valid pointer for size 0 on MS.NET */
10816                 size = 4;
10817
10818         res = g_try_malloc ((gulong)size);
10819 #endif
10820         if (!res) {
10821                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
10822                 return NULL;
10823         }
10824         return res;
10825 }
10826
10827 void
10828 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
10829 {
10830 #ifdef HOST_WIN32
10831         CoTaskMemFree (ptr);
10832 #else
10833         g_free (ptr);
10834 #endif
10835 }
10836
10837 gpointer
10838 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
10839 {
10840         void *res;
10841
10842 #ifdef HOST_WIN32
10843         res = CoTaskMemRealloc (ptr, size);
10844 #else
10845         res = g_try_realloc (ptr, (gulong)size);
10846 #endif
10847         if (!res) {
10848                 mono_set_pending_exception (mono_domain_get ()->out_of_memory_ex);
10849                 return NULL;
10850         }
10851         return res;
10852 }
10853
10854 void*
10855 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
10856 {
10857         return mono_array_addr_with_size_fast (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
10858 }
10859
10860 MonoDelegate*
10861 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionType *type)
10862 {
10863         MonoClass *klass = mono_type_get_class (type->type);
10864         if (!mono_class_init (klass)) {
10865                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10866                 return NULL;
10867         }
10868
10869         return mono_ftnptr_to_delegate (klass, ftn);
10870 }
10871
10872 gpointer
10873 ves_icall_System_Runtime_InteropServices_Marshal_GetFunctionPointerForDelegateInternal (MonoDelegate *delegate)
10874 {
10875         return mono_delegate_to_ftnptr (delegate);
10876 }
10877
10878 /**
10879  * mono_marshal_is_loading_type_info:
10880  *
10881  *  Return whenever mono_marshal_load_type_info () is being executed for KLASS by this
10882  * thread.
10883  */
10884 static gboolean
10885 mono_marshal_is_loading_type_info (MonoClass *klass)
10886 {
10887         GSList *loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
10888
10889         return g_slist_find (loads_list, klass) != NULL;
10890 }
10891
10892 /**
10893  * mono_marshal_load_type_info:
10894  *
10895  *  Initialize klass->marshal_info using information from metadata. This function can
10896  * recursively call itself, and the caller is responsible to avoid that by calling 
10897  * mono_marshal_is_loading_type_info () beforehand.
10898  *
10899  * LOCKING: Acquires the loader lock.
10900  */
10901 MonoMarshalType *
10902 mono_marshal_load_type_info (MonoClass* klass)
10903 {
10904         int j, count = 0;
10905         guint32 native_size = 0, min_align = 1, packing;
10906         MonoMarshalType *info;
10907         MonoClassField* field;
10908         gpointer iter;
10909         guint32 layout;
10910         GSList *loads_list;
10911
10912         g_assert (klass != NULL);
10913
10914         if (klass->marshal_info)
10915                 return klass->marshal_info;
10916
10917         if (!klass->inited)
10918                 mono_class_init (klass);
10919
10920         if (klass->marshal_info)
10921                 return klass->marshal_info;
10922
10923         /*
10924          * This function can recursively call itself, so we keep the list of classes which are
10925          * under initialization in a TLS list.
10926          */
10927         g_assert (!mono_marshal_is_loading_type_info (klass));
10928         loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
10929         loads_list = g_slist_prepend (loads_list, klass);
10930         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
10931         
10932         iter = NULL;
10933         while ((field = mono_class_get_fields (klass, &iter))) {
10934                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10935                         continue;
10936                 if (mono_field_is_deleted (field))
10937                         continue;
10938                 count++;
10939         }
10940
10941         layout = klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
10942
10943         /* The mempool is protected by the loader lock */
10944         info = (MonoMarshalType *)mono_image_alloc0 (klass->image, MONO_SIZEOF_MARSHAL_TYPE + sizeof (MonoMarshalField) * count);
10945         info->num_fields = count;
10946         
10947         /* Try to find a size for this type in metadata */
10948         mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
10949
10950         if (klass->parent) {
10951                 int parent_size = mono_class_native_size (klass->parent, NULL);
10952
10953                 /* Add parent size to real size */
10954                 native_size += parent_size;
10955                 info->native_size = parent_size;
10956         }
10957
10958         packing = klass->packing_size ? klass->packing_size : 8;
10959         iter = NULL;
10960         j = 0;
10961         while ((field = mono_class_get_fields (klass, &iter))) {
10962                 int size;
10963                 guint32 align;
10964                 
10965                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10966                         continue;
10967
10968                 if (mono_field_is_deleted (field))
10969                         continue;
10970                 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
10971                         mono_metadata_field_info_with_mempool (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1, 
10972                                                   NULL, NULL, &info->fields [j].mspec);
10973
10974                 info->fields [j].field = field;
10975
10976                 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
10977                         (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
10978                         /* This field is a hack inserted by MCS to empty structures */
10979                         continue;
10980                 }
10981
10982                 switch (layout) {
10983                 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
10984                 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
10985                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
10986                                                        &align, TRUE, klass->unicode);
10987                         align = klass->packing_size ? MIN (klass->packing_size, align): align;
10988                         min_align = MAX (align, min_align);
10989                         info->fields [j].offset = info->native_size;
10990                         info->fields [j].offset += align - 1;
10991                         info->fields [j].offset &= ~(align - 1);
10992                         info->native_size = info->fields [j].offset + size;
10993                         break;
10994                 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
10995                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
10996                                                        &align, TRUE, klass->unicode);
10997                         min_align = MAX (align, min_align);
10998                         info->fields [j].offset = field->offset - sizeof (MonoObject);
10999                         info->native_size = MAX (info->native_size, info->fields [j].offset + size);
11000                         break;
11001                 }       
11002                 j++;
11003         }
11004
11005         if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
11006                 info->native_size = MAX (native_size, info->native_size);
11007                 /*
11008                  * If the provided Size is equal or larger than the calculated size, and there
11009                  * was no Pack attribute, we set min_align to 1 to avoid native_size being increased
11010                  */
11011                 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
11012                         if (native_size && native_size == info->native_size && klass->packing_size == 0)
11013                                 min_align = 1;
11014                         else
11015                                 min_align = MIN (min_align, packing);
11016                 }
11017         }
11018
11019         if (info->native_size & (min_align - 1)) {
11020                 info->native_size += min_align - 1;
11021                 info->native_size &= ~(min_align - 1);
11022         }
11023
11024         info->min_align = min_align;
11025
11026         /* Update the class's blittable info, if the layouts don't match */
11027         if (info->native_size != mono_class_value_size (klass, NULL))
11028                 klass->blittable = FALSE;
11029
11030         /* If this is an array type, ensure that we have element info */
11031         if (klass->rank && !mono_marshal_is_loading_type_info (klass->element_class)) {
11032                 mono_marshal_load_type_info (klass->element_class);
11033         }
11034
11035         loads_list = (GSList *)mono_native_tls_get_value (load_type_info_tls_id);
11036         loads_list = g_slist_remove (loads_list, klass);
11037         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
11038
11039         mono_marshal_lock ();
11040         if (!klass->marshal_info) {
11041                 /*We do double-checking locking on marshal_info */
11042                 mono_memory_barrier ();
11043                 klass->marshal_info = info;
11044         }
11045         mono_marshal_unlock ();
11046
11047         return klass->marshal_info;
11048 }
11049
11050 /**
11051  * mono_class_native_size:
11052  * @klass: a class 
11053  * 
11054  * Returns: the native size of an object instance (when marshaled 
11055  * to unmanaged code) 
11056  */
11057 gint32
11058 mono_class_native_size (MonoClass *klass, guint32 *align)
11059 {       
11060         if (!klass->marshal_info) {
11061                 if (mono_marshal_is_loading_type_info (klass)) {
11062                         if (align)
11063                                 *align = 0;
11064                         return 0;
11065                 } else {
11066                         mono_marshal_load_type_info (klass);
11067                 }
11068         }
11069
11070         if (align)
11071                 *align = klass->marshal_info->min_align;
11072
11073         return klass->marshal_info->native_size;
11074 }
11075
11076 /*
11077  * mono_type_native_stack_size:
11078  * @t: the type to return the size it uses on the stack
11079  *
11080  * Returns: the number of bytes required to hold an instance of this
11081  * type on the native stack
11082  */
11083 int
11084 mono_type_native_stack_size (MonoType *t, guint32 *align)
11085 {
11086         guint32 tmp;
11087
11088         g_assert (t != NULL);
11089
11090         if (!align)
11091                 align = &tmp;
11092
11093         if (t->byref) {
11094                 *align = sizeof (gpointer);
11095                 return sizeof (gpointer);
11096         }
11097
11098         switch (t->type){
11099         case MONO_TYPE_BOOLEAN:
11100         case MONO_TYPE_CHAR:
11101         case MONO_TYPE_I1:
11102         case MONO_TYPE_U1:
11103         case MONO_TYPE_I2:
11104         case MONO_TYPE_U2:
11105         case MONO_TYPE_I4:
11106         case MONO_TYPE_U4:
11107                 *align = 4;
11108                 return 4;
11109         case MONO_TYPE_I:
11110         case MONO_TYPE_U:
11111         case MONO_TYPE_STRING:
11112         case MONO_TYPE_OBJECT:
11113         case MONO_TYPE_CLASS:
11114         case MONO_TYPE_SZARRAY:
11115         case MONO_TYPE_PTR:
11116         case MONO_TYPE_FNPTR:
11117         case MONO_TYPE_ARRAY:
11118                 *align = sizeof (gpointer);
11119                 return sizeof (gpointer);
11120         case MONO_TYPE_R4:
11121                 *align = 4;
11122                 return 4;
11123         case MONO_TYPE_R8:
11124                 *align = MONO_ABI_ALIGNOF (double);
11125                 return 8;
11126         case MONO_TYPE_I8:
11127         case MONO_TYPE_U8:
11128                 *align = MONO_ABI_ALIGNOF (gint64);
11129                 return 8;
11130         case MONO_TYPE_GENERICINST:
11131                 if (!mono_type_generic_inst_is_valuetype (t)) {
11132                         *align = sizeof (gpointer);
11133                         return sizeof (gpointer);
11134                 } 
11135                 /* Fall through */
11136         case MONO_TYPE_TYPEDBYREF:
11137         case MONO_TYPE_VALUETYPE: {
11138                 guint32 size;
11139                 MonoClass *klass = mono_class_from_mono_type (t);
11140
11141                 if (klass->enumtype)
11142                         return mono_type_native_stack_size (mono_class_enum_basetype (klass), align);
11143                 else {
11144                         size = mono_class_native_size (klass, align);
11145                         *align = *align + 3;
11146                         *align &= ~3;
11147                         
11148                         size +=  3;
11149                         size &= ~3;
11150
11151                         return size;
11152                 }
11153         }
11154         default:
11155                 g_error ("type 0x%02x unknown", t->type);
11156         }
11157         return 0;
11158 }
11159
11160 gint32
11161 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
11162                         gboolean as_field, gboolean unicode)
11163 {
11164         MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
11165         MonoClass *klass;
11166
11167         switch (native_type) {
11168         case MONO_NATIVE_BOOLEAN:
11169                 *align = 4;
11170                 return 4;
11171         case MONO_NATIVE_I1:
11172         case MONO_NATIVE_U1:
11173                 *align = 1;
11174                 return 1;
11175         case MONO_NATIVE_I2:
11176         case MONO_NATIVE_U2:
11177         case MONO_NATIVE_VARIANTBOOL:
11178                 *align = 2;
11179                 return 2;
11180         case MONO_NATIVE_I4:
11181         case MONO_NATIVE_U4:
11182         case MONO_NATIVE_ERROR:
11183                 *align = 4;
11184                 return 4;
11185         case MONO_NATIVE_I8:
11186         case MONO_NATIVE_U8:
11187                 *align = MONO_ABI_ALIGNOF (gint64);
11188                 return 8;
11189         case MONO_NATIVE_R4:
11190                 *align = 4;
11191                 return 4;
11192         case MONO_NATIVE_R8:
11193                 *align = MONO_ABI_ALIGNOF (double);
11194                 return 8;
11195         case MONO_NATIVE_INT:
11196         case MONO_NATIVE_UINT:
11197         case MONO_NATIVE_LPSTR:
11198         case MONO_NATIVE_LPWSTR:
11199         case MONO_NATIVE_LPTSTR:
11200         case MONO_NATIVE_BSTR:
11201         case MONO_NATIVE_ANSIBSTR:
11202         case MONO_NATIVE_TBSTR:
11203         case MONO_NATIVE_LPARRAY:
11204         case MONO_NATIVE_SAFEARRAY:
11205         case MONO_NATIVE_IUNKNOWN:
11206         case MONO_NATIVE_IDISPATCH:
11207         case MONO_NATIVE_INTERFACE:
11208         case MONO_NATIVE_ASANY:
11209         case MONO_NATIVE_FUNC:
11210         case MONO_NATIVE_LPSTRUCT:
11211                 *align = MONO_ABI_ALIGNOF (gpointer);
11212                 return sizeof (gpointer);
11213         case MONO_NATIVE_STRUCT: 
11214                 klass = mono_class_from_mono_type (type);
11215                 if (klass == mono_defaults.object_class &&
11216                         (mspec && mspec->native == MONO_NATIVE_STRUCT)) {
11217                 *align = 16;
11218                 return 16;
11219                 }
11220                 return mono_class_native_size (klass, align);
11221         case MONO_NATIVE_BYVALTSTR: {
11222                 int esize = unicode ? 2: 1;
11223                 g_assert (mspec);
11224                 *align = esize;
11225                 return mspec->data.array_data.num_elem * esize;
11226         }
11227         case MONO_NATIVE_BYVALARRAY: {
11228                 // FIXME: Have to consider ArraySubType
11229                 int esize;
11230                 klass = mono_class_from_mono_type (type);
11231                 if (klass->element_class == mono_defaults.char_class) {
11232                         esize = unicode ? 2 : 1;
11233                         *align = esize;
11234                 } else {
11235                         esize = mono_class_native_size (klass->element_class, align);
11236                 }
11237                 g_assert (mspec);
11238                 return mspec->data.array_data.num_elem * esize;
11239         }
11240         case MONO_NATIVE_CUSTOM:
11241                 *align = sizeof (gpointer);
11242                 return sizeof (gpointer);
11243                 break;
11244         case MONO_NATIVE_CURRENCY:
11245         case MONO_NATIVE_VBBYREFSTR:
11246         default:
11247                 g_error ("native type %02x not implemented", native_type); 
11248                 break;
11249         }
11250         g_assert_not_reached ();
11251         return 0;
11252 }
11253
11254 /* This is a JIT icall, it sets the pending exception and return NULL on error */
11255 gpointer
11256 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
11257 {
11258         MonoError error;
11259         MonoType *t;
11260         MonoClass *klass;
11261
11262         if (o == NULL)
11263                 return NULL;
11264
11265         t = &o->vtable->klass->byval_arg;
11266         switch (t->type) {
11267         case MONO_TYPE_I4:
11268         case MONO_TYPE_U4:
11269         case MONO_TYPE_PTR:
11270         case MONO_TYPE_I1:
11271         case MONO_TYPE_U1:
11272         case MONO_TYPE_BOOLEAN:
11273         case MONO_TYPE_I2:
11274         case MONO_TYPE_U2:
11275         case MONO_TYPE_CHAR:
11276         case MONO_TYPE_I8:
11277         case MONO_TYPE_U8:
11278         case MONO_TYPE_R4:
11279         case MONO_TYPE_R8:
11280                 return mono_object_unbox (o);
11281                 break;
11282         case MONO_TYPE_STRING:
11283                 switch (string_encoding) {
11284                 case MONO_NATIVE_LPWSTR:
11285                         return mono_marshal_string_to_utf16_copy ((MonoString*)o);
11286                         break;
11287                 case MONO_NATIVE_LPSTR:
11288                         return mono_string_to_lpstr ((MonoString*)o);
11289                         break;
11290                 default:
11291                         g_warning ("marshaling conversion %d not implemented", string_encoding);
11292                         g_assert_not_reached ();
11293                 }
11294                 break;
11295         case MONO_TYPE_CLASS:
11296         case MONO_TYPE_VALUETYPE: {
11297                 MonoMethod *method;
11298                 gpointer pa [3];
11299                 gpointer res;
11300                 MonoBoolean delete_old = FALSE;
11301
11302                 klass = t->data.klass;
11303
11304                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
11305                         break;
11306
11307                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
11308                         klass->blittable || klass->enumtype))
11309                         return mono_object_unbox (o);
11310
11311                 res = mono_marshal_alloc (mono_class_native_size (klass, NULL), &error);
11312                 if (!mono_error_ok (&error)) {
11313                         mono_error_set_pending_exception (&error);
11314                         return NULL;
11315                 }
11316
11317                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11318                         method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
11319
11320                         pa [0] = o;
11321                         pa [1] = &res;
11322                         pa [2] = &delete_old;
11323
11324                         mono_runtime_invoke_checked (method, NULL, pa, &error);
11325                         if (!mono_error_ok (&error)) {
11326                                 mono_error_set_pending_exception (&error);
11327                                 return NULL;
11328                         }
11329                 }
11330
11331                 return res;
11332         }
11333         default:
11334                 break;
11335         }
11336         mono_set_pending_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
11337         return NULL;
11338 }
11339
11340 /* This is a JIT icall, it sets the pending exception */
11341 void
11342 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
11343 {
11344         MonoError error;
11345         MonoType *t;
11346         MonoClass *klass;
11347
11348         if (o == NULL)
11349                 return;
11350
11351         t = &o->vtable->klass->byval_arg;
11352         switch (t->type) {
11353         case MONO_TYPE_STRING:
11354                 switch (string_encoding) {
11355                 case MONO_NATIVE_LPWSTR:
11356                 case MONO_NATIVE_LPSTR:
11357                         mono_marshal_free (ptr);
11358                         break;
11359                 default:
11360                         g_warning ("marshaling conversion %d not implemented", string_encoding);
11361                         g_assert_not_reached ();
11362                 }
11363                 break;
11364         case MONO_TYPE_CLASS:
11365         case MONO_TYPE_VALUETYPE: {
11366                 klass = t->data.klass;
11367
11368                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
11369                                                                  klass->blittable || klass->enumtype))
11370                         break;
11371
11372                 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
11373                         MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
11374                         gpointer pa [2];
11375
11376                         pa [0] = &ptr;
11377                         pa [1] = o;
11378
11379                         mono_runtime_invoke_checked (method, NULL, pa, &error);
11380                         if (!mono_error_ok (&error)) {
11381                                 mono_error_set_pending_exception (&error);
11382                                 return;
11383                         }
11384                 }
11385
11386                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11387                         mono_struct_delete_old (klass, (char *)ptr);
11388                 }
11389
11390                 mono_marshal_free (ptr);
11391                 break;
11392         }
11393         default:
11394                 break;
11395         }
11396 }
11397
11398 MonoMethod *
11399 mono_marshal_get_generic_array_helper (MonoClass *klass, MonoClass *iface, gchar *name, MonoMethod *method)
11400 {
11401         MonoMethodSignature *sig, *csig;
11402         MonoMethodBuilder *mb;
11403         MonoMethod *res;
11404         WrapperInfo *info;
11405         int i;
11406
11407         mb = mono_mb_new_no_dup_name (klass, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
11408         mb->method->slot = -1;
11409
11410         mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
11411                 METHOD_ATTRIBUTE_NEW_SLOT | METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
11412
11413         sig = mono_method_signature (method);
11414         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
11415         csig->generic_param_count = 0;
11416
11417 #ifndef DISABLE_JIT
11418         mono_mb_emit_ldarg (mb, 0);
11419         for (i = 0; i < csig->param_count; i++)
11420                 mono_mb_emit_ldarg (mb, i + 1);
11421         mono_mb_emit_managed_call (mb, method, NULL);
11422         mono_mb_emit_byte (mb, CEE_RET);
11423
11424         /* We can corlib internal methods */
11425         mb->skip_visibility = TRUE;
11426 #endif
11427         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER);
11428         info->d.generic_array_helper.method = method;
11429         res = mono_mb_create (mb, csig, csig->param_count + 16, info);
11430
11431         mono_mb_free (mb);
11432
11433         return res;
11434 }
11435
11436 /*
11437  * The mono_win32_compat_* functions are implementations of inline
11438  * Windows kernel32 APIs, which are DllImport-able under MS.NET,
11439  * although not exported by kernel32.
11440  *
11441  * We map the appropiate kernel32 entries to these functions using
11442  * dllmaps declared in the global etc/mono/config.
11443  */
11444
11445 void
11446 mono_win32_compat_CopyMemory (gpointer dest, gconstpointer source, gsize length)
11447 {
11448         if (!dest || !source)
11449                 return;
11450
11451         memcpy (dest, source, length);
11452 }
11453
11454 void
11455 mono_win32_compat_FillMemory (gpointer dest, gsize length, guchar fill)
11456 {
11457         memset (dest, fill, length);
11458 }
11459
11460 void
11461 mono_win32_compat_MoveMemory (gpointer dest, gconstpointer source, gsize length)
11462 {
11463         if (!dest || !source)
11464                 return;
11465
11466         memmove (dest, source, length);
11467 }
11468
11469 void
11470 mono_win32_compat_ZeroMemory (gpointer dest, gsize length)
11471 {
11472         memset (dest, 0, length);
11473 }
11474
11475 void
11476 mono_marshal_find_nonzero_bit_offset (guint8 *buf, int len, int *byte_offset, guint8 *bitmask)
11477 {
11478         int i;
11479         guint8 byte;
11480
11481         for (i = 0; i < len; ++i)
11482                 if (buf [i])
11483                         break;
11484
11485         g_assert (i < len);
11486
11487         byte = buf [i];
11488         while (byte && !(byte & 1))
11489                 byte >>= 1;
11490         g_assert (byte == 1);
11491
11492         *byte_offset = i;
11493         *bitmask = buf [i];
11494 }
11495
11496 MonoMethod *
11497 mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
11498 {
11499         MonoMethodBuilder *mb;
11500         MonoMethodSignature *sig, *csig;
11501         MonoExceptionClause *clause;
11502         MonoImage *image;
11503         MonoClass *klass;
11504         GHashTable *cache;
11505         MonoMethod *res;
11506         int i, param_count, sig_size, pos_leave;
11507         int coop_gc_var, coop_gc_dummy_local;
11508
11509         g_assert (method);
11510
11511         klass = method->klass;
11512         image = method->klass->image;
11513
11514         cache = get_cache (&mono_method_get_wrapper_cache (method)->thunk_invoke_cache, mono_aligned_addr_hash, NULL);
11515
11516         if ((res = mono_marshal_find_in_cache (cache, method)))
11517                 return res;
11518
11519         sig = mono_method_signature (method);
11520         mb = mono_mb_new (klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
11521
11522         /* add "this" and exception param */
11523         param_count = sig->param_count + sig->hasthis + 1;
11524
11525         /* dup & extend signature */
11526         csig = mono_metadata_signature_alloc (image, param_count);
11527         sig_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *);
11528         memcpy (csig, sig, sig_size);
11529         csig->param_count = param_count;
11530         csig->hasthis = 0;
11531         csig->pinvoke = 1;
11532         csig->call_convention = MONO_CALL_DEFAULT;
11533
11534         if (sig->hasthis) {
11535                 /* add "this" */
11536                 csig->params [0] = &klass->byval_arg;
11537                 /* move params up by one */
11538                 for (i = 0; i < sig->param_count; i++)
11539                         csig->params [i + 1] = sig->params [i];
11540         }
11541
11542         /* setup exception param as byref+[out] */
11543         csig->params [param_count - 1] = mono_metadata_type_dup (image,
11544                  &mono_defaults.exception_class->byval_arg);
11545         csig->params [param_count - 1]->byref = 1;
11546         csig->params [param_count - 1]->attrs = PARAM_ATTRIBUTE_OUT;
11547
11548         /* convert struct return to object */
11549         if (MONO_TYPE_ISSTRUCT (sig->ret))
11550                 csig->ret = &mono_defaults.object_class->byval_arg;
11551
11552 #ifndef DISABLE_JIT
11553         /* local 0 (temp for exception object) */
11554         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
11555
11556         /* local 1 (temp for result) */
11557         if (!MONO_TYPE_IS_VOID (sig->ret))
11558                 mono_mb_add_local (mb, sig->ret);
11559
11560         if (mono_threads_is_coop_enabled ()) {
11561                 /* local 4, the local to be used when calling the reset_blocking funcs */
11562                 /* tons of code hardcode 3 to be the return var */
11563                 coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
11564                 /* local 5, the local used to get a stack address for suspend funcs */
11565                 coop_gc_dummy_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
11566         }
11567
11568         /* clear exception arg */
11569         mono_mb_emit_ldarg (mb, param_count - 1);
11570         mono_mb_emit_byte (mb, CEE_LDNULL);
11571         mono_mb_emit_byte (mb, CEE_STIND_REF);
11572
11573         if (mono_threads_is_coop_enabled ()) {
11574                 /* FIXME this is technically wrong as the callback itself must be executed in gc unsafe context. */
11575                 mono_mb_emit_ldloc_addr (mb, coop_gc_dummy_local);
11576                 mono_mb_emit_icall (mb, mono_threads_reset_blocking_start);
11577                 mono_mb_emit_stloc (mb, coop_gc_var);
11578         }
11579
11580         /* try */
11581         clause = (MonoExceptionClause *)mono_image_alloc0 (image, sizeof (MonoExceptionClause));
11582         clause->try_offset = mono_mb_get_label (mb);
11583
11584         /* push method's args */
11585         for (i = 0; i < param_count - 1; i++) {
11586                 MonoType *type;
11587                 MonoClass *klass;
11588
11589                 mono_mb_emit_ldarg (mb, i);
11590
11591                 /* get the byval type of the param */
11592                 klass = mono_class_from_mono_type (csig->params [i]);
11593                 type = &klass->byval_arg;
11594
11595                 /* unbox struct args */
11596                 if (MONO_TYPE_ISSTRUCT (type)) {
11597                         mono_mb_emit_op (mb, CEE_UNBOX, klass);
11598
11599                         /* byref args & and the "this" arg must remain a ptr.
11600                            Otherwise make a copy of the value type */
11601                         if (!(csig->params [i]->byref || (i == 0 && sig->hasthis)))
11602                                 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
11603
11604                         csig->params [i] = &mono_defaults.object_class->byval_arg;
11605                 }
11606         }
11607
11608         /* call */
11609         if (method->flags & METHOD_ATTRIBUTE_VIRTUAL)
11610                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
11611         else
11612                 mono_mb_emit_op (mb, CEE_CALL, method);
11613
11614         /* save result at local 1 */
11615         if (!MONO_TYPE_IS_VOID (sig->ret))
11616                 mono_mb_emit_stloc (mb, 1);
11617
11618         pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
11619
11620         /* catch */
11621         clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
11622         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
11623         clause->data.catch_class = mono_defaults.object_class;
11624
11625         clause->handler_offset = mono_mb_get_label (mb);
11626
11627         /* store exception at local 0 */
11628         mono_mb_emit_stloc (mb, 0);
11629         mono_mb_emit_ldarg (mb, param_count - 1);
11630         mono_mb_emit_ldloc (mb, 0);
11631         mono_mb_emit_byte (mb, CEE_STIND_REF);
11632         mono_mb_emit_branch (mb, CEE_LEAVE);
11633
11634         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
11635
11636         mono_mb_set_clauses (mb, 1, clause);
11637
11638         mono_mb_patch_branch (mb, pos_leave);
11639         /* end-try */
11640
11641         if (!MONO_TYPE_IS_VOID (sig->ret)) {
11642                 mono_mb_emit_ldloc (mb, 1);
11643
11644                 /* box the return value */
11645                 if (MONO_TYPE_ISSTRUCT (sig->ret))
11646                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
11647         }
11648
11649         if (mono_threads_is_coop_enabled ()) {
11650                 /* XXX merge reset_blocking_end with detach */
11651                 mono_mb_emit_ldloc (mb, coop_gc_var);
11652                 mono_mb_emit_ldloc_addr (mb, coop_gc_dummy_local);
11653                 mono_mb_emit_icall (mb, mono_threads_reset_blocking_end);
11654         }
11655
11656         mono_mb_emit_byte (mb, CEE_RET);
11657 #endif
11658
11659         res = mono_mb_create_and_cache (cache, method, mb, csig, param_count + 16);
11660         mono_mb_free (mb);
11661
11662         return res;
11663 }
11664
11665 /*
11666  * mono_marshal_free_dynamic_wrappers:
11667  *
11668  *   Free wrappers of the dynamic method METHOD.
11669  */
11670 void
11671 mono_marshal_free_dynamic_wrappers (MonoMethod *method)
11672 {
11673         MonoImage *image = method->klass->image;
11674
11675         g_assert (method_is_dynamic (method));
11676
11677         /* This could be called during shutdown */
11678         if (marshal_mutex_initialized)
11679                 mono_marshal_lock ();
11680         /* 
11681          * FIXME: We currently leak the wrappers. Freeing them would be tricky as
11682          * they could be shared with other methods ?
11683          */
11684         if (image->wrapper_caches.runtime_invoke_direct_cache)
11685                 g_hash_table_remove (image->wrapper_caches.runtime_invoke_direct_cache, method);
11686         if (image->wrapper_caches.delegate_abstract_invoke_cache)
11687                 g_hash_table_foreach_remove (image->wrapper_caches.delegate_abstract_invoke_cache, signature_pointer_pair_matches_pointer, method);
11688         // FIXME: Need to clear the caches in other images as well
11689         if (image->delegate_bound_static_invoke_cache)
11690                 g_hash_table_remove (image->delegate_bound_static_invoke_cache, mono_method_signature (method));
11691
11692         if (marshal_mutex_initialized)
11693                 mono_marshal_unlock ();
11694 }