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