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