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