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