c26da5ae151b9db25e8b5aea3a371c0fd99e7eb0
[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_os_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_os_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                         mono_mb_emit_ldarg (mb, argnum);
6127
6128                         /* Create the managed array */
6129                         mono_mb_emit_ldarg (mb, param_num);
6130                         if (m->sig->params [param_num]->byref)
6131                                 // FIXME: Support other types
6132                                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
6133                         mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6134                         mono_mb_emit_op (mb, CEE_NEWARR, klass->element_class);
6135                         /* Store into argument */
6136                         mono_mb_emit_byte (mb, CEE_STIND_I);
6137                 }
6138
6139                 if (need_convert || need_free) {
6140                         /* FIXME: Optimize blittable case */
6141                         MonoClass *eklass;
6142                         guint32 label1, label2, label3;
6143                         int index_var, src_ptr, loc, esize;
6144
6145                         eklass = klass->element_class;
6146                         if ((eklass == mono_defaults.stringbuilder_class) || (eklass == mono_defaults.string_class))
6147                                 esize = sizeof (gpointer);
6148                         else if (eklass == mono_defaults.char_class)
6149                                 esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6150                         else
6151                                 esize = mono_class_native_size (eklass, NULL);
6152                         src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6153                         loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6154
6155                         /* Check null */
6156                         mono_mb_emit_ldarg (mb, argnum);
6157                         if (t->byref)
6158                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6159                         label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6160
6161                         mono_mb_emit_ldloc (mb, conv_arg);
6162                         mono_mb_emit_stloc (mb, src_ptr);
6163
6164                         /* Emit marshalling loop */
6165                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
6166                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6167                         mono_mb_emit_stloc (mb, index_var);
6168                         label2 = mono_mb_get_label (mb);
6169                         mono_mb_emit_ldloc (mb, index_var);
6170                         mono_mb_emit_ldarg (mb, argnum);
6171                         if (t->byref)
6172                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6173                         mono_mb_emit_byte (mb, CEE_LDLEN);
6174                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
6175
6176                         /* Emit marshalling code */
6177
6178                         if (eklass == mono_defaults.stringbuilder_class) {
6179                                 gboolean need_free2;
6180                                 MonoMarshalConv conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free2);
6181
6182                                 g_assert (conv != -1);
6183
6184                                 /* dest */
6185                                 mono_mb_emit_ldarg (mb, argnum);
6186                                 if (t->byref)
6187                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6188                                 mono_mb_emit_ldloc (mb, index_var);
6189                                 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6190
6191                                 /* src */
6192                                 mono_mb_emit_ldloc (mb, src_ptr);
6193                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6194
6195                                 mono_mb_emit_icall (mb, conv_to_icall (conv));
6196
6197                                 if (need_free) {
6198                                         /* src */
6199                                         mono_mb_emit_ldloc (mb, src_ptr);
6200                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6201
6202                                         mono_mb_emit_icall (mb, mono_marshal_free);
6203                                 }
6204                         }
6205                         else if (eklass == mono_defaults.string_class) {
6206                                 if (need_free) {
6207                                         /* src */
6208                                         mono_mb_emit_ldloc (mb, src_ptr);
6209                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6210
6211                                         mono_mb_emit_icall (mb, mono_marshal_free);
6212                                 }
6213                         }
6214                         else {
6215                                 if (need_convert) {
6216                                         /* set the src_ptr */
6217                                         mono_mb_emit_ldloc (mb, src_ptr);
6218                                         mono_mb_emit_stloc (mb, 0);
6219
6220                                         /* set dst_ptr */
6221                                         mono_mb_emit_ldarg (mb, argnum);
6222                                         if (t->byref)
6223                                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6224                                         mono_mb_emit_ldloc (mb, index_var);
6225                                         mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
6226                                         mono_mb_emit_stloc (mb, 1);
6227
6228                                         /* emit valuetype conversion code */
6229                                         emit_struct_conv_full (mb, eklass, TRUE, eklass == mono_defaults.char_class ? encoding : -1);
6230                                 }
6231
6232                                 if (need_free) {
6233                                         mono_mb_emit_ldloc (mb, src_ptr);
6234                                         mono_mb_emit_stloc (mb, loc);
6235                                         mono_mb_emit_ldloc (mb, loc);
6236
6237                                         emit_struct_free (mb, eklass, loc);
6238                                 }
6239                         }
6240
6241                         mono_mb_emit_add_to_local (mb, index_var, 1);
6242                         mono_mb_emit_add_to_local (mb, src_ptr, esize);
6243
6244                         mono_mb_emit_branch_label (mb, CEE_BR, label2);
6245
6246                         mono_mb_patch_branch (mb, label1);
6247                         mono_mb_patch_branch (mb, label3);
6248                 }
6249                 
6250                 if (klass->element_class->blittable) {
6251                         /* free memory allocated (if any) by MONO_MARSHAL_CONV_ARRAY_LPARRAY */
6252
6253                         mono_mb_emit_ldarg (mb, argnum);
6254                         if (t->byref)
6255                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
6256                         mono_mb_emit_ldloc (mb, conv_arg);
6257                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_FREE_LPARRAY));
6258                 }
6259
6260                 break;
6261
6262         case MARSHAL_ACTION_PUSH:
6263                 if (t->byref)
6264                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6265                 else
6266                         mono_mb_emit_ldloc (mb, conv_arg);
6267                 break;
6268
6269         case MARSHAL_ACTION_CONV_RESULT:
6270                 /* fixme: we need conversions here */
6271                 mono_mb_emit_stloc (mb, 3);
6272                 break;
6273
6274         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6275                 MonoClass *eklass;
6276                 guint32 label1, label2, label3;
6277                 int index_var, src_ptr, esize, param_num, num_elem;
6278                 MonoMarshalConv conv;
6279                 gboolean is_string = FALSE;
6280                 
6281                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6282                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6283
6284                 if (t->byref) {
6285                         char *msg = g_strdup ("Byref array marshalling to managed code is not implemented.");
6286                         mono_mb_emit_exception_marshal_directive (mb, msg);
6287                         return conv_arg;
6288                 }
6289                 if (!spec) {
6290                         char *msg = g_strdup ("[MarshalAs] attribute required to marshal arrays to managed code.");
6291                         mono_mb_emit_exception_marshal_directive (mb, msg);
6292                         return conv_arg;
6293                 }                       
6294                 if (spec->native != MONO_NATIVE_LPARRAY) {
6295                         char *msg = g_strdup ("Non LPArray marshalling of arrays to managed code is not implemented.");
6296                         mono_mb_emit_exception_marshal_directive (mb, msg);
6297                         return conv_arg;                        
6298                 }
6299
6300                 /* FIXME: t is from the method which is wrapped, not the delegate type */
6301                 /* g_assert (t->attrs & PARAM_ATTRIBUTE_IN); */
6302
6303                 param_num = spec->data.array_data.param_num;
6304                 num_elem = spec->data.array_data.num_elem;
6305                 if (spec->data.array_data.elem_mult == 0)
6306                         /* param_num is not specified */
6307                         param_num = -1;
6308
6309                 if (param_num == -1) {
6310                         if (num_elem <= 0) {
6311                                 char *msg = g_strdup ("Either SizeConst or SizeParamIndex should be specified when marshalling arrays to managed code.");
6312                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6313                                 return conv_arg;
6314                         }
6315                 }
6316
6317                 /* FIXME: Optimize blittable case */
6318
6319                 eklass = klass->element_class;
6320                 if (eklass == mono_defaults.string_class) {
6321                         is_string = TRUE;
6322                         conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
6323                 }
6324                 else if (eklass == mono_defaults.stringbuilder_class) {
6325                         is_string = TRUE;
6326                         conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
6327                 }
6328                 else
6329                         conv = -1;
6330
6331                 mono_marshal_load_type_info (eklass);
6332
6333                 if (is_string)
6334                         esize = sizeof (gpointer);
6335                 else
6336                         esize = mono_class_native_size (eklass, NULL);
6337                 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6338
6339                 mono_mb_emit_byte (mb, CEE_LDNULL);
6340                 mono_mb_emit_stloc (mb, conv_arg);
6341
6342                 /* Check param index */
6343                 if (param_num != -1) {
6344                         if (param_num >= m->sig->param_count) {
6345                                 char *msg = g_strdup ("Array size control parameter index is out of range.");
6346                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6347                                 return conv_arg;
6348                         }
6349                         switch (m->sig->params [param_num]->type) {
6350                         case MONO_TYPE_I1:
6351                         case MONO_TYPE_U1:
6352                         case MONO_TYPE_I2:
6353                         case MONO_TYPE_U2:
6354                         case MONO_TYPE_I4:
6355                         case MONO_TYPE_U4:
6356                         case MONO_TYPE_I:
6357                         case MONO_TYPE_U:
6358                         case MONO_TYPE_I8:
6359                         case MONO_TYPE_U8:
6360                                 break;
6361                         default: {
6362                                 char *msg = g_strdup ("Array size control parameter must be an integral type.");
6363                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6364                                 return conv_arg;
6365                         }
6366                         }
6367                 }
6368
6369                 /* Check null */
6370                 mono_mb_emit_ldarg (mb, argnum);
6371                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6372
6373                 mono_mb_emit_ldarg (mb, argnum);
6374                 mono_mb_emit_stloc (mb, src_ptr);
6375
6376                 /* Create managed array */
6377                 /* 
6378                  * The LPArray marshalling spec says that sometimes param_num starts 
6379                  * from 1, sometimes it starts from 0. But MS seems to allways start
6380                  * from 0.
6381                  */
6382
6383                 if (param_num == -1) {
6384                         mono_mb_emit_icon (mb, num_elem);
6385                 } else {
6386                         mono_mb_emit_ldarg (mb, param_num);
6387                         if (num_elem > 0) {
6388                                 mono_mb_emit_icon (mb, num_elem);
6389                                 mono_mb_emit_byte (mb, CEE_ADD);
6390                         }
6391                         mono_mb_emit_byte (mb, CEE_CONV_OVF_I);
6392                 }
6393
6394                 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
6395                 mono_mb_emit_stloc (mb, conv_arg);
6396
6397                 if (eklass->blittable) {
6398                         mono_mb_emit_ldloc (mb, conv_arg);
6399                         mono_mb_emit_byte (mb, CEE_CONV_I);
6400                         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6401                         mono_mb_emit_byte (mb, CEE_ADD);
6402                         mono_mb_emit_ldarg (mb, argnum);
6403                         mono_mb_emit_ldloc (mb, conv_arg);
6404                         mono_mb_emit_byte (mb, CEE_LDLEN);
6405                         mono_mb_emit_icon (mb, esize);
6406                         mono_mb_emit_byte (mb, CEE_MUL);
6407                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6408                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
6409                         break;
6410                 }
6411
6412                 /* Emit marshalling loop */
6413                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6414                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6415                 mono_mb_emit_stloc (mb, index_var);
6416                 label2 = mono_mb_get_label (mb);
6417                 mono_mb_emit_ldloc (mb, index_var);
6418                 mono_mb_emit_ldloc (mb, conv_arg);
6419                 mono_mb_emit_byte (mb, CEE_LDLEN);
6420                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6421
6422                 /* Emit marshalling code */
6423                 if (is_string) {
6424                         g_assert (conv != -1);
6425
6426                         mono_mb_emit_ldloc (mb, conv_arg);
6427                         mono_mb_emit_ldloc (mb, index_var);
6428
6429                         mono_mb_emit_ldloc (mb, src_ptr);
6430                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6431
6432                         mono_mb_emit_icall (mb, conv_to_icall (conv));
6433                         mono_mb_emit_byte (mb, CEE_STELEM_REF);
6434                 }
6435                 else {
6436                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6437                         mono_mb_emit_exception_marshal_directive (mb, msg);
6438                         return conv_arg;
6439                 }
6440
6441                 mono_mb_emit_add_to_local (mb, index_var, 1);
6442                 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6443
6444                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6445
6446                 mono_mb_patch_branch (mb, label1);
6447                 mono_mb_patch_branch (mb, label3);
6448                 
6449                 break;
6450         }
6451         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6452                 MonoClass *eklass;
6453                 guint32 label1, label2, label3;
6454                 int index_var, dest_ptr, esize, param_num, num_elem;
6455                 MonoMarshalConv conv;
6456                 gboolean is_string = FALSE;
6457
6458                 if (!spec)
6459                         /* Already handled in CONV_IN */
6460                         break;
6461                 
6462                 /* These are already checked in CONV_IN */
6463                 g_assert (!t->byref);
6464                 g_assert (spec->native == MONO_NATIVE_LPARRAY);
6465                 g_assert (t->attrs & PARAM_ATTRIBUTE_OUT);
6466
6467                 param_num = spec->data.array_data.param_num;
6468                 num_elem = spec->data.array_data.num_elem;
6469
6470                 if (spec->data.array_data.elem_mult == 0)
6471                         /* param_num is not specified */
6472                         param_num = -1;
6473
6474                 if (param_num == -1) {
6475                         if (num_elem <= 0) {
6476                                 g_assert_not_reached ();
6477                         }
6478                 }
6479
6480                 /* FIXME: Optimize blittable case */
6481
6482                 eklass = klass->element_class;
6483                 if (eklass == mono_defaults.string_class) {
6484                         is_string = TRUE;
6485                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6486                 }
6487                 else if (eklass == mono_defaults.stringbuilder_class) {
6488                         is_string = TRUE;
6489                         conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6490                 }
6491                 else
6492                         conv = -1;
6493
6494                 mono_marshal_load_type_info (eklass);
6495
6496                 if (is_string)
6497                         esize = sizeof (gpointer);
6498                 else
6499                         esize = mono_class_native_size (eklass, NULL);
6500
6501                 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6502
6503                 /* Check null */
6504                 mono_mb_emit_ldloc (mb, conv_arg);
6505                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6506
6507                 mono_mb_emit_ldarg (mb, argnum);
6508                 mono_mb_emit_stloc (mb, dest_ptr);
6509
6510                 if (eklass->blittable) {
6511                         /* dest */
6512                         mono_mb_emit_ldarg (mb, argnum);
6513                         /* src */
6514                         mono_mb_emit_ldloc (mb, conv_arg);
6515                         mono_mb_emit_byte (mb, CEE_CONV_I);
6516                         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
6517                         mono_mb_emit_byte (mb, CEE_ADD);
6518                         /* length */
6519                         mono_mb_emit_ldloc (mb, conv_arg);
6520                         mono_mb_emit_byte (mb, CEE_LDLEN);
6521                         mono_mb_emit_icon (mb, esize);
6522                         mono_mb_emit_byte (mb, CEE_MUL);
6523                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6524                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
6525                         break;
6526                 }
6527
6528                 /* Emit marshalling loop */
6529                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6530                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6531                 mono_mb_emit_stloc (mb, index_var);
6532                 label2 = mono_mb_get_label (mb);
6533                 mono_mb_emit_ldloc (mb, index_var);
6534                 mono_mb_emit_ldloc (mb, conv_arg);
6535                 mono_mb_emit_byte (mb, CEE_LDLEN);
6536                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6537
6538                 /* Emit marshalling code */
6539                 if (is_string) {
6540                         g_assert (conv != -1);
6541
6542                         /* dest */
6543                         mono_mb_emit_ldloc (mb, dest_ptr);
6544
6545                         /* src */
6546                         mono_mb_emit_ldloc (mb, conv_arg);
6547                         mono_mb_emit_ldloc (mb, index_var);
6548
6549                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6550
6551                         mono_mb_emit_icall (mb, conv_to_icall (conv));
6552                         mono_mb_emit_byte (mb, CEE_STIND_I);
6553                 }
6554                 else {
6555                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6556                         mono_mb_emit_exception_marshal_directive (mb, msg);
6557                         return conv_arg;
6558                 }
6559
6560                 mono_mb_emit_add_to_local (mb, index_var, 1);
6561                 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6562
6563                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6564
6565                 mono_mb_patch_branch (mb, label1);
6566                 mono_mb_patch_branch (mb, label3);
6567
6568                 break;
6569         }
6570         case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6571                 MonoClass *eklass;
6572                 guint32 label1, label2, label3;
6573                 int index_var, src, dest, esize;
6574                 MonoMarshalConv conv = -1;
6575                 gboolean is_string = FALSE;
6576                 
6577                 g_assert (!t->byref);
6578
6579                 eklass = klass->element_class;
6580
6581                 mono_marshal_load_type_info (eklass);
6582
6583                 if (eklass == mono_defaults.string_class) {
6584                         is_string = TRUE;
6585                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6586                 }
6587                 else {
6588                         g_assert_not_reached ();
6589                 }
6590
6591                 if (is_string)
6592                         esize = sizeof (gpointer);
6593                 else if (eklass == mono_defaults.char_class)
6594                         esize = mono_pinvoke_is_unicode (m->piinfo) ? 2 : 1;
6595                 else
6596                         esize = mono_class_native_size (eklass, NULL);
6597
6598                 src = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6599                 dest = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6600                         
6601                 mono_mb_emit_stloc (mb, src);
6602                 mono_mb_emit_ldloc (mb, src);
6603                 mono_mb_emit_stloc (mb, 3);
6604
6605                 /* Check for null */
6606                 mono_mb_emit_ldloc (mb, src);
6607                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6608
6609                 /* Allocate native array */
6610                 mono_mb_emit_icon (mb, esize);
6611                 mono_mb_emit_ldloc (mb, src);
6612                 mono_mb_emit_byte (mb, CEE_LDLEN);
6613
6614                 if (eklass == mono_defaults.string_class) {
6615                         /* Make the array bigger for the terminating null */
6616                         mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6617                         mono_mb_emit_byte (mb, CEE_ADD);
6618                 }
6619                 mono_mb_emit_byte (mb, CEE_MUL);
6620                 mono_mb_emit_icall (mb, mono_marshal_alloc);
6621                 mono_mb_emit_stloc (mb, dest);
6622                 mono_mb_emit_ldloc (mb, dest);
6623                 mono_mb_emit_stloc (mb, 3);
6624
6625                 /* Emit marshalling loop */
6626                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6627                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6628                 mono_mb_emit_stloc (mb, index_var);
6629                 label2 = mono_mb_get_label (mb);
6630                 mono_mb_emit_ldloc (mb, index_var);
6631                 mono_mb_emit_ldloc (mb, src);
6632                 mono_mb_emit_byte (mb, CEE_LDLEN);
6633                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6634
6635                 /* Emit marshalling code */
6636                 if (is_string) {
6637                         g_assert (conv != -1);
6638
6639                         /* dest */
6640                         mono_mb_emit_ldloc (mb, dest);
6641
6642                         /* src */
6643                         mono_mb_emit_ldloc (mb, src);
6644                         mono_mb_emit_ldloc (mb, index_var);
6645
6646                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6647
6648                         mono_mb_emit_icall (mb, conv_to_icall (conv));
6649                         mono_mb_emit_byte (mb, CEE_STIND_I);
6650                 }
6651                 else {
6652                         char *msg = g_strdup ("Marshalling of non-string arrays to managed code is not implemented.");
6653                         mono_mb_emit_exception_marshal_directive (mb, msg);
6654                         return conv_arg;
6655                 }
6656
6657                 mono_mb_emit_add_to_local (mb, index_var, 1);
6658                 mono_mb_emit_add_to_local (mb, dest, esize);
6659
6660                 mono_mb_emit_branch_label (mb, CEE_BR, label2);
6661
6662                 mono_mb_patch_branch (mb, label3);
6663                 mono_mb_patch_branch (mb, label1);
6664                 break;
6665         }
6666         default:
6667                 g_assert_not_reached ();
6668         }
6669 #endif
6670         return conv_arg;
6671 }
6672
6673 static MonoType*
6674 marshal_boolean_conv_in_get_local_type (MonoMarshalSpec *spec, guint8 *ldc_op /*out*/)
6675 {
6676         if (spec == NULL) {
6677                 return &mono_defaults.int32_class->byval_arg;
6678         } else {
6679                 switch (spec->native) {
6680                 case MONO_NATIVE_I1:
6681                 case MONO_NATIVE_U1:
6682                         return &mono_defaults.byte_class->byval_arg;
6683                 case MONO_NATIVE_VARIANTBOOL:
6684                         if (ldc_op) *ldc_op = CEE_LDC_I4_M1;
6685                         return &mono_defaults.int16_class->byval_arg;
6686                 case MONO_NATIVE_BOOLEAN:
6687                         return &mono_defaults.int32_class->byval_arg;
6688                 default:
6689                         g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
6690                         return &mono_defaults.int32_class->byval_arg;
6691                 }
6692         }
6693 }
6694
6695 static MonoClass*
6696 marshal_boolean_managed_conv_in_get_conv_arg_class (MonoMarshalSpec *spec, guint8 *ldop/*out*/)
6697 {
6698         MonoClass* conv_arg_class = mono_defaults.int32_class;
6699         if (spec) {
6700                 switch (spec->native) {
6701                 case MONO_NATIVE_I1:
6702                 case MONO_NATIVE_U1:
6703                         conv_arg_class = mono_defaults.byte_class;
6704                         if (ldop) *ldop = CEE_LDIND_I1;
6705                         break;
6706                 case MONO_NATIVE_VARIANTBOOL:
6707                         conv_arg_class = mono_defaults.int16_class;
6708                         if (ldop) *ldop = CEE_LDIND_I2;
6709                         break;
6710                 case MONO_NATIVE_BOOLEAN:
6711                         break;
6712                 default:
6713                         g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
6714                 }
6715         }
6716         return conv_arg_class;
6717 }
6718
6719 static int
6720 emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
6721                       MonoMarshalSpec *spec, 
6722                       int conv_arg, MonoType **conv_arg_type, 
6723                       MarshalAction action)
6724 {
6725 #ifdef DISABLE_JIT
6726         switch (action) {
6727         case MARSHAL_ACTION_CONV_IN:
6728                 if (t->byref)
6729                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
6730                 else
6731                         *conv_arg_type = marshal_boolean_conv_in_get_local_type (spec, NULL);
6732                 break;
6733
6734         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6735                 MonoClass* conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, NULL);
6736                 if (t->byref)
6737                         *conv_arg_type = &conv_arg_class->this_arg;
6738                 else
6739                         *conv_arg_type = &conv_arg_class->byval_arg;
6740                 break;
6741         }
6742
6743         }
6744 #else
6745         MonoMethodBuilder *mb = m->mb;
6746
6747         switch (action) {
6748         case MARSHAL_ACTION_CONV_IN: {
6749                 MonoType *local_type;
6750                 int label_false;
6751                 guint8 ldc_op = CEE_LDC_I4_1;
6752
6753                 local_type = marshal_boolean_conv_in_get_local_type (spec, &ldc_op);
6754                 if (t->byref)
6755                         *conv_arg_type = &mono_defaults.int_class->byval_arg;
6756                 else
6757                         *conv_arg_type = local_type;
6758                 conv_arg = mono_mb_add_local (mb, local_type);
6759                 
6760                 mono_mb_emit_ldarg (mb, argnum);
6761                 if (t->byref)
6762                         mono_mb_emit_byte (mb, CEE_LDIND_I1);
6763                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
6764                 mono_mb_emit_byte (mb, ldc_op);
6765                 mono_mb_emit_stloc (mb, conv_arg);
6766                 mono_mb_patch_branch (mb, label_false);
6767
6768                 break;
6769         }
6770
6771         case MARSHAL_ACTION_CONV_OUT:
6772         {
6773                 int label_false, label_end;
6774                 if (!t->byref)
6775                         break;
6776
6777                 mono_mb_emit_ldarg (mb, argnum);
6778                 mono_mb_emit_ldloc (mb, conv_arg);
6779                 
6780                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
6781                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6782
6783                 label_end = mono_mb_emit_branch (mb, CEE_BR);
6784                 mono_mb_patch_branch (mb, label_false);
6785                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6786                 mono_mb_patch_branch (mb, label_end);
6787
6788                 mono_mb_emit_byte (mb, CEE_STIND_I1);
6789                 break;
6790         }
6791
6792         case MARSHAL_ACTION_PUSH:
6793                 if (t->byref)
6794                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6795                 else if (conv_arg)
6796                         mono_mb_emit_ldloc (mb, conv_arg);
6797                 else
6798                         mono_mb_emit_ldarg (mb, argnum);
6799                 break;
6800
6801         case MARSHAL_ACTION_CONV_RESULT:
6802                 /* maybe we need to make sure that it fits within 8 bits */
6803                 mono_mb_emit_stloc (mb, 3);
6804                 break;
6805
6806         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6807                 MonoClass* conv_arg_class = mono_defaults.int32_class;
6808                 guint8 ldop = CEE_LDIND_I4;
6809                 int label_null, label_false;
6810
6811                 conv_arg_class = marshal_boolean_managed_conv_in_get_conv_arg_class (spec, &ldop);
6812                 conv_arg = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
6813
6814                 if (t->byref)
6815                         *conv_arg_type = &conv_arg_class->this_arg;
6816                 else
6817                         *conv_arg_type = &conv_arg_class->byval_arg;
6818
6819
6820                 mono_mb_emit_ldarg (mb, argnum);
6821                 
6822                 /* Check null */
6823                 if (t->byref) {
6824                         label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
6825                         mono_mb_emit_ldarg (mb, argnum);
6826                         mono_mb_emit_byte (mb, ldop);
6827                 } else
6828                         label_null = 0;
6829
6830                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
6831                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6832                 mono_mb_emit_stloc (mb, conv_arg);
6833                 mono_mb_patch_branch (mb, label_false);
6834
6835                 if (t->byref) 
6836                         mono_mb_patch_branch (mb, label_null);
6837                 break;
6838         }
6839
6840         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6841                 guint8 stop = CEE_STIND_I4;
6842                 guint8 ldc_op = CEE_LDC_I4_1;
6843                 int label_null,label_false, label_end;;
6844
6845                 if (!t->byref)
6846                         break;
6847                 if (spec) {
6848                         switch (spec->native) {
6849                         case MONO_NATIVE_I1:
6850                         case MONO_NATIVE_U1:
6851                                 stop = CEE_STIND_I1;
6852                                 break;
6853                         case MONO_NATIVE_VARIANTBOOL:
6854                                 stop = CEE_STIND_I2;
6855                                 ldc_op = CEE_LDC_I4_M1;
6856                                 break;
6857                         default:
6858                                 break;
6859                         }
6860                 }
6861                 
6862                 /* Check null */
6863                 mono_mb_emit_ldarg (mb, argnum);
6864                 label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
6865
6866                 mono_mb_emit_ldarg (mb, argnum);
6867                 mono_mb_emit_ldloc (mb, conv_arg);
6868
6869                 label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
6870                 mono_mb_emit_byte (mb, ldc_op);
6871                 label_end = mono_mb_emit_branch (mb, CEE_BR);
6872
6873                 mono_mb_patch_branch (mb, label_false);
6874                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6875                 mono_mb_patch_branch (mb, label_end);
6876
6877                 mono_mb_emit_byte (mb, stop);
6878                 mono_mb_patch_branch (mb, label_null);
6879                 break;
6880         }
6881
6882         default:
6883                 g_assert_not_reached ();
6884         }
6885 #endif
6886         return conv_arg;
6887 }
6888
6889 static int
6890 emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t, 
6891                   MonoMarshalSpec *spec, int conv_arg, 
6892                   MonoType **conv_arg_type, MarshalAction action)
6893 {
6894 #ifndef DISABLE_JIT
6895         MonoMethodBuilder *mb = m->mb;
6896
6897         switch (action) {
6898         case MARSHAL_ACTION_CONV_IN:
6899                 /* MS seems to allow this in some cases, ie. bxc #158 */
6900                 /*
6901                 if (MONO_TYPE_ISSTRUCT (t->data.type) && !mono_class_from_mono_type (t->data.type)->blittable) {
6902                         char *msg = g_strdup_printf ("Can not marshal 'parameter #%d': Pointers can not reference marshaled structures. Use byref instead.", argnum + 1);
6903                         mono_mb_emit_exception_marshal_directive (m->mb, msg);
6904                 }
6905                 */
6906                 break;
6907
6908         case MARSHAL_ACTION_PUSH:
6909                 mono_mb_emit_ldarg (mb, argnum);
6910                 break;
6911
6912         case MARSHAL_ACTION_CONV_RESULT:
6913                 /* no conversions necessary */
6914                 mono_mb_emit_stloc (mb, 3);
6915                 break;
6916
6917         default:
6918                 break;
6919         }
6920 #endif
6921         return conv_arg;
6922 }
6923
6924 static int
6925 emit_marshal_char (EmitMarshalContext *m, int argnum, MonoType *t, 
6926                    MonoMarshalSpec *spec, int conv_arg, 
6927                    MonoType **conv_arg_type, MarshalAction action)
6928 {
6929 #ifndef DISABLE_JIT
6930         MonoMethodBuilder *mb = m->mb;
6931
6932         switch (action) {
6933         case MARSHAL_ACTION_PUSH:
6934                 /* fixme: dont know how to marshal that. We cant simply
6935                  * convert it to a one byte UTF8 character, because an
6936                  * unicode character may need more that one byte in UTF8 */
6937                 mono_mb_emit_ldarg (mb, argnum);
6938                 break;
6939
6940         case MARSHAL_ACTION_CONV_RESULT:
6941                 /* fixme: we need conversions here */
6942                 mono_mb_emit_stloc (mb, 3);
6943                 break;
6944
6945         default:
6946                 break;
6947         }
6948 #endif
6949         return conv_arg;
6950 }
6951
6952 static int
6953 emit_marshal_scalar (EmitMarshalContext *m, int argnum, MonoType *t, 
6954                      MonoMarshalSpec *spec, int conv_arg, 
6955                      MonoType **conv_arg_type, MarshalAction action)
6956 {
6957 #ifndef DISABLE_JIT
6958         MonoMethodBuilder *mb = m->mb;
6959
6960         switch (action) {
6961         case MARSHAL_ACTION_PUSH:
6962                 mono_mb_emit_ldarg (mb, argnum);
6963                 break;
6964
6965         case MARSHAL_ACTION_CONV_RESULT:
6966                 /* no conversions necessary */
6967                 mono_mb_emit_stloc (mb, 3);
6968                 break;
6969
6970         default:
6971                 break;
6972         }
6973 #endif
6974         return conv_arg;
6975 }
6976
6977 static int
6978 emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t, 
6979               MonoMarshalSpec *spec, int conv_arg, 
6980               MonoType **conv_arg_type, MarshalAction action)
6981 {
6982         /* Ensure that we have marshalling info for this param */
6983         mono_marshal_load_type_info (mono_class_from_mono_type (t));
6984
6985         if (spec && spec->native == MONO_NATIVE_CUSTOM)
6986                 return emit_marshal_custom (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6987
6988         if (spec && spec->native == MONO_NATIVE_ASANY)
6989                 return emit_marshal_asany (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6990                         
6991         switch (t->type) {
6992         case MONO_TYPE_VALUETYPE:
6993                 if (t->data.klass == mono_defaults.handleref_class)
6994                         return emit_marshal_handleref (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6995                 
6996                 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6997         case MONO_TYPE_STRING:
6998                 return emit_marshal_string (m, argnum, t, spec, conv_arg, conv_arg_type, action);
6999         case MONO_TYPE_CLASS:
7000         case MONO_TYPE_OBJECT:
7001 #ifndef DISABLE_COM
7002                 if (spec && spec->native == MONO_NATIVE_STRUCT)
7003                         return emit_marshal_variant (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7004
7005                 if (spec && (spec->native == MONO_NATIVE_IUNKNOWN ||
7006                         spec->native == MONO_NATIVE_IDISPATCH ||
7007                         spec->native == MONO_NATIVE_INTERFACE))
7008                         return mono_cominterop_emit_marshal_com_interface (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7009                 if (spec && (spec->native == MONO_NATIVE_SAFEARRAY) && 
7010                         (spec->data.safearray_data.elem_type == MONO_VARIANT_VARIANT) && 
7011                         ((action == MARSHAL_ACTION_CONV_OUT) || (action == MARSHAL_ACTION_CONV_IN) || (action == MARSHAL_ACTION_PUSH)))
7012                         return mono_cominterop_emit_marshal_safearray (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7013 #endif
7014
7015                 if (mono_defaults.safehandle_class != NULL && t->data.klass &&
7016                     mono_class_is_subclass_of (t->data.klass,  mono_defaults.safehandle_class, FALSE))
7017                         return emit_marshal_safehandle (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7018                 
7019                 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7020         case MONO_TYPE_ARRAY:
7021         case MONO_TYPE_SZARRAY:
7022                 return emit_marshal_array (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7023         case MONO_TYPE_BOOLEAN:
7024                 return emit_marshal_boolean (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7025         case MONO_TYPE_PTR:
7026                 return emit_marshal_ptr (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7027         case MONO_TYPE_CHAR:
7028                 return emit_marshal_char (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7029         case MONO_TYPE_I1:
7030         case MONO_TYPE_U1:
7031         case MONO_TYPE_I2:
7032         case MONO_TYPE_U2:
7033         case MONO_TYPE_I4:
7034         case MONO_TYPE_U4:
7035         case MONO_TYPE_I:
7036         case MONO_TYPE_U:
7037         case MONO_TYPE_R4:
7038         case MONO_TYPE_R8:
7039         case MONO_TYPE_I8:
7040         case MONO_TYPE_U8:
7041         case MONO_TYPE_FNPTR:
7042                 return emit_marshal_scalar (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7043         case MONO_TYPE_GENERICINST:
7044                 if (mono_type_generic_inst_is_valuetype (t))
7045                         return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7046                 else
7047                         return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7048         default:
7049                 return conv_arg;
7050         }
7051 }
7052
7053 #ifndef DISABLE_JIT
7054 /**
7055  * mono_marshal_emit_native_wrapper:
7056  * @image: the image to use for looking up custom marshallers
7057  * @sig: The signature of the native function
7058  * @piinfo: Marshalling information
7059  * @mspecs: Marshalling information
7060  * @aot: whenever the created method will be compiled by the AOT compiler
7061  * @method: if non-NULL, the pinvoke method to call
7062  * @check_exceptions: Whenever to check for pending exceptions after the native call
7063  * @func_param: the function to call is passed as a boxed IntPtr as the first parameter
7064  *
7065  * generates IL code for the pinvoke wrapper, the generated code calls @func.
7066  */
7067 void
7068 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)
7069 {
7070         EmitMarshalContext m;
7071         MonoMethodSignature *csig;
7072         MonoClass *klass;
7073         int i, argnum, *tmp_locals;
7074         int type, param_shift = 0;
7075         static MonoMethodSignature *get_last_error_sig = NULL;
7076         int coop_gc_stack_dummy, coop_gc_var;
7077
7078         memset (&m, 0, sizeof (m));
7079         m.mb = mb;
7080         m.sig = sig;
7081         m.piinfo = piinfo;
7082
7083         /* we copy the signature, so that we can set pinvoke to 0 */
7084         if (func_param) {
7085                 /* The function address is passed as the first argument */
7086                 g_assert (!sig->hasthis);
7087                 param_shift += 1;
7088         }
7089         csig = mono_metadata_signature_dup_full (mb->method->klass->image, sig);
7090         csig->pinvoke = 1;
7091         m.csig = csig;
7092         m.image = image;
7093
7094         if (sig->hasthis)
7095                 param_shift += 1;
7096
7097         /* we allocate local for use with emit_struct_conv() */
7098         /* allocate local 0 (pointer) src_ptr */
7099         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7100         /* allocate local 1 (pointer) dst_ptr */
7101         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7102         /* allocate local 2 (boolean) delete_old */
7103         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7104
7105         /* delete_old = FALSE */
7106         mono_mb_emit_icon (mb, 0);
7107         mono_mb_emit_stloc (mb, 2);
7108
7109         if (!MONO_TYPE_IS_VOID(sig->ret)) {
7110                 /* allocate local 3 to store the return value */
7111                 mono_mb_add_local (mb, sig->ret);
7112         }
7113
7114         if (mono_threads_is_coop_enabled ()) {
7115                 /* local 4, dummy local used to get a stack address for suspend funcs */
7116                 coop_gc_stack_dummy = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7117                 /* local 5, the local to be used when calling the suspend funcs */
7118                 coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7119         }
7120
7121         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7122                 /* Return type custom marshaling */
7123                 /*
7124                  * Since we can't determine the return type of the unmanaged function,
7125                  * we assume it returns a pointer, and pass that pointer to
7126                  * MarshalNativeToManaged.
7127                  */
7128                 csig->ret = &mono_defaults.int_class->byval_arg;
7129         }
7130
7131         /* we first do all conversions */
7132         tmp_locals = alloca (sizeof (int) * sig->param_count);
7133         m.orig_conv_args = alloca (sizeof (int) * (sig->param_count + 1));
7134
7135         for (i = 0; i < sig->param_count; i ++) {
7136                 tmp_locals [i] = emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_CONV_IN);
7137         }
7138
7139         /* push all arguments */
7140
7141         if (sig->hasthis)
7142                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7143
7144         for (i = 0; i < sig->param_count; i++) {
7145                 emit_marshal (&m, i + param_shift, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
7146         }                       
7147
7148         if (mono_threads_is_coop_enabled ()) {
7149                 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7150                 mono_mb_emit_icall (mb, mono_threads_prepare_blocking);
7151                 mono_mb_emit_stloc (mb, coop_gc_var);
7152         }
7153
7154         /* call the native method */
7155         if (func_param) {
7156                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7157                 mono_mb_emit_op (mb, CEE_UNBOX, mono_defaults.int_class);
7158                 mono_mb_emit_byte (mb, CEE_LDIND_I);
7159                 mono_mb_emit_calli (mb, csig);
7160         } else if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
7161 #ifndef DISABLE_COM
7162                 mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
7163 #else
7164                 g_assert_not_reached ();
7165 #endif
7166         }
7167         else {
7168                 if (aot) {
7169                         /* Reuse the ICALL_ADDR opcode for pinvokes too */
7170                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7171                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7172                         mono_mb_emit_calli (mb, csig);
7173                 } else {                        
7174                         mono_mb_emit_native_call (mb, csig, func);
7175                 }
7176         }
7177
7178         /* Set LastError if needed */
7179         if (piinfo->piflags & PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR) {
7180                 if (!get_last_error_sig) {
7181                         get_last_error_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
7182                         get_last_error_sig->ret = &mono_defaults.int_class->byval_arg;
7183                         get_last_error_sig->pinvoke = 1;
7184                 }
7185
7186 #ifdef TARGET_WIN32
7187                 /* 
7188                  * Have to call GetLastError () early and without a wrapper, since various runtime components could
7189                  * clobber its value.
7190                  */
7191                 mono_mb_emit_native_call (mb, get_last_error_sig, GetLastError);
7192                 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7193 #else
7194                 mono_mb_emit_icall (mb, mono_marshal_set_last_error);
7195 #endif
7196         }               
7197
7198         if (mono_threads_is_coop_enabled ()) {
7199                 mono_mb_emit_ldloc (mb, coop_gc_var);
7200                 mono_mb_emit_ldloc_addr (mb, coop_gc_stack_dummy);
7201                 mono_mb_emit_icall (mb, mono_threads_finish_blocking);
7202         }
7203
7204         /* convert the result */
7205         if (!sig->ret->byref) {
7206                 MonoMarshalSpec *spec = mspecs [0];
7207                 type = sig->ret->type;
7208
7209                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7210                         emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7211                 } else {
7212
7213                 handle_enum:
7214                         switch (type) {
7215                         case MONO_TYPE_VOID:
7216                                 break;
7217                         case MONO_TYPE_VALUETYPE:
7218                                 klass = sig->ret->data.klass;
7219                                 if (klass->enumtype) {
7220                                         type = mono_class_enum_basetype (sig->ret->data.klass)->type;
7221                                         goto handle_enum;
7222                                 }
7223                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7224                                 break;
7225                         case MONO_TYPE_I1:
7226                         case MONO_TYPE_U1:
7227                         case MONO_TYPE_I2:
7228                         case MONO_TYPE_U2:
7229                         case MONO_TYPE_I4:
7230                         case MONO_TYPE_U4:
7231                         case MONO_TYPE_I:
7232                         case MONO_TYPE_U:
7233                         case MONO_TYPE_R4:
7234                         case MONO_TYPE_R8:
7235                         case MONO_TYPE_I8:
7236                         case MONO_TYPE_U8:
7237                         case MONO_TYPE_FNPTR:
7238                         case MONO_TYPE_STRING:
7239                         case MONO_TYPE_CLASS:
7240                         case MONO_TYPE_OBJECT:
7241                         case MONO_TYPE_BOOLEAN:
7242                         case MONO_TYPE_ARRAY:
7243                         case MONO_TYPE_SZARRAY:
7244                         case MONO_TYPE_CHAR:
7245                         case MONO_TYPE_PTR:
7246                         case MONO_TYPE_GENERICINST:
7247                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7248                                 break;
7249                         case MONO_TYPE_TYPEDBYREF:
7250                         default:
7251                                 g_warning ("return type 0x%02x unknown", sig->ret->type);       
7252                                 g_assert_not_reached ();
7253                         }
7254                 }
7255         } else {
7256                 mono_mb_emit_stloc (mb, 3);
7257         }
7258
7259         /* 
7260          * Need to call this after converting the result since MONO_VTADDR needs 
7261          * to be adjacent to the call instruction.
7262          */
7263         if (check_exceptions)
7264                 emit_thread_interrupt_checkpoint (mb);
7265
7266         /* we need to convert byref arguments back and free string arrays */
7267         for (i = 0; i < sig->param_count; i++) {
7268                 MonoType *t = sig->params [i];
7269                 MonoMarshalSpec *spec = mspecs [i + 1];
7270
7271                 argnum = i + param_shift;
7272
7273                 if (spec && ((spec->native == MONO_NATIVE_CUSTOM) || (spec->native == MONO_NATIVE_ASANY))) {
7274                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7275                         continue;
7276                 }
7277
7278                 switch (t->type) {
7279                 case MONO_TYPE_STRING:
7280                 case MONO_TYPE_VALUETYPE:
7281                 case MONO_TYPE_CLASS:
7282                 case MONO_TYPE_OBJECT:
7283                 case MONO_TYPE_SZARRAY:
7284                 case MONO_TYPE_BOOLEAN:
7285                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7286                         break;
7287                 default:
7288                         break;
7289                 }
7290         }
7291
7292         if (!MONO_TYPE_IS_VOID(sig->ret))
7293                 mono_mb_emit_ldloc (mb, 3);
7294
7295         mono_mb_emit_byte (mb, CEE_RET);
7296 }
7297 #endif /* DISABLE_JIT */
7298
7299 /**
7300  * mono_marshal_get_native_wrapper:
7301  * @method: The MonoMethod to wrap.
7302  * @check_exceptions: Whenever to check for pending exceptions
7303  *
7304  * generates IL code for the pinvoke wrapper (the generated method
7305  * calls the unmanaged code in piinfo->addr)
7306  * The wrapper info for the wrapper is a WrapperInfo structure.
7307  */
7308 MonoMethod *
7309 mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions, gboolean aot)
7310 {
7311         MonoMethodSignature *sig, *csig;
7312         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7313         MonoMethodBuilder *mb;
7314         MonoMarshalSpec **mspecs;
7315         MonoMethod *res;
7316         GHashTable *cache;
7317         gboolean pinvoke = FALSE;
7318         gpointer iter;
7319         int i;
7320         const char *exc_class = "MissingMethodException";
7321         const char *exc_arg = NULL;
7322         WrapperInfo *info;
7323
7324         g_assert (method != NULL);
7325         g_assert (mono_method_signature (method)->pinvoke);
7326
7327         GHashTable **cache_ptr;
7328
7329         if (aot) {
7330                 if (check_exceptions)
7331                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_check_cache;
7332                 else
7333                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_aot_cache;
7334         } else {
7335                 if (check_exceptions)
7336                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_check_cache;
7337                 else
7338                         cache_ptr = &mono_method_get_wrapper_cache (method)->native_wrapper_cache;
7339         }
7340
7341         cache = get_cache (cache_ptr, mono_aligned_addr_hash, NULL);
7342
7343         if ((res = mono_marshal_find_in_cache (cache, method)))
7344                 return res;
7345
7346         if (MONO_CLASS_IS_IMPORT (method->klass)) {
7347                 /* The COM code is not AOT compatible, it calls mono_custom_attrs_get_attr_checked () */
7348                 if (aot)
7349                         return method;
7350 #ifndef DISABLE_COM
7351                 return mono_cominterop_get_native_wrapper (method);
7352 #else
7353                 g_assert_not_reached ();
7354 #endif
7355         }
7356
7357         sig = mono_method_signature (method);
7358
7359         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
7360             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7361                 pinvoke = TRUE;
7362
7363         if (!piinfo->addr) {
7364                 if (pinvoke) {
7365                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
7366                                 exc_arg = "Method contains unsupported native code";
7367                         else if (!aot)
7368                                 mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7369                 } else {
7370                         piinfo->addr = mono_lookup_internal_call (method);
7371                 }
7372         }
7373
7374         /* hack - redirect certain string constructors to CreateString */
7375         if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
7376                 g_assert (!pinvoke);
7377                 g_assert (method->string_ctor);
7378                 g_assert (sig->hasthis);
7379
7380                 /* CreateString returns a value */
7381                 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7382                 csig->ret = &mono_defaults.string_class->byval_arg;
7383                 csig->pinvoke = 0;
7384
7385                 iter = NULL;
7386                 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
7387                         if (!strcmp ("CreateString", res->name) &&
7388                                 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
7389                                 WrapperInfo *info;
7390
7391                                 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
7392                                 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
7393
7394                                 /* create a wrapper to preserve .ctor in stack trace */
7395                                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
7396
7397 #ifndef DISABLE_JIT
7398                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7399                                 for (i = 1; i <= csig->param_count; i++)
7400                                         mono_mb_emit_ldarg (mb, i);
7401                                 mono_mb_emit_managed_call (mb, res, NULL);
7402                                 mono_mb_emit_byte (mb, CEE_RET);
7403 #endif
7404
7405                                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRING_CTOR);
7406                                 info->d.string_ctor.method = method;
7407
7408                                 /* use native_wrapper_cache because internal calls are looked up there */
7409                                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7410                                                                                                          csig->param_count + 1, info, NULL);
7411                                 mono_mb_free (mb);
7412
7413                                 return res;
7414                         }
7415                 }
7416
7417                 /* exception will be thrown */
7418                 piinfo->addr = NULL;
7419                 g_warning ("cannot find CreateString for .ctor");
7420         }
7421
7422         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7423
7424         mb->method->save_lmf = 1;
7425
7426         /*
7427          * In AOT mode and embedding scenarios, it is possible that the icall is not
7428          * registered in the runtime doing the AOT compilation.
7429          */
7430         if (!piinfo->addr && !aot) {
7431 #ifndef DISABLE_JIT
7432                 mono_mb_emit_exception (mb, exc_class, exc_arg);
7433 #endif
7434                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7435                 info->d.managed_to_native.method = method;
7436
7437                 csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7438                 csig->pinvoke = 0;
7439                 res = mono_mb_create_and_cache_full (cache, method, mb, csig,
7440                                                                                          csig->param_count + 16, info, NULL);
7441                 mono_mb_free (mb);
7442
7443                 return res;
7444         }
7445
7446         /* internal calls: we simply push all arguments and call the method (no conversions) */
7447         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
7448                 if (sig->hasthis)
7449                         csig = mono_metadata_signature_dup_add_this (method->klass->image, sig, method->klass);
7450                 else
7451                         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7452
7453                 /* hack - string constructors returns a value */
7454                 if (method->string_ctor)
7455                         csig->ret = &mono_defaults.string_class->byval_arg;
7456
7457 #ifndef DISABLE_JIT
7458                 if (sig->hasthis) {
7459                         int pos;
7460
7461                         /*
7462                          * Add a null check since public icalls can be called with 'call' which
7463                          * does no such check.
7464                          */
7465                         mono_mb_emit_byte (mb, CEE_LDARG_0);                    
7466                         pos = mono_mb_emit_branch (mb, CEE_BRTRUE);
7467                         mono_mb_emit_exception (mb, "NullReferenceException", NULL);
7468                         mono_mb_patch_branch (mb, pos);
7469
7470                         mono_mb_emit_byte (mb, CEE_LDARG_0);
7471                 }
7472
7473                 for (i = 0; i < sig->param_count; i++)
7474                         mono_mb_emit_ldarg (mb, i + sig->hasthis);
7475
7476                 if (aot) {
7477                         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7478                         mono_mb_emit_op (mb, CEE_MONO_ICALL_ADDR, &piinfo->method);
7479                         mono_mb_emit_calli (mb, csig);
7480                 } else {
7481                         g_assert (piinfo->addr);
7482                         mono_mb_emit_native_call (mb, csig, piinfo->addr);
7483                 }
7484                 if (check_exceptions)
7485                         emit_thread_interrupt_checkpoint (mb);
7486                 mono_mb_emit_byte (mb, CEE_RET);
7487 #endif
7488                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
7489                 info->d.managed_to_native.method = method;
7490
7491                 csig = mono_metadata_signature_dup_full (method->klass->image, csig);
7492                 csig->pinvoke = 0;
7493                 res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7494                                                                                          info, NULL);
7495
7496                 mono_mb_free (mb);
7497                 return res;
7498         }
7499
7500         g_assert (pinvoke);
7501         if (!aot)
7502                 g_assert (piinfo->addr);
7503
7504 #ifndef DISABLE_JIT
7505         mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
7506         mono_method_get_marshal_info (method, mspecs);
7507
7508         mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr, aot, check_exceptions, FALSE);
7509 #endif
7510         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PINVOKE);
7511         info->d.managed_to_native.method = method;
7512
7513         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
7514         csig->pinvoke = 0;
7515         res = mono_mb_create_and_cache_full (cache, method, mb, csig, csig->param_count + 16,
7516                                                                                  info, NULL);
7517         mono_mb_free (mb);
7518
7519 #ifndef DISABLE_JIT
7520         for (i = sig->param_count; i >= 0; i--)
7521                 if (mspecs [i])
7522                         mono_metadata_free_marshal_spec (mspecs [i]);
7523         g_free (mspecs);
7524 #endif
7525
7526         /* mono_method_print_code (res); */
7527
7528         return res;
7529 }
7530
7531 /**
7532  * mono_marshal_get_native_func_wrapper:
7533  * @image: The image to use for memory allocation and for looking up custom marshallers.
7534  * @sig: The signature of the function
7535  * @func: The native function to wrap
7536  *
7537  *   Returns a wrapper method around native functions, similar to the pinvoke
7538  * wrapper.
7539  */
7540 MonoMethod *
7541 mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig, 
7542                                                                           MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
7543 {
7544         MonoMethodSignature *csig;
7545
7546         SignaturePointerPair key, *new_key;
7547         MonoMethodBuilder *mb;
7548         MonoMethod *res;
7549         GHashTable *cache;
7550         gboolean found;
7551         char *name;
7552
7553         key.sig = sig;
7554         key.pointer = func;
7555
7556         // Generic types are not safe to place in MonoImage caches.
7557         g_assert (!sig->is_inflated);
7558
7559         cache = get_cache (&image->native_func_wrapper_cache, signature_pointer_pair_hash, signature_pointer_pair_equal);
7560         if ((res = mono_marshal_find_in_cache (cache, &key)))
7561                 return res;
7562
7563         name = g_strdup_printf ("wrapper_native_%p", func);
7564         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7565         mb->method->save_lmf = 1;
7566
7567 #ifndef DISABLE_JIT
7568         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func, FALSE, TRUE, FALSE);
7569 #endif
7570
7571         csig = mono_metadata_signature_dup_full (image, sig);
7572         csig->pinvoke = 0;
7573
7574         new_key = g_new (SignaturePointerPair,1);
7575         new_key->sig = csig;
7576         new_key->pointer = func;
7577
7578         res = mono_mb_create_and_cache_full (cache, new_key, mb, csig, csig->param_count + 16, NULL, &found);
7579         if (found)
7580                 g_free (new_key);
7581
7582         mono_mb_free (mb);
7583
7584         mono_marshal_set_wrapper_info (res, NULL);
7585
7586         return res;
7587 }
7588
7589 /*
7590  * The wrapper receives the native function as a boxed IntPtr as its 'this' argument. This is easier to support in
7591  * AOT.
7592  */
7593 MonoMethod*
7594 mono_marshal_get_native_func_wrapper_aot (MonoClass *klass)
7595 {
7596         MonoMethodSignature *sig, *csig;
7597         MonoMethodBuilder *mb;
7598         MonoMethod *res;
7599         GHashTable *cache;
7600         char *name;
7601         WrapperInfo *info;
7602         MonoMethodPInvoke mpiinfo;
7603         MonoMethodPInvoke *piinfo = &mpiinfo;
7604         MonoMarshalSpec **mspecs;
7605         MonoMethod *invoke = mono_get_delegate_invoke (klass);
7606         MonoImage *image = invoke->klass->image;
7607         int i;
7608
7609         // FIXME: include UnmanagedFunctionPointerAttribute info
7610
7611         /*
7612          * The wrapper is associated with the delegate type, to pick up the marshalling info etc.
7613          */
7614         cache = get_cache (&mono_method_get_wrapper_cache (invoke)->native_func_wrapper_aot_cache, mono_aligned_addr_hash, NULL);
7615
7616         if ((res = mono_marshal_find_in_cache (cache, invoke)))
7617                 return res;
7618
7619         memset (&mpiinfo, 0, sizeof (mpiinfo));
7620         parse_unmanaged_function_pointer_attr (klass, &mpiinfo);
7621
7622         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
7623         mono_method_get_marshal_info (invoke, mspecs);
7624         /* Freed below so don't alloc from mempool */
7625         sig = mono_metadata_signature_dup (mono_method_signature (invoke));
7626         sig->hasthis = 0;
7627
7628         name = g_strdup_printf ("wrapper_aot_native");
7629         mb = mono_mb_new (invoke->klass, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7630         mb->method->save_lmf = 1;
7631
7632 #ifndef DISABLE_JIT
7633         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, NULL, FALSE, TRUE, TRUE);
7634 #endif
7635
7636         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NATIVE_FUNC_AOT);
7637         info->d.managed_to_native.method = invoke;
7638
7639         g_assert (!sig->hasthis);
7640         csig = mono_metadata_signature_dup_add_this (image, sig, mono_defaults.object_class);
7641         csig->pinvoke = 0;
7642         res = mono_mb_create_and_cache_full (cache, invoke,
7643                                                                                  mb, csig, csig->param_count + 16,
7644                                                                                  info, NULL);
7645         mono_mb_free (mb);
7646
7647         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
7648                 if (mspecs [i])
7649                         mono_metadata_free_marshal_spec (mspecs [i]);
7650         g_free (mspecs);
7651         g_free (sig);
7652
7653         return res;
7654 }
7655
7656 /*
7657  * mono_marshal_emit_managed_wrapper:
7658  *
7659  *   Emit the body of a native-to-managed wrapper. INVOKE_SIG is the signature of
7660  * the delegate which wraps the managed method to be called. For closed delegates,
7661  * it could have fewer parameters than the method it wraps.
7662  * THIS_LOC is the memory location where the target of the delegate is stored.
7663  */
7664 void
7665 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, uint32_t target_handle)
7666 {
7667 #ifdef DISABLE_JIT
7668         MonoMethodSignature *sig, *csig;
7669         int i;
7670
7671         sig = m->sig;
7672         csig = m->csig;
7673
7674         /* we first do all conversions */
7675         for (i = 0; i < sig->param_count; i ++) {
7676                 MonoType *t = sig->params [i];
7677
7678                 switch (t->type) {
7679                 case MONO_TYPE_OBJECT:
7680                 case MONO_TYPE_CLASS:
7681                 case MONO_TYPE_VALUETYPE:
7682                 case MONO_TYPE_ARRAY:
7683                 case MONO_TYPE_SZARRAY:
7684                 case MONO_TYPE_STRING:
7685                 case MONO_TYPE_BOOLEAN:
7686                         emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
7687                 }
7688         }
7689
7690         if (!sig->ret->byref) {
7691                 switch (sig->ret->type) {
7692                 case MONO_TYPE_STRING:
7693                         csig->ret = &mono_defaults.int_class->byval_arg;
7694                         break;
7695                 default:
7696                         break;
7697                 }
7698         }
7699 #else
7700         MonoMethodSignature *sig, *csig;
7701         int i, *tmp_locals;
7702         gboolean closed = FALSE;
7703         int coop_gc_var, coop_gc_dummy_local;
7704
7705         sig = m->sig;
7706         csig = m->csig;
7707
7708         /* allocate local 0 (pointer) src_ptr */
7709         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7710         /* allocate local 1 (pointer) dst_ptr */
7711         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7712         /* allocate local 2 (boolean) delete_old */
7713         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7714
7715         if (!sig->hasthis && sig->param_count != invoke_sig->param_count) {
7716                 /* Closed delegate */
7717                 g_assert (sig->param_count == invoke_sig->param_count + 1);
7718                 closed = TRUE;
7719                 /* Use a new signature without the first argument */
7720                 sig = mono_metadata_signature_dup (sig);
7721                 memmove (&sig->params [0], &sig->params [1], (sig->param_count - 1) * sizeof (MonoType*));
7722                 sig->param_count --;
7723         }
7724
7725         if (!MONO_TYPE_IS_VOID(sig->ret)) {
7726                 /* allocate local 3 to store the return value */
7727                 mono_mb_add_local (mb, sig->ret);
7728         }
7729
7730         if (mono_threads_is_coop_enabled ()) {
7731                 /* local 4, the local to be used when calling the reset_blocking funcs */
7732                 /* tons of code hardcode 3 to be the return var */
7733                 coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7734                 /* local 5, the local used to get a stack address for suspend funcs */
7735                 coop_gc_dummy_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7736         }
7737
7738         mono_mb_emit_icon (mb, 0);
7739         mono_mb_emit_stloc (mb, 2);
7740
7741         /*
7742          * Might need to attach the thread to the JIT or change the
7743          * domain for the callback.
7744          */
7745         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7746         mono_mb_emit_byte (mb, CEE_MONO_JIT_ATTACH);
7747
7748         if (mono_threads_is_coop_enabled ()) {
7749                 /* XXX can we merge reset_blocking_start with JIT_ATTACH above and save one call? */
7750                 mono_mb_emit_ldloc_addr (mb, coop_gc_dummy_local);
7751                 mono_mb_emit_icall (mb, mono_threads_reset_blocking_start);
7752                 mono_mb_emit_stloc (mb, coop_gc_var);
7753         }
7754
7755         /* we first do all conversions */
7756         tmp_locals = alloca (sizeof (int) * sig->param_count);
7757         for (i = 0; i < sig->param_count; i ++) {
7758                 MonoType *t = sig->params [i];
7759
7760                 switch (t->type) {
7761                 case MONO_TYPE_OBJECT:
7762                 case MONO_TYPE_CLASS:
7763                 case MONO_TYPE_VALUETYPE:
7764                 case MONO_TYPE_ARRAY:
7765                 case MONO_TYPE_SZARRAY:
7766                 case MONO_TYPE_STRING:
7767                 case MONO_TYPE_BOOLEAN:
7768                         tmp_locals [i] = emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
7769
7770                         break;
7771                 default:
7772                         tmp_locals [i] = 0;
7773                         break;
7774                 }
7775         }
7776
7777         emit_thread_interrupt_checkpoint (mb);
7778
7779         if (sig->hasthis) {
7780                 if (target_handle) {
7781                         mono_mb_emit_icon (mb, (gint32)target_handle);
7782                         mono_mb_emit_icall (mb, mono_gchandle_get_target);
7783                 } else {
7784                         /* fixme: */
7785                         g_assert_not_reached ();
7786                 }
7787         } else if (closed) {
7788                 mono_mb_emit_icon (mb, (gint32)target_handle);
7789                 mono_mb_emit_icall (mb, mono_gchandle_get_target);
7790         }
7791
7792         for (i = 0; i < sig->param_count; i++) {
7793                 MonoType *t = sig->params [i];
7794
7795                 if (tmp_locals [i]) {
7796                         if (t->byref)
7797                                 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
7798                         else
7799                                 mono_mb_emit_ldloc (mb, tmp_locals [i]);
7800                 }
7801                 else
7802                         mono_mb_emit_ldarg (mb, i);
7803         }
7804
7805         mono_mb_emit_managed_call (mb, method, NULL);
7806
7807         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7808                 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7809         } else if (!sig->ret->byref) { 
7810                 switch (sig->ret->type) {
7811                 case MONO_TYPE_VOID:
7812                         break;
7813                 case MONO_TYPE_BOOLEAN:
7814                 case MONO_TYPE_I1:
7815                 case MONO_TYPE_U1:
7816                 case MONO_TYPE_CHAR:
7817                 case MONO_TYPE_I2:
7818                 case MONO_TYPE_U2:
7819                 case MONO_TYPE_I4:
7820                 case MONO_TYPE_U4:
7821                 case MONO_TYPE_I:
7822                 case MONO_TYPE_U:
7823                 case MONO_TYPE_PTR:
7824                 case MONO_TYPE_R4:
7825                 case MONO_TYPE_R8:
7826                 case MONO_TYPE_I8:
7827                 case MONO_TYPE_U8:
7828                 case MONO_TYPE_OBJECT:
7829                         mono_mb_emit_stloc (mb, 3);
7830                         break;
7831                 case MONO_TYPE_STRING:
7832                         csig->ret = &mono_defaults.int_class->byval_arg;
7833                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7834                         break;
7835                 case MONO_TYPE_VALUETYPE:
7836                 case MONO_TYPE_CLASS:
7837                 case MONO_TYPE_SZARRAY:
7838                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7839                         break;
7840                 default:
7841                         g_warning ("return type 0x%02x unknown", sig->ret->type);       
7842                         g_assert_not_reached ();
7843                 }
7844         } else {
7845                 mono_mb_emit_stloc (mb, 3);
7846         }
7847
7848         /* Convert byref arguments back */
7849         for (i = 0; i < sig->param_count; i ++) {
7850                 MonoType *t = sig->params [i];
7851                 MonoMarshalSpec *spec = mspecs [i + 1];
7852
7853                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7854                         emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7855                 }
7856                 else if (t->byref) {
7857                         switch (t->type) {
7858                         case MONO_TYPE_CLASS:
7859                         case MONO_TYPE_VALUETYPE:
7860                         case MONO_TYPE_OBJECT:
7861                         case MONO_TYPE_STRING:
7862                         case MONO_TYPE_BOOLEAN:
7863                                 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7864                                 break;
7865                         default:
7866                                 break;
7867                         }
7868                 }
7869                 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
7870                         /* The [Out] information is encoded in the delegate signature */
7871                         switch (t->type) {
7872                         case MONO_TYPE_SZARRAY:
7873                         case MONO_TYPE_CLASS:
7874                         case MONO_TYPE_VALUETYPE:
7875                                 emit_marshal (m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7876                                 break;
7877                         default:
7878                                 g_assert_not_reached ();
7879                         }
7880                 }
7881         }
7882
7883         if (mono_threads_is_coop_enabled ()) {
7884                 /* XXX merge reset_blocking_end with detach */
7885                 mono_mb_emit_ldloc (mb, coop_gc_var);
7886                 mono_mb_emit_ldloc_addr (mb, coop_gc_dummy_local);
7887                 mono_mb_emit_icall (mb, mono_threads_reset_blocking_end);
7888         }
7889
7890         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7891         mono_mb_emit_byte (mb, CEE_MONO_JIT_DETACH);
7892
7893         if (m->retobj_var) {
7894                 mono_mb_emit_ldloc (mb, m->retobj_var);
7895                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7896                 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m->retobj_class);
7897         }
7898         else {
7899                 if (!MONO_TYPE_IS_VOID(sig->ret))
7900                         mono_mb_emit_ldloc (mb, 3);
7901                 mono_mb_emit_byte (mb, CEE_RET);
7902         }
7903
7904         if (closed)
7905                 g_free (sig);
7906 #endif
7907 }
7908
7909 static void 
7910 mono_marshal_set_callconv_from_modopt (MonoMethod *method, MonoMethodSignature *csig)
7911 {
7912         MonoMethodSignature *sig;
7913         int i;
7914
7915 #ifdef TARGET_WIN32
7916         /* 
7917          * Under windows, delegates passed to native code must use the STDCALL
7918          * calling convention.
7919          */
7920         csig->call_convention = MONO_CALL_STDCALL;
7921 #endif
7922
7923         sig = mono_method_signature (method);
7924
7925         /* Change default calling convention if needed */
7926         /* Why is this a modopt ? */
7927         if (sig->ret && sig->ret->num_mods) {
7928                 for (i = 0; i < sig->ret->num_mods; ++i) {
7929                         MonoError error;
7930                         MonoClass *cmod_class = mono_class_get_checked (method->klass->image, sig->ret->modifiers [i].token, &error);
7931                         g_assert (mono_error_ok (&error));
7932                         if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
7933                                 if (!strcmp (cmod_class->name, "CallConvCdecl"))
7934                                         csig->call_convention = MONO_CALL_C;
7935                                 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
7936                                         csig->call_convention = MONO_CALL_STDCALL;
7937                                 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
7938                                         csig->call_convention = MONO_CALL_FASTCALL;
7939                                 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
7940                                         csig->call_convention = MONO_CALL_THISCALL;
7941                         }
7942                 }
7943         }
7944 }
7945
7946 /*
7947  * generates IL code to call managed methods from unmanaged code 
7948  * If target_handle==0, the wrapper info will be a WrapperInfo structure.
7949  */
7950 MonoMethod *
7951 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, uint32_t target_handle)
7952 {
7953         static MonoClass *UnmanagedFunctionPointerAttribute;
7954         MonoMethodSignature *sig, *csig, *invoke_sig;
7955         MonoMethodBuilder *mb;
7956         MonoMethod *res, *invoke;
7957         MonoMarshalSpec **mspecs;
7958         MonoMethodPInvoke piinfo;
7959         GHashTable *cache;
7960         int i;
7961         EmitMarshalContext m;
7962
7963         g_assert (method != NULL);
7964         g_assert (!mono_method_signature (method)->pinvoke);
7965
7966         /* 
7967          * FIXME: Should cache the method+delegate type pair, since the same method
7968          * could be called with different delegates, thus different marshalling
7969          * options.
7970          */
7971         cache = get_cache (&mono_method_get_wrapper_cache (method)->managed_wrapper_cache, mono_aligned_addr_hash, NULL);
7972
7973         if (!target_handle && (res = mono_marshal_find_in_cache (cache, method)))
7974                 return res;
7975
7976         invoke = mono_get_delegate_invoke (delegate_klass);
7977         invoke_sig = mono_method_signature (invoke);
7978
7979         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
7980         mono_method_get_marshal_info (invoke, mspecs);
7981
7982         sig = mono_method_signature (method);
7983
7984         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
7985
7986         /*the target gchandle must be the first entry after size and the wrapper itself.*/
7987         mono_mb_add_data (mb, GUINT_TO_POINTER (target_handle));
7988
7989         /* we copy the signature, so that we can modify it */
7990         if (target_handle)
7991                 /* Need to free this later */
7992                 csig = mono_metadata_signature_dup (invoke_sig);
7993         else
7994                 csig = mono_metadata_signature_dup_full (method->klass->image, invoke_sig);
7995         csig->hasthis = 0;
7996         csig->pinvoke = 1;
7997
7998         memset (&m, 0, sizeof (m));
7999         m.mb = mb;
8000         m.sig = sig;
8001         m.piinfo = NULL;
8002         m.retobj_var = 0;
8003         m.csig = csig;
8004         m.image = method->klass->image;
8005
8006         mono_marshal_set_callconv_from_modopt (invoke, csig);
8007
8008         /* Handle the UnmanagedFunctionPointerAttribute */
8009         if (!UnmanagedFunctionPointerAttribute)
8010                 UnmanagedFunctionPointerAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
8011
8012         /* The attribute is only available in Net 2.0 */
8013         if (UnmanagedFunctionPointerAttribute) {
8014                 MonoCustomAttrInfo *cinfo;
8015                 MonoCustomAttrEntry *attr;
8016
8017                 /* 
8018                  * The pinvoke attributes are stored in a real custom attribute. Obtain the
8019                  * contents of the attribute without constructing it, as that might not be
8020                  * possible when running in cross-compiling mode.
8021                  */
8022                 cinfo = mono_custom_attrs_from_class (delegate_klass);
8023                 attr = NULL;
8024                 if (cinfo) {
8025                         for (i = 0; i < cinfo->num_attrs; ++i) {
8026                                 MonoClass *ctor_class = cinfo->attrs [i].ctor->klass;
8027                                 if (mono_class_has_parent (ctor_class, UnmanagedFunctionPointerAttribute)) {
8028                                         attr = &cinfo->attrs [i];
8029                                         break;
8030                                 }
8031                         }
8032                 }
8033                 if (attr) {
8034                         MonoArray *typed_args, *named_args;
8035                         CattrNamedArg *arginfo;
8036                         MonoObject *o;
8037                         gint32 call_conv;
8038                         gint32 charset = 0;
8039                         MonoBoolean set_last_error = 0;
8040                         MonoError error;
8041
8042                         mono_reflection_create_custom_attr_data_args (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8043                         g_assert (mono_error_ok (&error));
8044                         g_assert (mono_array_length (typed_args) == 1);
8045
8046                         /* typed args */
8047                         o = mono_array_get (typed_args, MonoObject*, 0);
8048                         call_conv = *(gint32*)mono_object_unbox (o);
8049
8050                         /* named args */
8051                         for (i = 0; i < mono_array_length (named_args); ++i) {
8052                                 CattrNamedArg *narg = &arginfo [i];
8053
8054                                 o = mono_array_get (named_args, MonoObject*, i);
8055
8056                                 g_assert (narg->field);
8057                                 if (!strcmp (narg->field->name, "CharSet")) {
8058                                         charset = *(gint32*)mono_object_unbox (o);
8059                                 } else if (!strcmp (narg->field->name, "SetLastError")) {
8060                                         set_last_error = *(MonoBoolean*)mono_object_unbox (o);
8061                                 } else if (!strcmp (narg->field->name, "BestFitMapping")) {
8062                                         // best_fit_mapping = *(MonoBoolean*)mono_object_unbox (o);
8063                                 } else if (!strcmp (narg->field->name, "ThrowOnUnmappableChar")) {
8064                                         // throw_on_unmappable = *(MonoBoolean*)mono_object_unbox (o);
8065                                 } else {
8066                                         g_assert_not_reached ();
8067                                 }
8068                         }
8069
8070                         g_free (arginfo);
8071
8072                         memset (&piinfo, 0, sizeof (piinfo));
8073                         m.piinfo = &piinfo;
8074                         piinfo.piflags = (call_conv << 8) | (charset ? (charset - 1) * 2 : 1) | set_last_error;
8075
8076                         csig->call_convention = call_conv - 1;
8077                 }
8078
8079                 if (cinfo && !cinfo->cached)
8080                         mono_custom_attrs_free (cinfo);
8081         }
8082
8083         mono_marshal_emit_managed_wrapper (mb, invoke_sig, mspecs, &m, method, target_handle);
8084
8085         if (!target_handle) {
8086                 WrapperInfo *info;
8087
8088                 // FIXME: Associate it with the method+delegate_klass pair
8089                 info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8090                 info->d.native_to_managed.method = method;
8091                 info->d.native_to_managed.klass = delegate_klass;
8092
8093                 res = mono_mb_create_and_cache_full (cache, method,
8094                                                                                          mb, csig, sig->param_count + 16,
8095                                                                                          info, NULL);
8096         } else {
8097 #ifndef DISABLE_JIT
8098                 mb->dynamic = TRUE;
8099 #endif
8100                 res = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
8101         }
8102         mono_mb_free (mb);
8103
8104         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8105                 if (mspecs [i])
8106                         mono_metadata_free_marshal_spec (mspecs [i]);
8107         g_free (mspecs);
8108
8109         /* mono_method_print_code (res); */
8110
8111         return res;
8112 }
8113
8114 gpointer
8115 mono_marshal_get_vtfixup_ftnptr (MonoImage *image, guint32 token, guint16 type)
8116 {
8117         MonoMethod *method;
8118         MonoMethodSignature *sig;
8119         MonoMethodBuilder *mb;
8120         int i, param_count;
8121
8122         g_assert (token);
8123
8124         method = mono_get_method (image, token, NULL);
8125         g_assert (method);
8126
8127         if (type & (VTFIXUP_TYPE_FROM_UNMANAGED | VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN)) {
8128                 MonoMethodSignature *csig;
8129                 MonoMarshalSpec **mspecs;
8130                 EmitMarshalContext m;
8131
8132                 sig = mono_method_signature (method);
8133                 g_assert (!sig->hasthis);
8134
8135                 mspecs = g_new0 (MonoMarshalSpec*, sig->param_count + 1);
8136                 mono_method_get_marshal_info (method, mspecs);
8137
8138                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8139                 csig = mono_metadata_signature_dup_full (image, sig);
8140                 csig->hasthis = 0;
8141                 csig->pinvoke = 1;
8142
8143                 memset (&m, 0, sizeof (m));
8144                 m.mb = mb;
8145                 m.sig = sig;
8146                 m.piinfo = NULL;
8147                 m.retobj_var = 0;
8148                 m.csig = csig;
8149                 m.image = image;
8150
8151                 mono_marshal_set_callconv_from_modopt (method, csig);
8152
8153                 /* FIXME: Implement VTFIXUP_TYPE_FROM_UNMANAGED_RETAIN_APPDOMAIN. */
8154
8155                 mono_marshal_emit_managed_wrapper (mb, sig, mspecs, &m, method, 0);
8156
8157 #ifndef DISABLE_JIT
8158                 mb->dynamic = TRUE;
8159 #endif
8160                 method = mono_mb_create (mb, csig, sig->param_count + 16, NULL);
8161                 mono_mb_free (mb);
8162
8163                 for (i = sig->param_count; i >= 0; i--)
8164                         if (mspecs [i])
8165                                 mono_metadata_free_marshal_spec (mspecs [i]);
8166                 g_free (mspecs);
8167
8168                 return mono_compile_method (method);
8169         }
8170
8171         sig = mono_method_signature (method);
8172         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
8173
8174         param_count = sig->param_count + sig->hasthis;
8175 #ifndef DISABLE_JIT
8176         for (i = 0; i < param_count; i++)
8177                 mono_mb_emit_ldarg (mb, i);
8178
8179         if (type & VTFIXUP_TYPE_CALL_MOST_DERIVED)
8180                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
8181         else
8182                 mono_mb_emit_op (mb, CEE_CALL, method);
8183         mono_mb_emit_byte (mb, CEE_RET);
8184
8185         mb->dynamic = TRUE;
8186 #endif
8187
8188         method = mono_mb_create (mb, sig, param_count, NULL);
8189         mono_mb_free (mb);
8190
8191         return mono_compile_method (method);
8192 }
8193
8194 #ifndef DISABLE_JIT
8195
8196 /*
8197  * The code directly following this is the cache hit, value positive branch
8198  *
8199  * This function takes a new method builder with 0 locals and adds two locals
8200  * to create multiple out-branches and the fall through state of having the object
8201  * on the stack after a cache miss
8202  */
8203 static void
8204 generate_check_cache (int obj_arg_position, int class_arg_position, int cache_arg_position, // In-parameters
8205                                                                                         int *null_obj, int *cache_hit_neg, int *cache_hit_pos, // Out-parameters
8206                                                                                         MonoMethodBuilder *mb)
8207 {
8208         int cache_miss_pos;
8209
8210         /* allocate local 0 (pointer) obj_vtable */
8211         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8212         /* allocate local 1 (pointer) cached_vtable */
8213         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8214
8215         /*if (!obj)*/
8216         mono_mb_emit_ldarg (mb, obj_arg_position);
8217         *null_obj = mono_mb_emit_branch (mb, CEE_BRFALSE);
8218
8219         /*obj_vtable = obj->vtable;*/
8220         mono_mb_emit_ldarg (mb, obj_arg_position);
8221         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
8222         mono_mb_emit_byte (mb, CEE_LDIND_I);
8223         mono_mb_emit_stloc (mb, 0);
8224
8225         /* cached_vtable = *cache*/
8226         mono_mb_emit_ldarg (mb, cache_arg_position);
8227         mono_mb_emit_byte (mb, CEE_LDIND_I);
8228         mono_mb_emit_stloc (mb, 1);
8229
8230         mono_mb_emit_ldloc (mb, 1);
8231         mono_mb_emit_byte (mb, CEE_LDC_I4);
8232         mono_mb_emit_i4 (mb, ~0x1);
8233         mono_mb_emit_byte (mb, CEE_CONV_I);
8234         mono_mb_emit_byte (mb, CEE_AND);
8235         mono_mb_emit_ldloc (mb, 0);
8236         /*if ((cached_vtable & ~0x1)== obj_vtable)*/
8237         cache_miss_pos = mono_mb_emit_branch (mb, CEE_BNE_UN);
8238
8239         /*return (cached_vtable & 0x1) ? NULL : obj;*/
8240         mono_mb_emit_ldloc (mb, 1);
8241         mono_mb_emit_byte(mb, CEE_LDC_I4_1);
8242         mono_mb_emit_byte (mb, CEE_CONV_U);
8243         mono_mb_emit_byte (mb, CEE_AND);
8244         *cache_hit_neg = mono_mb_emit_branch (mb, CEE_BRTRUE);
8245         *cache_hit_pos = mono_mb_emit_branch (mb, CEE_BR);
8246
8247         // slow path
8248         mono_mb_patch_branch (mb, cache_miss_pos);
8249
8250         // if isinst
8251         mono_mb_emit_ldarg (mb, obj_arg_position);
8252         mono_mb_emit_ldarg (mb, class_arg_position);
8253         mono_mb_emit_ldarg (mb, cache_arg_position);
8254         mono_mb_emit_icall (mb, mono_marshal_isinst_with_cache);
8255 }
8256
8257 #endif /* DISABLE_JIT */
8258
8259 /*
8260  * This does the equivalent of mono_object_castclass_with_cache.
8261  * The wrapper info for the wrapper is a WrapperInfo structure.
8262  */
8263 MonoMethod *
8264 mono_marshal_get_castclass_with_cache (void)
8265 {
8266         static MonoMethod *cached;
8267         MonoMethod *res;
8268         MonoMethodBuilder *mb;
8269         MonoMethodSignature *sig;
8270         int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos, invalid_cast_pos;
8271         WrapperInfo *info;
8272
8273         const int obj_arg_position = 0;
8274         const int class_arg_position = 1;
8275         const int cache_arg_position = 2;
8276
8277         if (cached)
8278                 return cached;
8279
8280         mb = mono_mb_new (mono_defaults.object_class, "__castclass_with_cache", MONO_WRAPPER_CASTCLASS);
8281         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8282         sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
8283         sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
8284         sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
8285         sig->ret = &mono_defaults.object_class->byval_arg;
8286         sig->pinvoke = 0;
8287
8288 #ifndef DISABLE_JIT
8289         generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
8290                                                                                                 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
8291         invalid_cast_pos = mono_mb_emit_branch (mb, CEE_BRFALSE);
8292
8293         /*return obj;*/
8294         mono_mb_patch_branch (mb, positive_cache_hit_pos);
8295         mono_mb_emit_ldarg (mb, obj_arg_position);
8296         mono_mb_emit_byte (mb, CEE_RET);
8297
8298         /*fails*/
8299         mono_mb_patch_branch (mb, negative_cache_hit_pos);
8300         mono_mb_patch_branch (mb, invalid_cast_pos);
8301         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8302
8303         /*return null*/
8304         mono_mb_patch_branch (mb, return_null_pos);
8305         mono_mb_emit_byte (mb, CEE_LDNULL);
8306         mono_mb_emit_byte (mb, CEE_RET);
8307 #endif /* DISABLE_JIT */
8308
8309         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE);
8310         res = mono_mb_create (mb, sig, 8, info);
8311         STORE_STORE_FENCE;
8312
8313         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8314                 mono_free_method (res);
8315                 mono_metadata_free_method_signature (sig);
8316         }
8317         mono_mb_free (mb);
8318
8319         return cached;
8320 }
8321
8322 static MonoObject *
8323 mono_marshal_isinst_with_cache (MonoObject *obj, MonoClass *klass, uintptr_t *cache)
8324 {
8325         MonoObject *isinst = mono_object_isinst (obj, klass);
8326
8327 #ifndef DISABLE_REMOTING
8328         if (obj->vtable->klass == mono_defaults.transparent_proxy_class)
8329                 return isinst;
8330 #endif
8331
8332         uintptr_t cache_update = (uintptr_t)obj->vtable;
8333         if (!isinst)
8334                 cache_update = cache_update | 0x1;
8335
8336         *cache = cache_update;
8337
8338         return isinst;
8339 }
8340
8341 /*
8342  * This does the equivalent of mono_object_isinst_with_cache.
8343  * The wrapper info for the wrapper is a WrapperInfo structure.
8344  */
8345 MonoMethod *
8346 mono_marshal_get_isinst_with_cache (void)
8347 {
8348         static MonoMethod *cached;
8349         MonoMethod *res;
8350         MonoMethodBuilder *mb;
8351         MonoMethodSignature *sig;
8352         int return_null_pos, positive_cache_hit_pos, negative_cache_hit_pos;
8353         WrapperInfo *info;
8354
8355         const int obj_arg_position = 0;
8356         const int class_arg_position = 1;
8357         const int cache_arg_position = 2;
8358
8359         if (cached)
8360                 return cached;
8361
8362         mb = mono_mb_new (mono_defaults.object_class, "__isinst_with_cache", MONO_WRAPPER_CASTCLASS);
8363         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8364         // The object
8365         sig->params [obj_arg_position] = &mono_defaults.object_class->byval_arg;
8366         // The class
8367         sig->params [class_arg_position] = &mono_defaults.int_class->byval_arg;
8368         // The cache
8369         sig->params [cache_arg_position] = &mono_defaults.int_class->byval_arg;
8370         sig->ret = &mono_defaults.object_class->byval_arg;
8371         sig->pinvoke = 0;
8372
8373 #ifndef DISABLE_JIT
8374         generate_check_cache (obj_arg_position, class_arg_position, cache_arg_position, 
8375                 &return_null_pos, &negative_cache_hit_pos, &positive_cache_hit_pos, mb);
8376         // Return the object gotten via the slow path.
8377         mono_mb_emit_byte (mb, CEE_RET);
8378
8379         // return NULL;
8380         mono_mb_patch_branch (mb, negative_cache_hit_pos);
8381         mono_mb_patch_branch (mb, return_null_pos);
8382         mono_mb_emit_byte (mb, CEE_LDNULL);
8383         mono_mb_emit_byte (mb, CEE_RET);
8384
8385         // return obj
8386         mono_mb_patch_branch (mb, positive_cache_hit_pos);
8387         mono_mb_emit_ldarg (mb, 0);
8388         mono_mb_emit_byte (mb, CEE_RET);
8389 #endif
8390
8391         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ISINST_WITH_CACHE);
8392         res = mono_mb_create (mb, sig, 8, info);
8393         STORE_STORE_FENCE;
8394
8395         if (InterlockedCompareExchangePointer ((volatile gpointer *)&cached, res, NULL)) {
8396                 mono_free_method (res);
8397                 mono_metadata_free_method_signature (sig);
8398         }
8399         mono_mb_free (mb);
8400
8401         return cached;
8402 }
8403
8404 /*
8405  * mono_marshal_get_isinst:
8406  * @klass: the type of the field
8407  *
8408  * This method generates a function which can be used to check if an object is
8409  * an instance of the given type, icluding the case where the object is a proxy.
8410  * The generated function has the following signature:
8411  * MonoObject* __isinst_wrapper_ (MonoObject *obj)
8412  */
8413 MonoMethod *
8414 mono_marshal_get_isinst (MonoClass *klass)
8415 {
8416         static MonoMethodSignature *isint_sig = NULL;
8417         GHashTable *cache;
8418         MonoMethod *res;
8419         WrapperInfo *info;
8420         int pos_was_ok, pos_end;
8421 #ifndef DISABLE_REMOTING
8422         int pos_end2, pos_failed;
8423 #endif
8424         char *name;
8425         MonoMethodBuilder *mb;
8426
8427         cache = get_cache (&klass->image->isinst_cache, mono_aligned_addr_hash, NULL);
8428         if ((res = mono_marshal_find_in_cache (cache, klass)))
8429                 return res;
8430
8431         if (!isint_sig) {
8432                 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8433                 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
8434                 isint_sig->ret = &mono_defaults.object_class->byval_arg;
8435                 isint_sig->pinvoke = 0;
8436         }
8437         
8438         name = g_strdup_printf ("__isinst_wrapper_%s", klass->name); 
8439         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ISINST);
8440         g_free (name);
8441         
8442         mb->method->save_lmf = 1;
8443
8444 #ifndef DISABLE_JIT
8445         /* check if the object is a proxy that needs special cast */
8446         mono_mb_emit_ldarg (mb, 0);
8447         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8448         mono_mb_emit_op (mb, CEE_MONO_CISINST, klass);
8449
8450         /* The result of MONO_CISINST can be:
8451                 0) the type check succeeded
8452                 1) the type check did not succeed
8453                 2) a CanCastTo call is needed */
8454 #ifndef DISABLE_REMOTING
8455         mono_mb_emit_byte (mb, CEE_DUP);
8456         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8457
8458         mono_mb_emit_byte (mb, CEE_LDC_I4_2);
8459         pos_failed = mono_mb_emit_branch (mb, CEE_BNE_UN);
8460         
8461         /* get the real proxy from the transparent proxy*/
8462
8463         mono_mb_emit_ldarg (mb, 0);
8464         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8465         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8466         
8467         /* fail */
8468         
8469         mono_mb_patch_branch (mb, pos_failed);
8470         mono_mb_emit_byte (mb, CEE_LDNULL);
8471         pos_end2 = mono_mb_emit_branch (mb, CEE_BR);
8472         
8473         /* success */
8474         
8475         mono_mb_patch_branch (mb, pos_was_ok);
8476         mono_mb_emit_byte (mb, CEE_POP);
8477         mono_mb_emit_ldarg (mb, 0);
8478         
8479         /* the end */
8480         
8481         mono_mb_patch_branch (mb, pos_end);
8482         mono_mb_patch_branch (mb, pos_end2);
8483         mono_mb_emit_byte (mb, CEE_RET);
8484 #else
8485         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8486
8487         /* fail */
8488
8489         mono_mb_emit_byte (mb, CEE_LDNULL);
8490         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8491
8492         /* success */
8493
8494         mono_mb_patch_branch (mb, pos_was_ok);
8495         mono_mb_emit_ldarg (mb, 0);
8496
8497         /* the end */
8498
8499         mono_mb_patch_branch (mb, pos_end);
8500         mono_mb_emit_byte (mb, CEE_RET);
8501 #endif /* DISABLE_REMOTING */
8502 #endif /* DISABLE_JIT */
8503
8504         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8505         info->d.proxy.klass = klass;
8506         res = mono_mb_create_and_cache_full (cache, klass, mb, isint_sig, isint_sig->param_count + 16, info, NULL);
8507         mono_mb_free (mb);
8508
8509         return res;
8510 }
8511
8512 /*
8513  * mono_marshal_get_castclass:
8514  * @klass: the type of the field
8515  *
8516  * This method generates a function which can be used to cast an object to
8517  * an instance of the given type, icluding the case where the object is a proxy.
8518  * The generated function has the following signature:
8519  * MonoObject* __castclass_wrapper_ (MonoObject *obj)
8520  * The wrapper info for the wrapper is a WrapperInfo structure.
8521  */
8522 MonoMethod *
8523 mono_marshal_get_castclass (MonoClass *klass)
8524 {
8525         static MonoMethodSignature *castclass_sig = NULL;
8526         GHashTable *cache;
8527         MonoMethod *res;
8528 #ifndef DISABLE_REMOTING
8529         int pos_was_ok, pos_was_ok2;
8530 #endif
8531         char *name;
8532         MonoMethodBuilder *mb;
8533         WrapperInfo *info;
8534
8535         cache = get_cache (&klass->image->castclass_cache, mono_aligned_addr_hash, NULL);
8536         if ((res = mono_marshal_find_in_cache (cache, klass)))
8537                 return res;
8538
8539         if (!castclass_sig) {
8540                 castclass_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8541                 castclass_sig->params [0] = &mono_defaults.object_class->byval_arg;
8542                 castclass_sig->ret = &mono_defaults.object_class->byval_arg;
8543                 castclass_sig->pinvoke = 0;
8544         }
8545         
8546         name = g_strdup_printf ("__castclass_wrapper_%s", klass->name); 
8547         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_CASTCLASS);
8548         g_free (name);
8549         
8550         mb->method->save_lmf = 1;
8551
8552 #ifndef DISABLE_JIT
8553         /* check if the object is a proxy that needs special cast */
8554         mono_mb_emit_ldarg (mb, 0);
8555         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8556         mono_mb_emit_op (mb, CEE_MONO_CCASTCLASS, klass);
8557
8558         /* The result of MONO_CCASTCLASS can be:
8559                 0) the cast is valid
8560                 1) cast of unknown proxy type
8561                 or an exception if the cast is is invalid
8562         */
8563 #ifndef DISABLE_REMOTING
8564         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8565
8566         /* get the real proxy from the transparent proxy*/
8567
8568         mono_mb_emit_ldarg (mb, 0);
8569         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8570         pos_was_ok2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
8571         
8572         /* fail */
8573         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8574         
8575         /* success */
8576         mono_mb_patch_branch (mb, pos_was_ok);
8577         mono_mb_patch_branch (mb, pos_was_ok2);
8578 #else
8579         /* MONO_CCASTCLASS leaves an int in the stack with the result, pop it. */
8580         mono_mb_emit_byte (mb, CEE_POP);
8581 #endif /* DISABLE_REMOTING */
8582
8583         mono_mb_emit_ldarg (mb, 0);
8584         
8585         /* the end */
8586         mono_mb_emit_byte (mb, CEE_RET);
8587 #endif /* DISABLE_JIT */
8588
8589         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8590
8591         res = mono_mb_create_and_cache_full (cache, klass, mb, castclass_sig, castclass_sig->param_count + 16,
8592                                                                                  info, NULL);
8593         mono_mb_free (mb);
8594
8595         return res;
8596 }
8597
8598 /**
8599  * mono_marshal_get_struct_to_ptr:
8600  * @klass:
8601  *
8602  * generates IL code for StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)
8603  * The wrapper info for the wrapper is a WrapperInfo structure.
8604  */
8605 MonoMethod *
8606 mono_marshal_get_struct_to_ptr (MonoClass *klass)
8607 {
8608         MonoMethodBuilder *mb;
8609         static MonoMethod *stoptr = NULL;
8610         MonoMethod *res;
8611         WrapperInfo *info;
8612
8613         g_assert (klass != NULL);
8614
8615         mono_marshal_load_type_info (klass);
8616
8617         if (klass->marshal_info->str_to_ptr)
8618                 return klass->marshal_info->str_to_ptr;
8619
8620         if (!stoptr) 
8621                 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
8622         g_assert (stoptr);
8623
8624         mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
8625
8626 #ifndef DISABLE_JIT
8627         if (klass->blittable) {
8628                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8629                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8630                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8631                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8632                 mono_mb_emit_byte (mb, CEE_PREFIX1);
8633                 mono_mb_emit_byte (mb, CEE_CPBLK);
8634         } else {
8635
8636                 /* allocate local 0 (pointer) src_ptr */
8637                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8638                 /* allocate local 1 (pointer) dst_ptr */
8639                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8640                 /* allocate local 2 (boolean) delete_old */
8641                 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8642                 mono_mb_emit_byte (mb, CEE_LDARG_2);
8643                 mono_mb_emit_stloc (mb, 2);
8644
8645                 /* initialize src_ptr to point to the start of object data */
8646                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8647                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8648                 mono_mb_emit_stloc (mb, 0);
8649
8650                 /* initialize dst_ptr */
8651                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8652                 mono_mb_emit_stloc (mb, 1);
8653
8654                 emit_struct_conv (mb, klass, FALSE);
8655         }
8656
8657         mono_mb_emit_byte (mb, CEE_RET);
8658 #endif
8659         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_STRUCTURE_TO_PTR);
8660         res = mono_mb_create (mb, mono_signature_no_pinvoke (stoptr), 0, info);
8661         mono_mb_free (mb);
8662
8663         klass->marshal_info->str_to_ptr = res;
8664         return res;
8665 }
8666
8667 /**
8668  * mono_marshal_get_ptr_to_struct:
8669  * @klass:
8670  *
8671  * generates IL code for PtrToStructure (IntPtr src, object structure)
8672  * The wrapper info for the wrapper is a WrapperInfo structure.
8673  */
8674 MonoMethod *
8675 mono_marshal_get_ptr_to_struct (MonoClass *klass)
8676 {
8677         MonoMethodBuilder *mb;
8678         static MonoMethodSignature *ptostr = NULL;
8679         MonoMethod *res;
8680         WrapperInfo *info;
8681
8682         g_assert (klass != NULL);
8683
8684         mono_marshal_load_type_info (klass);
8685
8686         if (klass->marshal_info->ptr_to_str)
8687                 return klass->marshal_info->ptr_to_str;
8688
8689         if (!ptostr) {
8690                 MonoMethodSignature *sig;
8691
8692                 /* Create the signature corresponding to
8693                           static void PtrToStructure (IntPtr ptr, object structure);
8694                    defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
8695                 sig = mono_create_icall_signature ("void ptr object");
8696                 sig = mono_metadata_signature_dup_full (mono_defaults.corlib, sig);
8697                 sig->pinvoke = 0;
8698                 mono_memory_barrier ();
8699                 ptostr = sig;
8700         }
8701
8702         mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
8703
8704 #ifndef DISABLE_JIT
8705         if (klass->blittable) {
8706                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8707                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8708                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8709                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8710                 mono_mb_emit_byte (mb, CEE_PREFIX1);
8711                 mono_mb_emit_byte (mb, CEE_CPBLK);
8712         } else {
8713
8714                 /* allocate local 0 (pointer) src_ptr */
8715                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8716                 /* allocate local 1 (pointer) dst_ptr */
8717                 mono_mb_add_local (mb, &klass->this_arg);
8718                 
8719                 /* initialize src_ptr to point to the start of object data */
8720                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8721                 mono_mb_emit_stloc (mb, 0);
8722
8723                 /* initialize dst_ptr */
8724                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8725                 mono_mb_emit_op (mb, CEE_UNBOX, klass);
8726                 mono_mb_emit_stloc (mb, 1);
8727
8728                 emit_struct_conv (mb, klass, TRUE);
8729         }
8730
8731         mono_mb_emit_byte (mb, CEE_RET);
8732 #endif
8733         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_PTR_TO_STRUCTURE);
8734         res = mono_mb_create (mb, ptostr, 0, info);
8735         mono_mb_free (mb);
8736
8737         klass->marshal_info->ptr_to_str = res;
8738         return res;
8739 }
8740
8741 /*
8742  * Return a dummy wrapper for METHOD which is called by synchronized wrappers.
8743  * This is used to avoid infinite recursion since it is hard to determine where to
8744  * replace a method with its synchronized wrapper, and where not.
8745  * The runtime should execute METHOD instead of the wrapper.
8746  * The wrapper info for the wrapper is a WrapperInfo structure.
8747  */
8748 MonoMethod *
8749 mono_marshal_get_synchronized_inner_wrapper (MonoMethod *method)
8750 {
8751         MonoMethodBuilder *mb;
8752         WrapperInfo *info;
8753         MonoMethodSignature *sig;
8754         MonoMethod *res;
8755         MonoGenericContext *ctx = NULL;
8756         MonoGenericContainer *container = NULL;
8757
8758         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
8759                 ctx = &((MonoMethodInflated*)method)->context;
8760                 method = ((MonoMethodInflated*)method)->declaring;
8761                 container = mono_method_get_generic_container (method);
8762                 if (!container)
8763                         container = method->klass->generic_container;
8764                 g_assert (container);
8765         }
8766
8767         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
8768 #ifndef DISABLE_JIT
8769         mono_mb_emit_exception_full (mb, "System", "ExecutionEngineException", "Shouldn't be called.");
8770         mono_mb_emit_byte (mb, CEE_RET);
8771 #endif
8772         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
8773
8774         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_SYNCHRONIZED_INNER);
8775         info->d.synchronized_inner.method = method;
8776         res = mono_mb_create (mb, sig, 0, info);
8777         mono_mb_free (mb);
8778         if (ctx) {
8779                 MonoError error;
8780                 res = mono_class_inflate_generic_method_checked (res, ctx, &error);
8781                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8782         }
8783         return res;
8784 }
8785
8786 /*
8787  * generates IL code for the synchronized wrapper: the generated method
8788  * calls METHOD while locking 'this' or the parent type.
8789  */
8790 MonoMethod *
8791 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
8792 {
8793         static MonoMethod *enter_method, *exit_method, *gettypefromhandle_method;
8794         MonoMethodSignature *sig;
8795         MonoExceptionClause *clause;
8796         MonoMethodBuilder *mb;
8797         MonoMethod *res;
8798         GHashTable *cache;
8799         WrapperInfo *info;
8800         int i, pos, pos2, this_local, taken_local, ret_local = 0;
8801         MonoGenericContext *ctx = NULL;
8802         MonoMethod *orig_method = NULL;
8803         MonoGenericContainer *container = NULL;
8804
8805         g_assert (method);
8806
8807         if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
8808                 return method;
8809
8810         /* FIXME: Support generic methods too */
8811         if (method->is_inflated && !mono_method_get_context (method)->method_inst) {
8812                 orig_method = method;
8813                 ctx = &((MonoMethodInflated*)method)->context;
8814                 method = ((MonoMethodInflated*)method)->declaring;
8815                 container = mono_method_get_generic_container (method);
8816                 if (!container)
8817                         container = method->klass->generic_container;
8818                 g_assert (container);
8819         }
8820
8821         /*
8822          * Check cache
8823          */
8824         if (ctx) {
8825                 cache = get_cache (&((MonoMethodInflated*)orig_method)->owner->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
8826                 res = check_generic_wrapper_cache (cache, orig_method, orig_method, method);
8827                 if (res)
8828                         return res;
8829         } else {
8830                 cache = get_cache (&method->klass->image->wrapper_caches.synchronized_cache, mono_aligned_addr_hash, NULL);
8831                 if ((res = mono_marshal_find_in_cache (cache, method)))
8832                         return res;
8833         }
8834
8835         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
8836         sig->pinvoke = 0;
8837
8838         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
8839
8840         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
8841         info->d.synchronized.method = method;
8842
8843 #ifndef DISABLE_JIT
8844         mb->skip_visibility = 1;
8845         /* result */
8846         if (!MONO_TYPE_IS_VOID (sig->ret))
8847                 ret_local = mono_mb_add_local (mb, sig->ret);
8848 #endif
8849
8850         if (method->klass->valuetype && !(method->flags & MONO_METHOD_ATTR_STATIC)) {
8851                 mono_class_set_failure (method->klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
8852 #ifndef DISABLE_JIT
8853                 /* This will throw the type load exception when the wrapper is compiled */
8854                 mono_mb_emit_byte (mb, CEE_LDNULL);
8855                 mono_mb_emit_op (mb, CEE_ISINST, method->klass);
8856                 mono_mb_emit_byte (mb, CEE_POP);
8857
8858                 if (!MONO_TYPE_IS_VOID (sig->ret))
8859                         mono_mb_emit_ldloc (mb, ret_local);
8860                 mono_mb_emit_byte (mb, CEE_RET);
8861 #endif
8862
8863                 res = mono_mb_create_and_cache_full (cache, method,
8864                                                                                          mb, sig, sig->param_count + 16, info, NULL);
8865                 mono_mb_free (mb);
8866
8867                 return res;
8868         }
8869
8870 #ifndef DISABLE_JIT
8871         /* this */
8872         this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
8873         taken_local = mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8874
8875         clause = mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
8876         clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
8877 #endif
8878
8879         mono_marshal_lock ();
8880
8881         if (!enter_method) {
8882                 MonoMethodDesc *desc;
8883
8884                 desc = mono_method_desc_new ("Monitor:enter_with_atomic_var(object,bool&)", FALSE);
8885                 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
8886                 g_assert (enter_method);
8887                 mono_method_desc_free (desc);
8888
8889                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
8890                 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
8891                 g_assert (exit_method);
8892                 mono_method_desc_free (desc);
8893
8894                 desc = mono_method_desc_new ("Type:GetTypeFromHandle", FALSE);
8895                 gettypefromhandle_method = mono_method_desc_search_in_class (desc, mono_defaults.systemtype_class);
8896                 g_assert (gettypefromhandle_method);
8897                 mono_method_desc_free (desc);
8898         }
8899
8900         mono_marshal_unlock ();
8901
8902 #ifndef DISABLE_JIT
8903         /* Push this or the type object */
8904         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
8905                 /* We have special handling for this in the JIT */
8906                 int index = mono_mb_add_data (mb, method->klass);
8907                 mono_mb_add_data (mb, mono_defaults.typehandle_class);
8908                 mono_mb_emit_byte (mb, CEE_LDTOKEN);
8909                 mono_mb_emit_i4 (mb, index);
8910
8911                 mono_mb_emit_managed_call (mb, gettypefromhandle_method, NULL);
8912         }
8913         else
8914                 mono_mb_emit_ldarg (mb, 0);
8915         mono_mb_emit_stloc (mb, this_local);
8916
8917         /* Call Monitor::Enter() */
8918         mono_mb_emit_ldloc (mb, this_local);
8919         mono_mb_emit_ldloc_addr (mb, taken_local);
8920         mono_mb_emit_managed_call (mb, enter_method, NULL);
8921
8922         clause->try_offset = mono_mb_get_label (mb);
8923
8924         /* Call the method */
8925         if (sig->hasthis)
8926                 mono_mb_emit_ldarg (mb, 0);
8927         for (i = 0; i < sig->param_count; i++)
8928                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
8929
8930         if (ctx) {
8931                 MonoError error;
8932                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
8933                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8934         } else {
8935                 mono_mb_emit_managed_call (mb, method, NULL);
8936         }
8937
8938         if (!MONO_TYPE_IS_VOID (sig->ret))
8939                 mono_mb_emit_stloc (mb, ret_local);
8940
8941         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8942
8943         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
8944         clause->handler_offset = mono_mb_get_label (mb);
8945
8946         /* Call Monitor::Exit() if needed */
8947         mono_mb_emit_ldloc (mb, taken_local);
8948         pos2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
8949         mono_mb_emit_ldloc (mb, this_local);
8950         mono_mb_emit_managed_call (mb, exit_method, NULL);
8951         mono_mb_patch_branch (mb, pos2);
8952         mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8953
8954         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
8955
8956         mono_mb_patch_branch (mb, pos);
8957         if (!MONO_TYPE_IS_VOID (sig->ret))
8958                 mono_mb_emit_ldloc (mb, ret_local);
8959         mono_mb_emit_byte (mb, CEE_RET);
8960
8961         mono_mb_set_clauses (mb, 1, clause);
8962 #endif
8963
8964         if (ctx) {
8965                 MonoMethod *def;
8966                 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
8967                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
8968         } else {
8969                 res = mono_mb_create_and_cache_full (cache, method,
8970                                                                                          mb, sig, sig->param_count + 16, info, NULL);
8971         }
8972         mono_mb_free (mb);
8973
8974         return res;     
8975 }
8976
8977
8978 /*
8979  * the returned method calls 'method' unboxing the this argument
8980  */
8981 MonoMethod *
8982 mono_marshal_get_unbox_wrapper (MonoMethod *method)
8983 {
8984         MonoMethodSignature *sig = mono_method_signature (method);
8985         int i;
8986         MonoMethodBuilder *mb;
8987         MonoMethod *res;
8988         GHashTable *cache;
8989         WrapperInfo *info;
8990
8991         cache = get_cache (&mono_method_get_wrapper_cache (method)->unbox_wrapper_cache, mono_aligned_addr_hash, NULL);
8992
8993         if ((res = mono_marshal_find_in_cache (cache, method)))
8994                 return res;
8995
8996         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
8997
8998         g_assert (sig->hasthis);
8999         
9000 #ifndef DISABLE_JIT
9001         mono_mb_emit_ldarg (mb, 0); 
9002         mono_mb_emit_icon (mb, sizeof (MonoObject));
9003         mono_mb_emit_byte (mb, CEE_ADD);
9004         for (i = 0; i < sig->param_count; ++i)
9005                 mono_mb_emit_ldarg (mb, i + 1);
9006         mono_mb_emit_managed_call (mb, method, NULL);
9007         mono_mb_emit_byte (mb, CEE_RET);
9008 #endif
9009
9010         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9011         info->d.unbox.method = method;
9012
9013         res = mono_mb_create_and_cache_full (cache, method,
9014                                                                                  mb, sig, sig->param_count + 16, info, NULL);
9015         mono_mb_free (mb);
9016
9017         /* mono_method_print_code (res); */
9018
9019         return res;     
9020 }
9021
9022 enum {
9023         STELEMREF_OBJECT, /*no check at all*/
9024         STELEMREF_SEALED_CLASS, /*check vtable->klass->element_type */
9025         STELEMREF_CLASS, /*only the klass->parents check*/
9026         STELEMREF_INTERFACE, /*interfaces without variant generic arguments. */
9027         STELEMREF_COMPLEX, /*arrays, MBR or types with variant generic args - go straight to icalls*/
9028         STELEMREF_KIND_COUNT
9029 };
9030
9031 static const char *strelemref_wrapper_name[] = {
9032         "object", "sealed_class", "class", "interface", "complex"
9033 };
9034
9035 static gboolean
9036 is_monomorphic_array (MonoClass *klass)
9037 {
9038         MonoClass *element_class;
9039         if (klass->rank != 1)
9040                 return FALSE;
9041
9042         element_class = klass->element_class;
9043         return (element_class->flags & TYPE_ATTRIBUTE_SEALED) || element_class->valuetype;
9044 }
9045
9046 static int
9047 get_virtual_stelemref_kind (MonoClass *element_class)
9048 {
9049         if (element_class == mono_defaults.object_class)
9050                 return STELEMREF_OBJECT;
9051         if (is_monomorphic_array (element_class))
9052                 return STELEMREF_SEALED_CLASS;
9053         /* Compressed interface bitmaps require code that is quite complex, so don't optimize for it. */
9054         if (MONO_CLASS_IS_INTERFACE (element_class) && !mono_class_has_variant_generic_params (element_class))
9055 #ifdef COMPRESSED_INTERFACE_BITMAP
9056                 return STELEMREF_COMPLEX;
9057 #else
9058                 return STELEMREF_INTERFACE;
9059 #endif
9060         /*Arrays are sealed but are covariant on their element type, We can't use any of the fast paths.*/
9061         if (mono_class_is_marshalbyref (element_class) || element_class->rank || mono_class_has_variant_generic_params (element_class))
9062                 return STELEMREF_COMPLEX;
9063         if (element_class->flags & TYPE_ATTRIBUTE_SEALED)
9064                 return STELEMREF_SEALED_CLASS;
9065         return STELEMREF_CLASS;
9066 }
9067
9068 #ifndef DISABLE_JIT
9069
9070 static void
9071 load_array_element_address (MonoMethodBuilder *mb)
9072 {
9073         mono_mb_emit_ldarg (mb, 0);
9074         mono_mb_emit_ldarg (mb, 1);
9075         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9076 }
9077
9078 static void
9079 load_array_class (MonoMethodBuilder *mb, int aklass)
9080 {
9081         mono_mb_emit_ldarg (mb, 0);
9082         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9083         mono_mb_emit_byte (mb, CEE_LDIND_I);
9084         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9085         mono_mb_emit_byte (mb, CEE_LDIND_I);
9086         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9087         mono_mb_emit_byte (mb, CEE_LDIND_I);
9088         mono_mb_emit_stloc (mb, aklass);
9089 }
9090
9091 static void
9092 load_value_class (MonoMethodBuilder *mb, int vklass)
9093 {
9094         mono_mb_emit_ldarg (mb, 2);
9095         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9096         mono_mb_emit_byte (mb, CEE_LDIND_I);
9097         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9098         mono_mb_emit_byte (mb, CEE_LDIND_I);
9099         mono_mb_emit_stloc (mb, vklass);
9100 }
9101 #endif
9102
9103 #if 0
9104 static void
9105 record_slot_vstore (MonoObject *array, size_t index, MonoObject *value)
9106 {
9107         char *name = mono_type_get_full_name (array->vtable->klass->element_class);
9108         printf ("slow vstore of %s\n", name);
9109         g_free (name);
9110 }
9111 #endif
9112
9113 /*
9114  * The wrapper info for the wrapper is a WrapperInfo structure.
9115  *
9116  * TODO:
9117  *      - Separate simple interfaces from variant interfaces or mbr types. This way we can avoid the icall for them.
9118  *      - Emit a (new) mono bytecode that produces OP_COND_EXC_NE_UN to raise ArrayTypeMismatch
9119  *      - Maybe mve some MonoClass field into the vtable to reduce the number of loads
9120  *      - Add a case for arrays of arrays.
9121  */
9122 static MonoMethod*
9123 get_virtual_stelemref_wrapper (int kind)
9124 {
9125         static MonoMethod *cached_methods [STELEMREF_KIND_COUNT] = { NULL }; /*object iface sealed regular*/
9126         static MonoMethodSignature *signature;
9127         MonoMethodBuilder *mb;
9128         MonoMethod *res;
9129         char *name;
9130         const char *param_names [16];
9131         guint32 b1, b2, b3;
9132         int aklass, vklass, vtable, uiid;
9133         int array_slot_addr;
9134         WrapperInfo *info;
9135
9136         if (cached_methods [kind])
9137                 return cached_methods [kind];
9138
9139         name = g_strdup_printf ("virt_stelemref_%s", strelemref_wrapper_name [kind]);
9140         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STELEMREF);
9141         g_free (name);
9142
9143         if (!signature) {
9144                 MonoMethodSignature *sig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
9145
9146                 /* void this::stelemref (size_t idx, void* value) */
9147                 sig->ret = &mono_defaults.void_class->byval_arg;
9148                 sig->hasthis = TRUE;
9149                 sig->params [0] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9150                 sig->params [1] = &mono_defaults.object_class->byval_arg;
9151                 signature = sig;
9152         }
9153
9154 #ifndef DISABLE_JIT
9155         param_names [0] = "index";
9156         param_names [1] = "value";
9157         mono_mb_set_param_names (mb, param_names);
9158
9159         /*For now simply call plain old stelemref*/
9160         switch (kind) {
9161         case STELEMREF_OBJECT:
9162                 /* ldelema (implicit bound check) */
9163                 load_array_element_address (mb);
9164                 /* do_store */
9165                 mono_mb_emit_ldarg (mb, 2);
9166                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9167                 mono_mb_emit_byte (mb, CEE_RET);
9168                 break;
9169
9170         case STELEMREF_COMPLEX:
9171                 /*
9172                 <ldelema (bound check)>
9173                 if (!value)
9174                         goto store;
9175                 if (!mono_object_isinst (value, aklass))
9176                         goto do_exception;
9177
9178                  do_store:
9179                          *array_slot_addr = value;
9180
9181                 do_exception:
9182                         throw new ArrayTypeMismatchException ();
9183                 */
9184
9185                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9186                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9187
9188 #if 0
9189                 {
9190                         /*Use this to debug/record stores that are going thru the slow path*/
9191                         MonoMethodSignature *csig;
9192                         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9193                         csig->ret = &mono_defaults.void_class->byval_arg;
9194                         csig->params [0] = &mono_defaults.object_class->byval_arg;
9195                         csig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9196                         csig->params [2] = &mono_defaults.object_class->byval_arg;
9197                         mono_mb_emit_ldarg (mb, 0);
9198                         mono_mb_emit_ldarg (mb, 1);
9199                         mono_mb_emit_ldarg (mb, 2);
9200                         mono_mb_emit_native_call (mb, csig, record_slot_vstore);
9201                 }
9202 #endif
9203
9204                 /* ldelema (implicit bound check) */
9205                 load_array_element_address (mb);
9206                 mono_mb_emit_stloc (mb, array_slot_addr);
9207
9208                 /* if (!value) goto do_store */
9209                 mono_mb_emit_ldarg (mb, 2);
9210                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9211
9212                 /* aklass = array->vtable->klass->element_class */
9213                 load_array_class (mb, aklass);
9214
9215                 /*if (mono_object_isinst (value, aklass)) */
9216                 mono_mb_emit_ldarg (mb, 2);
9217                 mono_mb_emit_ldloc (mb, aklass);
9218                 mono_mb_emit_icall (mb, mono_object_isinst);
9219                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9220
9221                 /* do_store: */
9222                 mono_mb_patch_branch (mb, b1);
9223                 mono_mb_emit_ldloc (mb, array_slot_addr);
9224                 mono_mb_emit_ldarg (mb, 2);
9225                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9226                 mono_mb_emit_byte (mb, CEE_RET);
9227
9228                 /* do_exception: */
9229                 mono_mb_patch_branch (mb, b2);
9230
9231                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9232                 break;
9233
9234         case STELEMREF_SEALED_CLASS:
9235                 /*
9236                 <ldelema (bound check)>
9237                 if (!value)
9238                         goto store;
9239
9240                 aklass = array->vtable->klass->element_class;
9241                 vklass = value->vtable->klass;
9242
9243                 if (vklass != aklass)
9244                         goto do_exception;
9245
9246                 do_store:
9247                          *array_slot_addr = value;
9248
9249                 do_exception:
9250                         throw new ArrayTypeMismatchException ();
9251                 */
9252                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9253                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9254                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9255
9256
9257                 /* ldelema (implicit bound check) */
9258                 load_array_element_address (mb);
9259                 mono_mb_emit_stloc (mb, array_slot_addr);
9260
9261                 /* if (!value) goto do_store */
9262                 mono_mb_emit_ldarg (mb, 2);
9263                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9264
9265                 /* aklass = array->vtable->klass->element_class */
9266                 load_array_class (mb, aklass);
9267
9268                 /* vklass = value->vtable->klass */
9269                 load_value_class (mb, vklass);
9270
9271                 /*if (vklass != aklass) goto do_exception; */
9272                 mono_mb_emit_ldloc (mb, aklass);
9273                 mono_mb_emit_ldloc (mb, vklass);
9274                 b2 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9275
9276                 /* do_store: */
9277                 mono_mb_patch_branch (mb, b1);
9278                 mono_mb_emit_ldloc (mb, array_slot_addr);
9279                 mono_mb_emit_ldarg (mb, 2);
9280                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9281                 mono_mb_emit_byte (mb, CEE_RET);
9282
9283                 /* do_exception: */
9284                 mono_mb_patch_branch (mb, b2);
9285                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9286                 break;
9287
9288         case STELEMREF_CLASS:
9289                 /*
9290                 the method:
9291                 <ldelema (bound check)>
9292                 if (!value)
9293                         goto do_store;
9294
9295                 aklass = array->vtable->klass->element_class;
9296                 vklass = value->vtable->klass;
9297
9298                 if (vklass->idepth < aklass->idepth)
9299                         goto do_exception;
9300
9301                 if (vklass->supertypes [aklass->idepth - 1] != aklass)
9302                         goto do_exception;
9303
9304                 do_store:
9305                         *array_slot_addr = value;
9306                         return;
9307
9308                 long:
9309                         throw new ArrayTypeMismatchException ();
9310                 */
9311                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9312                 vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9313                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9314
9315                 /* ldelema (implicit bound check) */
9316                 load_array_element_address (mb);
9317                 mono_mb_emit_stloc (mb, array_slot_addr);
9318
9319                 /* if (!value) goto do_store */
9320                 mono_mb_emit_ldarg (mb, 2);
9321                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9322
9323                 /* aklass = array->vtable->klass->element_class */
9324                 load_array_class (mb, aklass);
9325
9326                 /* vklass = value->vtable->klass */
9327                 load_value_class (mb, vklass);
9328
9329                 /*if (mono_object_isinst (value, aklass)) */
9330                 mono_mb_emit_ldarg (mb, 2);
9331                 mono_mb_emit_ldloc (mb, aklass);
9332                 mono_mb_emit_icall (mb, mono_object_isinst);
9333                 b2 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9334
9335                 /* if (vklass->idepth < aklass->idepth) goto failue */
9336                 mono_mb_emit_ldloc (mb, vklass);
9337                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9338                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9339
9340                 mono_mb_emit_ldloc (mb, aklass);
9341                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9342                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9343
9344                 b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
9345
9346                 /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
9347                 mono_mb_emit_ldloc (mb, vklass);
9348                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
9349                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9350
9351                 mono_mb_emit_ldloc (mb, aklass);
9352                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9353                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9354                 mono_mb_emit_icon (mb, 1);
9355                 mono_mb_emit_byte (mb, CEE_SUB);
9356                 mono_mb_emit_icon (mb, sizeof (void*));
9357                 mono_mb_emit_byte (mb, CEE_MUL);
9358                 mono_mb_emit_byte (mb, CEE_ADD);
9359                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9360
9361                 mono_mb_emit_ldloc (mb, aklass);
9362                 b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9363
9364                 /* do_store: */
9365                 mono_mb_patch_branch (mb, b1);
9366                 mono_mb_emit_ldloc (mb, array_slot_addr);
9367                 mono_mb_emit_ldarg (mb, 2);
9368                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9369                 mono_mb_emit_byte (mb, CEE_RET);
9370
9371                 /* do_exception: */
9372                 mono_mb_patch_branch (mb, b2);
9373                 mono_mb_patch_branch (mb, b3);
9374
9375                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9376                 break;
9377
9378         case STELEMREF_INTERFACE:
9379                 /*Mono *klass;
9380                 MonoVTable *vt;
9381                 unsigned uiid;
9382                 if (value == NULL)
9383                         goto store;
9384
9385                 klass = array->obj.vtable->klass->element_class;
9386                 vt = value->vtable;
9387                 uiid = klass->interface_id;
9388                 if (uiid > vt->max_interface_id)
9389                         goto exception;
9390                 if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7))))
9391                         goto exception;
9392                 store:
9393                         mono_array_setref (array, index, value);
9394                         return;
9395                 exception:
9396                         mono_raise_exception (mono_get_exception_array_type_mismatch ());*/
9397
9398                 array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9399                 aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9400                 vtable = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9401                 uiid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9402
9403                 /* ldelema (implicit bound check) */
9404                 load_array_element_address (mb);
9405                 mono_mb_emit_stloc (mb, array_slot_addr);
9406
9407                 /* if (!value) goto do_store */
9408                 mono_mb_emit_ldarg (mb, 2);
9409                 b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9410
9411                 /* klass = array->vtable->klass->element_class */
9412                 load_array_class (mb, aklass);
9413
9414                 /* vt = value->vtable */
9415                 mono_mb_emit_ldarg (mb, 2);
9416                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9417                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9418                 mono_mb_emit_stloc (mb, vtable);
9419
9420                 /* uiid = klass->interface_id; */
9421                 mono_mb_emit_ldloc (mb, aklass);
9422                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, interface_id));
9423                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9424                 mono_mb_emit_stloc (mb, uiid);
9425
9426                 /*if (uiid > vt->max_interface_id)*/
9427                 mono_mb_emit_ldloc (mb, uiid);
9428                 mono_mb_emit_ldloc (mb, vtable);
9429                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, max_interface_id));
9430                 mono_mb_emit_byte (mb, CEE_LDIND_U2);
9431                 b2 = mono_mb_emit_branch (mb, CEE_BGT_UN);
9432
9433                 /* if (!(vt->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7)))) */
9434
9435                 /*vt->interface_bitmap*/
9436                 mono_mb_emit_ldloc (mb, vtable);
9437                 mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, interface_bitmap));
9438                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9439
9440                 /*uiid >> 3*/
9441                 mono_mb_emit_ldloc (mb, uiid);
9442                 mono_mb_emit_icon (mb, 3);
9443                 mono_mb_emit_byte (mb, CEE_SHR_UN);
9444
9445                 /*vt->interface_bitmap [(uiid) >> 3]*/
9446                 mono_mb_emit_byte (mb, CEE_ADD); /*interface_bitmap is a guint8 array*/
9447                 mono_mb_emit_byte (mb, CEE_LDIND_U1);
9448
9449                 /*(1 << ((uiid)&7)))*/
9450                 mono_mb_emit_icon (mb, 1);
9451                 mono_mb_emit_ldloc (mb, uiid);
9452                 mono_mb_emit_icon (mb, 7);
9453                 mono_mb_emit_byte (mb, CEE_AND);
9454                 mono_mb_emit_byte (mb, CEE_SHL);
9455
9456                 /*bitwise and the whole thing*/
9457                 mono_mb_emit_byte (mb, CEE_AND);
9458                 b3 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9459
9460                 /* do_store: */
9461                 mono_mb_patch_branch (mb, b1);
9462                 mono_mb_emit_ldloc (mb, array_slot_addr);
9463                 mono_mb_emit_ldarg (mb, 2);
9464                 mono_mb_emit_byte (mb, CEE_STIND_REF);
9465                 mono_mb_emit_byte (mb, CEE_RET);
9466
9467                 /* do_exception: */
9468                 mono_mb_patch_branch (mb, b2);
9469                 mono_mb_patch_branch (mb, b3);
9470                 mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9471                 break;
9472
9473         default:
9474                 mono_mb_emit_ldarg (mb, 0);
9475                 mono_mb_emit_ldarg (mb, 1);
9476                 mono_mb_emit_ldarg (mb, 2);
9477                 mono_mb_emit_managed_call (mb, mono_marshal_get_stelemref (), NULL);
9478                 mono_mb_emit_byte (mb, CEE_RET);
9479                 g_assert (0);
9480         }
9481 #endif /* DISABLE_JIT */
9482         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_VIRTUAL_STELEMREF);
9483         info->d.virtual_stelemref.kind = kind;
9484         res = mono_mb_create (mb, signature, 4, info);
9485         res->flags |= METHOD_ATTRIBUTE_VIRTUAL;
9486
9487         mono_marshal_lock ();
9488         if (!cached_methods [kind]) {
9489                 cached_methods [kind] = res;
9490                 mono_marshal_unlock ();
9491         } else {
9492                 mono_marshal_unlock ();
9493                 mono_free_method (res);
9494         }
9495
9496         mono_mb_free (mb);
9497         return cached_methods [kind];
9498 }
9499
9500 MonoMethod*
9501 mono_marshal_get_virtual_stelemref (MonoClass *array_class)
9502 {
9503         int kind;
9504
9505         g_assert (array_class->rank == 1);
9506         kind = get_virtual_stelemref_kind (array_class->element_class);
9507
9508         return get_virtual_stelemref_wrapper (kind);
9509 }
9510
9511 MonoMethod**
9512 mono_marshal_get_virtual_stelemref_wrappers (int *nwrappers)
9513 {
9514         MonoMethod **res;
9515         int i;
9516
9517         *nwrappers = STELEMREF_KIND_COUNT;
9518         res = g_malloc0 (STELEMREF_KIND_COUNT * sizeof (MonoMethod*));
9519         for (i = 0; i < STELEMREF_KIND_COUNT; ++i)
9520                 res [i] = get_virtual_stelemref_wrapper (i);
9521         return res;
9522 }
9523
9524 /*
9525  * The wrapper info for the wrapper is a WrapperInfo structure.
9526  */
9527 MonoMethod*
9528 mono_marshal_get_stelemref (void)
9529 {
9530         static MonoMethod* ret = NULL;
9531         MonoMethodSignature *sig;
9532         MonoMethodBuilder *mb;
9533         WrapperInfo *info;
9534         
9535         guint32 b1, b2, b3, b4;
9536         guint32 copy_pos;
9537         int aklass, vklass;
9538         int array_slot_addr;
9539         
9540         if (ret)
9541                 return ret;
9542         
9543         mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
9544         
9545
9546         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9547
9548         /* void stelemref (void* array, int idx, void* value) */
9549         sig->ret = &mono_defaults.void_class->byval_arg;
9550         sig->params [0] = &mono_defaults.object_class->byval_arg;
9551         sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9552         sig->params [2] = &mono_defaults.object_class->byval_arg;
9553
9554 #ifndef DISABLE_JIT
9555         aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9556         vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9557         array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9558         
9559         /*
9560         the method:
9561         <ldelema (bound check)>
9562         if (!value)
9563                 goto store;
9564         
9565         aklass = array->vtable->klass->element_class;
9566         vklass = value->vtable->klass;
9567         
9568         if (vklass->idepth < aklass->idepth)
9569                 goto long;
9570         
9571         if (vklass->supertypes [aklass->idepth - 1] != aklass)
9572                 goto long;
9573         
9574         store:
9575                 *array_slot_addr = value;
9576                 return;
9577         
9578         long:
9579                 if (mono_object_isinst (value, aklass))
9580                         goto store;
9581                 
9582                 throw new ArrayTypeMismatchException ();
9583         */
9584         
9585         /* ldelema (implicit bound check) */
9586         mono_mb_emit_ldarg (mb, 0);
9587         mono_mb_emit_ldarg (mb, 1);
9588         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9589         mono_mb_emit_stloc (mb, array_slot_addr);
9590                 
9591         /* if (!value) goto do_store */
9592         mono_mb_emit_ldarg (mb, 2);
9593         b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9594         
9595         /* aklass = array->vtable->klass->element_class */
9596         mono_mb_emit_ldarg (mb, 0);
9597         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9598         mono_mb_emit_byte (mb, CEE_LDIND_I);
9599         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9600         mono_mb_emit_byte (mb, CEE_LDIND_I);
9601         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, element_class));
9602         mono_mb_emit_byte (mb, CEE_LDIND_I);
9603         mono_mb_emit_stloc (mb, aklass);
9604         
9605         /* vklass = value->vtable->klass */
9606         mono_mb_emit_ldarg (mb, 2);
9607         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9608         mono_mb_emit_byte (mb, CEE_LDIND_I);
9609         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9610         mono_mb_emit_byte (mb, CEE_LDIND_I);
9611         mono_mb_emit_stloc (mb, vklass);
9612         
9613         /* if (vklass->idepth < aklass->idepth) goto failue */
9614         mono_mb_emit_ldloc (mb, vklass);
9615         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9616         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9617         
9618         mono_mb_emit_ldloc (mb, aklass);
9619         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9620         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9621         
9622         b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
9623         
9624         /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
9625         mono_mb_emit_ldloc (mb, vklass);
9626         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, supertypes));
9627         mono_mb_emit_byte (mb, CEE_LDIND_I);
9628         
9629         mono_mb_emit_ldloc (mb, aklass);
9630         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoClass, idepth));
9631         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9632         mono_mb_emit_icon (mb, 1);
9633         mono_mb_emit_byte (mb, CEE_SUB);
9634         mono_mb_emit_icon (mb, sizeof (void*));
9635         mono_mb_emit_byte (mb, CEE_MUL);
9636         mono_mb_emit_byte (mb, CEE_ADD);
9637         mono_mb_emit_byte (mb, CEE_LDIND_I);
9638         
9639         mono_mb_emit_ldloc (mb, aklass);
9640         
9641         b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9642         
9643         copy_pos = mono_mb_get_label (mb);
9644         /* do_store */
9645         mono_mb_patch_branch (mb, b1);
9646         mono_mb_emit_ldloc (mb, array_slot_addr);
9647         mono_mb_emit_ldarg (mb, 2);
9648         mono_mb_emit_byte (mb, CEE_STIND_REF);
9649         
9650         mono_mb_emit_byte (mb, CEE_RET);
9651         
9652         /* the hard way */
9653         mono_mb_patch_branch (mb, b2);
9654         mono_mb_patch_branch (mb, b3);
9655         
9656         mono_mb_emit_ldarg (mb, 2);
9657         mono_mb_emit_ldloc (mb, aklass);
9658         mono_mb_emit_icall (mb, mono_object_isinst);
9659         
9660         b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
9661         mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
9662         mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9663         
9664         mono_mb_emit_byte (mb, CEE_RET);
9665 #endif
9666         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
9667         ret = mono_mb_create (mb, sig, 4, info);
9668         mono_mb_free (mb);
9669
9670         return ret;
9671 }
9672
9673 /*
9674  * mono_marshal_get_gsharedvt_in_wrapper:
9675  *
9676  *   This wrapper handles calls from normal code to gsharedvt code.
9677  *
9678  * The wrapper info for the wrapper is a WrapperInfo structure.
9679  */
9680 MonoMethod*
9681 mono_marshal_get_gsharedvt_in_wrapper (void)
9682 {
9683         static MonoMethod* ret = NULL;
9684         MonoMethodSignature *sig;
9685         MonoMethodBuilder *mb;
9686         WrapperInfo *info;
9687
9688         if (ret)
9689                 return ret;
9690         
9691         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_in", MONO_WRAPPER_UNKNOWN);
9692         
9693         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
9694         sig->ret = &mono_defaults.void_class->byval_arg;
9695
9696 #ifndef DISABLE_JIT
9697         /*
9698          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
9699          */
9700         mono_mb_emit_byte (mb, CEE_RET);
9701 #endif
9702         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_IN);
9703         ret = mono_mb_create (mb, sig, 4, info);
9704         mono_mb_free (mb);
9705
9706         return ret;
9707 }
9708
9709 /*
9710  * mono_marshal_get_gsharedvt_out_wrapper:
9711  *
9712  *   This wrapper handles calls from gsharedvt code to normal code.
9713  *
9714  * The wrapper info for the wrapper is a WrapperInfo structure.
9715  */
9716 MonoMethod*
9717 mono_marshal_get_gsharedvt_out_wrapper (void)
9718 {
9719         static MonoMethod* ret = NULL;
9720         MonoMethodSignature *sig;
9721         MonoMethodBuilder *mb;
9722         WrapperInfo *info;
9723
9724         if (ret)
9725                 return ret;
9726         
9727         mb = mono_mb_new (mono_defaults.object_class, "gsharedvt_out", MONO_WRAPPER_UNKNOWN);
9728         
9729         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
9730         sig->ret = &mono_defaults.void_class->byval_arg;
9731
9732 #ifndef DISABLE_JIT
9733         /*
9734          * The body is generated by the JIT, we use a wrapper instead of a trampoline so EH works.
9735          */
9736         mono_mb_emit_byte (mb, CEE_RET);
9737 #endif
9738         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GSHAREDVT_OUT);
9739         ret = mono_mb_create (mb, sig, 4, info);
9740         mono_mb_free (mb);
9741
9742         return ret;
9743 }
9744
9745 typedef struct {
9746         int rank;
9747         int elem_size;
9748         MonoMethod *method;
9749 } ArrayElemAddr;
9750
9751 /* LOCKING: vars accessed under the marshal lock */
9752 static ArrayElemAddr *elem_addr_cache = NULL;
9753 static int elem_addr_cache_size = 0;
9754 static int elem_addr_cache_next = 0;
9755
9756 /**
9757  * mono_marshal_get_array_address:
9758  * @rank: rank of the array type
9759  * @elem_size: size in bytes of an element of an array.
9760  *
9761  * Returns a MonoMethod that implements the code to get the address
9762  * of an element in a multi-dimenasional array of @rank dimensions.
9763  * The returned method takes an array as the first argument and then
9764  * @rank indexes for the @rank dimensions.
9765  * If ELEM_SIZE is 0, read the array size from the array object.
9766  */
9767 MonoMethod*
9768 mono_marshal_get_array_address (int rank, int elem_size)
9769 {
9770         MonoMethod *ret;
9771         MonoMethodBuilder *mb;
9772         MonoMethodSignature *sig;
9773         WrapperInfo *info;
9774         char *name;
9775         int i, bounds, ind, realidx;
9776         int branch_pos, *branch_positions;
9777         int cached;
9778
9779         ret = NULL;
9780         mono_marshal_lock ();
9781         for (i = 0; i < elem_addr_cache_next; ++i) {
9782                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
9783                         ret = elem_addr_cache [i].method;
9784                         break;
9785                 }
9786         }
9787         mono_marshal_unlock ();
9788         if (ret)
9789                 return ret;
9790
9791         branch_positions = g_new0 (int, rank);
9792
9793         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1 + rank);
9794
9795         /* void* address (void* array, int idx0, int idx1, int idx2, ...) */
9796         sig->ret = &mono_defaults.int_class->byval_arg;
9797         sig->params [0] = &mono_defaults.object_class->byval_arg;
9798         for (i = 0; i < rank; ++i) {
9799                 sig->params [i + 1] = &mono_defaults.int32_class->byval_arg;
9800         }
9801
9802         name = g_strdup_printf ("ElementAddr_%d", elem_size);
9803         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
9804         g_free (name);
9805         
9806 #ifndef DISABLE_JIT
9807         bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9808         ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9809         realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9810
9811         /* bounds = array->bounds; */
9812         mono_mb_emit_ldarg (mb, 0);
9813         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, bounds));
9814         mono_mb_emit_byte (mb, CEE_LDIND_I);
9815         mono_mb_emit_stloc (mb, bounds);
9816
9817         /* ind is the overall element index, realidx is the partial index in a single dimension */
9818         /* ind = idx0 - bounds [0].lower_bound */
9819         mono_mb_emit_ldarg (mb, 1);
9820         mono_mb_emit_ldloc (mb, bounds);
9821         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
9822         mono_mb_emit_byte (mb, CEE_ADD);
9823         mono_mb_emit_byte (mb, CEE_LDIND_I4);
9824         mono_mb_emit_byte (mb, CEE_SUB);
9825         mono_mb_emit_stloc (mb, ind);
9826         /* if (ind >= bounds [0].length) goto exeception; */
9827         mono_mb_emit_ldloc (mb, ind);
9828         mono_mb_emit_ldloc (mb, bounds);
9829         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
9830         mono_mb_emit_byte (mb, CEE_ADD);
9831         mono_mb_emit_byte (mb, CEE_LDIND_I4);
9832         /* note that we use unsigned comparison */
9833         branch_pos = mono_mb_emit_branch (mb, CEE_BGE_UN);
9834
9835         /* For large ranks (> 4?) use a loop n IL later to reduce code size.
9836          * We could also decide to ignore the passed elem_size and get it
9837          * from the array object, to reduce the number of methods we generate:
9838          * the additional cost is 3 memory loads and a non-immediate mul.
9839          */
9840         for (i = 1; i < rank; ++i) {
9841                 /* realidx = idxi - bounds [i].lower_bound */
9842                 mono_mb_emit_ldarg (mb, 1 + i);
9843                 mono_mb_emit_ldloc (mb, bounds);
9844                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
9845                 mono_mb_emit_byte (mb, CEE_ADD);
9846                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9847                 mono_mb_emit_byte (mb, CEE_SUB);
9848                 mono_mb_emit_stloc (mb, realidx);
9849                 /* if (realidx >= bounds [i].length) goto exeception; */
9850                 mono_mb_emit_ldloc (mb, realidx);
9851                 mono_mb_emit_ldloc (mb, bounds);
9852                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
9853                 mono_mb_emit_byte (mb, CEE_ADD);
9854                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9855                 branch_positions [i] = mono_mb_emit_branch (mb, CEE_BGE_UN);
9856                 /* ind = ind * bounds [i].length + realidx */
9857                 mono_mb_emit_ldloc (mb, ind);
9858                 mono_mb_emit_ldloc (mb, bounds);
9859                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
9860                 mono_mb_emit_byte (mb, CEE_ADD);
9861                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9862                 mono_mb_emit_byte (mb, CEE_MUL);
9863                 mono_mb_emit_ldloc (mb, realidx);
9864                 mono_mb_emit_byte (mb, CEE_ADD);
9865                 mono_mb_emit_stloc (mb, ind);
9866         }
9867
9868         /* return array->vector + ind * element_size */
9869         mono_mb_emit_ldarg (mb, 0);
9870         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, vector));
9871         mono_mb_emit_ldloc (mb, ind);
9872         if (elem_size) {
9873                 mono_mb_emit_icon (mb, elem_size);
9874         } else {
9875                 /* Load arr->vtable->klass->sizes.element_class */
9876                 mono_mb_emit_ldarg (mb, 0);
9877                 mono_mb_emit_byte (mb, CEE_CONV_I);
9878                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
9879                 mono_mb_emit_byte (mb, CEE_ADD);
9880                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9881                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
9882                 mono_mb_emit_byte (mb, CEE_ADD);
9883                 mono_mb_emit_byte (mb, CEE_LDIND_I);
9884                 /* sizes is an union, so this reads sizes.element_size */
9885                 mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
9886                 mono_mb_emit_byte (mb, CEE_ADD);
9887                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9888         }
9889                 mono_mb_emit_byte (mb, CEE_MUL);
9890         mono_mb_emit_byte (mb, CEE_ADD);
9891         mono_mb_emit_byte (mb, CEE_RET);
9892
9893         /* patch the branches to get here and throw */
9894         for (i = 1; i < rank; ++i) {
9895                 mono_mb_patch_branch (mb, branch_positions [i]);
9896         }
9897         mono_mb_patch_branch (mb, branch_pos);
9898         /* throw exception */
9899         mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
9900
9901         g_free (branch_positions);
9902 #endif /* DISABLE_JIT */
9903
9904         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ELEMENT_ADDR);
9905         info->d.element_addr.rank = rank;
9906         info->d.element_addr.elem_size = elem_size;
9907         ret = mono_mb_create (mb, sig, 4, info);
9908         mono_mb_free (mb);
9909
9910         /* cache the result */
9911         cached = 0;
9912         mono_marshal_lock ();
9913         for (i = 0; i < elem_addr_cache_next; ++i) {
9914                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
9915                         /* FIXME: free ret */
9916                         ret = elem_addr_cache [i].method;
9917                         cached = TRUE;
9918                         break;
9919                 }
9920         }
9921         if (!cached) {
9922                 if (elem_addr_cache_next >= elem_addr_cache_size) {
9923                         int new_size = elem_addr_cache_size + 4;
9924                         ArrayElemAddr *new_array = g_new0 (ArrayElemAddr, new_size);
9925                         memcpy (new_array, elem_addr_cache, elem_addr_cache_size * sizeof (ArrayElemAddr));
9926                         g_free (elem_addr_cache);
9927                         elem_addr_cache = new_array;
9928                         elem_addr_cache_size = new_size;
9929                 }
9930                 elem_addr_cache [elem_addr_cache_next].rank = rank;
9931                 elem_addr_cache [elem_addr_cache_next].elem_size = elem_size;
9932                 elem_addr_cache [elem_addr_cache_next].method = ret;
9933                 elem_addr_cache_next ++;
9934         }
9935         mono_marshal_unlock ();
9936         return ret;
9937 }
9938
9939 /*
9940  * mono_marshal_get_array_accessor_wrapper:
9941  *
9942  *   Return a wrapper which just calls METHOD, which should be an Array Get/Set/Address method.
9943  */
9944 MonoMethod *
9945 mono_marshal_get_array_accessor_wrapper (MonoMethod *method)
9946 {
9947         MonoMethodSignature *sig;
9948         MonoMethodBuilder *mb;
9949         MonoMethod *res;
9950         GHashTable *cache;
9951         int i;
9952         MonoGenericContext *ctx = NULL;
9953         MonoMethod *orig_method = NULL;
9954         MonoGenericContainer *container = NULL;
9955         WrapperInfo *info;
9956
9957         /*
9958          * These wrappers are needed to avoid the JIT replacing the calls to these methods with intrinsics
9959          * inside runtime invoke wrappers, thereby making the wrappers not unshareable.
9960          * FIXME: Use generic methods.
9961          */
9962         /*
9963          * Check cache
9964          */
9965         if (ctx) {
9966                 cache = NULL;
9967                 g_assert_not_reached ();
9968         } else {
9969                 cache = get_cache (&method->klass->image->array_accessor_cache, mono_aligned_addr_hash, NULL);
9970                 if ((res = mono_marshal_find_in_cache (cache, method)))
9971                         return res;
9972         }
9973
9974         sig = mono_metadata_signature_dup_full (method->klass->image, mono_method_signature (method));
9975         sig->pinvoke = 0;
9976
9977         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNKNOWN);
9978
9979 #ifndef DISABLE_JIT
9980         /* Call the method */
9981         if (sig->hasthis)
9982                 mono_mb_emit_ldarg (mb, 0);
9983         for (i = 0; i < sig->param_count; i++)
9984                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
9985
9986         if (ctx) {
9987                 MonoError error;
9988                 mono_mb_emit_managed_call (mb, mono_class_inflate_generic_method_checked (method, &container->context, &error), NULL);
9989                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9990         } else {
9991                 mono_mb_emit_managed_call (mb, method, NULL);
9992         }
9993         mono_mb_emit_byte (mb, CEE_RET);
9994 #endif
9995
9996         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_ARRAY_ACCESSOR);
9997         info->d.array_accessor.method = method;
9998
9999         if (ctx) {
10000                 MonoMethod *def;
10001                 def = mono_mb_create_and_cache_full (cache, method, mb, sig, sig->param_count + 16, info, NULL);
10002                 res = cache_generic_wrapper (cache, orig_method, def, ctx, orig_method);
10003         } else {
10004                 res = mono_mb_create_and_cache_full (cache, method,
10005                                                                                          mb, sig, sig->param_count + 16,
10006                                                                                          info, NULL);
10007         }
10008         mono_mb_free (mb);
10009
10010         return res;     
10011 }
10012
10013 void*
10014 mono_marshal_alloc (gulong size)
10015 {
10016         gpointer res;
10017
10018 #ifdef HOST_WIN32
10019         res = CoTaskMemAlloc (size);
10020 #else
10021         res = g_try_malloc ((gulong)size);
10022         if (!res)
10023                 mono_gc_out_of_memory ((gulong)size);
10024 #endif
10025         return res;
10026 }
10027
10028 void
10029 mono_marshal_free (gpointer ptr)
10030 {
10031 #ifdef HOST_WIN32
10032         CoTaskMemFree (ptr);
10033 #else
10034         g_free (ptr);
10035 #endif
10036 }
10037
10038 void
10039 mono_marshal_free_array (gpointer *ptr, int size) 
10040 {
10041         int i;
10042
10043         if (!ptr)
10044                 return;
10045
10046         for (i = 0; i < size; i++)
10047                 if (ptr [i])
10048                         g_free (ptr [i]);
10049 }
10050
10051 void *
10052 mono_marshal_string_to_utf16 (MonoString *s)
10053 {
10054         return s ? mono_string_chars (s) : NULL;
10055 }
10056
10057 static void *
10058 mono_marshal_string_to_utf16_copy (MonoString *s)
10059 {
10060         if (s == NULL) {
10061                 return NULL;
10062         } else {
10063                 gunichar2 *res = mono_marshal_alloc ((mono_string_length (s) * 2) + 2);
10064                 memcpy (res, mono_string_chars (s), mono_string_length (s) * 2);
10065                 res [mono_string_length (s)] = 0;
10066                 return res;
10067         }
10068 }
10069
10070 /**
10071  * mono_marshal_set_last_error:
10072  *
10073  * This function is invoked to set the last error value from a P/Invoke call
10074  * which has SetLastError set.
10075  */
10076 void
10077 mono_marshal_set_last_error (void)
10078 {
10079 #ifdef WIN32
10080         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
10081 #else
10082         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (errno));
10083 #endif
10084 }
10085
10086 static void
10087 mono_marshal_set_last_error_windows (int error)
10088 {
10089 #ifdef WIN32
10090         mono_native_tls_set_value (last_error_tls_id, GINT_TO_POINTER (error));
10091 #endif
10092 }
10093
10094 void
10095 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
10096                                                                     gpointer dest, gint32 length)
10097 {
10098         int element_size;
10099         void *source_addr;
10100
10101         MONO_CHECK_ARG_NULL (src,);
10102         MONO_CHECK_ARG_NULL (dest,);
10103
10104         if (src->obj.vtable->klass->rank != 1) {
10105                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10106                 return;
10107         }
10108         if (start_index < 0) {
10109                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10110                 return;
10111         }
10112         if (length < 0) {
10113                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10114                 return;
10115         }
10116         if (start_index + length > mono_array_length (src)) {
10117                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10118                 return;
10119         }
10120
10121         element_size = mono_array_element_size (src->obj.vtable->klass);
10122
10123         /* no references should be involved */
10124         source_addr = mono_array_addr_with_size_fast (src, element_size, start_index);
10125
10126         memcpy (dest, source_addr, length * element_size);
10127 }
10128
10129 void
10130 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
10131                                                                       MonoArray *dest, gint32 length)
10132 {
10133         int element_size;
10134         void *dest_addr;
10135
10136         MONO_CHECK_ARG_NULL (src,);
10137         MONO_CHECK_ARG_NULL (dest,);
10138
10139         if (dest->obj.vtable->klass->rank != 1) {
10140                 mono_set_pending_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
10141                 return;
10142         }
10143         if (start_index < 0) {
10144                 mono_set_pending_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
10145                 return;
10146         }
10147         if (length < 0) {
10148                 mono_set_pending_exception (mono_get_exception_argument ("length", "Must be >= 0"));
10149                 return;
10150         }
10151         if (start_index + length > mono_array_length (dest)) {
10152                 mono_set_pending_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
10153                 return;
10154         }
10155         element_size = mono_array_element_size (dest->obj.vtable->klass);
10156           
10157         /* no references should be involved */
10158         dest_addr = mono_array_addr_with_size_fast (dest, element_size, start_index);
10159
10160         memcpy (dest_addr, src, length * element_size);
10161 }
10162
10163 MonoString *
10164 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr)
10165 {
10166         if (ptr == NULL)
10167                 return NULL;
10168         else
10169                 return mono_string_new (mono_domain_get (), ptr);
10170 }
10171
10172 MonoString *
10173 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
10174 {
10175         if (ptr == NULL) {
10176                 mono_set_pending_exception (mono_get_exception_argument_null ("ptr"));
10177                 return NULL;
10178         } else {
10179                 return mono_string_new_len (mono_domain_get (), ptr, len);
10180         }
10181 }
10182
10183 MonoString *
10184 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
10185 {
10186         MonoDomain *domain = mono_domain_get (); 
10187         int len = 0;
10188         guint16 *t = ptr;
10189
10190         if (ptr == NULL)
10191                 return NULL;
10192
10193         while (*t++)
10194                 len++;
10195
10196         return mono_string_new_utf16 (domain, ptr, len);
10197 }
10198
10199 MonoString *
10200 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
10201 {
10202         MonoDomain *domain = mono_domain_get (); 
10203
10204         if (ptr == NULL) {
10205                 mono_set_pending_exception (mono_get_exception_argument_null ("ptr"));
10206                 return NULL;
10207         } else {
10208                 return mono_string_new_utf16 (domain, ptr, len);
10209         }
10210 }
10211
10212 guint32 
10213 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
10214 {
10215         return (GPOINTER_TO_INT (mono_native_tls_get_value (last_error_tls_id)));
10216 }
10217
10218 guint32 
10219 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionType *rtype)
10220 {
10221         MonoClass *klass;
10222         MonoType *type;
10223         guint32 layout;
10224
10225         MONO_CHECK_ARG_NULL (rtype, 0);
10226
10227         type = rtype->type;
10228         klass = mono_class_from_mono_type (type);
10229         if (!mono_class_init (klass)) {
10230                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10231                 return 0;
10232         }
10233
10234         layout = (klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK);
10235
10236         if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
10237                 return sizeof (gpointer);
10238         } else if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
10239                 gchar *msg;
10240                 MonoException *exc;
10241
10242                 msg = g_strdup_printf ("Type %s cannot be marshaled as an unmanaged structure.", klass->name);
10243                 exc = mono_get_exception_argument ("t", msg);
10244                 g_free (msg);
10245                 mono_set_pending_exception (exc);
10246                 return 0;
10247         }
10248
10249         return mono_class_native_size (klass, NULL);
10250 }
10251
10252 void
10253 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
10254 {
10255         MonoMethod *method;
10256         gpointer pa [3];
10257
10258         MONO_CHECK_ARG_NULL (obj,);
10259         MONO_CHECK_ARG_NULL (dst,);
10260
10261         method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
10262
10263         pa [0] = obj;
10264         pa [1] = &dst;
10265         pa [2] = &delete_old;
10266
10267         mono_runtime_invoke (method, NULL, pa, NULL);
10268 }
10269
10270 static void
10271 ptr_to_structure (gpointer src, MonoObject *dst)
10272 {
10273         MonoMethod *method;
10274         gpointer pa [2];
10275
10276         method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
10277
10278         pa [0] = &src;
10279         pa [1] = dst;
10280
10281         mono_runtime_invoke (method, NULL, pa, NULL);
10282 }
10283
10284 void
10285 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
10286 {
10287         MonoType *t;
10288
10289         MONO_CHECK_ARG_NULL (src,);
10290         MONO_CHECK_ARG_NULL (dst,);
10291         
10292         t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
10293
10294         if (t->type == MONO_TYPE_VALUETYPE) {
10295                 MonoException *exc;
10296                 gchar *tmp;
10297
10298                 tmp = g_strdup_printf ("Destination is a boxed value type.");
10299                 exc = mono_get_exception_argument ("dst", tmp);
10300                 g_free (tmp);  
10301
10302                 mono_set_pending_exception (exc);
10303                 return;
10304         }
10305
10306         ptr_to_structure (src, dst);
10307 }
10308
10309 MonoObject *
10310 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
10311 {
10312         MonoClass *klass;
10313         MonoDomain *domain = mono_domain_get (); 
10314         MonoObject *res;
10315
10316         if (src == NULL)
10317                 return NULL;
10318         MONO_CHECK_ARG_NULL (type, NULL);
10319
10320         klass = mono_class_from_mono_type (type->type);
10321         if (!mono_class_init (klass)) {
10322                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10323                 return NULL;
10324         }
10325
10326         res = mono_object_new (domain, klass);
10327
10328         ptr_to_structure (src, res);
10329
10330         return res;
10331 }
10332
10333 int
10334 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *type, MonoString *field_name)
10335 {
10336         MonoMarshalType *info;
10337         MonoClass *klass;
10338         char *fname;
10339         int match_index = -1;
10340         
10341         MONO_CHECK_ARG_NULL (type, 0);
10342         MONO_CHECK_ARG_NULL (field_name, 0);
10343
10344         fname = mono_string_to_utf8 (field_name);
10345         klass = mono_class_from_mono_type (type->type);
10346         if (!mono_class_init (klass)) {
10347                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10348                 return 0;
10349         }
10350
10351         while (klass && match_index == -1) {
10352                 MonoClassField* field;
10353                 int i = 0;
10354                 gpointer iter = NULL;
10355                 while ((field = mono_class_get_fields (klass, &iter))) {
10356                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10357                                 continue;
10358                         if (!strcmp (fname, mono_field_get_name (field))) {
10359                                 match_index = i;
10360                                 break;
10361                         }
10362                         i ++;
10363                 }
10364
10365                 if (match_index == -1)
10366                         klass = klass->parent;
10367         }
10368
10369         g_free (fname);
10370
10371         if(match_index == -1) {
10372                 MonoException* exc;
10373                 gchar *tmp;
10374
10375                 /* Get back original class instance */
10376                 klass = mono_class_from_mono_type (type->type);
10377
10378                 tmp = g_strdup_printf ("Field passed in is not a marshaled member of the type %s", klass->name);
10379                 exc = mono_get_exception_argument ("fieldName", tmp);
10380                 g_free (tmp);
10381  
10382                 mono_set_pending_exception ((MonoException*)exc);
10383                 return 0;
10384         }
10385
10386         info = mono_marshal_load_type_info (klass);     
10387         return info->fields [match_index].offset;
10388 }
10389
10390 gpointer
10391 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
10392 {
10393 #ifdef HOST_WIN32
10394         char* tres, *ret;
10395         size_t len;
10396         tres = mono_string_to_utf8 (string);
10397         if (!tres)
10398                 return tres;
10399
10400         len = strlen (tres) + 1;
10401         ret = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (len);
10402         memcpy (ret, tres, len);
10403         g_free (tres);
10404         return ret;
10405
10406 #else
10407         return mono_string_to_utf8 (string);
10408 #endif
10409 }
10410
10411 gpointer
10412 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
10413 {
10414         if (string == NULL)
10415                 return NULL;
10416         else {
10417 #ifdef TARGET_WIN32
10418                 gunichar2 *res = ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal 
10419                         ((mono_string_length (string) + 1) * 2);
10420 #else
10421                 gunichar2 *res = g_malloc ((mono_string_length (string) + 1) * 2);              
10422 #endif
10423                 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
10424                 res [mono_string_length (string)] = 0;
10425                 return res;
10426         }
10427 }
10428
10429 static void
10430 mono_struct_delete_old (MonoClass *klass, char *ptr)
10431 {
10432         MonoMarshalType *info;
10433         int i;
10434
10435         info = mono_marshal_load_type_info (klass);
10436
10437         for (i = 0; i < info->num_fields; i++) {
10438                 MonoMarshalConv conv;
10439                 MonoType *ftype = info->fields [i].field->type;
10440                 char *cpos;
10441
10442                 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
10443                         continue;
10444
10445                 mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, 
10446                                 klass->unicode, &conv);
10447                         
10448                 cpos = ptr + info->fields [i].offset;
10449
10450                 switch (conv) {
10451                 case MONO_MARSHAL_CONV_NONE:
10452                         if (MONO_TYPE_ISSTRUCT (ftype)) {
10453                                 mono_struct_delete_old (ftype->data.klass, cpos);
10454                                 continue;
10455                         }
10456                         break;
10457                 case MONO_MARSHAL_CONV_STR_LPWSTR:
10458                         /* We assume this field points inside a MonoString */
10459                         break;
10460                 case MONO_MARSHAL_CONV_STR_LPTSTR:
10461 #ifdef TARGET_WIN32
10462                         /* We assume this field points inside a MonoString 
10463                          * on Win32 */
10464                         break;
10465 #endif
10466                 case MONO_MARSHAL_CONV_STR_LPSTR:
10467                 case MONO_MARSHAL_CONV_STR_BSTR:
10468                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
10469                 case MONO_MARSHAL_CONV_STR_TBSTR:
10470                         mono_marshal_free (*(gpointer *)cpos);
10471                         break;
10472
10473                 default:
10474                         continue;
10475                 }
10476         }
10477 }
10478
10479 void
10480 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
10481 {
10482         MonoClass *klass;
10483
10484         MONO_CHECK_ARG_NULL (src,);
10485         MONO_CHECK_ARG_NULL (type,);
10486
10487         klass = mono_class_from_mono_type (type->type);
10488         if (!mono_class_init (klass)) {
10489                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10490                 return;
10491         }
10492
10493         mono_struct_delete_old (klass, (char *)src);
10494 }
10495
10496 void*
10497 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (gpointer size)
10498 {
10499         gpointer res;
10500         size_t s = (size_t)size;
10501
10502         if (s == 0)
10503                 /* This returns a valid pointer for size 0 on MS.NET */
10504                 s = 4;
10505
10506 #ifdef HOST_WIN32
10507         res = GlobalAlloc (GMEM_FIXED, s);
10508 #else
10509         res = g_try_malloc (s);
10510 #endif
10511         if (!res)
10512                 mono_gc_out_of_memory (s);
10513
10514         return res;
10515 }
10516
10517 gpointer
10518 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocHGlobal (gpointer ptr, gpointer size)
10519 {
10520         gpointer res;
10521         size_t s = (size_t)size;
10522
10523         if (ptr == NULL) {
10524                 mono_gc_out_of_memory (s);
10525                 return NULL;
10526         }
10527
10528 #ifdef HOST_WIN32
10529         res = GlobalReAlloc (ptr, s, GMEM_MOVEABLE);
10530 #else
10531         res = g_try_realloc (ptr, s);
10532 #endif
10533         if (!res)
10534                 mono_gc_out_of_memory (s);
10535
10536         return res;
10537 }
10538
10539 void
10540 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
10541 {
10542 #ifdef HOST_WIN32
10543         GlobalFree (ptr);
10544 #else
10545         g_free (ptr);
10546 #endif
10547 }
10548
10549 void*
10550 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
10551 {
10552         void *res;
10553
10554 #ifdef HOST_WIN32
10555         res = CoTaskMemAlloc (size);
10556 #else
10557         if ((gulong)size == 0)
10558                 /* This returns a valid pointer for size 0 on MS.NET */
10559                 size = 4;
10560
10561         res = g_try_malloc ((gulong)size);
10562 #endif
10563         if (!res)
10564                 mono_gc_out_of_memory ((gulong)size);
10565         return res;
10566 }
10567
10568 void
10569 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
10570 {
10571 #ifdef HOST_WIN32
10572         CoTaskMemFree (ptr);
10573 #else
10574         g_free (ptr);
10575 #endif
10576 }
10577
10578 gpointer
10579 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
10580 {
10581         void *res;
10582
10583 #ifdef HOST_WIN32
10584         res = CoTaskMemRealloc (ptr, size);
10585 #else
10586         res = g_try_realloc (ptr, (gulong)size);
10587 #endif
10588         if (!res)
10589                 mono_gc_out_of_memory ((gulong)size);
10590         return res;
10591 }
10592
10593 void*
10594 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
10595 {
10596         return mono_array_addr_with_size_fast (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
10597 }
10598
10599 MonoDelegate*
10600 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionType *type)
10601 {
10602         MonoClass *klass = mono_type_get_class (type->type);
10603         if (!mono_class_init (klass)) {
10604                 mono_set_pending_exception (mono_class_get_exception_for_failure (klass));
10605                 return NULL;
10606         }
10607
10608         return mono_ftnptr_to_delegate (klass, ftn);
10609 }
10610
10611 /**
10612  * mono_marshal_is_loading_type_info:
10613  *
10614  *  Return whenever mono_marshal_load_type_info () is being executed for KLASS by this
10615  * thread.
10616  */
10617 static gboolean
10618 mono_marshal_is_loading_type_info (MonoClass *klass)
10619 {
10620         GSList *loads_list = mono_native_tls_get_value (load_type_info_tls_id);
10621
10622         return g_slist_find (loads_list, klass) != NULL;
10623 }
10624
10625 /**
10626  * mono_marshal_load_type_info:
10627  *
10628  *  Initialize klass->marshal_info using information from metadata. This function can
10629  * recursively call itself, and the caller is responsible to avoid that by calling 
10630  * mono_marshal_is_loading_type_info () beforehand.
10631  *
10632  * LOCKING: Acquires the loader lock.
10633  */
10634 MonoMarshalType *
10635 mono_marshal_load_type_info (MonoClass* klass)
10636 {
10637         int j, count = 0;
10638         guint32 native_size = 0, min_align = 1, packing;
10639         MonoMarshalType *info;
10640         MonoClassField* field;
10641         gpointer iter;
10642         guint32 layout;
10643         GSList *loads_list;
10644
10645         g_assert (klass != NULL);
10646
10647         if (klass->marshal_info)
10648                 return klass->marshal_info;
10649
10650         if (!klass->inited)
10651                 mono_class_init (klass);
10652
10653         if (klass->marshal_info)
10654                 return klass->marshal_info;
10655
10656         /*
10657          * This function can recursively call itself, so we keep the list of classes which are
10658          * under initialization in a TLS list.
10659          */
10660         g_assert (!mono_marshal_is_loading_type_info (klass));
10661         loads_list = mono_native_tls_get_value (load_type_info_tls_id);
10662         loads_list = g_slist_prepend (loads_list, klass);
10663         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
10664         
10665         iter = NULL;
10666         while ((field = mono_class_get_fields (klass, &iter))) {
10667                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10668                         continue;
10669                 if (mono_field_is_deleted (field))
10670                         continue;
10671                 count++;
10672         }
10673
10674         layout = klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
10675
10676         /* The mempool is protected by the loader lock */
10677         info = mono_image_alloc0 (klass->image, MONO_SIZEOF_MARSHAL_TYPE + sizeof (MonoMarshalField) * count);
10678         info->num_fields = count;
10679         
10680         /* Try to find a size for this type in metadata */
10681         mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
10682
10683         if (klass->parent) {
10684                 int parent_size = mono_class_native_size (klass->parent, NULL);
10685
10686                 /* Add parent size to real size */
10687                 native_size += parent_size;
10688                 info->native_size = parent_size;
10689         }
10690
10691         packing = klass->packing_size ? klass->packing_size : 8;
10692         iter = NULL;
10693         j = 0;
10694         while ((field = mono_class_get_fields (klass, &iter))) {
10695                 int size;
10696                 guint32 align;
10697                 
10698                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10699                         continue;
10700
10701                 if (mono_field_is_deleted (field))
10702                         continue;
10703                 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
10704                         mono_metadata_field_info_with_mempool (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1, 
10705                                                   NULL, NULL, &info->fields [j].mspec);
10706
10707                 info->fields [j].field = field;
10708
10709                 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
10710                         (strcmp (mono_field_get_name (field), "$PRIVATE$") == 0)) {
10711                         /* This field is a hack inserted by MCS to empty structures */
10712                         continue;
10713                 }
10714
10715                 switch (layout) {
10716                 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
10717                 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
10718                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
10719                                                        &align, TRUE, klass->unicode);
10720                         align = klass->packing_size ? MIN (klass->packing_size, align): align;
10721                         min_align = MAX (align, min_align);
10722                         info->fields [j].offset = info->native_size;
10723                         info->fields [j].offset += align - 1;
10724                         info->fields [j].offset &= ~(align - 1);
10725                         info->native_size = info->fields [j].offset + size;
10726                         break;
10727                 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
10728                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
10729                                                        &align, TRUE, klass->unicode);
10730                         min_align = MAX (align, min_align);
10731                         info->fields [j].offset = field->offset - sizeof (MonoObject);
10732                         info->native_size = MAX (info->native_size, info->fields [j].offset + size);
10733                         break;
10734                 }       
10735                 j++;
10736         }
10737
10738         if (layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
10739                 info->native_size = MAX (native_size, info->native_size);
10740                 /*
10741                  * If the provided Size is equal or larger than the calculated size, and there
10742                  * was no Pack attribute, we set min_align to 1 to avoid native_size being increased
10743                  */
10744                 if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
10745                         if (native_size && native_size == info->native_size && klass->packing_size == 0)
10746                                 min_align = 1;
10747                         else
10748                                 min_align = MIN (min_align, packing);
10749                 }
10750         }
10751
10752         if (info->native_size & (min_align - 1)) {
10753                 info->native_size += min_align - 1;
10754                 info->native_size &= ~(min_align - 1);
10755         }
10756
10757         info->min_align = min_align;
10758
10759         /* Update the class's blittable info, if the layouts don't match */
10760         if (info->native_size != mono_class_value_size (klass, NULL))
10761                 klass->blittable = FALSE;
10762
10763         /* If this is an array type, ensure that we have element info */
10764         if (klass->rank && !mono_marshal_is_loading_type_info (klass->element_class)) {
10765                 mono_marshal_load_type_info (klass->element_class);
10766         }
10767
10768         loads_list = mono_native_tls_get_value (load_type_info_tls_id);
10769         loads_list = g_slist_remove (loads_list, klass);
10770         mono_native_tls_set_value (load_type_info_tls_id, loads_list);
10771
10772         mono_marshal_lock ();
10773         if (!klass->marshal_info) {
10774                 /*We do double-checking locking on marshal_info */
10775                 mono_memory_barrier ();
10776                 klass->marshal_info = info;
10777         }
10778         mono_marshal_unlock ();
10779
10780         return klass->marshal_info;
10781 }
10782
10783 /**
10784  * mono_class_native_size:
10785  * @klass: a class 
10786  * 
10787  * Returns: the native size of an object instance (when marshaled 
10788  * to unmanaged code) 
10789  */
10790 gint32
10791 mono_class_native_size (MonoClass *klass, guint32 *align)
10792 {       
10793         if (!klass->marshal_info) {
10794                 if (mono_marshal_is_loading_type_info (klass)) {
10795                         if (align)
10796                                 *align = 0;
10797                         return 0;
10798                 } else {
10799                         mono_marshal_load_type_info (klass);
10800                 }
10801         }
10802
10803         if (align)
10804                 *align = klass->marshal_info->min_align;
10805
10806         return klass->marshal_info->native_size;
10807 }
10808
10809 /*
10810  * mono_type_native_stack_size:
10811  * @t: the type to return the size it uses on the stack
10812  *
10813  * Returns: the number of bytes required to hold an instance of this
10814  * type on the native stack
10815  */
10816 int
10817 mono_type_native_stack_size (MonoType *t, guint32 *align)
10818 {
10819         guint32 tmp;
10820
10821         g_assert (t != NULL);
10822
10823         if (!align)
10824                 align = &tmp;
10825
10826         if (t->byref) {
10827                 *align = sizeof (gpointer);
10828                 return sizeof (gpointer);
10829         }
10830
10831         switch (t->type){
10832         case MONO_TYPE_BOOLEAN:
10833         case MONO_TYPE_CHAR:
10834         case MONO_TYPE_I1:
10835         case MONO_TYPE_U1:
10836         case MONO_TYPE_I2:
10837         case MONO_TYPE_U2:
10838         case MONO_TYPE_I4:
10839         case MONO_TYPE_U4:
10840                 *align = 4;
10841                 return 4;
10842         case MONO_TYPE_I:
10843         case MONO_TYPE_U:
10844         case MONO_TYPE_STRING:
10845         case MONO_TYPE_OBJECT:
10846         case MONO_TYPE_CLASS:
10847         case MONO_TYPE_SZARRAY:
10848         case MONO_TYPE_PTR:
10849         case MONO_TYPE_FNPTR:
10850         case MONO_TYPE_ARRAY:
10851                 *align = sizeof (gpointer);
10852                 return sizeof (gpointer);
10853         case MONO_TYPE_R4:
10854                 *align = 4;
10855                 return 4;
10856         case MONO_TYPE_R8:
10857                 *align = MONO_ABI_ALIGNOF (double);
10858                 return 8;
10859         case MONO_TYPE_I8:
10860         case MONO_TYPE_U8:
10861                 *align = MONO_ABI_ALIGNOF (gint64);
10862                 return 8;
10863         case MONO_TYPE_GENERICINST:
10864                 if (!mono_type_generic_inst_is_valuetype (t)) {
10865                         *align = sizeof (gpointer);
10866                         return sizeof (gpointer);
10867                 } 
10868                 /* Fall through */
10869         case MONO_TYPE_TYPEDBYREF:
10870         case MONO_TYPE_VALUETYPE: {
10871                 guint32 size;
10872                 MonoClass *klass = mono_class_from_mono_type (t);
10873
10874                 if (klass->enumtype)
10875                         return mono_type_native_stack_size (mono_class_enum_basetype (klass), align);
10876                 else {
10877                         size = mono_class_native_size (klass, align);
10878                         *align = *align + 3;
10879                         *align &= ~3;
10880                         
10881                         size +=  3;
10882                         size &= ~3;
10883
10884                         return size;
10885                 }
10886         }
10887         default:
10888                 g_error ("type 0x%02x unknown", t->type);
10889         }
10890         return 0;
10891 }
10892
10893 gint32
10894 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
10895                         gboolean as_field, gboolean unicode)
10896 {
10897         MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
10898         MonoClass *klass;
10899
10900         switch (native_type) {
10901         case MONO_NATIVE_BOOLEAN:
10902                 *align = 4;
10903                 return 4;
10904         case MONO_NATIVE_I1:
10905         case MONO_NATIVE_U1:
10906                 *align = 1;
10907                 return 1;
10908         case MONO_NATIVE_I2:
10909         case MONO_NATIVE_U2:
10910         case MONO_NATIVE_VARIANTBOOL:
10911                 *align = 2;
10912                 return 2;
10913         case MONO_NATIVE_I4:
10914         case MONO_NATIVE_U4:
10915         case MONO_NATIVE_ERROR:
10916                 *align = 4;
10917                 return 4;
10918         case MONO_NATIVE_I8:
10919         case MONO_NATIVE_U8:
10920                 *align = MONO_ABI_ALIGNOF (gint64);
10921                 return 8;
10922         case MONO_NATIVE_R4:
10923                 *align = 4;
10924                 return 4;
10925         case MONO_NATIVE_R8:
10926                 *align = MONO_ABI_ALIGNOF (double);
10927                 return 8;
10928         case MONO_NATIVE_INT:
10929         case MONO_NATIVE_UINT:
10930         case MONO_NATIVE_LPSTR:
10931         case MONO_NATIVE_LPWSTR:
10932         case MONO_NATIVE_LPTSTR:
10933         case MONO_NATIVE_BSTR:
10934         case MONO_NATIVE_ANSIBSTR:
10935         case MONO_NATIVE_TBSTR:
10936         case MONO_NATIVE_LPARRAY:
10937         case MONO_NATIVE_SAFEARRAY:
10938         case MONO_NATIVE_IUNKNOWN:
10939         case MONO_NATIVE_IDISPATCH:
10940         case MONO_NATIVE_INTERFACE:
10941         case MONO_NATIVE_ASANY:
10942         case MONO_NATIVE_FUNC:
10943         case MONO_NATIVE_LPSTRUCT:
10944                 *align = MONO_ABI_ALIGNOF (gpointer);
10945                 return sizeof (gpointer);
10946         case MONO_NATIVE_STRUCT: 
10947                 klass = mono_class_from_mono_type (type);
10948                 if (klass == mono_defaults.object_class &&
10949                         (mspec && mspec->native == MONO_NATIVE_STRUCT)) {
10950                 *align = 16;
10951                 return 16;
10952                 }
10953                 return mono_class_native_size (klass, align);
10954         case MONO_NATIVE_BYVALTSTR: {
10955                 int esize = unicode ? 2: 1;
10956                 g_assert (mspec);
10957                 *align = esize;
10958                 return mspec->data.array_data.num_elem * esize;
10959         }
10960         case MONO_NATIVE_BYVALARRAY: {
10961                 // FIXME: Have to consider ArraySubType
10962                 int esize;
10963                 klass = mono_class_from_mono_type (type);
10964                 if (klass->element_class == mono_defaults.char_class) {
10965                         esize = unicode ? 2 : 1;
10966                         *align = esize;
10967                 } else {
10968                         esize = mono_class_native_size (klass->element_class, align);
10969                 }
10970                 g_assert (mspec);
10971                 return mspec->data.array_data.num_elem * esize;
10972         }
10973         case MONO_NATIVE_CUSTOM:
10974                 *align = sizeof (gpointer);
10975                 return sizeof (gpointer);
10976                 break;
10977         case MONO_NATIVE_CURRENCY:
10978         case MONO_NATIVE_VBBYREFSTR:
10979         default:
10980                 g_error ("native type %02x not implemented", native_type); 
10981                 break;
10982         }
10983         g_assert_not_reached ();
10984         return 0;
10985 }
10986
10987 gpointer
10988 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
10989 {
10990         MonoType *t;
10991         MonoClass *klass;
10992
10993         if (o == NULL)
10994                 return NULL;
10995
10996         t = &o->vtable->klass->byval_arg;
10997         switch (t->type) {
10998         case MONO_TYPE_I4:
10999         case MONO_TYPE_U4:
11000         case MONO_TYPE_PTR:
11001         case MONO_TYPE_I1:
11002         case MONO_TYPE_U1:
11003         case MONO_TYPE_BOOLEAN:
11004         case MONO_TYPE_I2:
11005         case MONO_TYPE_U2:
11006         case MONO_TYPE_CHAR:
11007         case MONO_TYPE_I8:
11008         case MONO_TYPE_U8:
11009         case MONO_TYPE_R4:
11010         case MONO_TYPE_R8:
11011                 return mono_object_unbox (o);
11012                 break;
11013         case MONO_TYPE_STRING:
11014                 switch (string_encoding) {
11015                 case MONO_NATIVE_LPWSTR:
11016                         return mono_marshal_string_to_utf16_copy ((MonoString*)o);
11017                         break;
11018                 case MONO_NATIVE_LPSTR:
11019                         return mono_string_to_lpstr ((MonoString*)o);
11020                         break;
11021                 default:
11022                         g_warning ("marshaling conversion %d not implemented", string_encoding);
11023                         g_assert_not_reached ();
11024                 }
11025                 break;
11026         case MONO_TYPE_CLASS:
11027         case MONO_TYPE_VALUETYPE: {
11028                 MonoMethod *method;
11029                 gpointer pa [3];
11030                 gpointer res;
11031                 MonoBoolean delete_old = FALSE;
11032
11033                 klass = t->data.klass;
11034
11035                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
11036                         break;
11037
11038                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
11039                         klass->blittable || klass->enumtype))
11040                         return mono_object_unbox (o);
11041
11042                 res = mono_marshal_alloc (mono_class_native_size (klass, NULL));
11043
11044                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11045                         method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
11046
11047                         pa [0] = o;
11048                         pa [1] = &res;
11049                         pa [2] = &delete_old;
11050
11051                         mono_runtime_invoke (method, NULL, pa, NULL);
11052                 }
11053
11054                 return res;
11055         }
11056         default:
11057                 break;
11058         }
11059         mono_raise_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
11060         return NULL;
11061 }
11062
11063 void
11064 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
11065 {
11066         MonoType *t;
11067         MonoClass *klass;
11068
11069         if (o == NULL)
11070                 return;
11071
11072         t = &o->vtable->klass->byval_arg;
11073         switch (t->type) {
11074         case MONO_TYPE_STRING:
11075                 switch (string_encoding) {
11076                 case MONO_NATIVE_LPWSTR:
11077                 case MONO_NATIVE_LPSTR:
11078                         mono_marshal_free (ptr);
11079                         break;
11080                 default:
11081                         g_warning ("marshaling conversion %d not implemented", string_encoding);
11082                         g_assert_not_reached ();
11083                 }
11084                 break;
11085         case MONO_TYPE_CLASS:
11086         case MONO_TYPE_VALUETYPE: {
11087                 klass = t->data.klass;
11088
11089                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
11090                                                                  klass->blittable || klass->enumtype))
11091                         break;
11092
11093                 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
11094                         MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
11095                         gpointer pa [2];
11096
11097                         pa [0] = &ptr;
11098                         pa [1] = o;
11099
11100                         mono_runtime_invoke (method, NULL, pa, NULL);
11101                 }
11102
11103                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
11104                         mono_struct_delete_old (klass, ptr);
11105                 }
11106
11107                 mono_marshal_free (ptr);
11108                 break;
11109         }
11110         default:
11111                 break;
11112         }
11113 }
11114
11115 MonoMethod *
11116 mono_marshal_get_generic_array_helper (MonoClass *klass, MonoClass *iface, gchar *name, MonoMethod *method)
11117 {
11118         MonoMethodSignature *sig, *csig;
11119         MonoMethodBuilder *mb;
11120         MonoMethod *res;
11121         WrapperInfo *info;
11122         int i;
11123
11124         mb = mono_mb_new_no_dup_name (klass, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
11125         mb->method->slot = -1;
11126
11127         mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
11128                 METHOD_ATTRIBUTE_NEW_SLOT | METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
11129
11130         sig = mono_method_signature (method);
11131         csig = mono_metadata_signature_dup_full (method->klass->image, sig);
11132         csig->generic_param_count = 0;
11133
11134 #ifndef DISABLE_JIT
11135         mono_mb_emit_ldarg (mb, 0);
11136         for (i = 0; i < csig->param_count; i++)
11137                 mono_mb_emit_ldarg (mb, i + 1);
11138         mono_mb_emit_managed_call (mb, method, NULL);
11139         mono_mb_emit_byte (mb, CEE_RET);
11140
11141         /* We can corlib internal methods */
11142         mb->skip_visibility = TRUE;
11143 #endif
11144         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER);
11145         info->d.generic_array_helper.method = method;
11146         res = mono_mb_create (mb, csig, csig->param_count + 16, info);
11147
11148         mono_mb_free (mb);
11149
11150         return res;
11151 }
11152
11153 /*
11154  * The mono_win32_compat_* functions are implementations of inline
11155  * Windows kernel32 APIs, which are DllImport-able under MS.NET,
11156  * although not exported by kernel32.
11157  *
11158  * We map the appropiate kernel32 entries to these functions using
11159  * dllmaps declared in the global etc/mono/config.
11160  */
11161
11162 void
11163 mono_win32_compat_CopyMemory (gpointer dest, gconstpointer source, gsize length)
11164 {
11165         if (!dest || !source)
11166                 return;
11167
11168         memcpy (dest, source, length);
11169 }
11170
11171 void
11172 mono_win32_compat_FillMemory (gpointer dest, gsize length, guchar fill)
11173 {
11174         memset (dest, fill, length);
11175 }
11176
11177 void
11178 mono_win32_compat_MoveMemory (gpointer dest, gconstpointer source, gsize length)
11179 {
11180         if (!dest || !source)
11181                 return;
11182
11183         memmove (dest, source, length);
11184 }
11185
11186 void
11187 mono_win32_compat_ZeroMemory (gpointer dest, gsize length)
11188 {
11189         memset (dest, 0, length);
11190 }
11191
11192 void
11193 mono_marshal_find_nonzero_bit_offset (guint8 *buf, int len, int *byte_offset, guint8 *bitmask)
11194 {
11195         int i;
11196         guint8 byte;
11197
11198         for (i = 0; i < len; ++i)
11199                 if (buf [i])
11200                         break;
11201
11202         g_assert (i < len);
11203
11204         byte = buf [i];
11205         while (byte && !(byte & 1))
11206                 byte >>= 1;
11207         g_assert (byte == 1);
11208
11209         *byte_offset = i;
11210         *bitmask = buf [i];
11211 }
11212
11213 MonoMethod *
11214 mono_marshal_get_thunk_invoke_wrapper (MonoMethod *method)
11215 {
11216         MonoMethodBuilder *mb;
11217         MonoMethodSignature *sig, *csig;
11218         MonoExceptionClause *clause;
11219         MonoImage *image;
11220         MonoClass *klass;
11221         GHashTable *cache;
11222         MonoMethod *res;
11223         int i, param_count, sig_size, pos_leave;
11224         int coop_gc_var, coop_gc_dummy_local;
11225
11226         g_assert (method);
11227
11228         klass = method->klass;
11229         image = method->klass->image;
11230
11231         cache = get_cache (&mono_method_get_wrapper_cache (method)->thunk_invoke_cache, mono_aligned_addr_hash, NULL);
11232
11233         if ((res = mono_marshal_find_in_cache (cache, method)))
11234                 return res;
11235
11236         sig = mono_method_signature (method);
11237         mb = mono_mb_new (klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
11238
11239         /* add "this" and exception param */
11240         param_count = sig->param_count + sig->hasthis + 1;
11241
11242         /* dup & extend signature */
11243         csig = mono_metadata_signature_alloc (image, param_count);
11244         sig_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *);
11245         memcpy (csig, sig, sig_size);
11246         csig->param_count = param_count;
11247         csig->hasthis = 0;
11248         csig->pinvoke = 1;
11249         csig->call_convention = MONO_CALL_DEFAULT;
11250
11251         if (sig->hasthis) {
11252                 /* add "this" */
11253                 csig->params [0] = &klass->byval_arg;
11254                 /* move params up by one */
11255                 for (i = 0; i < sig->param_count; i++)
11256                         csig->params [i + 1] = sig->params [i];
11257         }
11258
11259         /* setup exception param as byref+[out] */
11260         csig->params [param_count - 1] = mono_metadata_type_dup (image,
11261                  &mono_defaults.exception_class->byval_arg);
11262         csig->params [param_count - 1]->byref = 1;
11263         csig->params [param_count - 1]->attrs = PARAM_ATTRIBUTE_OUT;
11264
11265         /* convert struct return to object */
11266         if (MONO_TYPE_ISSTRUCT (sig->ret))
11267                 csig->ret = &mono_defaults.object_class->byval_arg;
11268
11269 #ifndef DISABLE_JIT
11270         /* local 0 (temp for exception object) */
11271         mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
11272
11273         /* local 1 (temp for result) */
11274         if (!MONO_TYPE_IS_VOID (sig->ret))
11275                 mono_mb_add_local (mb, sig->ret);
11276
11277         if (mono_threads_is_coop_enabled ()) {
11278                 /* local 4, the local to be used when calling the reset_blocking funcs */
11279                 /* tons of code hardcode 3 to be the return var */
11280                 coop_gc_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
11281                 /* local 5, the local used to get a stack address for suspend funcs */
11282                 coop_gc_dummy_local = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
11283         }
11284
11285         /* clear exception arg */
11286         mono_mb_emit_ldarg (mb, param_count - 1);
11287         mono_mb_emit_byte (mb, CEE_LDNULL);
11288         mono_mb_emit_byte (mb, CEE_STIND_REF);
11289
11290         if (mono_threads_is_coop_enabled ()) {
11291                 /* FIXME this is technically wrong as the callback itself must be executed in gc unsafe context. */
11292                 mono_mb_emit_ldloc_addr (mb, coop_gc_dummy_local);
11293                 mono_mb_emit_icall (mb, mono_threads_reset_blocking_start);
11294                 mono_mb_emit_stloc (mb, coop_gc_var);
11295         }
11296
11297         /* try */
11298         clause = mono_image_alloc0 (image, sizeof (MonoExceptionClause));
11299         clause->try_offset = mono_mb_get_label (mb);
11300
11301         /* push method's args */
11302         for (i = 0; i < param_count - 1; i++) {
11303                 MonoType *type;
11304                 MonoClass *klass;
11305
11306                 mono_mb_emit_ldarg (mb, i);
11307
11308                 /* get the byval type of the param */
11309                 klass = mono_class_from_mono_type (csig->params [i]);
11310                 type = &klass->byval_arg;
11311
11312                 /* unbox struct args */
11313                 if (MONO_TYPE_ISSTRUCT (type)) {
11314                         mono_mb_emit_op (mb, CEE_UNBOX, klass);
11315
11316                         /* byref args & and the "this" arg must remain a ptr.
11317                            Otherwise make a copy of the value type */
11318                         if (!(csig->params [i]->byref || (i == 0 && sig->hasthis)))
11319                                 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
11320
11321                         csig->params [i] = &mono_defaults.object_class->byval_arg;
11322                 }
11323         }
11324
11325         /* call */
11326         if (method->flags & METHOD_ATTRIBUTE_VIRTUAL)
11327                 mono_mb_emit_op (mb, CEE_CALLVIRT, method);
11328         else
11329                 mono_mb_emit_op (mb, CEE_CALL, method);
11330
11331         /* save result at local 1 */
11332         if (!MONO_TYPE_IS_VOID (sig->ret))
11333                 mono_mb_emit_stloc (mb, 1);
11334
11335         pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
11336
11337         /* catch */
11338         clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
11339         clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
11340         clause->data.catch_class = mono_defaults.object_class;
11341
11342         clause->handler_offset = mono_mb_get_label (mb);
11343
11344         /* store exception at local 0 */
11345         mono_mb_emit_stloc (mb, 0);
11346         mono_mb_emit_ldarg (mb, param_count - 1);
11347         mono_mb_emit_ldloc (mb, 0);
11348         mono_mb_emit_byte (mb, CEE_STIND_REF);
11349         mono_mb_emit_branch (mb, CEE_LEAVE);
11350
11351         clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
11352
11353         mono_mb_set_clauses (mb, 1, clause);
11354
11355         mono_mb_patch_branch (mb, pos_leave);
11356         /* end-try */
11357
11358         if (!MONO_TYPE_IS_VOID (sig->ret)) {
11359                 mono_mb_emit_ldloc (mb, 1);
11360
11361                 /* box the return value */
11362                 if (MONO_TYPE_ISSTRUCT (sig->ret))
11363                         mono_mb_emit_op (mb, CEE_BOX, mono_class_from_mono_type (sig->ret));
11364         }
11365
11366         if (mono_threads_is_coop_enabled ()) {
11367                 /* XXX merge reset_blocking_end with detach */
11368                 mono_mb_emit_ldloc (mb, coop_gc_var);
11369                 mono_mb_emit_ldloc_addr (mb, coop_gc_dummy_local);
11370                 mono_mb_emit_icall (mb, mono_threads_reset_blocking_end);
11371         }
11372
11373         mono_mb_emit_byte (mb, CEE_RET);
11374 #endif
11375
11376         res = mono_mb_create_and_cache (cache, method, mb, csig, param_count + 16);
11377         mono_mb_free (mb);
11378
11379         return res;
11380 }
11381
11382 /*
11383  * mono_marshal_free_dynamic_wrappers:
11384  *
11385  *   Free wrappers of the dynamic method METHOD.
11386  */
11387 void
11388 mono_marshal_free_dynamic_wrappers (MonoMethod *method)
11389 {
11390         MonoImage *image = method->klass->image;
11391
11392         g_assert (method_is_dynamic (method));
11393
11394         /* This could be called during shutdown */
11395         if (marshal_mutex_initialized)
11396                 mono_marshal_lock ();
11397         /* 
11398          * FIXME: We currently leak the wrappers. Freeing them would be tricky as
11399          * they could be shared with other methods ?
11400          */
11401         if (image->wrapper_caches.runtime_invoke_direct_cache)
11402                 g_hash_table_remove (image->wrapper_caches.runtime_invoke_direct_cache, method);
11403         if (image->wrapper_caches.delegate_abstract_invoke_cache)
11404                 g_hash_table_foreach_remove (image->wrapper_caches.delegate_abstract_invoke_cache, signature_pointer_pair_matches_pointer, method);
11405         // FIXME: Need to clear the caches in other images as well
11406         if (image->delegate_bound_static_invoke_cache)
11407                 g_hash_table_remove (image->delegate_bound_static_invoke_cache, mono_method_signature (method));
11408
11409         if (marshal_mutex_initialized)
11410                 mono_marshal_unlock ();
11411 }