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