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