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