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