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