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