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