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