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