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