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