40937175dc7080d9b628f6c76eaf4cd8caedf5cd
[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         
3308         mono_domain_assemblies_lock (domain);
3309         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
3310                 ass = tmp->data;
3311                 if (ass->image == image)
3312                         break;
3313         }
3314         mono_domain_assemblies_unlock (domain);
3315         
3316         return tmp != NULL;
3317 }
3318
3319 /* mono_marshal_get_xappdomain_dispatch ()
3320  * Generates a method that dispatches a method call from another domain into
3321  * the current domain.
3322  */
3323 static MonoMethod *
3324 mono_marshal_get_xappdomain_dispatch (MonoMethod *method, int *marshal_types, int complex_count, int complex_out_count, int ret_marshal_type)
3325 {
3326         MonoMethodSignature *sig, *csig;
3327         MonoMethodBuilder *mb;
3328         MonoMethod *res;
3329         int i, j, param_index, copy_locals_base;
3330         MonoClass *ret_class = NULL;
3331         int loc_array=0, loc_return=0, loc_serialized_exc=0;
3332         MonoExceptionClause *main_clause;
3333         MonoMethodHeader *header;
3334         int pos, pos_leave;
3335         gboolean copy_return;
3336
3337         if ((res = mono_marshal_remoting_find_in_cache (method, MONO_WRAPPER_XDOMAIN_DISPATCH)))
3338                 return res;
3339
3340         sig = mono_method_signature (method);
3341         copy_return = (sig->ret->type != MONO_TYPE_VOID && ret_marshal_type != MONO_MARSHAL_SERIALIZE);
3342
3343         j = 0;
3344         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3 + sig->param_count - complex_count);
3345         csig->params [j++] = &mono_defaults.object_class->byval_arg;
3346         csig->params [j++] = &byte_array_class->this_arg;
3347         csig->params [j++] = &byte_array_class->this_arg;
3348         for (i = 0; i < sig->param_count; i++) {
3349                 if (marshal_types [i] != MONO_MARSHAL_SERIALIZE)
3350                         csig->params [j++] = sig->params [i];
3351         }
3352         if (copy_return)
3353                 csig->ret = sig->ret;
3354         else
3355                 csig->ret = &mono_defaults.void_class->byval_arg;
3356         csig->pinvoke = 1;
3357         csig->hasthis = FALSE;
3358
3359         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_XDOMAIN_DISPATCH);
3360         mb->method->save_lmf = 1;
3361
3362         /* Locals */
3363
3364         loc_serialized_exc = mono_mb_add_local (mb, &byte_array_class->byval_arg);
3365         if (complex_count > 0)
3366                 loc_array = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3367         if (sig->ret->type != MONO_TYPE_VOID) {
3368                 loc_return = mono_mb_add_local (mb, sig->ret);
3369                 ret_class = mono_class_from_mono_type (sig->ret);
3370         }
3371
3372         /* try */
3373
3374         main_clause = g_new0 (MonoExceptionClause, 1);
3375         main_clause->try_offset = mb->pos;
3376
3377         /* Clean the call context */
3378
3379         mono_mb_emit_byte (mb, CEE_LDNULL);
3380         mono_mb_emit_managed_call (mb, method_set_call_context, NULL);
3381         mono_mb_emit_byte (mb, CEE_POP);
3382
3383         /* Deserialize call data */
3384
3385         mono_mb_emit_ldarg (mb, 1);
3386         mono_mb_emit_byte (mb, CEE_LDIND_REF);
3387         mono_mb_emit_byte (mb, CEE_DUP);
3388         pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
3389         
3390         mono_marshal_emit_xdomain_copy_value (mb, byte_array_class);
3391         mono_mb_emit_managed_call (mb, method_rs_deserialize, NULL);
3392         
3393         if (complex_count > 0)
3394                 mono_mb_emit_stloc (mb, loc_array);
3395         else
3396                 mono_mb_emit_byte (mb, CEE_POP);
3397
3398         mono_mb_patch_addr_s (mb, pos, mb->pos - (pos + 1));
3399
3400         /* Get the target object */
3401         
3402         mono_mb_emit_ldarg (mb, 0);
3403         mono_mb_emit_managed_call (mb, method_rs_appdomain_target, NULL);
3404
3405         /* Load the arguments */
3406         
3407         copy_locals_base = mb->locals;
3408         param_index = 3;        // Index of the first non-serialized parameter of this wrapper
3409         j = 0;
3410         for (i = 0; i < sig->param_count; i++) {
3411                 MonoType *pt = sig->params [i];
3412                 MonoClass *pclass = mono_class_from_mono_type (pt);
3413                 switch (marshal_types [i]) {
3414                 case MONO_MARSHAL_SERIALIZE: {
3415                         /* take the value from the serialized array */
3416                         mono_mb_emit_ldloc (mb, loc_array);
3417                         mono_mb_emit_icon (mb, j++);
3418                         if (pt->byref) {
3419                                 if (pclass->valuetype) {
3420                                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
3421                                         mono_mb_emit_op (mb, CEE_UNBOX, pclass);
3422                                 } else {
3423                                         mono_mb_emit_op (mb, CEE_LDELEMA, pclass);
3424                                 }
3425                         } else {
3426                                 if (pclass->valuetype) {
3427                                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
3428                                         mono_mb_emit_op (mb, CEE_UNBOX, pclass);
3429                                         mono_mb_emit_op (mb, CEE_LDOBJ, pclass);
3430                                 } else {
3431                                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
3432                                         if (pclass != mono_defaults.object_class) {
3433                                                 mono_mb_emit_op (mb, CEE_CASTCLASS, pclass);
3434                                         }
3435                                 }
3436                         }
3437                         break;
3438                 }
3439                 case MONO_MARSHAL_COPY_OUT: {
3440                         /* Keep a local copy of the value since we need to copy it back after the call */
3441                         int copy_local = mono_mb_add_local (mb, &(pclass->byval_arg));
3442                         mono_mb_emit_ldarg (mb, param_index++);
3443                         mono_marshal_emit_xdomain_copy_value (mb, pclass);
3444                         mono_mb_emit_byte (mb, CEE_DUP);
3445                         mono_mb_emit_stloc (mb, copy_local);
3446                         break;
3447                 }
3448                 case MONO_MARSHAL_COPY: {
3449                         mono_mb_emit_ldarg (mb, param_index);
3450                         if (pt->byref) {
3451                                 mono_mb_emit_byte (mb, CEE_DUP);
3452                                 mono_mb_emit_byte (mb, CEE_DUP);
3453                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
3454                                 mono_marshal_emit_xdomain_copy_value (mb, pclass);
3455                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
3456                         } else {
3457                                 mono_marshal_emit_xdomain_copy_value (mb, pclass);
3458                         }
3459                         param_index++;
3460                         break;
3461                 }
3462                 case MONO_MARSHAL_NONE:
3463                         mono_mb_emit_ldarg (mb, param_index++);
3464                         break;
3465                 }
3466         }
3467
3468         /* Make the call to the real object */
3469
3470         emit_thread_force_interrupt_checkpoint (mb);
3471         
3472         mono_mb_emit_op (mb, CEE_CALLVIRT, method);
3473
3474         if (sig->ret->type != MONO_TYPE_VOID)
3475                 mono_mb_emit_stloc (mb, loc_return);
3476
3477         /* copy back MONO_MARSHAL_COPY_OUT parameters */
3478
3479         j = 0;
3480         param_index = 3;
3481         for (i = 0; i < sig->param_count; i++) {
3482                 if (marshal_types [i] == MONO_MARSHAL_SERIALIZE) continue;
3483                 if (marshal_types [i] == MONO_MARSHAL_COPY_OUT) {
3484                         mono_mb_emit_ldloc (mb, copy_locals_base + (j++));
3485                         mono_mb_emit_ldarg (mb, param_index);
3486                         mono_marshal_emit_xdomain_copy_out_value (mb, mono_class_from_mono_type (sig->params [i]));
3487                 }
3488                 param_index++;
3489         }
3490
3491         /* Serialize the return values */
3492         
3493         if (complex_out_count > 0) {
3494                 /* Reset parameters in the array that don't need to be serialized back */
3495                 j = 0;
3496                 for (i = 0; i < sig->param_count; i++) {
3497                         if (marshal_types[i] != MONO_MARSHAL_SERIALIZE) continue;
3498                         if (!sig->params [i]->byref) {
3499                                 mono_mb_emit_ldloc (mb, loc_array);
3500                                 mono_mb_emit_icon (mb, j);
3501                                 mono_mb_emit_byte (mb, CEE_LDNULL);
3502                                 mono_mb_emit_byte (mb, CEE_STELEM_REF);
3503                         }
3504                         j++;
3505                 }
3506         
3507                 /* Add the return value to the array */
3508         
3509                 if (ret_marshal_type == MONO_MARSHAL_SERIALIZE) {
3510                         mono_mb_emit_ldloc (mb, loc_array);
3511                         mono_mb_emit_icon (mb, complex_count);  /* The array has an additional slot to hold the ret value */
3512                         mono_mb_emit_ldloc (mb, loc_return);
3513                         if (ret_class->valuetype) {
3514                                 mono_mb_emit_op (mb, CEE_BOX, ret_class);
3515                         }
3516                         mono_mb_emit_byte (mb, CEE_STELEM_REF);
3517                 }
3518         
3519                 /* Serialize */
3520         
3521                 mono_mb_emit_ldarg (mb, 1);
3522                 mono_mb_emit_ldloc (mb, loc_array);
3523                 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
3524                 mono_mb_emit_byte (mb, CEE_STIND_REF);
3525         } else if (ret_marshal_type == MONO_MARSHAL_SERIALIZE) {
3526                 mono_mb_emit_ldarg (mb, 1);
3527                 mono_mb_emit_ldloc (mb, loc_return);
3528                 if (ret_class->valuetype) {
3529                         mono_mb_emit_op (mb, CEE_BOX, ret_class);
3530                 }
3531                 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
3532                 mono_mb_emit_byte (mb, CEE_STIND_REF);
3533         } else {
3534                 mono_mb_emit_ldarg (mb, 1);
3535                 mono_mb_emit_byte (mb, CEE_LDNULL);
3536                 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
3537                 mono_mb_emit_byte (mb, CEE_STIND_REF);
3538         }
3539
3540         mono_mb_emit_ldarg (mb, 2);
3541         mono_mb_emit_byte (mb, CEE_LDNULL);
3542         mono_mb_emit_byte (mb, CEE_STIND_REF);
3543         pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
3544
3545         /* Main exception catch */
3546         main_clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
3547         main_clause->try_len = mb->pos - main_clause->try_offset;
3548         main_clause->data.catch_class = mono_defaults.object_class;
3549         
3550         /* handler code */
3551         main_clause->handler_offset = mb->pos;
3552         mono_mb_emit_managed_call (mb, method_rs_serialize_exc, NULL);
3553         mono_mb_emit_stloc (mb, loc_serialized_exc);
3554         mono_mb_emit_ldarg (mb, 2);
3555         mono_mb_emit_ldloc (mb, loc_serialized_exc);
3556         mono_mb_emit_byte (mb, CEE_STIND_REF);
3557         mono_mb_emit_branch (mb, CEE_LEAVE);
3558         main_clause->handler_len = mb->pos - main_clause->handler_offset;
3559         /* end catch */
3560
3561         mono_mb_patch_addr (mb, pos_leave, mb->pos - (pos_leave + 4));
3562         
3563         if (copy_return)
3564                 mono_mb_emit_ldloc (mb, loc_return);
3565
3566         mono_mb_emit_byte (mb, CEE_RET);
3567
3568         res = mono_remoting_mb_create_and_cache (method, mb, csig, csig->param_count + 16);
3569         mono_mb_free (mb);
3570
3571         header = ((MonoMethodNormal *)res)->header;
3572         header->num_clauses = 1;
3573         header->clauses = main_clause;
3574
3575         return res;
3576 }
3577
3578 /* mono_marshal_get_xappdomain_invoke ()
3579  * Generates a fast remoting wrapper for cross app domain calls.
3580  */
3581 MonoMethod *
3582 mono_marshal_get_xappdomain_invoke (MonoMethod *method)
3583 {
3584         MonoMethodSignature *sig;
3585         MonoMethodBuilder *mb;
3586         MonoMethod *res;
3587         int i, j, complex_count, complex_out_count, copy_locals_base;
3588         int *marshal_types;
3589         MonoClass *ret_class = NULL;
3590         MonoMethod *xdomain_method;
3591         int ret_marshal_type = MONO_MARSHAL_NONE;
3592         int loc_array=0, loc_serialized_data=-1, loc_real_proxy;
3593         int loc_old_domainid, loc_domainid, loc_return=0, loc_serialized_exc=0, loc_context;
3594         int pos, pos_dispatch, pos_noex;
3595         gboolean copy_return = FALSE;
3596
3597         g_assert (method);
3598         
3599         if (method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE || method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE)
3600                 return method;
3601
3602         /* we cant remote methods without this pointer */
3603         if (!mono_method_signature (method)->hasthis)
3604                 return method;
3605
3606         if (!mono_marshal_supports_fast_xdomain (method))
3607                 return mono_marshal_get_remoting_invoke (method);
3608         
3609         mono_remoting_marshal_init ();
3610
3611         if ((res = mono_marshal_remoting_find_in_cache (method, MONO_WRAPPER_XDOMAIN_INVOKE)))
3612                 return res;
3613         
3614         sig = signature_no_pinvoke (method);
3615
3616         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_XDOMAIN_INVOKE);
3617         mb->method->save_lmf = 1;
3618
3619         /* Count the number of parameters that need to be serialized */
3620
3621         marshal_types = alloca (sizeof (int) * sig->param_count);
3622         complex_count = complex_out_count = 0;
3623         for (i = 0; i < sig->param_count; i++) {
3624                 MonoType *ptype = sig->params[i];
3625                 int mt = mono_get_xdomain_marshal_type (ptype);
3626                 
3627                 /* If the [Out] attribute is applied to a parameter that can be internally copied,
3628                  * the copy will be made by reusing the original object instance
3629                  */
3630                 if ((ptype->attrs & PARAM_ATTRIBUTE_OUT) != 0 && mt == MONO_MARSHAL_COPY && !ptype->byref)
3631                         mt = MONO_MARSHAL_COPY_OUT;
3632                 else if (mt == MONO_MARSHAL_SERIALIZE) {
3633                         complex_count++;
3634                         if (ptype->byref) complex_out_count++;
3635                 }
3636                 marshal_types [i] = mt;
3637         }
3638
3639         if (sig->ret->type != MONO_TYPE_VOID) {
3640                 ret_marshal_type = mono_get_xdomain_marshal_type (sig->ret);
3641                 ret_class = mono_class_from_mono_type (sig->ret);
3642                 copy_return = ret_marshal_type != MONO_MARSHAL_SERIALIZE;
3643         }
3644         
3645         /* Locals */
3646
3647         if (complex_count > 0)
3648                 loc_array = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3649         loc_serialized_data = mono_mb_add_local (mb, &byte_array_class->byval_arg);
3650         loc_real_proxy = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3651         if (copy_return)
3652                 loc_return = mono_mb_add_local (mb, sig->ret);
3653         loc_old_domainid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
3654         loc_domainid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
3655         loc_serialized_exc = mono_mb_add_local (mb, &byte_array_class->byval_arg);
3656         loc_context = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
3657
3658         /* Save thread domain data */
3659
3660         mono_mb_emit_icall (mb, mono_context_get);
3661         mono_mb_emit_byte (mb, CEE_DUP);
3662         mono_mb_emit_stloc (mb, loc_context);
3663
3664         /* If the thread is not running in the default context, it needs to go
3665          * through the whole remoting sink, since the context is going to change
3666          */
3667         mono_mb_emit_managed_call (mb, method_needs_context_sink, NULL);
3668         pos = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
3669         
3670         /* Another case in which the fast path can't be used: when the target domain
3671          * has a different image for the same assembly.
3672          */
3673
3674         /* Get the target domain id */
3675
3676         mono_mb_emit_ldarg (mb, 0);
3677         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, rp));
3678         mono_mb_emit_byte (mb, CEE_LDIND_REF);
3679         mono_mb_emit_byte (mb, CEE_DUP);
3680         mono_mb_emit_stloc (mb, loc_real_proxy);
3681
3682         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoRealProxy, target_domain_id));
3683         mono_mb_emit_byte (mb, CEE_LDIND_I4);
3684         mono_mb_emit_stloc (mb, loc_domainid);
3685
3686         /* Check if the target domain has the same image for the required assembly */
3687
3688         mono_mb_emit_ldloc (mb, loc_domainid);
3689         mono_mb_emit_ptr (mb, method->klass->image);
3690         mono_mb_emit_icall (mb, mono_marshal_check_domain_image);
3691         mono_mb_emit_byte (mb, CEE_BRTRUE_S);
3692         pos_dispatch = mb->pos;
3693         mono_mb_emit_byte (mb, 0);
3694
3695         /* Use the whole remoting sink to dispatch this message */
3696
3697         mono_mb_patch_addr_s (mb, pos, mb->pos - pos - 1);
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_addr_s (mb, pos_dispatch, mb->pos - pos_dispatch - 1);
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->native != MONO_NATIVE_LPARRAY) {
6476                         char *msg = g_strdup ("Non LPArray marshalling of arrays to managed code is not implemented.");
6477                         mono_mb_emit_exception_marshal_directive (mb, msg);
6478                         return conv_arg;                        
6479                 }
6480
6481                 /* FIXME: t is from the method which is wrapped, not the delegate type */
6482                 /* g_assert (t->attrs & PARAM_ATTRIBUTE_IN); */
6483
6484                 param_num = spec->data.array_data.param_num;
6485                 num_elem = spec->data.array_data.num_elem;
6486                 if (spec->data.array_data.elem_mult == 0)
6487                         /* param_num is not specified */
6488                         param_num = -1;
6489
6490                 if (param_num == -1) {
6491                         if (num_elem <= 0) {
6492                                 char *msg = g_strdup ("Either SizeConst or SizeParamIndex should be specified when marshalling arrays to managed code.");
6493                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6494                                 return conv_arg;
6495                         }
6496                 }
6497
6498                 /* FIXME: Optimize blittable case */
6499
6500                 eklass = klass->element_class;
6501                 if (eklass == mono_defaults.string_class) {
6502                         is_string = TRUE;
6503                         conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
6504                 }
6505                 else if (eklass == mono_defaults.stringbuilder_class) {
6506                         is_string = TRUE;
6507                         conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
6508                 }
6509                 else
6510                         conv = -1;
6511
6512                 mono_marshal_load_type_info (eklass);
6513
6514                 if (is_string)
6515                         esize = sizeof (gpointer);
6516                 else
6517                         esize = mono_class_native_size (eklass, NULL);
6518                 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6519                 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6520
6521                 mono_mb_emit_byte (mb, CEE_LDNULL);
6522                 mono_mb_emit_stloc (mb, conv_arg);
6523
6524                 /* Check param index */
6525                 if (param_num != -1) {
6526                         if (param_num >= m->sig->param_count) {
6527                                 char *msg = g_strdup ("Array size control parameter index is out of range.");
6528                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6529                                 return conv_arg;
6530                         }
6531                         switch (m->sig->params [param_num]->type) {
6532                         case MONO_TYPE_I1:
6533                         case MONO_TYPE_U1:
6534                         case MONO_TYPE_I2:
6535                         case MONO_TYPE_U2:
6536                         case MONO_TYPE_I4:
6537                         case MONO_TYPE_U4:
6538                         case MONO_TYPE_I:
6539                         case MONO_TYPE_U:
6540                         case MONO_TYPE_I8:
6541                         case MONO_TYPE_U8:
6542                                 break;
6543                         default: {
6544                                 char *msg = g_strdup ("Array size control parameter must be an integral type.");
6545                                 mono_mb_emit_exception_marshal_directive (mb, msg);
6546                                 return conv_arg;
6547                         }
6548                         }
6549                 }
6550
6551                 /* Check null */
6552                 mono_mb_emit_ldarg (mb, argnum);
6553                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6554
6555                 mono_mb_emit_ldarg (mb, argnum);
6556                 mono_mb_emit_stloc (mb, src_ptr);
6557
6558                 /* Create managed array */
6559                 /* 
6560                  * The LPArray marshalling spec says that sometimes param_num starts 
6561                  * from 1, sometimes it starts from 0. But MS seems to allways start
6562                  * from 0.
6563                  */
6564
6565                 if (param_num == -1)
6566                         mono_mb_emit_icon (mb, num_elem);
6567                 else {
6568                         /* FIXME: Add the two together */
6569                         mono_mb_emit_ldarg (mb, param_num);
6570                         if (num_elem > 0) {
6571                                 mono_mb_emit_icon (mb, num_elem);
6572                                 mono_mb_emit_byte (mb, CEE_ADD);
6573                         }
6574                 }
6575
6576                 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
6577                 mono_mb_emit_stloc (mb, conv_arg);
6578
6579                 if (eklass->blittable) {
6580                         mono_mb_emit_ldloc (mb, conv_arg);
6581                         mono_mb_emit_byte (mb, CEE_CONV_I);
6582                         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoArray, vector));
6583                         mono_mb_emit_byte (mb, CEE_ADD);
6584                         mono_mb_emit_ldarg (mb, argnum);
6585                         mono_mb_emit_ldloc (mb, conv_arg);
6586                         mono_mb_emit_byte (mb, CEE_LDLEN);
6587                         mono_mb_emit_icon (mb, esize);
6588                         mono_mb_emit_byte (mb, CEE_MUL);
6589                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6590                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
6591                         break;
6592                 }
6593
6594                 /* Emit marshalling loop */
6595                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6596                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6597                 mono_mb_emit_stloc (mb, index_var);
6598                 label2 = mb->pos;
6599                 mono_mb_emit_ldloc (mb, index_var);
6600                 mono_mb_emit_ldloc (mb, conv_arg);
6601                 mono_mb_emit_byte (mb, CEE_LDLEN);
6602                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6603
6604                 /* Emit marshalling code */
6605                 if (is_string) {
6606                         g_assert (conv != -1);
6607
6608                         mono_mb_emit_ldloc (mb, conv_arg);
6609                         mono_mb_emit_ldloc (mb, index_var);
6610
6611                         mono_mb_emit_ldloc (mb, src_ptr);
6612                         mono_mb_emit_byte (mb, CEE_LDIND_I);
6613
6614                         mono_mb_emit_icall (mb, conv_to_icall (conv));
6615                         mono_mb_emit_byte (mb, CEE_STELEM_REF);
6616                 }
6617                 else {
6618                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6619                         mono_mb_emit_exception_marshal_directive (mb, msg);
6620                         return conv_arg;
6621                 }
6622
6623                 mono_mb_emit_add_to_local (mb, index_var, 1);
6624                 mono_mb_emit_add_to_local (mb, src_ptr, esize);
6625
6626                 mono_mb_emit_byte (mb, CEE_BR);
6627                 mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
6628
6629                 mono_mb_patch_branch (mb, label1);
6630                 mono_mb_patch_branch (mb, label3);
6631                 
6632                 break;
6633         }
6634         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6635                 MonoClass *eklass;
6636                 guint32 label1, label2, label3;
6637                 int index_var, dest_ptr, loc, esize, param_num, num_elem;
6638                 MonoMarshalConv conv;
6639                 gboolean is_string = FALSE;
6640                 
6641                 /* These are already checked in CONV_IN */
6642                 g_assert (!t->byref);
6643                 g_assert (spec->native == MONO_NATIVE_LPARRAY);
6644                 g_assert (t->attrs & PARAM_ATTRIBUTE_OUT);
6645
6646                 param_num = spec->data.array_data.param_num;
6647                 num_elem = spec->data.array_data.num_elem;
6648
6649                 if (spec->data.array_data.elem_mult == 0)
6650                         /* param_num is not specified */
6651                         param_num = -1;
6652
6653                 if (param_num == -1) {
6654                         if (num_elem <= 0) {
6655                                 g_assert_not_reached ();
6656                         }
6657                 }
6658
6659                 /* FIXME: Optimize blittable case */
6660
6661                 eklass = klass->element_class;
6662                 if (eklass == mono_defaults.string_class) {
6663                         is_string = TRUE;
6664                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6665                 }
6666                 else if (eklass == mono_defaults.stringbuilder_class) {
6667                         is_string = TRUE;
6668                         conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6669                 }
6670                 else
6671                         conv = -1;
6672
6673                 mono_marshal_load_type_info (eklass);
6674
6675                 if (is_string)
6676                         esize = sizeof (gpointer);
6677                 else
6678                         esize = mono_class_native_size (eklass, NULL);
6679
6680                 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6681                 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6682
6683                 /* Check null */
6684                 mono_mb_emit_ldloc (mb, conv_arg);
6685                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6686
6687                 mono_mb_emit_ldarg (mb, argnum);
6688                 mono_mb_emit_stloc (mb, dest_ptr);
6689
6690                 if (eklass->blittable) {
6691                         /* dest */
6692                         mono_mb_emit_ldarg (mb, argnum);
6693                         /* src */
6694                         mono_mb_emit_ldloc (mb, conv_arg);
6695                         mono_mb_emit_byte (mb, CEE_CONV_I);
6696                         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoArray, vector));
6697                         mono_mb_emit_byte (mb, CEE_ADD);
6698                         /* length */
6699                         mono_mb_emit_ldloc (mb, conv_arg);
6700                         mono_mb_emit_byte (mb, CEE_LDLEN);
6701                         mono_mb_emit_icon (mb, esize);
6702                         mono_mb_emit_byte (mb, CEE_MUL);
6703                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6704                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
6705                         break;
6706                 }
6707
6708                 /* Emit marshalling loop */
6709                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6710                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6711                 mono_mb_emit_stloc (mb, index_var);
6712                 label2 = mb->pos;
6713                 mono_mb_emit_ldloc (mb, index_var);
6714                 mono_mb_emit_ldloc (mb, conv_arg);
6715                 mono_mb_emit_byte (mb, CEE_LDLEN);
6716                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6717
6718                 /* Emit marshalling code */
6719                 if (is_string) {
6720                         g_assert (conv != -1);
6721
6722                         /* dest */
6723                         mono_mb_emit_ldloc (mb, dest_ptr);
6724
6725                         /* src */
6726                         mono_mb_emit_ldloc (mb, conv_arg);
6727                         mono_mb_emit_ldloc (mb, index_var);
6728
6729                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6730
6731                         mono_mb_emit_icall (mb, conv_to_icall (conv));
6732                         mono_mb_emit_byte (mb, CEE_STIND_I);
6733                 }
6734                 else {
6735                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
6736                         mono_mb_emit_exception_marshal_directive (mb, msg);
6737                         return conv_arg;
6738                 }
6739
6740                 mono_mb_emit_add_to_local (mb, index_var, 1);
6741                 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
6742
6743                 mono_mb_emit_byte (mb, CEE_BR);
6744                 mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
6745
6746                 mono_mb_patch_branch (mb, label1);
6747                 mono_mb_patch_branch (mb, label3);
6748
6749                 break;
6750         }
6751         case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6752                 MonoClass *eklass;
6753                 guint32 label1, label2, label3;
6754                 int index_var, src, dest, esize;
6755                 MonoMarshalConv conv = -1;
6756                 gboolean is_string = FALSE;
6757                 
6758                 g_assert (!t->byref);
6759
6760                 eklass = klass->element_class;
6761
6762                 mono_marshal_load_type_info (eklass);
6763
6764                 if (eklass == mono_defaults.string_class) {
6765                         is_string = TRUE;
6766                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6767                 }
6768                 else {
6769                         g_assert_not_reached ();
6770                 }
6771
6772                 if (is_string)
6773                         esize = sizeof (gpointer);
6774                 else
6775                         esize = mono_class_native_size (eklass, NULL);
6776
6777                 src = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6778                 dest = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6779                         
6780                 mono_mb_emit_stloc (mb, src);
6781                 mono_mb_emit_ldloc (mb, src);
6782                 mono_mb_emit_stloc (mb, 3);
6783
6784                 /* Check for null */
6785                 mono_mb_emit_ldloc (mb, src);
6786                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6787
6788                 /* Allocate native array */
6789                 mono_mb_emit_icon (mb, esize);
6790                 mono_mb_emit_ldloc (mb, src);
6791                 mono_mb_emit_byte (mb, CEE_LDLEN);
6792
6793                 if (eklass == mono_defaults.string_class) {
6794                         /* Make the array bigger for the terminating null */
6795                         mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6796                         mono_mb_emit_byte (mb, CEE_ADD);
6797                 }
6798                 mono_mb_emit_byte (mb, CEE_MUL);
6799                 mono_mb_emit_icall (mb, mono_marshal_alloc);
6800                 mono_mb_emit_stloc (mb, dest);
6801                 mono_mb_emit_ldloc (mb, dest);
6802                 mono_mb_emit_stloc (mb, 3);
6803
6804                 /* Emit marshalling loop */
6805                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6806                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6807                 mono_mb_emit_stloc (mb, index_var);
6808                 label2 = mb->pos;
6809                 mono_mb_emit_ldloc (mb, index_var);
6810                 mono_mb_emit_ldloc (mb, src);
6811                 mono_mb_emit_byte (mb, CEE_LDLEN);
6812                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
6813
6814                 /* Emit marshalling code */
6815                 if (is_string) {
6816                         g_assert (conv != -1);
6817
6818                         /* dest */
6819                         mono_mb_emit_ldloc (mb, dest);
6820
6821                         /* src */
6822                         mono_mb_emit_ldloc (mb, src);
6823                         mono_mb_emit_ldloc (mb, index_var);
6824
6825                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
6826
6827                         mono_mb_emit_icall (mb, conv_to_icall (conv));
6828                         mono_mb_emit_byte (mb, CEE_STIND_I);
6829                 }
6830                 else {
6831                         char *msg = g_strdup ("Marshalling of non-string arrays to managed code is not implemented.");
6832                         mono_mb_emit_exception_marshal_directive (mb, msg);
6833                         return conv_arg;
6834                 }
6835
6836                 mono_mb_emit_add_to_local (mb, index_var, 1);
6837                 mono_mb_emit_add_to_local (mb, dest, esize);
6838
6839                 mono_mb_emit_byte (mb, CEE_BR);
6840                 mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
6841
6842                 mono_mb_patch_branch (mb, label3);
6843                 mono_mb_patch_branch (mb, label1);
6844                 break;
6845         }
6846         default:
6847                 g_assert_not_reached ();
6848         }
6849
6850         return conv_arg;
6851 }
6852
6853 static int
6854 emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
6855                                           MonoMarshalSpec *spec, 
6856                                           int conv_arg, MonoType **conv_arg_type, 
6857                                           MarshalAction action)
6858 {
6859         MonoMethodBuilder *mb = m->mb;
6860
6861         switch (action) {
6862         case MARSHAL_ACTION_CONV_IN: {
6863                 MonoType *local_type;
6864                 int variant_bool = 0;
6865                 if (!t->byref)
6866                         break;
6867                 if (spec == NULL) {
6868                         local_type = &mono_defaults.int32_class->byval_arg;
6869                 } else {
6870                         switch (spec->native) {
6871                         case MONO_NATIVE_I1:
6872                                 local_type = &mono_defaults.byte_class->byval_arg;
6873                                 break;
6874                         case MONO_NATIVE_VARIANTBOOL:
6875                                 local_type = &mono_defaults.int16_class->byval_arg;
6876                                 variant_bool = 1;
6877                                 break;
6878                         default:
6879                                 g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
6880                                 local_type = &mono_defaults.int32_class->byval_arg;
6881                                 break;
6882                         }
6883                 }
6884                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
6885                 conv_arg = mono_mb_add_local (mb, local_type);
6886                 mono_mb_emit_ldarg (mb, argnum);
6887                 mono_mb_emit_byte (mb, CEE_LDIND_I1);
6888                 if (variant_bool)
6889                         mono_mb_emit_byte (mb, CEE_NEG);
6890                 mono_mb_emit_stloc (mb, conv_arg);
6891                 break;
6892         }
6893
6894         case MARSHAL_ACTION_CONV_OUT:
6895                 if (!t->byref)
6896                         break;
6897                 mono_mb_emit_ldarg (mb, argnum);
6898                 mono_mb_emit_ldloc (mb, conv_arg);
6899                 if (spec != NULL && spec->native == MONO_NATIVE_VARIANTBOOL)
6900                         mono_mb_emit_byte (mb, CEE_NEG);
6901                 mono_mb_emit_byte (mb, CEE_STIND_I1);
6902                 break;
6903
6904         case MARSHAL_ACTION_PUSH:
6905                 if (t->byref)
6906                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6907                 else
6908                         mono_mb_emit_ldarg (mb, argnum);
6909                 break;
6910
6911         case MARSHAL_ACTION_CONV_RESULT:
6912                 /* maybe we need to make sure that it fits within 8 bits */
6913                 mono_mb_emit_stloc (mb, 3);
6914                 break;
6915
6916         default:
6917                 g_assert_not_reached ();
6918         }
6919
6920         return conv_arg;
6921 }
6922
6923 static int
6924 emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t, 
6925                                   MonoMarshalSpec *spec, int conv_arg, 
6926                                   MonoType **conv_arg_type, MarshalAction action)
6927 {
6928         MonoMethodBuilder *mb = m->mb;
6929
6930         switch (action) {
6931         case MARSHAL_ACTION_CONV_IN:
6932                 if (MONO_TYPE_ISSTRUCT (t->data.type)) {
6933                         char *msg = g_strdup_printf ("Can not marshal 'parameter #%d': Pointers can not reference marshaled structures. Use byref instead.", argnum + 1);
6934                         mono_mb_emit_exception_marshal_directive (m->mb, msg);
6935                 }
6936                 break;
6937
6938         case MARSHAL_ACTION_PUSH:
6939                 mono_mb_emit_ldarg (mb, argnum);
6940                 break;
6941
6942         case MARSHAL_ACTION_CONV_RESULT:
6943                 /* no conversions necessary */
6944                 mono_mb_emit_stloc (mb, 3);
6945                 break;
6946
6947         default:
6948                 break;
6949         }
6950
6951         return conv_arg;
6952 }
6953
6954 static int
6955 emit_marshal_char (EmitMarshalContext *m, int argnum, MonoType *t, 
6956                                    MonoMarshalSpec *spec, int conv_arg, 
6957                                    MonoType **conv_arg_type, MarshalAction action)
6958 {
6959         MonoMethodBuilder *mb = m->mb;
6960
6961         switch (action) {
6962         case MARSHAL_ACTION_PUSH:
6963                 /* fixme: dont know how to marshal that. We cant simply
6964                  * convert it to a one byte UTF8 character, because an
6965                  * unicode character may need more that one byte in UTF8 */
6966                 mono_mb_emit_ldarg (mb, argnum);
6967                 break;
6968
6969         case MARSHAL_ACTION_CONV_RESULT:
6970                 /* fixme: we need conversions here */
6971                 mono_mb_emit_stloc (mb, 3);
6972                 break;
6973
6974         default:
6975                 break;
6976         }
6977
6978         return conv_arg;
6979 }
6980
6981 static int
6982 emit_marshal_scalar (EmitMarshalContext *m, int argnum, MonoType *t, 
6983                                          MonoMarshalSpec *spec, int conv_arg, 
6984                                          MonoType **conv_arg_type, MarshalAction action)
6985 {
6986         MonoMethodBuilder *mb = m->mb;
6987
6988         switch (action) {
6989         case MARSHAL_ACTION_PUSH:
6990                 mono_mb_emit_ldarg (mb, argnum);
6991                 break;
6992
6993         case MARSHAL_ACTION_CONV_RESULT:
6994                 /* no conversions necessary */
6995                 mono_mb_emit_stloc (mb, 3);
6996                 break;
6997
6998         default:
6999                 break;
7000         }
7001
7002         return conv_arg;
7003 }
7004
7005 static int
7006 emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t, 
7007                           MonoMarshalSpec *spec, int conv_arg, 
7008                           MonoType **conv_arg_type, MarshalAction action)
7009 {
7010         /* Ensure that we have marshalling info for this param */
7011         mono_marshal_load_type_info (mono_class_from_mono_type (t));
7012
7013         if (spec && spec->native == MONO_NATIVE_CUSTOM)
7014                 return emit_marshal_custom (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7015
7016         if (spec && spec->native == MONO_NATIVE_ASANY)
7017                 return emit_marshal_asany (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7018                         
7019         switch (t->type) {
7020         case MONO_TYPE_VALUETYPE:
7021                 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7022         case MONO_TYPE_STRING:
7023                 return emit_marshal_string (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7024         case MONO_TYPE_CLASS:
7025         case MONO_TYPE_OBJECT:
7026                 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7027         case MONO_TYPE_ARRAY:
7028         case MONO_TYPE_SZARRAY:
7029                 return emit_marshal_array (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7030         case MONO_TYPE_BOOLEAN:
7031                 return emit_marshal_boolean (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7032         case MONO_TYPE_PTR:
7033                 return emit_marshal_ptr (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7034         case MONO_TYPE_CHAR:
7035                 return emit_marshal_char (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7036         case MONO_TYPE_I1:
7037         case MONO_TYPE_U1:
7038         case MONO_TYPE_I2:
7039         case MONO_TYPE_U2:
7040         case MONO_TYPE_I4:
7041         case MONO_TYPE_U4:
7042         case MONO_TYPE_I:
7043         case MONO_TYPE_U:
7044         case MONO_TYPE_R4:
7045         case MONO_TYPE_R8:
7046         case MONO_TYPE_I8:
7047         case MONO_TYPE_U8:
7048         case MONO_TYPE_FNPTR:
7049                 return emit_marshal_scalar (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7050         }
7051
7052         return conv_arg;
7053 }
7054
7055 /**
7056  * mono_marshal_emit_native_wrapper:
7057  * @sig: The signature of the native function
7058  * @piinfo: Marshalling information
7059  * @mspecs: Marshalling information
7060  * @func: the native function to call
7061  *
7062  * generates IL code for the pinvoke wrapper, the generated code calls @func.
7063  */
7064 static void
7065 mono_marshal_emit_native_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *sig, MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
7066 {
7067         EmitMarshalContext m;
7068         MonoMethodSignature *csig;
7069         MonoClass *klass;
7070         int i, argnum, *tmp_locals;
7071         int type;
7072         static MonoMethodSignature *get_last_error_sig = NULL;
7073
7074         m.mb = mb;
7075         m.piinfo = piinfo;
7076
7077         /* we copy the signature, so that we can set pinvoke to 0 */
7078         csig = signature_dup (mb->method->klass->image, sig);
7079         csig->pinvoke = 1;
7080         m.csig = csig;
7081
7082         /* we allocate local for use with emit_struct_conv() */
7083         /* allocate local 0 (pointer) src_ptr */
7084         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7085         /* allocate local 1 (pointer) dst_ptr */
7086         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7087         /* allocate local 2 (boolean) delete_old */
7088         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7089
7090         /* delete_old = FALSE */
7091         mono_mb_emit_icon (mb, 0);
7092         mono_mb_emit_stloc (mb, 2);
7093
7094         if (!MONO_TYPE_IS_VOID(sig->ret)) {
7095                 /* allocate local 3 to store the return value */
7096                 mono_mb_add_local (mb, sig->ret);
7097         }
7098
7099         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7100                 /* Return type custom marshaling */
7101                 /*
7102                  * Since we can't determine the return type of the unmanaged function,
7103                  * we assume it returns a pointer, and pass that pointer to
7104                  * MarshalNativeToManaged.
7105                  */
7106                 csig->ret = &mono_defaults.int_class->byval_arg;
7107         }
7108
7109         /* we first do all conversions */
7110         tmp_locals = alloca (sizeof (int) * sig->param_count);
7111         m.orig_conv_args = alloca (sizeof (int) * (sig->param_count + 1));
7112
7113         for (i = 0; i < sig->param_count; i ++) {
7114                 tmp_locals [i] = emit_marshal (&m, i + sig->hasthis, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_CONV_IN);
7115         }
7116
7117         /* push all arguments */
7118
7119         if (sig->hasthis)
7120                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7121
7122
7123         for (i = 0; i < sig->param_count; i++) {
7124                 emit_marshal (&m, i + sig->hasthis, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
7125         }                       
7126
7127         /* call the native method */
7128         if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
7129                 mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
7130         }
7131         else {
7132                 mono_mb_emit_native_call (mb, csig, func);
7133         }
7134
7135         /* Set LastError if needed */
7136         if (piinfo->piflags & PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR) {
7137                 if (!get_last_error_sig) {
7138                         get_last_error_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
7139                         get_last_error_sig->ret = &mono_defaults.int_class->byval_arg;
7140                         get_last_error_sig->pinvoke = 1;
7141                 }
7142
7143 #ifdef PLATFORM_WIN32
7144                 /* 
7145                  * Have to call GetLastError () early and without a wrapper, since various runtime components could
7146                  * clobber its value.
7147                  */
7148                 mono_mb_emit_native_call (mb, get_last_error_sig, GetLastError);
7149                 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7150 #else
7151                 mono_mb_emit_icall (mb, mono_marshal_set_last_error);
7152 #endif
7153         }               
7154
7155         /* convert the result */
7156         if (!sig->ret->byref) {
7157                 MonoMarshalSpec *spec = mspecs [0];
7158                 type = sig->ret->type;
7159
7160                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7161                         emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7162                 } else {
7163
7164                 handle_enum:
7165                         switch (type) {
7166                         case MONO_TYPE_VOID:
7167                                 break;
7168                         case MONO_TYPE_VALUETYPE:
7169                                 klass = sig->ret->data.klass;
7170                                 if (klass->enumtype) {
7171                                         type = sig->ret->data.klass->enum_basetype->type;
7172                                         goto handle_enum;
7173                                 }
7174                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7175                                 break;
7176                         case MONO_TYPE_I1:
7177                         case MONO_TYPE_U1:
7178                         case MONO_TYPE_I2:
7179                         case MONO_TYPE_U2:
7180                         case MONO_TYPE_I4:
7181                         case MONO_TYPE_U4:
7182                         case MONO_TYPE_I:
7183                         case MONO_TYPE_U:
7184                         case MONO_TYPE_R4:
7185                         case MONO_TYPE_R8:
7186                         case MONO_TYPE_I8:
7187                         case MONO_TYPE_U8:
7188                         case MONO_TYPE_FNPTR:
7189                         case MONO_TYPE_STRING:
7190                         case MONO_TYPE_CLASS:
7191                         case MONO_TYPE_OBJECT:
7192                         case MONO_TYPE_BOOLEAN:
7193                         case MONO_TYPE_ARRAY:
7194                         case MONO_TYPE_SZARRAY:
7195                         case MONO_TYPE_CHAR:
7196                         case MONO_TYPE_PTR:
7197                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7198                                 break;
7199                         case MONO_TYPE_TYPEDBYREF:
7200                         default:
7201                                 g_warning ("return type 0x%02x unknown", sig->ret->type);       
7202                                 g_assert_not_reached ();
7203                         }
7204                 }
7205         } else {
7206                 mono_mb_emit_stloc (mb, 3);
7207         }
7208
7209         /* 
7210          * Need to call this after converting the result since MONO_VTADDR needs 
7211          * to be adjacent to the call instruction.
7212          */
7213         emit_thread_interrupt_checkpoint (mb);
7214
7215         /* we need to convert byref arguments back and free string arrays */
7216         for (i = 0; i < sig->param_count; i++) {
7217                 MonoType *t = sig->params [i];
7218                 MonoMarshalSpec *spec = mspecs [i + 1];
7219
7220                 argnum = i + sig->hasthis;
7221
7222                 if (spec && ((spec->native == MONO_NATIVE_CUSTOM) || (spec->native == MONO_NATIVE_ASANY))) {
7223                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7224                         continue;
7225                 }
7226
7227                 switch (t->type) {
7228                 case MONO_TYPE_STRING:
7229                 case MONO_TYPE_VALUETYPE:
7230                 case MONO_TYPE_CLASS:
7231                 case MONO_TYPE_OBJECT:
7232                 case MONO_TYPE_SZARRAY:
7233                 case MONO_TYPE_BOOLEAN:
7234                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7235                         break;
7236                 }
7237         }
7238
7239         if (!MONO_TYPE_IS_VOID(sig->ret))
7240                 mono_mb_emit_ldloc (mb, 3);
7241
7242         mono_mb_emit_byte (mb, CEE_RET);
7243 }
7244
7245 /**
7246  * mono_marshal_get_native_wrapper:
7247  * @method: The MonoMethod to wrap.
7248  *
7249  * generates IL code for the pinvoke wrapper (the generated method
7250  * calls the unmanaged code in piinfo->addr)
7251  */
7252 MonoMethod *
7253 mono_marshal_get_native_wrapper (MonoMethod *method)
7254 {
7255         MonoMethodSignature *sig, *csig;
7256         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7257         MonoMethodBuilder *mb;
7258         MonoMarshalSpec **mspecs;
7259         MonoMethod *res;
7260         GHashTable *cache;
7261         gboolean pinvoke = FALSE;
7262         gpointer iter;
7263         int i;
7264         const char *exc_class = "MissingMethodException";
7265         const char *exc_arg = NULL;
7266
7267         g_assert (method != NULL);
7268         g_assert (mono_method_signature (method)->pinvoke);
7269
7270         cache = method->klass->image->native_wrapper_cache;
7271         if ((res = mono_marshal_find_in_cache (cache, method)))
7272                 return res;
7273
7274         if (MONO_CLASS_IS_IMPORT (method->klass))
7275                 return cominterop_get_native_wrapper (method);
7276
7277         sig = mono_method_signature (method);
7278
7279         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
7280             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7281                 pinvoke = TRUE;
7282
7283         if (!piinfo->addr) {
7284                 if (pinvoke)
7285                         mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
7286                 else
7287                         piinfo->addr = mono_lookup_internal_call (method);
7288         }
7289
7290         /* hack - redirect certain string constructors to CreateString */
7291         if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
7292                 g_assert (!pinvoke);
7293                 g_assert (method->string_ctor);
7294                 g_assert (sig->hasthis);
7295
7296                 /* CreateString returns a value */
7297                 csig = signature_dup (method->klass->image, sig);
7298                 csig->ret = &mono_defaults.string_class->byval_arg;
7299                 csig->pinvoke = 0;
7300
7301                 iter = NULL;
7302                 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
7303                         if (!strcmp ("CreateString", res->name) &&
7304                                 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
7305
7306                                 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
7307                                 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
7308
7309                                 /* create a wrapper to preserve .ctor in stack trace */
7310                                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
7311
7312                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7313                                 for (i = 1; i <= csig->param_count; i++)
7314                                         mono_mb_emit_ldarg (mb, i);
7315                                 mono_mb_emit_managed_call (mb, res, NULL);
7316                                 mono_mb_emit_byte (mb, CEE_RET);
7317
7318                                 /* use native_wrapper_cache because internal calls are looked up there */
7319                                 res = mono_mb_create_and_cache (cache, method,
7320                                         mb, csig, csig->param_count + 1);
7321
7322                                 mono_mb_free (mb);
7323
7324                                 return res;
7325                         }
7326                 }
7327
7328                 /* exception will be thrown */
7329                 piinfo->addr = NULL;
7330                 g_warning ("cannot find CreateString for .ctor");
7331         }
7332
7333         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7334
7335         mb->method->save_lmf = 1;
7336         
7337         if (!piinfo->addr) {
7338                 mono_mb_emit_exception (mb, exc_class, exc_arg);
7339                 csig = signature_dup (method->klass->image, sig);
7340                 csig->pinvoke = 0;
7341                 res = mono_mb_create_and_cache (cache, method,
7342                                                                                 mb, csig, csig->param_count + 16);
7343                 mono_mb_free (mb);
7344                 return res;
7345         }
7346
7347         /* internal calls: we simply push all arguments and call the method (no conversions) */
7348         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
7349
7350                 /* hack - string constructors returns a value */
7351                 if (method->string_ctor) {
7352                         csig = signature_dup (method->klass->image, sig);
7353                         csig->ret = &mono_defaults.string_class->byval_arg;
7354                 } else
7355                         csig = sig;
7356
7357                 if (sig->hasthis)
7358                         mono_mb_emit_byte (mb, CEE_LDARG_0);
7359
7360                 for (i = 0; i < sig->param_count; i++)
7361                         mono_mb_emit_ldarg (mb, i + sig->hasthis);
7362
7363                 g_assert (piinfo->addr);
7364                 mono_mb_emit_native_call (mb, csig, piinfo->addr);
7365                 emit_thread_interrupt_checkpoint (mb);
7366                 mono_mb_emit_byte (mb, CEE_RET);
7367
7368                 csig = signature_dup (method->klass->image, csig);
7369                 csig->pinvoke = 0;
7370                 res = mono_mb_create_and_cache (cache, method,
7371                                                                                 mb, csig, csig->param_count + 16);
7372                 mono_mb_free (mb);
7373                 return res;
7374         }
7375
7376         g_assert (pinvoke);
7377
7378         mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
7379         mono_method_get_marshal_info (method, mspecs);
7380
7381         mono_marshal_emit_native_wrapper (mb, sig, piinfo, mspecs, piinfo->addr);
7382
7383         csig = signature_dup (method->klass->image, sig);
7384         csig->pinvoke = 0;
7385         res = mono_mb_create_and_cache (cache, method,
7386                                                                         mb, csig, csig->param_count + 16);
7387         mono_mb_free (mb);
7388
7389         for (i = sig->param_count; i >= 0; i--)
7390                 if (mspecs [i])
7391                         mono_metadata_free_marshal_spec (mspecs [i]);
7392         g_free (mspecs);
7393
7394         /* 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)); */ 
7395
7396         return res;
7397 }
7398
7399 /**
7400  * mono_marshal_get_native_func_wrapper:
7401  * @sig: The signature of the function
7402  * @func: The native function to wrap
7403  *
7404  *   Returns a wrapper method around native functions, similar to the pinvoke
7405  * wrapper.
7406  */
7407 MonoMethod *
7408 mono_marshal_get_native_func_wrapper (MonoMethodSignature *sig, 
7409                                                                           MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
7410 {
7411         MonoMethodSignature *csig;
7412
7413         MonoMethodBuilder *mb;
7414         MonoMethod *res;
7415         GHashTable *cache;
7416         char *name;
7417
7418         cache = mono_defaults.corlib->native_wrapper_cache;
7419         if ((res = mono_marshal_find_in_cache (cache, func)))
7420                 return res;
7421
7422         name = g_strdup_printf ("wrapper_native_%p", func);
7423         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
7424         mb->method->save_lmf = 1;
7425
7426         mono_marshal_emit_native_wrapper (mb, sig, piinfo, mspecs, func);
7427
7428         csig = signature_dup (mb->method->klass->image, sig);
7429         csig->pinvoke = 0;
7430         res = mono_mb_create_and_cache (cache, func,
7431                                                                         mb, csig, csig->param_count + 16);
7432         mono_mb_free (mb);
7433
7434         /* 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)); */ 
7435
7436         return res;
7437 }
7438                              
7439 /*
7440  * generates IL code to call managed methods from unmanaged code 
7441  */
7442 MonoMethod *
7443 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, MonoObject *this)
7444 {
7445         static MonoClass *UnmanagedFunctionPointerAttribute;
7446         MonoMethodSignature *sig, *csig, *invoke_sig;
7447         MonoMethodBuilder *mb;
7448         MonoMethod *res, *invoke;
7449         MonoMarshalSpec **mspecs;
7450         MonoMethodPInvoke piinfo;
7451         GHashTable *cache;
7452         int i, *tmp_locals;
7453         EmitMarshalContext m;
7454
7455         g_assert (method != NULL);
7456         g_assert (!mono_method_signature (method)->pinvoke);
7457
7458         /* 
7459          * FIXME: Should cache the method+delegate type pair, since the same method
7460          * could be called with different delegates, thus different marshalling
7461          * options.
7462          */
7463         cache = method->klass->image->managed_wrapper_cache;
7464         if (!this && (res = mono_marshal_find_in_cache (cache, method)))
7465                 return res;
7466
7467         invoke = mono_class_get_method_from_name (delegate_klass, "Invoke", mono_method_signature (method)->param_count);
7468         invoke_sig = mono_method_signature (invoke);
7469
7470         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
7471         mono_method_get_marshal_info (invoke, mspecs);
7472
7473         sig = mono_method_signature (method);
7474
7475         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
7476
7477         /* allocate local 0 (pointer) src_ptr */
7478         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7479         /* allocate local 1 (pointer) dst_ptr */
7480         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7481         /* allocate local 2 (boolean) delete_old */
7482         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7483
7484         if (!MONO_TYPE_IS_VOID(sig->ret)) {
7485                 /* allocate local 3 to store the return value */
7486                 mono_mb_add_local (mb, sig->ret);
7487         }
7488
7489         mono_mb_emit_icon (mb, 0);
7490         mono_mb_emit_stloc (mb, 2);
7491
7492         /* we copy the signature, so that we can modify it */
7493         csig = signature_dup (method->klass->image, sig);
7494         csig->hasthis = 0;
7495         csig->pinvoke = 1;
7496
7497         m.mb = mb;
7498         m.sig = sig;
7499         m.piinfo = NULL;
7500         m.retobj_var = 0;
7501         m.csig = csig;
7502
7503 #ifdef PLATFORM_WIN32
7504         /* 
7505          * Under windows, delegates passed to native code must use the STDCALL
7506          * calling convention.
7507          */
7508         csig->call_convention = MONO_CALL_STDCALL;
7509 #endif
7510
7511         /* Change default calling convention if needed */
7512         /* Why is this a modopt ? */
7513         if (invoke_sig->ret && invoke_sig->ret->num_mods) {
7514                 for (i = 0; i < invoke_sig->ret->num_mods; ++i) {
7515                         MonoClass *cmod_class = mono_class_get (delegate_klass->image, invoke_sig->ret->modifiers [i].token);
7516                         g_assert (cmod_class);
7517                         if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
7518                                 if (!strcmp (cmod_class->name, "CallConvCdecl"))
7519                                         csig->call_convention = MONO_CALL_C;
7520                                 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
7521                                         csig->call_convention = MONO_CALL_STDCALL;
7522                                 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
7523                                         csig->call_convention = MONO_CALL_FASTCALL;
7524                                 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
7525                                         csig->call_convention = MONO_CALL_THISCALL;
7526                         }
7527                 }
7528         }
7529
7530         /* Handle the UnmanagedFunctionPointerAttribute */
7531         if (!UnmanagedFunctionPointerAttribute)
7532                 UnmanagedFunctionPointerAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
7533
7534         /* The attribute is only available in Net 2.0 */
7535         if (UnmanagedFunctionPointerAttribute) {
7536                 MonoReflectionUnmanagedFunctionPointerAttribute *attr;
7537                 MonoCustomAttrInfo *cinfo;
7538
7539                 /* 
7540                  * The pinvoke attributes are stored in a real custom attribute so we have to
7541                  * construct it.
7542                  */
7543                 cinfo = mono_custom_attrs_from_class (delegate_klass);
7544                 if (cinfo) {
7545                         attr = (MonoReflectionUnmanagedFunctionPointerAttribute*)mono_custom_attrs_get_attr (cinfo, UnmanagedFunctionPointerAttribute);
7546                         if (attr) {
7547                                 memset (&piinfo, 0, sizeof (piinfo));
7548                                 m.piinfo = &piinfo;
7549                                 piinfo.piflags = (attr->call_conv << 8) | (attr->charset ? (attr->charset - 1) * 2 : 1) | attr->set_last_error;
7550
7551                                 csig->call_convention = attr->call_conv - 1;
7552                         }
7553                         if (!cinfo->cached)
7554                                 mono_custom_attrs_free (cinfo);
7555                 }
7556         }
7557
7558         /* fixme: howto handle this ? */
7559         if (sig->hasthis) {
7560                 if (this) {
7561                         mono_mb_emit_ptr (mb, this);
7562                 } else {
7563                         /* fixme: */
7564                         g_assert_not_reached ();
7565                 }
7566         } 
7567
7568         /* we first do all conversions */
7569         tmp_locals = alloca (sizeof (int) * sig->param_count);
7570         for (i = 0; i < sig->param_count; i ++) {
7571                 MonoType *t = sig->params [i];
7572                 
7573                 switch (t->type) {
7574                 case MONO_TYPE_OBJECT:
7575                 case MONO_TYPE_CLASS:
7576                 case MONO_TYPE_VALUETYPE:
7577                 case MONO_TYPE_ARRAY:
7578                 case MONO_TYPE_SZARRAY:
7579                 case MONO_TYPE_STRING:
7580                         tmp_locals [i] = emit_marshal (&m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
7581
7582                         break;
7583                 default:
7584                         tmp_locals [i] = 0;
7585                         break;
7586                 }
7587         }
7588
7589         emit_thread_interrupt_checkpoint (mb);
7590
7591         for (i = 0; i < sig->param_count; i++) {
7592                 MonoType *t = sig->params [i];
7593
7594                 if (tmp_locals [i]) {
7595                         if (t->byref)
7596                                 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
7597                         else
7598                                 mono_mb_emit_ldloc (mb, tmp_locals [i]);
7599                 }
7600                 else
7601                         mono_mb_emit_ldarg (mb, i);
7602         }
7603
7604         mono_mb_emit_managed_call (mb, method, NULL);
7605
7606         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7607                 emit_marshal (&m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7608         }
7609         else
7610         if (!sig->ret->byref) { 
7611                 switch (sig->ret->type) {
7612                 case MONO_TYPE_VOID:
7613                         break;
7614                 case MONO_TYPE_BOOLEAN:
7615                 case MONO_TYPE_I1:
7616                 case MONO_TYPE_U1:
7617                 case MONO_TYPE_I2:
7618                 case MONO_TYPE_U2:
7619                 case MONO_TYPE_I4:
7620                 case MONO_TYPE_U4:
7621                 case MONO_TYPE_I:
7622                 case MONO_TYPE_U:
7623                 case MONO_TYPE_PTR:
7624                 case MONO_TYPE_R4:
7625                 case MONO_TYPE_R8:
7626                 case MONO_TYPE_I8:
7627                 case MONO_TYPE_U8:
7628                 case MONO_TYPE_OBJECT:
7629                         mono_mb_emit_stloc (mb, 3);
7630                         break;
7631                 case MONO_TYPE_STRING:
7632                         csig->ret = &mono_defaults.int_class->byval_arg;
7633                         emit_marshal (&m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7634                         break;
7635                 case MONO_TYPE_VALUETYPE:
7636                 case MONO_TYPE_CLASS:
7637                 case MONO_TYPE_SZARRAY:
7638                         emit_marshal (&m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
7639                         break;
7640                 default:
7641                         g_warning ("return type 0x%02x unknown", sig->ret->type);       
7642                         g_assert_not_reached ();
7643                 }
7644         } else {
7645                 mono_mb_emit_stloc (mb, 3);
7646         }
7647
7648         /* Convert byref arguments back */
7649         for (i = 0; i < sig->param_count; i ++) {
7650                 MonoType *t = sig->params [i];
7651                 MonoMarshalSpec *spec = mspecs [i + 1];
7652
7653                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7654                         emit_marshal (&m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7655                 }
7656                 else if (t->byref) {
7657                         switch (t->type) {
7658                         case MONO_TYPE_CLASS:
7659                         case MONO_TYPE_VALUETYPE:
7660                                 emit_marshal (&m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7661                                 break;
7662                         }
7663                 }
7664                 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
7665                         /* The [Out] information is encoded in the delegate signature */
7666                         switch (t->type) {
7667                         case MONO_TYPE_SZARRAY:
7668                                 emit_marshal (&m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
7669                                 break;
7670                         default:
7671                                 g_assert_not_reached ();
7672                         }
7673                 }
7674         }
7675
7676         if (m.retobj_var) {
7677                 mono_mb_emit_ldloc (mb, m.retobj_var);
7678                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7679                 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m.retobj_class);
7680         }
7681         else {
7682                 if (!MONO_TYPE_IS_VOID(sig->ret))
7683                         mono_mb_emit_ldloc (mb, 3);
7684                 mono_mb_emit_byte (mb, CEE_RET);
7685         }
7686
7687         if (!this)
7688                 res = mono_mb_create_and_cache (cache, method,
7689                                                                                          mb, csig, sig->param_count + 16);
7690         else {
7691                 mb->dynamic = 1;
7692                 res = mono_mb_create_method (mb, csig, sig->param_count + 16);
7693         }
7694         mono_mb_free (mb);
7695
7696         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
7697                 if (mspecs [i])
7698                         mono_metadata_free_marshal_spec (mspecs [i]);
7699         g_free (mspecs);
7700
7701         /* 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)); */
7702
7703         return res;
7704 }
7705
7706 static MonoReflectionType *
7707 type_from_handle (MonoType *handle)
7708 {
7709         MonoDomain *domain = mono_domain_get (); 
7710         MonoClass *klass = mono_class_from_mono_type (handle);
7711
7712         MONO_ARCH_SAVE_REGS;
7713
7714         mono_class_init (klass);
7715         return mono_type_get_object (domain, handle);
7716 }
7717
7718 /*
7719  * mono_marshal_get_isinst:
7720  * @klass: the type of the field
7721  *
7722  * This method generates a function which can be used to check if an object is
7723  * an instance of the given type, icluding the case where the object is a proxy.
7724  * The generated function has the following signature:
7725  * MonoObject* __isinst_wrapper_ (MonoObject *obj)
7726  */
7727 MonoMethod *
7728 mono_marshal_get_isinst (MonoClass *klass)
7729 {
7730         static MonoMethodSignature *isint_sig = NULL;
7731         GHashTable *cache;
7732         MonoMethod *res;
7733         int pos_was_ok, pos_failed, pos_end, pos_end2;
7734         char *name;
7735         MonoMethodBuilder *mb;
7736
7737         cache = klass->image->isinst_cache;
7738         if ((res = mono_marshal_find_in_cache (cache, klass)))
7739                 return res;
7740
7741         if (!isint_sig) {
7742                 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
7743                 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
7744                 isint_sig->ret = &mono_defaults.object_class->byval_arg;
7745                 isint_sig->pinvoke = 0;
7746         }
7747         
7748         name = g_strdup_printf ("__isinst_wrapper_%s", klass->name); 
7749         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ISINST);
7750         g_free (name);
7751         
7752         mb->method->save_lmf = 1;
7753
7754         /* check if the object is a proxy that needs special cast */
7755         mono_mb_emit_ldarg (mb, 0);
7756         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7757         mono_mb_emit_op (mb, CEE_MONO_CISINST, klass);
7758
7759         /* The result of MONO_ISINST can be:
7760                 0) the type check succeeded
7761                 1) the type check did not succeed
7762                 2) a CanCastTo call is needed */
7763         
7764         mono_mb_emit_byte (mb, CEE_DUP);
7765         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
7766
7767         mono_mb_emit_byte (mb, CEE_LDC_I4_2);
7768         pos_failed = mono_mb_emit_branch (mb, CEE_BNE_UN);
7769         
7770         /* get the real proxy from the transparent proxy*/
7771
7772         mono_mb_emit_ldarg (mb, 0);
7773         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
7774         pos_end = mono_mb_emit_branch (mb, CEE_BR);
7775         
7776         /* fail */
7777         
7778         mono_mb_patch_addr (mb, pos_failed, mb->pos - (pos_failed + 4));
7779         mono_mb_emit_byte (mb, CEE_LDNULL);
7780         pos_end2 = mono_mb_emit_branch (mb, CEE_BR);
7781         
7782         /* success */
7783         
7784         mono_mb_patch_addr (mb, pos_was_ok, mb->pos - (pos_was_ok + 4));
7785         mono_mb_emit_byte (mb, CEE_POP);
7786         mono_mb_emit_ldarg (mb, 0);
7787         
7788         /* the end */
7789         
7790         mono_mb_patch_addr (mb, pos_end, mb->pos - (pos_end + 4));
7791         mono_mb_patch_addr (mb, pos_end2, mb->pos - (pos_end2 + 4));
7792         mono_mb_emit_byte (mb, CEE_RET);
7793
7794         res = mono_mb_create_and_cache (cache, klass, mb, isint_sig, isint_sig->param_count + 16);
7795         mono_mb_free (mb);
7796
7797         return res;
7798 }
7799
7800 /*
7801  * mono_marshal_get_castclass:
7802  * @klass: the type of the field
7803  *
7804  * This method generates a function which can be used to cast an object to
7805  * an instance of the given type, icluding the case where the object is a proxy.
7806  * The generated function has the following signature:
7807  * MonoObject* __castclass_wrapper_ (MonoObject *obj)
7808  */
7809 MonoMethod *
7810 mono_marshal_get_castclass (MonoClass *klass)
7811 {
7812         static MonoMethodSignature *castclass_sig = NULL;
7813         GHashTable *cache;
7814         MonoMethod *res;
7815         int pos_was_ok, pos_was_ok2;
7816         char *name;
7817         MonoMethodBuilder *mb;
7818
7819         cache = klass->image->castclass_cache;
7820         if ((res = mono_marshal_find_in_cache (cache, klass)))
7821                 return res;
7822
7823         if (!castclass_sig) {
7824                 castclass_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
7825                 castclass_sig->params [0] = &mono_defaults.object_class->byval_arg;
7826                 castclass_sig->ret = &mono_defaults.object_class->byval_arg;
7827                 castclass_sig->pinvoke = 0;
7828         }
7829         
7830         name = g_strdup_printf ("__castclass_wrapper_%s", klass->name); 
7831         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_CASTCLASS);
7832         g_free (name);
7833         
7834         mb->method->save_lmf = 1;
7835
7836         /* check if the object is a proxy that needs special cast */
7837         mono_mb_emit_ldarg (mb, 0);
7838         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
7839         mono_mb_emit_op (mb, CEE_MONO_CCASTCLASS, klass);
7840
7841         /* The result of MONO_ISINST can be:
7842                 0) the cast is valid
7843                 1) cast of unknown proxy type
7844                 or an exception if the cast is is invalid
7845         */
7846         
7847         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
7848
7849         /* get the real proxy from the transparent proxy*/
7850
7851         mono_mb_emit_ldarg (mb, 0);
7852         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
7853         pos_was_ok2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
7854         
7855         /* fail */
7856         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
7857         
7858         /* success */
7859         mono_mb_patch_addr (mb, pos_was_ok, mb->pos - (pos_was_ok + 4));
7860         mono_mb_patch_addr (mb, pos_was_ok2, mb->pos - (pos_was_ok2 + 4));
7861         mono_mb_emit_ldarg (mb, 0);
7862         
7863         /* the end */
7864         mono_mb_emit_byte (mb, CEE_RET);
7865
7866         res = mono_mb_create_and_cache (cache, klass, mb, castclass_sig, castclass_sig->param_count + 16);
7867         mono_mb_free (mb);
7868
7869         return res;
7870 }
7871
7872 MonoMethod *
7873 mono_marshal_get_proxy_cancast (MonoClass *klass)
7874 {
7875         static MonoMethodSignature *isint_sig = NULL;
7876         GHashTable *cache;
7877         MonoMethod *res;
7878         int pos_failed, pos_end;
7879         char *name;
7880         MonoMethod *can_cast_to;
7881         MonoMethodDesc *desc;
7882         MonoMethodBuilder *mb;
7883
7884         cache = klass->image->proxy_isinst_cache;
7885         if ((res = mono_marshal_find_in_cache (cache, klass)))
7886                 return res;
7887
7888         if (!isint_sig) {
7889                 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
7890                 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
7891                 isint_sig->ret = &mono_defaults.object_class->byval_arg;
7892                 isint_sig->pinvoke = 0;
7893         }
7894         
7895         name = g_strdup_printf ("__proxy_isinst_wrapper_%s", klass->name); 
7896         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_PROXY_ISINST);
7897         g_free (name);
7898         
7899         mb->method->save_lmf = 1;
7900
7901         /* get the real proxy from the transparent proxy*/
7902         mono_mb_emit_ldarg (mb, 0);
7903         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, rp));
7904         mono_mb_emit_byte (mb, CEE_LDIND_REF);
7905         
7906         /* get the reflection type from the type handle */
7907         mono_mb_emit_ptr (mb, &klass->byval_arg);
7908         mono_mb_emit_icall (mb, type_from_handle);
7909         
7910         mono_mb_emit_ldarg (mb, 0);
7911         
7912         /* make the call to CanCastTo (type, ob) */
7913         desc = mono_method_desc_new ("IRemotingTypeInfo:CanCastTo", FALSE);
7914         can_cast_to = mono_method_desc_search_in_class (desc, mono_defaults.iremotingtypeinfo_class);
7915         g_assert (can_cast_to);
7916         mono_method_desc_free (desc);
7917         mono_mb_emit_op (mb, CEE_CALLVIRT, can_cast_to);
7918         
7919         pos_failed = mono_mb_emit_branch (mb, CEE_BRFALSE);
7920
7921         /* Upgrade the proxy vtable by calling: mono_upgrade_remote_class_wrapper (type, ob)*/
7922         mono_mb_emit_ptr (mb, &klass->byval_arg);
7923         mono_mb_emit_icall (mb, type_from_handle);
7924         mono_mb_emit_ldarg (mb, 0);
7925         
7926         mono_mb_emit_icall (mb, mono_upgrade_remote_class_wrapper);
7927         emit_thread_interrupt_checkpoint (mb);
7928         
7929         mono_mb_emit_ldarg (mb, 0);
7930         pos_end = mono_mb_emit_branch (mb, CEE_BR);
7931         
7932         /* fail */
7933         
7934         mono_mb_patch_addr (mb, pos_failed, mb->pos - (pos_failed + 4));
7935         mono_mb_emit_byte (mb, CEE_LDNULL);
7936         
7937         /* the end */
7938         
7939         mono_mb_patch_addr (mb, pos_end, mb->pos - (pos_end + 4));
7940         mono_mb_emit_byte (mb, CEE_RET);
7941
7942         res = mono_mb_create_and_cache (cache, klass, mb, isint_sig, isint_sig->param_count + 16);
7943         mono_mb_free (mb);
7944
7945         return res;
7946 }
7947
7948 void
7949 mono_upgrade_remote_class_wrapper (MonoReflectionType *rtype, MonoTransparentProxy *tproxy)
7950 {
7951         MonoClass *klass;
7952         MonoDomain *domain = ((MonoObject*)tproxy)->vtable->domain;
7953         klass = mono_class_from_mono_type (rtype->type);
7954         mono_upgrade_remote_class (domain, (MonoObject*)tproxy, klass);
7955 }
7956
7957 /**
7958  * mono_marshal_get_struct_to_ptr:
7959  * @klass:
7960  *
7961  * generates IL code for StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)
7962  */
7963 MonoMethod *
7964 mono_marshal_get_struct_to_ptr (MonoClass *klass)
7965 {
7966         MonoMethodBuilder *mb;
7967         static MonoMethod *stoptr = NULL;
7968         MonoMethod *res;
7969
7970         g_assert (klass != NULL);
7971
7972         mono_marshal_load_type_info (klass);
7973
7974         if (klass->marshal_info->str_to_ptr)
7975                 return klass->marshal_info->str_to_ptr;
7976
7977         if (!stoptr) 
7978                 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
7979         g_assert (stoptr);
7980
7981         mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
7982
7983         if (klass->blittable) {
7984                 mono_mb_emit_byte (mb, CEE_LDARG_1);
7985                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7986                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
7987                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
7988                 mono_mb_emit_byte (mb, CEE_PREFIX1);
7989                 mono_mb_emit_byte (mb, CEE_CPBLK);
7990         } else {
7991
7992                 /* allocate local 0 (pointer) src_ptr */
7993                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7994                 /* allocate local 1 (pointer) dst_ptr */
7995                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7996                 /* allocate local 2 (boolean) delete_old */
7997                 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7998                 mono_mb_emit_byte (mb, CEE_LDARG_2);
7999                 mono_mb_emit_stloc (mb, 2);
8000
8001                 /* initialize src_ptr to point to the start of object data */
8002                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8003                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8004                 mono_mb_emit_stloc (mb, 0);
8005
8006                 /* initialize dst_ptr */
8007                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8008                 mono_mb_emit_stloc (mb, 1);
8009
8010                 emit_struct_conv (mb, klass, FALSE);
8011         }
8012
8013         mono_mb_emit_byte (mb, CEE_RET);
8014
8015         res = mono_mb_create_method (mb, mono_method_signature (stoptr), 0);
8016         mono_mb_free (mb);
8017
8018         klass->marshal_info->str_to_ptr = res;
8019         return res;
8020 }
8021
8022 /**
8023  * mono_marshal_get_ptr_to_struct:
8024  * @klass:
8025  *
8026  * generates IL code for PtrToStructure (IntPtr src, object structure)
8027  */
8028 MonoMethod *
8029 mono_marshal_get_ptr_to_struct (MonoClass *klass)
8030 {
8031         MonoMethodBuilder *mb;
8032         static MonoMethodSignature *ptostr = NULL;
8033         MonoMethod *res;
8034
8035         g_assert (klass != NULL);
8036
8037         mono_marshal_load_type_info (klass);
8038
8039         if (klass->marshal_info->ptr_to_str)
8040                 return klass->marshal_info->ptr_to_str;
8041
8042         if (!ptostr)
8043                 /* Create the signature corresponding to
8044                           static void PtrToStructure (IntPtr ptr, object structure);
8045                    defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
8046                 ptostr = mono_create_icall_signature ("void ptr object");
8047
8048         mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
8049
8050         if (klass->blittable) {
8051                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8052                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8053                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8054                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8055                 mono_mb_emit_byte (mb, CEE_PREFIX1);
8056                 mono_mb_emit_byte (mb, CEE_CPBLK);
8057         } else {
8058
8059                 /* allocate local 0 (pointer) src_ptr */
8060                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8061                 /* allocate local 1 (pointer) dst_ptr */
8062                 mono_mb_add_local (mb, &klass->this_arg);
8063                 
8064                 /* initialize src_ptr to point to the start of object data */
8065                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8066                 mono_mb_emit_stloc (mb, 0);
8067
8068                 /* initialize dst_ptr */
8069                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8070                 mono_mb_emit_op (mb, CEE_UNBOX, klass);
8071                 mono_mb_emit_stloc (mb, 1);
8072
8073                 emit_struct_conv (mb, klass, TRUE);
8074         }
8075
8076         mono_mb_emit_byte (mb, CEE_RET);
8077
8078         res = mono_mb_create_method (mb, ptostr, 0);
8079         mono_mb_free (mb);
8080
8081         klass->marshal_info->ptr_to_str = res;
8082         return res;
8083 }
8084
8085 /*
8086  * generates IL code for the synchronized wrapper: the generated method
8087  * calls METHOD while locking 'this' or the parent type.
8088  */
8089 MonoMethod *
8090 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
8091 {
8092         static MonoMethod *enter_method, *exit_method;
8093         MonoMethodSignature *sig;
8094         MonoExceptionClause *clause;
8095         MonoMethodHeader *header;
8096         MonoMethodBuilder *mb;
8097         MonoMethod *res;
8098         GHashTable *cache;
8099         int i, pos, this_local, ret_local = 0;
8100
8101         g_assert (method);
8102
8103         if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
8104                 return method;
8105
8106         cache = method->klass->image->synchronized_cache;
8107         if ((res = mono_marshal_find_in_cache (cache, method)))
8108                 return res;
8109
8110         sig = signature_dup (method->klass->image, mono_method_signature (method));
8111         sig->pinvoke = 0;
8112
8113         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
8114
8115         /* result */
8116         if (!MONO_TYPE_IS_VOID (sig->ret))
8117                 ret_local = mono_mb_add_local (mb, sig->ret);
8118
8119         /* this */
8120         this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
8121
8122         mono_loader_lock ();
8123         clause = mono_mempool_alloc0 (method->klass->image->mempool, sizeof (MonoExceptionClause));
8124         mono_loader_unlock ();
8125         clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
8126
8127         if (!enter_method) {
8128                 MonoMethodDesc *desc;
8129
8130                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
8131                 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
8132                 g_assert (enter_method);
8133                 mono_method_desc_free (desc);
8134                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
8135                 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
8136                 g_assert (exit_method);
8137                 mono_method_desc_free (desc);
8138         }
8139
8140         /* Push this or the type object */
8141         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
8142                 /*
8143                  * GetTypeFromHandle isn't called as a managed method because it has
8144                  * a funky calling sequence, e.g. ldtoken+GetTypeFromHandle gets
8145                  * transformed into something else by the JIT.
8146                  */
8147                 mono_mb_emit_ptr (mb, &method->klass->byval_arg);
8148                 mono_mb_emit_icall (mb, type_from_handle);
8149         }
8150         else
8151                 mono_mb_emit_ldarg (mb, 0);
8152         mono_mb_emit_stloc (mb, this_local);
8153
8154         /* Call Monitor::Enter() */
8155         mono_mb_emit_ldloc (mb, this_local);
8156         mono_mb_emit_managed_call (mb, enter_method, NULL);
8157
8158         clause->try_offset = mb->pos;
8159
8160         /* Call the method */
8161         if (sig->hasthis)
8162                 mono_mb_emit_ldarg (mb, 0);
8163         for (i = 0; i < sig->param_count; i++)
8164                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
8165         
8166         /* this is needed to avoid recursion */
8167         mono_mb_emit_byte (mb, CEE_PREFIX1);
8168         mono_mb_emit_op (mb, CEE_LDFTN, method);
8169         mono_mb_emit_calli (mb, mono_method_signature (method));
8170
8171         if (!MONO_TYPE_IS_VOID (sig->ret))
8172                 mono_mb_emit_stloc (mb, ret_local);
8173
8174         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8175
8176         clause->try_len = mb->pos - clause->try_offset;
8177         clause->handler_offset = mb->pos;
8178
8179         /* Call Monitor::Exit() */
8180         mono_mb_emit_ldloc (mb, this_local);
8181 /*      mono_mb_emit_native_call (mb, exit_sig, mono_monitor_exit); */
8182         mono_mb_emit_managed_call (mb, exit_method, NULL);
8183         mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8184
8185         clause->handler_len = mb->pos - clause->handler_offset;
8186
8187         mono_mb_patch_branch (mb, pos);
8188         if (!MONO_TYPE_IS_VOID (sig->ret))
8189                 mono_mb_emit_ldloc (mb, ret_local);
8190         mono_mb_emit_byte (mb, CEE_RET);
8191
8192         res = mono_mb_create_and_cache (cache, method,
8193                                                                         mb, sig, sig->param_count + 16);
8194         mono_mb_free (mb);
8195
8196         header = ((MonoMethodNormal *)res)->header;
8197         header->num_clauses = 1;
8198         header->clauses = clause;
8199
8200         return res;     
8201 }
8202
8203
8204 /*
8205  * the returned method calls 'method' unboxing the this argument
8206  */
8207 MonoMethod *
8208 mono_marshal_get_unbox_wrapper (MonoMethod *method)
8209 {
8210         MonoMethodSignature *sig = mono_method_signature (method);
8211         int i;
8212         MonoMethodBuilder *mb;
8213         MonoMethod *res;
8214         GHashTable *cache;
8215
8216         cache = method->klass->image->unbox_wrapper_cache;
8217         if ((res = mono_marshal_find_in_cache (cache, method)))
8218                 return res;
8219
8220         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
8221
8222         g_assert (sig->hasthis);
8223         
8224         mono_mb_emit_ldarg (mb, 0); 
8225         mono_mb_emit_icon (mb, sizeof (MonoObject));
8226         mono_mb_emit_byte (mb, CEE_ADD);
8227         for (i = 0; i < sig->param_count; ++i)
8228                 mono_mb_emit_ldarg (mb, i + 1);
8229         mono_mb_emit_managed_call (mb, method, NULL);
8230         mono_mb_emit_byte (mb, CEE_RET);
8231
8232         res = mono_mb_create_and_cache (cache, method,
8233                                                                                  mb, sig, sig->param_count + 16);
8234         mono_mb_free (mb);
8235
8236         /* 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)); */
8237
8238         return res;     
8239 }
8240
8241 MonoMethod*
8242 mono_marshal_get_stelemref ()
8243 {
8244         static MonoMethod* ret = NULL;
8245         MonoMethodSignature *sig;
8246         MonoMethodBuilder *mb;
8247         
8248         guint32 b1, b2, b3, b4;
8249         guint32 copy_pos;
8250         int aklass, vklass;
8251         int array_slot_addr;
8252         
8253         if (ret)
8254                 return ret;
8255         
8256         mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
8257         
8258
8259         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
8260
8261         /* void stelemref (void* array, int idx, void* value) */
8262         sig->ret = &mono_defaults.void_class->byval_arg;
8263         sig->params [0] = &mono_defaults.object_class->byval_arg;
8264         sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
8265         sig->params [2] = &mono_defaults.object_class->byval_arg;
8266                 
8267         aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8268         vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8269         array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
8270         
8271         /*
8272         the method:
8273         <ldelema (bound check)>
8274         if (!value)
8275                 goto store;
8276         
8277         aklass = array->vtable->klass->element_class;
8278         vklass = value->vtable->klass;
8279         
8280         if (vklass->idepth < aklass->idepth)
8281                 goto long;
8282         
8283         if (vklass->supertypes [aklass->idepth - 1] != aklass)
8284                 goto long;
8285         
8286         store:
8287                 *array_slot_addr = value;
8288                 return;
8289         
8290         long:
8291                 if (mono_object_isinst (value, aklass))
8292                         goto store;
8293                 
8294                 throw new ArrayTypeMismatchException ();
8295         */
8296         
8297         /* ldelema (implicit bound check) */
8298         mono_mb_emit_ldarg (mb, 0);
8299         mono_mb_emit_ldarg (mb, 1);
8300         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
8301         mono_mb_emit_stloc (mb, array_slot_addr);
8302                 
8303         /* if (!value) goto do_store */
8304         mono_mb_emit_ldarg (mb, 2);
8305         b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
8306         
8307         /* aklass = array->vtable->klass->element_class */
8308         mono_mb_emit_ldarg (mb, 0);
8309         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoObject, vtable));
8310         mono_mb_emit_byte (mb, CEE_LDIND_I);
8311         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoVTable, klass));
8312         mono_mb_emit_byte (mb, CEE_LDIND_I);
8313         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, element_class));
8314         mono_mb_emit_byte (mb, CEE_LDIND_I);
8315         mono_mb_emit_stloc (mb, aklass);
8316         
8317         /* vklass = value->vtable->klass */
8318         mono_mb_emit_ldarg (mb, 2);
8319         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoObject, vtable));
8320         mono_mb_emit_byte (mb, CEE_LDIND_I);
8321         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoVTable, klass));
8322         mono_mb_emit_byte (mb, CEE_LDIND_I);
8323         mono_mb_emit_stloc (mb, vklass);
8324         
8325         /* if (vklass->idepth < aklass->idepth) goto failue */
8326         mono_mb_emit_ldloc (mb, vklass);
8327         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, idepth));
8328         mono_mb_emit_byte (mb, CEE_LDIND_U2);
8329         
8330         mono_mb_emit_ldloc (mb, aklass);
8331         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, idepth));
8332         mono_mb_emit_byte (mb, CEE_LDIND_U2);
8333         
8334         b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
8335         
8336         /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
8337         mono_mb_emit_ldloc (mb, vklass);
8338         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, supertypes));
8339         mono_mb_emit_byte (mb, CEE_LDIND_I);
8340         
8341         mono_mb_emit_ldloc (mb, aklass);
8342         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, idepth));
8343         mono_mb_emit_byte (mb, CEE_LDIND_U2);
8344         mono_mb_emit_icon (mb, 1);
8345         mono_mb_emit_byte (mb, CEE_SUB);
8346         mono_mb_emit_icon (mb, sizeof (void*));
8347         mono_mb_emit_byte (mb, CEE_MUL);
8348         mono_mb_emit_byte (mb, CEE_ADD);
8349         mono_mb_emit_byte (mb, CEE_LDIND_I);
8350         
8351         mono_mb_emit_ldloc (mb, aklass);
8352         
8353         b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
8354         
8355         copy_pos = mb->pos;
8356         /* do_store */
8357         mono_mb_patch_branch (mb, b1);
8358         mono_mb_emit_ldloc (mb, array_slot_addr);
8359         mono_mb_emit_ldarg (mb, 2);
8360         mono_mb_emit_byte (mb, CEE_STIND_REF);
8361         
8362         mono_mb_emit_byte (mb, CEE_RET);
8363         
8364         /* the hard way */
8365         mono_mb_patch_branch (mb, b2);
8366         mono_mb_patch_branch (mb, b3);
8367         
8368         mono_mb_emit_ldarg (mb, 2);
8369         mono_mb_emit_ldloc (mb, aklass);
8370         mono_mb_emit_icall (mb, mono_object_isinst);
8371         
8372         b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
8373         mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
8374         mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
8375         
8376         mono_mb_emit_byte (mb, CEE_RET);
8377         ret = mono_mb_create_method (mb, sig, 4);
8378         mono_mb_free (mb);
8379         return ret;
8380 }
8381
8382 MonoMethod*
8383 mono_marshal_get_write_barrier (void)
8384 {
8385         static MonoMethod* ret = NULL;
8386         MonoMethodSignature *sig;
8387         MonoMethodBuilder *mb;
8388         int max_stack = 2;
8389
8390         if (ret)
8391                 return ret;
8392         
8393         mb = mono_mb_new (mono_defaults.object_class, "writebarrier", MONO_WRAPPER_WRITE_BARRIER);
8394
8395         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
8396
8397         /* void writebarrier (MonoObject** addr, MonoObject* obj) */
8398         sig->ret = &mono_defaults.void_class->byval_arg;
8399         sig->params [0] = &mono_defaults.object_class->this_arg;
8400         sig->params [1] = &mono_defaults.object_class->byval_arg;
8401
8402         /* just the store right now: add an hook for the GC to use, maybe something
8403          * that can be used for stelemref as well
8404          * We need a write barrier variant to be used with struct copies as well, though
8405          * there are also other approaches possible, like writing a wrapper specific to
8406          * the struct or to the reference pattern in the struct...
8407          * Depending on the GC, we may want variants that take the object we store to
8408          * when it is available.
8409          */
8410         mono_mb_emit_ldarg (mb, 0);
8411         mono_mb_emit_ldarg (mb, 1);
8412         mono_mb_emit_icall (mb, mono_gc_wbarrier_generic_store);
8413         /*mono_mb_emit_byte (mb, CEE_STIND_REF);*/
8414
8415         mono_mb_emit_byte (mb, CEE_RET);
8416
8417         ret = mono_mb_create_method (mb, sig, max_stack);
8418         mono_mb_free (mb);
8419         return ret;
8420 }
8421
8422 void*
8423 mono_marshal_alloc (gulong size)
8424 {
8425         gpointer res;
8426
8427 #ifdef PLATFORM_WIN32
8428         res = CoTaskMemAlloc (size);
8429 #else
8430         res = g_try_malloc ((gulong)size);
8431         if (!res)
8432                 mono_gc_out_of_memory ((gulong)size);
8433 #endif
8434         return res;
8435 }
8436
8437 void
8438 mono_marshal_free (gpointer ptr)
8439 {
8440 #ifdef PLATFORM_WIN32
8441         CoTaskMemFree (ptr);
8442 #else
8443         g_free (ptr);
8444 #endif
8445 }
8446
8447 void
8448 mono_marshal_free_array (gpointer *ptr, int size) 
8449 {
8450         int i;
8451
8452         if (!ptr)
8453                 return;
8454
8455         for (i = 0; i < size; i++)
8456                 if (ptr [i])
8457                         g_free (ptr [i]);
8458 }
8459
8460 void *
8461 mono_marshal_realloc (gpointer ptr, gpointer size) 
8462 {
8463         MONO_ARCH_SAVE_REGS;
8464
8465         return g_try_realloc (ptr, (gulong)size);
8466 }
8467
8468 void *
8469 mono_marshal_string_to_utf16 (MonoString *s)
8470 {
8471         return s ? mono_string_chars (s) : NULL;
8472 }
8473
8474 /**
8475  * mono_marshal_set_last_error:
8476  *
8477  * This function is invoked to set the last error value from a P/Invoke call
8478  * which has SetLastError set.
8479  */
8480 void
8481 mono_marshal_set_last_error (void)
8482 {
8483 #ifdef WIN32
8484         TlsSetValue (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
8485 #else
8486         TlsSetValue (last_error_tls_id, GINT_TO_POINTER (errno));
8487 #endif
8488 }
8489
8490 static void
8491 mono_marshal_set_last_error_windows (int error)
8492 {
8493 #ifdef WIN32
8494         TlsSetValue (last_error_tls_id, GINT_TO_POINTER (error));
8495 #endif
8496 }
8497
8498 void
8499 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
8500                                                                     gpointer dest, gint32 length)
8501 {
8502         int element_size;
8503         void *source_addr;
8504
8505         MONO_ARCH_SAVE_REGS;
8506
8507         MONO_CHECK_ARG_NULL (src);
8508         MONO_CHECK_ARG_NULL (dest);
8509
8510         g_assert (src->obj.vtable->klass->rank == 1);
8511         g_assert (start_index >= 0);
8512         g_assert (length >= 0);
8513         g_assert (start_index + length <= mono_array_length (src));
8514
8515         element_size = mono_array_element_size (src->obj.vtable->klass);
8516
8517         /* no references should be involved */
8518         source_addr = mono_array_addr_with_size (src, element_size, start_index);
8519
8520         memcpy (dest, source_addr, length * element_size);
8521 }
8522
8523 void
8524 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
8525                                                                       MonoArray *dest, gint32 length)
8526 {
8527         int element_size;
8528         void *dest_addr;
8529
8530         MONO_ARCH_SAVE_REGS;
8531
8532         MONO_CHECK_ARG_NULL (src);
8533         MONO_CHECK_ARG_NULL (dest);
8534
8535         g_assert (dest->obj.vtable->klass->rank == 1);
8536         g_assert (start_index >= 0);
8537         g_assert (length >= 0);
8538         g_assert (start_index + length <= mono_array_length (dest));
8539
8540         element_size = mono_array_element_size (dest->obj.vtable->klass);
8541           
8542         /* no references should be involved */
8543         dest_addr = mono_array_addr_with_size (dest, element_size, start_index);
8544
8545         memcpy (dest_addr, src, length * element_size);
8546 }
8547
8548 #if NO_UNALIGNED_ACCESS
8549 #define RETURN_UNALIGNED(type, addr) \
8550         { \
8551                 type val; \
8552                 memcpy(&val, p + offset, sizeof(val)); \
8553                 return val; \
8554         }
8555 #define WRITE_UNALIGNED(type, addr, val) \
8556         memcpy(addr, &val, sizeof(type))
8557 #else
8558 #define RETURN_UNALIGNED(type, addr) \
8559         return *(type*)(p + offset);
8560 #define WRITE_UNALIGNED(type, addr, val) \
8561         (*(type *)(addr) = (val))
8562 #endif
8563
8564 gpointer
8565 ves_icall_System_Runtime_InteropServices_Marshal_ReadIntPtr (gpointer ptr, gint32 offset)
8566 {
8567         char *p = ptr;
8568
8569         MONO_ARCH_SAVE_REGS;
8570
8571         RETURN_UNALIGNED(gpointer, p + offset);
8572 }
8573
8574 unsigned char
8575 ves_icall_System_Runtime_InteropServices_Marshal_ReadByte (gpointer ptr, gint32 offset)
8576 {
8577         char *p = ptr;
8578
8579         MONO_ARCH_SAVE_REGS;
8580
8581         return *(unsigned char*)(p + offset);
8582 }
8583
8584 gint16
8585 ves_icall_System_Runtime_InteropServices_Marshal_ReadInt16 (gpointer ptr, gint32 offset)
8586 {
8587         char *p = ptr;
8588
8589         MONO_ARCH_SAVE_REGS;
8590
8591         RETURN_UNALIGNED(gint16, p + offset);
8592 }
8593
8594 gint32
8595 ves_icall_System_Runtime_InteropServices_Marshal_ReadInt32 (gpointer ptr, gint32 offset)
8596 {
8597         char *p = ptr;
8598
8599         MONO_ARCH_SAVE_REGS;
8600
8601         RETURN_UNALIGNED(gint32, p + offset);
8602 }
8603
8604 gint64
8605 ves_icall_System_Runtime_InteropServices_Marshal_ReadInt64 (gpointer ptr, gint32 offset)
8606 {
8607         char *p = ptr;
8608
8609         MONO_ARCH_SAVE_REGS;
8610
8611         RETURN_UNALIGNED(gint64, p + offset);
8612 }
8613
8614 void
8615 ves_icall_System_Runtime_InteropServices_Marshal_WriteByte (gpointer ptr, gint32 offset, unsigned char val)
8616 {
8617         char *p = ptr;
8618
8619         MONO_ARCH_SAVE_REGS;
8620
8621         *(unsigned char*)(p + offset) = val;
8622 }
8623
8624 void
8625 ves_icall_System_Runtime_InteropServices_Marshal_WriteIntPtr (gpointer ptr, gint32 offset, gpointer val)
8626 {
8627         char *p = ptr;
8628
8629         MONO_ARCH_SAVE_REGS;
8630
8631         WRITE_UNALIGNED(gpointer, p + offset, val);
8632 }
8633
8634 void
8635 ves_icall_System_Runtime_InteropServices_Marshal_WriteInt16 (gpointer ptr, gint32 offset, gint16 val)
8636 {
8637         char *p = ptr;
8638
8639         MONO_ARCH_SAVE_REGS;
8640
8641         WRITE_UNALIGNED(gint16, p + offset, val);
8642 }
8643
8644 void
8645 ves_icall_System_Runtime_InteropServices_Marshal_WriteInt32 (gpointer ptr, gint32 offset, gint32 val)
8646 {
8647         char *p = ptr;
8648
8649         MONO_ARCH_SAVE_REGS;
8650
8651         WRITE_UNALIGNED(gint32, p + offset, val);
8652 }
8653
8654 void
8655 ves_icall_System_Runtime_InteropServices_Marshal_WriteInt64 (gpointer ptr, gint32 offset, gint64 val)
8656 {
8657         char *p = ptr;
8658
8659         MONO_ARCH_SAVE_REGS;
8660
8661         WRITE_UNALIGNED(gint64, p + offset, val);
8662 }
8663
8664 MonoString *
8665 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr)
8666 {
8667         MONO_ARCH_SAVE_REGS;
8668
8669         if (ptr == NULL)
8670                 return NULL;
8671         else
8672                 return mono_string_new (mono_domain_get (), ptr);
8673 }
8674
8675 MonoString *
8676 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
8677 {
8678         MONO_ARCH_SAVE_REGS;
8679
8680         if (ptr == NULL) {
8681                 mono_raise_exception (mono_get_exception_argument_null ("ptr"));
8682                 g_assert_not_reached ();
8683                 return NULL;
8684         } else
8685                 return mono_string_new_len (mono_domain_get (), ptr, len);
8686 }
8687
8688 MonoString *
8689 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
8690 {
8691         MonoDomain *domain = mono_domain_get (); 
8692         int len = 0;
8693         guint16 *t = ptr;
8694
8695         MONO_ARCH_SAVE_REGS;
8696
8697         if (ptr == NULL)
8698                 return NULL;
8699
8700         while (*t++)
8701                 len++;
8702
8703         return mono_string_new_utf16 (domain, ptr, len);
8704 }
8705
8706 MonoString *
8707 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
8708 {
8709         MonoDomain *domain = mono_domain_get (); 
8710
8711         MONO_ARCH_SAVE_REGS;
8712
8713         if (ptr == NULL) {
8714                 mono_raise_exception (mono_get_exception_argument_null ("ptr"));
8715                 g_assert_not_reached ();
8716                 return NULL;
8717         } else
8718                 return mono_string_new_utf16 (domain, ptr, len);
8719 }
8720
8721 MonoString *
8722 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringBSTR (gpointer ptr)
8723 {
8724         MONO_ARCH_SAVE_REGS;
8725
8726         return mono_string_from_bstr(ptr);
8727 }
8728
8729 gpointer
8730 ves_icall_System_Runtime_InteropServices_Marshal_StringToBSTR (MonoString* ptr)
8731 {
8732         MONO_ARCH_SAVE_REGS;
8733
8734         return mono_string_to_bstr(ptr);
8735 }
8736
8737 #ifdef  __i386__
8738 #ifdef _MSC_VER
8739 #define STDCALL __stdcall
8740 #else
8741 #define STDCALL __attribute__((stdcall))
8742 #endif
8743 #else
8744 #define STDCALL
8745 #endif
8746
8747 typedef struct
8748 {
8749         int (STDCALL *QueryInterface)(gpointer pUnk, gpointer riid, gpointer* ppv);
8750         int (STDCALL *AddRef)(gpointer pUnk);
8751         int (STDCALL *Release)(gpointer pUnk);
8752 } MonoIUnknown;
8753
8754 void
8755 ves_icall_System_Runtime_InteropServices_Marshal_FreeBSTR (gpointer ptr)
8756 {
8757         MONO_ARCH_SAVE_REGS;
8758
8759         mono_free_bstr (ptr);
8760 }
8761
8762 int
8763 ves_icall_System_Runtime_InteropServices_Marshal_AddRef (gpointer pUnk)
8764 {
8765         MONO_ARCH_SAVE_REGS;
8766
8767         return (*(MonoIUnknown**)pUnk)->AddRef(pUnk);
8768 }
8769
8770 int
8771 ves_icall_System_Runtime_InteropServices_Marshal_QueryInterface (gpointer pUnk, gpointer riid, gpointer* ppv)
8772 {
8773         MONO_ARCH_SAVE_REGS;
8774
8775         return (*(MonoIUnknown**)pUnk)->QueryInterface(pUnk, riid, ppv);
8776 }
8777
8778 int
8779 ves_icall_System_Runtime_InteropServices_Marshal_Release (gpointer pUnk)
8780 {
8781         MONO_ARCH_SAVE_REGS;
8782
8783         return (*(MonoIUnknown**)pUnk)->Release(pUnk);
8784 }
8785
8786 guint32
8787 ves_icall_System_Runtime_InteropServices_Marshal_GetComSlotForMethodInfoInternal (MonoReflectionMethod *m)
8788 {
8789         MONO_ARCH_SAVE_REGS;
8790
8791         return cominterop_get_com_slot_for_method (m->method);
8792 }
8793
8794 guint32 
8795 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
8796 {
8797         MONO_ARCH_SAVE_REGS;
8798
8799         return (GPOINTER_TO_INT (TlsGetValue (last_error_tls_id)));
8800 }
8801
8802 guint32 
8803 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionType *rtype)
8804 {
8805         MonoClass *klass;
8806         MonoType *type;
8807         guint32 layout;
8808
8809         MONO_ARCH_SAVE_REGS;
8810
8811         MONO_CHECK_ARG_NULL (rtype);
8812
8813         type = rtype->type;
8814         klass = mono_class_from_mono_type (type);
8815         layout = (klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK);
8816
8817         if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
8818                 gchar *msg;
8819                 MonoException *exc;
8820
8821                 msg = g_strdup_printf ("Type %s cannot be marshaled as an unmanaged structure.", klass->name);
8822                 exc = mono_get_exception_argument ("t", msg);
8823                 g_free (msg);
8824                 mono_raise_exception (exc);
8825         }
8826
8827
8828         return mono_class_native_size (klass, NULL);
8829 }
8830
8831 void
8832 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
8833 {
8834         MonoMethod *method;
8835         gpointer pa [3];
8836
8837         MONO_ARCH_SAVE_REGS;
8838
8839         MONO_CHECK_ARG_NULL (obj);
8840         MONO_CHECK_ARG_NULL (dst);
8841
8842         method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
8843
8844         pa [0] = obj;
8845         pa [1] = &dst;
8846         pa [2] = &delete_old;
8847
8848         mono_runtime_invoke (method, NULL, pa, NULL);
8849 }
8850
8851 static void
8852 ptr_to_structure (gpointer src, MonoObject *dst)
8853 {
8854         MonoMethod *method;
8855         gpointer pa [2];
8856
8857         method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
8858
8859         pa [0] = &src;
8860         pa [1] = dst;
8861
8862         mono_runtime_invoke (method, NULL, pa, NULL);
8863 }
8864
8865 void
8866 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
8867 {
8868         MonoType *t;
8869
8870         MONO_ARCH_SAVE_REGS;
8871
8872         MONO_CHECK_ARG_NULL (src);
8873         MONO_CHECK_ARG_NULL (dst);
8874         
8875         t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
8876
8877         if (t->type == MONO_TYPE_VALUETYPE) {
8878                 MonoException *exc;
8879                 gchar *tmp;
8880
8881                 tmp = g_strdup_printf ("Destination is a boxed value type.");
8882                 exc = mono_get_exception_argument ("dst", tmp);
8883                 g_free (tmp);  
8884
8885                 mono_raise_exception (exc);
8886                 return;
8887         }
8888
8889         ptr_to_structure (src, dst);
8890 }
8891
8892 MonoObject *
8893 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
8894 {
8895         MonoDomain *domain = mono_domain_get (); 
8896         MonoObject *res;
8897
8898         MONO_ARCH_SAVE_REGS;
8899
8900         MONO_CHECK_ARG_NULL (src);
8901         MONO_CHECK_ARG_NULL (type);
8902
8903         res = mono_object_new (domain, mono_class_from_mono_type (type->type));
8904
8905         ptr_to_structure (src, res);
8906
8907         return res;
8908 }
8909
8910 int
8911 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *type, MonoString *field_name)
8912 {
8913         MonoMarshalType *info;
8914         MonoClass *klass;
8915         char *fname;
8916         int match_index = -1;
8917         
8918         MONO_ARCH_SAVE_REGS;
8919
8920         MONO_CHECK_ARG_NULL (type);
8921         MONO_CHECK_ARG_NULL (field_name);
8922
8923         fname = mono_string_to_utf8 (field_name);
8924         klass = mono_class_from_mono_type (type->type);
8925
8926         while (klass && match_index == -1) {
8927                 MonoClassField* field;
8928                 int i = 0;
8929                 gpointer iter = NULL;
8930                 while ((field = mono_class_get_fields (klass, &iter))) {
8931                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
8932                                 continue;
8933                         if (!strcmp (fname, field->name)) {
8934                                 match_index = i;
8935                                 break;
8936                         }
8937                         i ++;
8938                 }
8939
8940                 if (match_index == -1)
8941                         klass = klass->parent;
8942         }
8943
8944         g_free (fname);
8945
8946         if(match_index == -1) {
8947                 MonoException* exc;
8948                 gchar *tmp;
8949
8950                 /* Get back original class instance */
8951                 klass = mono_class_from_mono_type (type->type);
8952
8953                 tmp = g_strdup_printf ("Field passed in is not a marshaled member of the type %s", klass->name);
8954                 exc = mono_get_exception_argument ("fieldName", tmp);
8955                 g_free (tmp);
8956  
8957                 mono_raise_exception ((MonoException*)exc);
8958         }
8959
8960         info = mono_marshal_load_type_info (klass);     
8961         return info->fields [match_index].offset;
8962 }
8963
8964 gpointer
8965 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
8966 {
8967         MONO_ARCH_SAVE_REGS;
8968
8969         return mono_string_to_utf8 (string);
8970 }
8971
8972 gpointer
8973 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
8974 {
8975         MONO_ARCH_SAVE_REGS;
8976
8977         if (string == NULL)
8978                 return NULL;
8979         else {
8980                 gunichar2 *res = g_malloc ((mono_string_length (string) + 1) * 2);
8981                 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
8982                 res [mono_string_length (string)] = 0;
8983                 return res;
8984         }
8985 }
8986
8987 static void
8988 mono_struct_delete_old (MonoClass *klass, char *ptr)
8989 {
8990         MonoMarshalType *info;
8991         int i;
8992
8993         info = mono_marshal_load_type_info (klass);
8994
8995         for (i = 0; i < info->num_fields; i++) {
8996                 MonoMarshalNative ntype;
8997                 MonoMarshalConv conv;
8998                 MonoType *ftype = info->fields [i].field->type;
8999                 char *cpos;
9000
9001                 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
9002                         continue;
9003
9004                 ntype = mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, 
9005                                                 klass->unicode, &conv);
9006                         
9007                 cpos = ptr + info->fields [i].offset;
9008
9009                 switch (conv) {
9010                 case MONO_MARSHAL_CONV_NONE:
9011                         if (MONO_TYPE_ISSTRUCT (ftype)) {
9012                                 mono_struct_delete_old (ftype->data.klass, cpos);
9013                                 continue;
9014                         }
9015                         break;
9016                 case MONO_MARSHAL_CONV_STR_LPWSTR:
9017                         /* We assume this field points inside a MonoString */
9018                         break;
9019                 case MONO_MARSHAL_CONV_STR_LPSTR:
9020                 case MONO_MARSHAL_CONV_STR_LPTSTR:
9021                 case MONO_MARSHAL_CONV_STR_BSTR:
9022                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
9023                 case MONO_MARSHAL_CONV_STR_TBSTR:
9024                         mono_marshal_free (*(gpointer *)cpos);
9025                         break;
9026                 default:
9027                         continue;
9028                 }
9029         }
9030 }
9031
9032 void
9033 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
9034 {
9035         MonoClass *klass;
9036
9037         MONO_ARCH_SAVE_REGS;
9038
9039         MONO_CHECK_ARG_NULL (src);
9040         MONO_CHECK_ARG_NULL (type);
9041
9042         klass = mono_class_from_mono_type (type->type);
9043
9044         mono_struct_delete_old (klass, (char *)src);
9045 }
9046
9047
9048 /* FIXME: on win32 we should probably use GlobalAlloc(). */
9049 void*
9050 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (int size)
9051 {
9052         gpointer res;
9053
9054         MONO_ARCH_SAVE_REGS;
9055
9056         if ((gulong)size == 0)
9057                 /* This returns a valid pointer for size 0 on MS.NET */
9058                 size = 4;
9059
9060         res = g_try_malloc ((gulong)size);
9061         if (!res)
9062                 mono_gc_out_of_memory ((gulong)size);
9063
9064         return res;
9065 }
9066
9067 void
9068 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
9069 {
9070         MONO_ARCH_SAVE_REGS;
9071
9072         g_free (ptr);
9073 }
9074
9075 void*
9076 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
9077 {
9078         MONO_ARCH_SAVE_REGS;
9079
9080 #ifdef PLATFORM_WIN32
9081         return CoTaskMemAlloc (size);
9082 #else
9083         return g_try_malloc ((gulong)size);
9084 #endif
9085 }
9086
9087 void
9088 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
9089 {
9090         MONO_ARCH_SAVE_REGS;
9091
9092 #ifdef PLATFORM_WIN32
9093         CoTaskMemFree (ptr);
9094 #else
9095         g_free (ptr);
9096 #endif
9097 }
9098
9099 void*
9100 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
9101 {
9102         return mono_array_addr_with_size (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
9103 }
9104
9105 MonoDelegate*
9106 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionType *type)
9107 {
9108         return mono_ftnptr_to_delegate (mono_type_get_class (type->type), ftn);
9109 }
9110
9111 /* Only used for COM RCWs */
9112 MonoObject *
9113 ves_icall_System_ComObject_CreateRCW (MonoReflectionType *type)
9114 {
9115         MonoClass *klass;
9116         MonoDomain *domain;
9117         MonoObject *obj;
9118         
9119         MONO_ARCH_SAVE_REGS;
9120
9121         domain = mono_object_domain (type);
9122         klass = mono_class_from_mono_type (type->type);
9123
9124         /* call mono_object_new_alloc_specific instead of mono_object_new
9125          * because we want to actually create object. mono_object_new checks
9126          * to see if type is import and creates transparent proxy. this method
9127          * is called by the corresponding real proxy to create the real RCW.
9128          * Constructor does not need to be called. Will be called later.
9129         */
9130         obj = mono_object_new_alloc_specific (mono_class_vtable (domain, klass));
9131         return obj;
9132 }
9133
9134 static gboolean    
9135 cominterop_finalizer (gpointer key, gpointer value, gpointer user_data)
9136 {
9137         ves_icall_System_Runtime_InteropServices_Marshal_Release (value);
9138         return TRUE;
9139 }
9140
9141 void
9142 ves_icall_System_ComObject_Finalizer(MonoComObject* obj)
9143 {
9144         g_assert(obj);
9145         if (obj->itf_hash)
9146                 g_hash_table_foreach_remove (obj->itf_hash, cominterop_finalizer, NULL);
9147         obj->itf_hash = NULL;
9148 }
9149
9150 #define MONO_IUNKNOWN_INTERFACE_SLOT 0
9151
9152 gpointer
9153 ves_icall_System_ComObject_FindInterface (MonoComObject* obj, MonoReflectionType* type)
9154 {
9155         MonoClass* klass;
9156         g_assert(obj);
9157         g_assert(obj->itf_hash);
9158
9159         klass = mono_class_from_mono_type (type->type);
9160
9161         return g_hash_table_lookup (obj->itf_hash, GUINT_TO_POINTER ((guint)klass->interface_id));
9162 }
9163
9164 void
9165 ves_icall_System_ComObject_CacheInterface (MonoComObject* obj, MonoReflectionType* type, gpointer pItf)
9166 {
9167         MonoClass* klass;
9168         g_assert(obj);
9169         g_assert(obj->itf_hash);
9170
9171         klass = mono_class_from_mono_type (type->type);
9172
9173         g_hash_table_insert (obj->itf_hash, GUINT_TO_POINTER ((guint)klass->interface_id), pItf);
9174 }
9175
9176 gpointer
9177 ves_icall_System_ComObject_GetIUnknown (MonoComObject* obj)
9178 {
9179         g_assert(obj);
9180         if (!obj->itf_hash)
9181                 return NULL;
9182         return g_hash_table_lookup (obj->itf_hash, MONO_IUNKNOWN_INTERFACE_SLOT);
9183 }
9184
9185 void
9186 ves_icall_System_ComObject_SetIUnknown (MonoComObject* obj, gpointer pUnk)
9187 {
9188         g_assert(obj);
9189         g_assert(!obj->itf_hash);
9190         obj->itf_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
9191         g_hash_table_insert (obj->itf_hash, MONO_IUNKNOWN_INTERFACE_SLOT, pUnk);
9192 }
9193
9194 MonoMarshalType *
9195 mono_marshal_load_type_info (MonoClass* klass)
9196 {
9197         int j, count = 0;
9198         guint32 native_size = 0, min_align = 1;
9199         MonoMarshalType *info;
9200         MonoClassField* field;
9201         gpointer iter;
9202         guint32 layout;
9203
9204         g_assert (klass != NULL);
9205
9206         if (klass->marshal_info)
9207                 return klass->marshal_info;
9208
9209         if (!klass->inited)
9210                 mono_class_init (klass);
9211         
9212         iter = NULL;
9213         while ((field = mono_class_get_fields (klass, &iter))) {
9214                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
9215                         continue;
9216                 if (mono_field_is_deleted (field))
9217                         continue;
9218                 count++;
9219         }
9220
9221         layout = klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
9222
9223         klass->marshal_info = info = g_malloc0 (sizeof (MonoMarshalType) + sizeof (MonoMarshalField) * count);
9224         info->num_fields = count;
9225         
9226         /* Try to find a size for this type in metadata */
9227         mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
9228
9229         if (klass->parent) {
9230                 int parent_size = mono_class_native_size (klass->parent, NULL);
9231
9232                 /* Add parent size to real size */
9233                 native_size += parent_size;
9234                 info->native_size = parent_size;
9235         }
9236         
9237         iter = NULL;
9238         j = 0;
9239         while ((field = mono_class_get_fields (klass, &iter))) {
9240                 int size;
9241                 guint32 align;
9242                 
9243                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
9244                         continue;
9245
9246                 if (mono_field_is_deleted (field))
9247                         continue;
9248                 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
9249                         mono_metadata_field_info (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1, 
9250                                                   NULL, NULL, &info->fields [j].mspec);
9251
9252                 info->fields [j].field = field;
9253
9254                 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
9255                         (strcmp (field->name, "$PRIVATE$") == 0)) {
9256                         /* This field is a hack inserted by MCS to empty structures */
9257                         continue;
9258                 }
9259
9260                 switch (layout) {
9261                 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
9262                 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
9263                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
9264                                                        &align, TRUE, klass->unicode);
9265                         align = klass->packing_size ? MIN (klass->packing_size, align): align;
9266                         min_align = MAX (align, min_align);
9267                         info->fields [j].offset = info->native_size;
9268                         info->fields [j].offset += align - 1;
9269                         info->fields [j].offset &= ~(align - 1);
9270                         info->native_size = info->fields [j].offset + size;
9271                         break;
9272                 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
9273                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
9274                                                        &align, TRUE, klass->unicode);
9275                         align = klass->packing_size ? MIN (klass->packing_size, align): align;
9276                         min_align = MAX (align, min_align);
9277                         info->fields [j].offset = field->offset - sizeof (MonoObject);
9278                         info->native_size = MAX (info->native_size, info->fields [j].offset + size);
9279                         break;
9280                 }       
9281                 j++;
9282         }
9283
9284         if(layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
9285                 info->native_size = MAX (native_size, info->native_size);
9286         }
9287
9288         if (info->native_size & (min_align - 1)) {
9289                 info->native_size += min_align - 1;
9290                 info->native_size &= ~(min_align - 1);
9291         }
9292
9293         /* Update the class's blittable info, if the layouts don't match */
9294         if (info->native_size != mono_class_value_size (klass, NULL))
9295                 klass->blittable = FALSE;
9296
9297         /* If this is an array type, ensure that we have element info */
9298         if (klass->element_class) {
9299                 mono_marshal_load_type_info (klass->element_class);
9300         }
9301
9302         return klass->marshal_info;
9303 }
9304
9305 /**
9306  * mono_class_native_size:
9307  * @klass: a class 
9308  * 
9309  * Returns: the native size of an object instance (when marshaled 
9310  * to unmanaged code) 
9311  */
9312 gint32
9313 mono_class_native_size (MonoClass *klass, guint32 *align)
9314 {       
9315         if (!klass->marshal_info)
9316                 mono_marshal_load_type_info (klass);
9317
9318         if (align)
9319                 *align = klass->min_align;
9320
9321         return klass->marshal_info->native_size;
9322 }
9323
9324 /*
9325  * mono_type_native_stack_size:
9326  * @t: the type to return the size it uses on the stack
9327  *
9328  * Returns: the number of bytes required to hold an instance of this
9329  * type on the native stack
9330  */
9331 int
9332 mono_type_native_stack_size (MonoType *t, guint32 *align)
9333 {
9334         guint32 tmp;
9335
9336         g_assert (t != NULL);
9337
9338         if (!align)
9339                 align = &tmp;
9340
9341         if (t->byref) {
9342                 *align = 4;
9343                 return 4;
9344         }
9345
9346         switch (t->type){
9347         case MONO_TYPE_BOOLEAN:
9348         case MONO_TYPE_CHAR:
9349         case MONO_TYPE_I1:
9350         case MONO_TYPE_U1:
9351         case MONO_TYPE_I2:
9352         case MONO_TYPE_U2:
9353         case MONO_TYPE_I4:
9354         case MONO_TYPE_U4:
9355         case MONO_TYPE_I:
9356         case MONO_TYPE_U:
9357         case MONO_TYPE_STRING:
9358         case MONO_TYPE_OBJECT:
9359         case MONO_TYPE_CLASS:
9360         case MONO_TYPE_SZARRAY:
9361         case MONO_TYPE_PTR:
9362         case MONO_TYPE_FNPTR:
9363         case MONO_TYPE_ARRAY:
9364         case MONO_TYPE_TYPEDBYREF:
9365                 *align = 4;
9366                 return 4;
9367         case MONO_TYPE_R4:
9368                 *align = 4;
9369                 return 4;
9370         case MONO_TYPE_I8:
9371         case MONO_TYPE_U8:
9372         case MONO_TYPE_R8:
9373                 *align = 4;
9374                 return 8;
9375         case MONO_TYPE_VALUETYPE: {
9376                 guint32 size;
9377
9378                 if (t->data.klass->enumtype)
9379                         return mono_type_native_stack_size (t->data.klass->enum_basetype, align);
9380                 else {
9381                         size = mono_class_native_size (t->data.klass, align);
9382                         *align = *align + 3;
9383                         *align &= ~3;
9384                         
9385                         size +=  3;
9386                         size &= ~3;
9387
9388                         return size;
9389                 }
9390         }
9391         default:
9392                 g_error ("type 0x%02x unknown", t->type);
9393         }
9394         return 0;
9395 }
9396
9397 /* __alignof__ returns the preferred alignment of values not the actual alignment used by
9398    the compiler so is wrong e.g. for Linux where doubles are aligned on a 4 byte boundary
9399    but __alignof__ returns 8 - using G_STRUCT_OFFSET works better */
9400 #define ALIGNMENT(type) G_STRUCT_OFFSET(struct { char c; type x; }, x)
9401
9402 gint32
9403 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
9404                         gboolean as_field, gboolean unicode)
9405 {
9406         MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
9407         MonoClass *klass;
9408
9409         switch (native_type) {
9410         case MONO_NATIVE_BOOLEAN:
9411                 *align = 4;
9412                 return 4;
9413         case MONO_NATIVE_I1:
9414         case MONO_NATIVE_U1:
9415                 *align = 1;
9416                 return 1;
9417         case MONO_NATIVE_I2:
9418         case MONO_NATIVE_U2:
9419         case MONO_NATIVE_VARIANTBOOL:
9420                 *align = 2;
9421                 return 2;
9422         case MONO_NATIVE_I4:
9423         case MONO_NATIVE_U4:
9424         case MONO_NATIVE_ERROR:
9425                 *align = 4;
9426                 return 4;
9427         case MONO_NATIVE_I8:
9428         case MONO_NATIVE_U8:
9429                 *align = ALIGNMENT(guint64);
9430                 return 8;
9431         case MONO_NATIVE_R4:
9432                 *align = 4;
9433                 return 4;
9434         case MONO_NATIVE_R8:
9435                 *align = ALIGNMENT(double);
9436                 return 8;
9437         case MONO_NATIVE_INT:
9438         case MONO_NATIVE_UINT:
9439         case MONO_NATIVE_LPSTR:
9440         case MONO_NATIVE_LPWSTR:
9441         case MONO_NATIVE_LPTSTR:
9442         case MONO_NATIVE_BSTR:
9443         case MONO_NATIVE_ANSIBSTR:
9444         case MONO_NATIVE_TBSTR:
9445         case MONO_NATIVE_LPARRAY:
9446         case MONO_NATIVE_SAFEARRAY:
9447         case MONO_NATIVE_IUNKNOWN:
9448         case MONO_NATIVE_IDISPATCH:
9449         case MONO_NATIVE_INTERFACE:
9450         case MONO_NATIVE_ASANY:
9451         case MONO_NATIVE_FUNC:
9452         case MONO_NATIVE_LPSTRUCT:
9453                 *align = ALIGNMENT(gpointer);
9454                 return sizeof (gpointer);
9455         case MONO_NATIVE_STRUCT: 
9456                 klass = mono_class_from_mono_type (type);
9457                 return mono_class_native_size (klass, align);
9458         case MONO_NATIVE_BYVALTSTR: {
9459                 int esize = unicode ? 2: 1;
9460                 g_assert (mspec);
9461                 *align = esize;
9462                 return mspec->data.array_data.num_elem * esize;
9463         }
9464         case MONO_NATIVE_BYVALARRAY: {
9465                 // FIXME: Have to consider ArraySubType
9466                 int esize;
9467                 klass = mono_class_from_mono_type (type);
9468                 if (klass->element_class == mono_defaults.char_class) {
9469                         esize = unicode ? 2 : 1;
9470                         *align = esize;
9471                 } else {
9472                         esize = mono_class_native_size (klass->element_class, align);
9473                 }
9474                 g_assert (mspec);
9475                 return mspec->data.array_data.num_elem * esize;
9476         }
9477         case MONO_NATIVE_CUSTOM:
9478                 g_assert_not_reached ();
9479                 break;
9480         case MONO_NATIVE_CURRENCY:
9481         case MONO_NATIVE_VBBYREFSTR:
9482         default:
9483                 g_error ("native type %02x not implemented", native_type); 
9484                 break;
9485         }
9486         g_assert_not_reached ();
9487         return 0;
9488 }
9489
9490 gpointer
9491 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
9492 {
9493         MonoType *t;
9494         MonoClass *klass;
9495
9496         if (o == NULL)
9497                 return NULL;
9498
9499         t = &o->vtable->klass->byval_arg;
9500         switch (t->type) {
9501         case MONO_TYPE_I4:
9502         case MONO_TYPE_U4:
9503         case MONO_TYPE_PTR:
9504         case MONO_TYPE_I1:
9505         case MONO_TYPE_U1:
9506         case MONO_TYPE_BOOLEAN:
9507         case MONO_TYPE_I2:
9508         case MONO_TYPE_U2:
9509         case MONO_TYPE_CHAR:
9510         case MONO_TYPE_I8:
9511         case MONO_TYPE_U8:
9512         case MONO_TYPE_R4:
9513         case MONO_TYPE_R8:
9514                 return mono_object_unbox (o);
9515                 break;
9516         case MONO_TYPE_STRING:
9517                 switch (string_encoding) {
9518                 case MONO_NATIVE_LPWSTR:
9519                         return mono_string_to_utf16 ((MonoString*)o);
9520                         break;
9521                 case MONO_NATIVE_LPSTR:
9522                         return mono_string_to_lpstr ((MonoString*)o);
9523                         break;
9524                 default:
9525                         g_warning ("marshaling conversion %d not implemented", string_encoding);
9526                         g_assert_not_reached ();
9527                 }
9528                 break;
9529         case MONO_TYPE_CLASS:
9530         case MONO_TYPE_VALUETYPE: {
9531                 MonoMethod *method;
9532                 gpointer pa [3];
9533                 gpointer res;
9534                 MonoBoolean delete_old = FALSE;
9535
9536                 klass = t->data.klass;
9537
9538                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
9539                         break;
9540
9541                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
9542                         klass->blittable || klass->enumtype))
9543                         return mono_object_unbox (o);
9544
9545                 res = mono_marshal_alloc (mono_class_native_size (klass, NULL));
9546
9547                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
9548                         method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
9549
9550                         pa [0] = o;
9551                         pa [1] = &res;
9552                         pa [2] = &delete_old;
9553
9554                         mono_runtime_invoke (method, NULL, pa, NULL);
9555                 }
9556
9557                 return res;
9558         }
9559         }
9560
9561         mono_raise_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
9562
9563         return NULL;
9564 }
9565
9566 void
9567 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
9568 {
9569         MonoType *t;
9570         MonoClass *klass;
9571
9572         if (o == NULL)
9573                 return;
9574
9575         t = &o->vtable->klass->byval_arg;
9576         switch (t->type) {
9577         case MONO_TYPE_STRING:
9578                 switch (string_encoding) {
9579                 case MONO_NATIVE_LPWSTR:
9580                 case MONO_NATIVE_LPSTR:
9581                         mono_marshal_free (ptr);
9582                         break;
9583                 default:
9584                         g_warning ("marshaling conversion %d not implemented", string_encoding);
9585                         g_assert_not_reached ();
9586                 }
9587                 break;
9588         case MONO_TYPE_CLASS:
9589         case MONO_TYPE_VALUETYPE: {
9590                 klass = t->data.klass;
9591
9592                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
9593                                                                  klass->blittable || klass->enumtype))
9594                         break;
9595
9596                 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
9597                         MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
9598                         gpointer pa [2];
9599
9600                         pa [0] = &ptr;
9601                         pa [1] = o;
9602
9603                         mono_runtime_invoke (method, NULL, pa, NULL);
9604                 }
9605
9606                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
9607                         mono_struct_delete_old (klass, ptr);
9608                 }
9609
9610                 mono_marshal_free (ptr);
9611                 break;
9612         }
9613         default:
9614                 break;
9615         }
9616 }