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