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