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