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