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