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