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