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