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