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