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