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