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