e6b9b6628bc5326608872431e9d34d2799defef4
[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         static MonoMethod *get_object_for_native_variant = NULL;
6793         static MonoMethod *get_native_variant_for_object = NULL;
6794         
6795         if (!get_object_for_native_variant)
6796                 get_object_for_native_variant = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetObjectForNativeVariant", 1);
6797         g_assert (get_object_for_native_variant);
6798
6799         if (!get_native_variant_for_object)
6800                 get_native_variant_for_object = mono_class_get_method_from_name (mono_defaults.marshal_class, "GetNativeVariantForObject", 2);
6801         g_assert (get_native_variant_for_object);
6802
6803         switch (action) {
6804         case MARSHAL_ACTION_CONV_IN: {
6805                 conv_arg = mono_mb_add_local (mb, &mono_defaults.variant_class->byval_arg);
6806                 
6807                 if (t->byref)
6808                         *conv_arg_type = &mono_defaults.variant_class->this_arg;
6809                 else
6810                         *conv_arg_type = &mono_defaults.variant_class->byval_arg;
6811
6812                 if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
6813                         break;
6814
6815                 mono_mb_emit_ldarg (mb, argnum);
6816                 if (t->byref)
6817                         mono_mb_emit_byte(mb, CEE_LDIND_REF);
6818                 mono_mb_emit_ldloc_addr (mb, conv_arg);
6819                 mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6820                 break;
6821         }
6822
6823         case MARSHAL_ACTION_CONV_OUT: {
6824                 static MonoMethod *variant_clear = NULL;
6825
6826                 if (!variant_clear)
6827                         variant_clear = mono_class_get_method_from_name (mono_defaults.variant_class, "Clear", 0);
6828                 g_assert (variant_clear);
6829
6830
6831                 if (t->byref) {
6832                         mono_mb_emit_ldarg (mb, argnum);
6833                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6834                         mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6835                         mono_mb_emit_byte (mb, CEE_STIND_REF);
6836                 }
6837
6838                 mono_mb_emit_ldloc_addr (mb, conv_arg);
6839                 mono_mb_emit_managed_call (mb, variant_clear, NULL);
6840                 break;
6841         }
6842
6843         case MARSHAL_ACTION_PUSH:
6844                 if (t->byref)
6845                         mono_mb_emit_ldloc_addr (mb, conv_arg);
6846                 else
6847                         mono_mb_emit_ldloc (mb, conv_arg);
6848                 break;
6849
6850         case MARSHAL_ACTION_CONV_RESULT: {
6851                 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6852                 mono_mb_emit_exception_marshal_directive (mb, msg);
6853                 break;
6854         }
6855
6856         case MARSHAL_ACTION_MANAGED_CONV_IN: {
6857                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6858
6859                 if (t->byref)
6860                         *conv_arg_type = &mono_defaults.variant_class->this_arg;
6861                 else
6862                         *conv_arg_type = &mono_defaults.variant_class->byval_arg;
6863
6864                 if (t->byref && t->attrs & PARAM_ATTRIBUTE_OUT)
6865                         break;
6866
6867                 if (t->byref)
6868                         mono_mb_emit_ldarg (mb, argnum);
6869                 else
6870                         mono_mb_emit_ldarg_addr (mb, argnum);
6871                 mono_mb_emit_managed_call (mb, get_object_for_native_variant, NULL);
6872                 mono_mb_emit_stloc (mb, conv_arg);
6873                 break;
6874         }
6875
6876         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
6877                 if (t->byref) {
6878                         mono_mb_emit_ldloc (mb, conv_arg);
6879                         mono_mb_emit_ldarg (mb, argnum);
6880                         mono_mb_emit_managed_call (mb, get_native_variant_for_object, NULL);
6881                 }
6882                 break;
6883         }
6884
6885         case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
6886                 char *msg = g_strdup ("Marshalling of VARIANT not supported as a return type.");
6887                 mono_mb_emit_exception_marshal_directive (mb, msg);
6888                 break;
6889         }
6890
6891         default:
6892                 g_assert_not_reached ();
6893         }
6894
6895         return conv_arg;
6896 }
6897
6898 static int
6899 emit_marshal_array (EmitMarshalContext *m, int argnum, MonoType *t,
6900                                         MonoMarshalSpec *spec, 
6901                                         int conv_arg, MonoType **conv_arg_type, 
6902                                         MarshalAction action)
6903 {
6904         MonoMethodBuilder *mb = m->mb;
6905         MonoClass *klass = mono_class_from_mono_type (t);
6906         gboolean need_convert, need_free;
6907         MonoMarshalNative encoding;
6908
6909         encoding = mono_marshal_get_string_encoding (m->piinfo, spec);
6910
6911         switch (action) {
6912         case MARSHAL_ACTION_CONV_IN:
6913                 *conv_arg_type = &mono_defaults.object_class->byval_arg;
6914                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6915
6916                 if (klass->element_class->blittable) {
6917                         mono_mb_emit_ldarg (mb, argnum);
6918                         if (t->byref)
6919                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6920                         mono_mb_emit_icall (mb, conv_to_icall (MONO_MARSHAL_CONV_ARRAY_LPARRAY));
6921                         mono_mb_emit_stloc (mb, conv_arg);
6922                 } else {
6923                         MonoClass *eklass;
6924                         guint32 label1, label2, label3;
6925                         int index_var, src_var, dest_ptr, esize;
6926                         MonoMarshalConv conv;
6927                         gboolean is_string = FALSE;
6928
6929                         dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
6930
6931                         eklass = klass->element_class;
6932
6933                         if (eklass == mono_defaults.string_class) {
6934                                 is_string = TRUE;
6935                                 conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
6936                         }
6937                         else if (eklass == mono_defaults.stringbuilder_class) {
6938                                 is_string = TRUE;
6939                                 conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
6940                         }
6941                         else
6942                                 conv = -1;
6943
6944                         src_var = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
6945                         mono_mb_emit_ldarg (mb, argnum);
6946                         if (t->byref)
6947                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
6948                         mono_mb_emit_stloc (mb, src_var);
6949
6950                         /* Check null */
6951                         mono_mb_emit_ldloc (mb, src_var);
6952                         mono_mb_emit_stloc (mb, conv_arg);
6953                         mono_mb_emit_ldloc (mb, src_var);
6954                         label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
6955
6956                         if (is_string) {
6957                                 if (conv == -1) {
6958                                         char *msg = g_strdup_printf ("string/stringbuilder marshalling conversion %d not implemented", encoding);
6959                                         MonoException *exc = mono_get_exception_not_implemented (msg);
6960                                         g_warning (msg);
6961                                         g_free (msg);
6962                                         mono_raise_exception (exc);
6963                                 }
6964                         }
6965
6966                         if (is_string)
6967                                 esize = sizeof (gpointer);
6968                         else
6969                                 esize = mono_class_native_size (eklass, NULL);
6970
6971                         /* allocate space for the native struct and store the address */
6972                         mono_mb_emit_icon (mb, esize);
6973                         mono_mb_emit_ldloc (mb, src_var);
6974                         mono_mb_emit_byte (mb, CEE_LDLEN);
6975
6976                         if (eklass == mono_defaults.string_class) {
6977                                 /* Make the array bigger for the terminating null */
6978                                 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
6979                                 mono_mb_emit_byte (mb, CEE_ADD);
6980                         }
6981                         mono_mb_emit_byte (mb, CEE_MUL);
6982                         mono_mb_emit_byte (mb, CEE_PREFIX1);
6983                         mono_mb_emit_byte (mb, CEE_LOCALLOC);
6984                         mono_mb_emit_stloc (mb, conv_arg);
6985
6986                         mono_mb_emit_ldloc (mb, conv_arg);
6987                         mono_mb_emit_stloc (mb, dest_ptr);
6988
6989                         /* Emit marshalling loop */
6990                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
6991                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
6992                         mono_mb_emit_stloc (mb, index_var);
6993                         label2 = mb->pos;
6994                         mono_mb_emit_ldloc (mb, index_var);
6995                         mono_mb_emit_ldloc (mb, src_var);
6996                         mono_mb_emit_byte (mb, CEE_LDLEN);
6997                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
6998
6999                         /* Emit marshalling code */
7000
7001                         if (is_string) {
7002                                 mono_mb_emit_ldloc (mb, dest_ptr);
7003                                 mono_mb_emit_ldloc (mb, src_var);
7004                                 mono_mb_emit_ldloc (mb, index_var);
7005                                 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
7006                                 mono_mb_emit_icall (mb, conv_to_icall (conv));
7007                                 mono_mb_emit_byte (mb, CEE_STIND_I);
7008                         } else {
7009                                 /* set the src_ptr */
7010                                 mono_mb_emit_ldloc (mb, src_var);
7011                                 mono_mb_emit_ldloc (mb, index_var);
7012                                 mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
7013                                 mono_mb_emit_stloc (mb, 0);
7014
7015                                 /* set dst_ptr */
7016                                 mono_mb_emit_ldloc (mb, dest_ptr);
7017                                 mono_mb_emit_stloc (mb, 1);
7018
7019                                 /* emit valuetype conversion code */
7020                                 emit_struct_conv (mb, eklass, FALSE);
7021                         }
7022
7023                         mono_mb_emit_add_to_local (mb, index_var, 1);
7024                         mono_mb_emit_add_to_local (mb, dest_ptr, esize);
7025                         
7026                         mono_mb_emit_byte (mb, CEE_BR);
7027                         mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
7028
7029                         mono_mb_patch_branch (mb, label3);
7030
7031                         if (eklass == mono_defaults.string_class) {
7032                                 /* Null terminate */
7033                                 mono_mb_emit_ldloc (mb, dest_ptr);
7034                                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7035                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
7036                         }
7037
7038                         mono_mb_patch_branch (mb, label1);
7039                 }
7040
7041                 break;
7042
7043         case MARSHAL_ACTION_CONV_OUT:
7044                 /* Unicode character arrays are implicitly marshalled as [Out] under MS.NET */
7045                 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);
7046                 need_free = mono_marshal_need_free (&klass->element_class->byval_arg, 
7047                                                                                         m->piinfo, spec);
7048
7049                 if (need_convert || need_free) {
7050                         /* FIXME: Optimize blittable case */
7051                         MonoClass *eklass;
7052                         guint32 label1, label2, label3;
7053                         int index_var, src_ptr, loc, esize;
7054
7055                         eklass = klass->element_class;
7056                         if ((eklass == mono_defaults.stringbuilder_class) || (eklass == mono_defaults.string_class))
7057                                 esize = sizeof (gpointer);
7058                         else
7059                                 esize = mono_class_native_size (eklass, NULL);
7060                         src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7061                         loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7062
7063                         /* Check null */
7064                         mono_mb_emit_ldarg (mb, argnum);
7065                         if (t->byref)
7066                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
7067                         label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
7068
7069                         mono_mb_emit_ldloc (mb, conv_arg);
7070                         mono_mb_emit_stloc (mb, src_ptr);
7071
7072                         /* Emit marshalling loop */
7073                         index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);                                
7074                         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7075                         mono_mb_emit_stloc (mb, index_var);
7076                         label2 = mb->pos;
7077                         mono_mb_emit_ldloc (mb, index_var);
7078                         mono_mb_emit_ldarg (mb, argnum);
7079                         if (t->byref)
7080                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
7081                         mono_mb_emit_byte (mb, CEE_LDLEN);
7082                         label3 = mono_mb_emit_branch (mb, CEE_BGE);
7083
7084                         /* Emit marshalling code */
7085
7086                         if (eklass == mono_defaults.stringbuilder_class) {
7087                                 gboolean need_free2;
7088                                 MonoMarshalConv conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free2);
7089
7090                                 g_assert (conv != -1);
7091
7092                                 /* dest */
7093                                 mono_mb_emit_ldarg (mb, argnum);
7094                                 if (t->byref)
7095                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
7096                                 mono_mb_emit_ldloc (mb, index_var);
7097                                 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
7098
7099                                 /* src */
7100                                 mono_mb_emit_ldloc (mb, src_ptr);
7101                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
7102
7103                                 mono_mb_emit_icall (mb, conv_to_icall (conv));
7104
7105                                 if (need_free) {
7106                                         /* src */
7107                                         mono_mb_emit_ldloc (mb, src_ptr);
7108                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
7109
7110                                         mono_mb_emit_icall (mb, mono_marshal_free);
7111                                 }
7112                         }
7113                         else if (eklass == mono_defaults.string_class) {
7114                                 if (need_free) {
7115                                         /* src */
7116                                         mono_mb_emit_ldloc (mb, src_ptr);
7117                                         mono_mb_emit_byte (mb, CEE_LDIND_I);
7118
7119                                         mono_mb_emit_icall (mb, mono_marshal_free);
7120                                 }
7121                         }
7122                         else {
7123                                 if (need_convert) {
7124                                         /* set the src_ptr */
7125                                         mono_mb_emit_ldloc (mb, src_ptr);
7126                                         mono_mb_emit_stloc (mb, 0);
7127
7128                                         /* set dst_ptr */
7129                                         mono_mb_emit_ldarg (mb, argnum);
7130                                         if (t->byref)
7131                                                 mono_mb_emit_byte (mb, CEE_LDIND_I);
7132                                         mono_mb_emit_ldloc (mb, index_var);
7133                                         mono_mb_emit_op (mb, CEE_LDELEMA, eklass);
7134                                         mono_mb_emit_stloc (mb, 1);
7135
7136                                         /* emit valuetype conversion code */
7137                                         emit_struct_conv (mb, eklass, TRUE);
7138                                 }
7139
7140                                 if (need_free) {
7141                                         mono_mb_emit_ldloc (mb, src_ptr);
7142                                         mono_mb_emit_stloc (mb, loc);
7143                                         mono_mb_emit_ldloc (mb, loc);
7144
7145                                         emit_struct_free (mb, eklass, loc);
7146                                 }
7147                         }
7148
7149                         mono_mb_emit_add_to_local (mb, index_var, 1);
7150                         mono_mb_emit_add_to_local (mb, src_ptr, esize);
7151
7152                         mono_mb_emit_byte (mb, CEE_BR);
7153                         mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
7154
7155                         mono_mb_patch_branch (mb, label1);
7156                         mono_mb_patch_branch (mb, label3);
7157                 }
7158                 break;
7159
7160         case MARSHAL_ACTION_PUSH:
7161                 if (t->byref)
7162                         mono_mb_emit_ldloc_addr (mb, conv_arg);
7163                 else
7164                         mono_mb_emit_ldloc (mb, conv_arg);
7165                 break;
7166
7167         case MARSHAL_ACTION_CONV_RESULT:
7168                 /* fixme: we need conversions here */
7169                 mono_mb_emit_stloc (mb, 3);
7170                 break;
7171
7172         case MARSHAL_ACTION_MANAGED_CONV_IN: {
7173                 MonoClass *eklass;
7174                 guint32 label1, label2, label3;
7175                 int index_var, src_ptr, loc, esize, param_num, num_elem;
7176                 MonoMarshalConv conv;
7177                 gboolean is_string = FALSE;
7178                 
7179                 conv_arg = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
7180                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
7181
7182                 if (t->byref) {
7183                         char *msg = g_strdup ("Byref array marshalling to managed code is not implemented.");
7184                         mono_mb_emit_exception_marshal_directive (mb, msg);
7185                         return conv_arg;
7186                 }
7187                 if (!spec) {
7188                         char *msg = g_strdup ("[MarshalAs] attribute required to marshal arrays to managed code.");
7189                         mono_mb_emit_exception_marshal_directive (mb, msg);
7190                         return conv_arg;
7191                 }                       
7192                 if (spec->native != MONO_NATIVE_LPARRAY) {
7193                         char *msg = g_strdup ("Non LPArray marshalling of arrays to managed code is not implemented.");
7194                         mono_mb_emit_exception_marshal_directive (mb, msg);
7195                         return conv_arg;                        
7196                 }
7197
7198                 /* FIXME: t is from the method which is wrapped, not the delegate type */
7199                 /* g_assert (t->attrs & PARAM_ATTRIBUTE_IN); */
7200
7201                 param_num = spec->data.array_data.param_num;
7202                 num_elem = spec->data.array_data.num_elem;
7203                 if (spec->data.array_data.elem_mult == 0)
7204                         /* param_num is not specified */
7205                         param_num = -1;
7206
7207                 if (param_num == -1) {
7208                         if (num_elem <= 0) {
7209                                 char *msg = g_strdup ("Either SizeConst or SizeParamIndex should be specified when marshalling arrays to managed code.");
7210                                 mono_mb_emit_exception_marshal_directive (mb, msg);
7211                                 return conv_arg;
7212                         }
7213                 }
7214
7215                 /* FIXME: Optimize blittable case */
7216
7217                 eklass = klass->element_class;
7218                 if (eklass == mono_defaults.string_class) {
7219                         is_string = TRUE;
7220                         conv = mono_marshal_get_ptr_to_string_conv (m->piinfo, spec, &need_free);
7221                 }
7222                 else if (eklass == mono_defaults.stringbuilder_class) {
7223                         is_string = TRUE;
7224                         conv = mono_marshal_get_ptr_to_stringbuilder_conv (m->piinfo, spec, &need_free);
7225                 }
7226                 else
7227                         conv = -1;
7228
7229                 mono_marshal_load_type_info (eklass);
7230
7231                 if (is_string)
7232                         esize = sizeof (gpointer);
7233                 else
7234                         esize = mono_class_native_size (eklass, NULL);
7235                 src_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7236                 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7237
7238                 mono_mb_emit_byte (mb, CEE_LDNULL);
7239                 mono_mb_emit_stloc (mb, conv_arg);
7240
7241                 /* Check param index */
7242                 if (param_num != -1) {
7243                         if (param_num >= m->sig->param_count) {
7244                                 char *msg = g_strdup ("Array size control parameter index is out of range.");
7245                                 mono_mb_emit_exception_marshal_directive (mb, msg);
7246                                 return conv_arg;
7247                         }
7248                         switch (m->sig->params [param_num]->type) {
7249                         case MONO_TYPE_I1:
7250                         case MONO_TYPE_U1:
7251                         case MONO_TYPE_I2:
7252                         case MONO_TYPE_U2:
7253                         case MONO_TYPE_I4:
7254                         case MONO_TYPE_U4:
7255                         case MONO_TYPE_I:
7256                         case MONO_TYPE_U:
7257                         case MONO_TYPE_I8:
7258                         case MONO_TYPE_U8:
7259                                 break;
7260                         default: {
7261                                 char *msg = g_strdup ("Array size control parameter must be an integral type.");
7262                                 mono_mb_emit_exception_marshal_directive (mb, msg);
7263                                 return conv_arg;
7264                         }
7265                         }
7266                 }
7267
7268                 /* Check null */
7269                 mono_mb_emit_ldarg (mb, argnum);
7270                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
7271
7272                 mono_mb_emit_ldarg (mb, argnum);
7273                 mono_mb_emit_stloc (mb, src_ptr);
7274
7275                 /* Create managed array */
7276                 /* 
7277                  * The LPArray marshalling spec says that sometimes param_num starts 
7278                  * from 1, sometimes it starts from 0. But MS seems to allways start
7279                  * from 0.
7280                  */
7281
7282                 if (param_num == -1)
7283                         mono_mb_emit_icon (mb, num_elem);
7284                 else {
7285                         /* FIXME: Add the two together */
7286                         mono_mb_emit_ldarg (mb, param_num);
7287                         if (num_elem > 0) {
7288                                 mono_mb_emit_icon (mb, num_elem);
7289                                 mono_mb_emit_byte (mb, CEE_ADD);
7290                         }
7291                 }
7292
7293                 mono_mb_emit_op (mb, CEE_NEWARR, eklass);
7294                 mono_mb_emit_stloc (mb, conv_arg);
7295
7296                 if (eklass->blittable) {
7297                         mono_mb_emit_ldloc (mb, conv_arg);
7298                         mono_mb_emit_byte (mb, CEE_CONV_I);
7299                         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoArray, vector));
7300                         mono_mb_emit_byte (mb, CEE_ADD);
7301                         mono_mb_emit_ldarg (mb, argnum);
7302                         mono_mb_emit_ldloc (mb, conv_arg);
7303                         mono_mb_emit_byte (mb, CEE_LDLEN);
7304                         mono_mb_emit_icon (mb, esize);
7305                         mono_mb_emit_byte (mb, CEE_MUL);
7306                         mono_mb_emit_byte (mb, CEE_PREFIX1);
7307                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
7308                         break;
7309                 }
7310
7311                 /* Emit marshalling loop */
7312                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7313                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7314                 mono_mb_emit_stloc (mb, index_var);
7315                 label2 = mb->pos;
7316                 mono_mb_emit_ldloc (mb, index_var);
7317                 mono_mb_emit_ldloc (mb, conv_arg);
7318                 mono_mb_emit_byte (mb, CEE_LDLEN);
7319                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
7320
7321                 /* Emit marshalling code */
7322                 if (is_string) {
7323                         g_assert (conv != -1);
7324
7325                         mono_mb_emit_ldloc (mb, conv_arg);
7326                         mono_mb_emit_ldloc (mb, index_var);
7327
7328                         mono_mb_emit_ldloc (mb, src_ptr);
7329                         mono_mb_emit_byte (mb, CEE_LDIND_I);
7330
7331                         mono_mb_emit_icall (mb, conv_to_icall (conv));
7332                         mono_mb_emit_byte (mb, CEE_STELEM_REF);
7333                 }
7334                 else {
7335                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
7336                         mono_mb_emit_exception_marshal_directive (mb, msg);
7337                         return conv_arg;
7338                 }
7339
7340                 mono_mb_emit_add_to_local (mb, index_var, 1);
7341                 mono_mb_emit_add_to_local (mb, src_ptr, esize);
7342
7343                 mono_mb_emit_byte (mb, CEE_BR);
7344                 mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
7345
7346                 mono_mb_patch_branch (mb, label1);
7347                 mono_mb_patch_branch (mb, label3);
7348                 
7349                 break;
7350         }
7351         case MARSHAL_ACTION_MANAGED_CONV_OUT: {
7352                 MonoClass *eklass;
7353                 guint32 label1, label2, label3;
7354                 int index_var, dest_ptr, loc, esize, param_num, num_elem;
7355                 MonoMarshalConv conv;
7356                 gboolean is_string = FALSE;
7357
7358                 if (!spec)
7359                         /* Already handled in CONV_IN */
7360                         break;
7361                 
7362                 /* These are already checked in CONV_IN */
7363                 g_assert (!t->byref);
7364                 g_assert (spec->native == MONO_NATIVE_LPARRAY);
7365                 g_assert (t->attrs & PARAM_ATTRIBUTE_OUT);
7366
7367                 param_num = spec->data.array_data.param_num;
7368                 num_elem = spec->data.array_data.num_elem;
7369
7370                 if (spec->data.array_data.elem_mult == 0)
7371                         /* param_num is not specified */
7372                         param_num = -1;
7373
7374                 if (param_num == -1) {
7375                         if (num_elem <= 0) {
7376                                 g_assert_not_reached ();
7377                         }
7378                 }
7379
7380                 /* FIXME: Optimize blittable case */
7381
7382                 eklass = klass->element_class;
7383                 if (eklass == mono_defaults.string_class) {
7384                         is_string = TRUE;
7385                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
7386                 }
7387                 else if (eklass == mono_defaults.stringbuilder_class) {
7388                         is_string = TRUE;
7389                         conv = mono_marshal_get_stringbuilder_to_ptr_conv (m->piinfo, spec);
7390                 }
7391                 else
7392                         conv = -1;
7393
7394                 mono_marshal_load_type_info (eklass);
7395
7396                 if (is_string)
7397                         esize = sizeof (gpointer);
7398                 else
7399                         esize = mono_class_native_size (eklass, NULL);
7400
7401                 dest_ptr = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7402                 loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7403
7404                 /* Check null */
7405                 mono_mb_emit_ldloc (mb, conv_arg);
7406                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
7407
7408                 mono_mb_emit_ldarg (mb, argnum);
7409                 mono_mb_emit_stloc (mb, dest_ptr);
7410
7411                 if (eklass->blittable) {
7412                         /* dest */
7413                         mono_mb_emit_ldarg (mb, argnum);
7414                         /* src */
7415                         mono_mb_emit_ldloc (mb, conv_arg);
7416                         mono_mb_emit_byte (mb, CEE_CONV_I);
7417                         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoArray, vector));
7418                         mono_mb_emit_byte (mb, CEE_ADD);
7419                         /* length */
7420                         mono_mb_emit_ldloc (mb, conv_arg);
7421                         mono_mb_emit_byte (mb, CEE_LDLEN);
7422                         mono_mb_emit_icon (mb, esize);
7423                         mono_mb_emit_byte (mb, CEE_MUL);
7424                         mono_mb_emit_byte (mb, CEE_PREFIX1);
7425                         mono_mb_emit_byte (mb, CEE_CPBLK);                      
7426                         break;
7427                 }
7428
7429                 /* Emit marshalling loop */
7430                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7431                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7432                 mono_mb_emit_stloc (mb, index_var);
7433                 label2 = mb->pos;
7434                 mono_mb_emit_ldloc (mb, index_var);
7435                 mono_mb_emit_ldloc (mb, conv_arg);
7436                 mono_mb_emit_byte (mb, CEE_LDLEN);
7437                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
7438
7439                 /* Emit marshalling code */
7440                 if (is_string) {
7441                         g_assert (conv != -1);
7442
7443                         /* dest */
7444                         mono_mb_emit_ldloc (mb, dest_ptr);
7445
7446                         /* src */
7447                         mono_mb_emit_ldloc (mb, conv_arg);
7448                         mono_mb_emit_ldloc (mb, index_var);
7449
7450                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
7451
7452                         mono_mb_emit_icall (mb, conv_to_icall (conv));
7453                         mono_mb_emit_byte (mb, CEE_STIND_I);
7454                 }
7455                 else {
7456                         char *msg = g_strdup ("Marshalling of non-string and non-blittable arrays to managed code is not implemented.");
7457                         mono_mb_emit_exception_marshal_directive (mb, msg);
7458                         return conv_arg;
7459                 }
7460
7461                 mono_mb_emit_add_to_local (mb, index_var, 1);
7462                 mono_mb_emit_add_to_local (mb, dest_ptr, esize);
7463
7464                 mono_mb_emit_byte (mb, CEE_BR);
7465                 mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
7466
7467                 mono_mb_patch_branch (mb, label1);
7468                 mono_mb_patch_branch (mb, label3);
7469
7470                 break;
7471         }
7472         case MARSHAL_ACTION_MANAGED_CONV_RESULT: {
7473                 MonoClass *eklass;
7474                 guint32 label1, label2, label3;
7475                 int index_var, src, dest, esize;
7476                 MonoMarshalConv conv = -1;
7477                 gboolean is_string = FALSE;
7478                 
7479                 g_assert (!t->byref);
7480
7481                 eklass = klass->element_class;
7482
7483                 mono_marshal_load_type_info (eklass);
7484
7485                 if (eklass == mono_defaults.string_class) {
7486                         is_string = TRUE;
7487                         conv = mono_marshal_get_string_to_ptr_conv (m->piinfo, spec);
7488                 }
7489                 else {
7490                         g_assert_not_reached ();
7491                 }
7492
7493                 if (is_string)
7494                         esize = sizeof (gpointer);
7495                 else
7496                         esize = mono_class_native_size (eklass, NULL);
7497
7498                 src = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
7499                 dest = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7500                         
7501                 mono_mb_emit_stloc (mb, src);
7502                 mono_mb_emit_ldloc (mb, src);
7503                 mono_mb_emit_stloc (mb, 3);
7504
7505                 /* Check for null */
7506                 mono_mb_emit_ldloc (mb, src);
7507                 label1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
7508
7509                 /* Allocate native array */
7510                 mono_mb_emit_icon (mb, esize);
7511                 mono_mb_emit_ldloc (mb, src);
7512                 mono_mb_emit_byte (mb, CEE_LDLEN);
7513
7514                 if (eklass == mono_defaults.string_class) {
7515                         /* Make the array bigger for the terminating null */
7516                         mono_mb_emit_byte (mb, CEE_LDC_I4_1);
7517                         mono_mb_emit_byte (mb, CEE_ADD);
7518                 }
7519                 mono_mb_emit_byte (mb, CEE_MUL);
7520                 mono_mb_emit_icall (mb, mono_marshal_alloc);
7521                 mono_mb_emit_stloc (mb, dest);
7522                 mono_mb_emit_ldloc (mb, dest);
7523                 mono_mb_emit_stloc (mb, 3);
7524
7525                 /* Emit marshalling loop */
7526                 index_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7527                 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
7528                 mono_mb_emit_stloc (mb, index_var);
7529                 label2 = mb->pos;
7530                 mono_mb_emit_ldloc (mb, index_var);
7531                 mono_mb_emit_ldloc (mb, src);
7532                 mono_mb_emit_byte (mb, CEE_LDLEN);
7533                 label3 = mono_mb_emit_branch (mb, CEE_BGE);
7534
7535                 /* Emit marshalling code */
7536                 if (is_string) {
7537                         g_assert (conv != -1);
7538
7539                         /* dest */
7540                         mono_mb_emit_ldloc (mb, dest);
7541
7542                         /* src */
7543                         mono_mb_emit_ldloc (mb, src);
7544                         mono_mb_emit_ldloc (mb, index_var);
7545
7546                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
7547
7548                         mono_mb_emit_icall (mb, conv_to_icall (conv));
7549                         mono_mb_emit_byte (mb, CEE_STIND_I);
7550                 }
7551                 else {
7552                         char *msg = g_strdup ("Marshalling of non-string arrays to managed code is not implemented.");
7553                         mono_mb_emit_exception_marshal_directive (mb, msg);
7554                         return conv_arg;
7555                 }
7556
7557                 mono_mb_emit_add_to_local (mb, index_var, 1);
7558                 mono_mb_emit_add_to_local (mb, dest, esize);
7559
7560                 mono_mb_emit_byte (mb, CEE_BR);
7561                 mono_mb_emit_i4 (mb, label2 - (mb->pos + 4));
7562
7563                 mono_mb_patch_branch (mb, label3);
7564                 mono_mb_patch_branch (mb, label1);
7565                 break;
7566         }
7567         default:
7568                 g_assert_not_reached ();
7569         }
7570
7571         return conv_arg;
7572 }
7573
7574 static int
7575 emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
7576                                           MonoMarshalSpec *spec, 
7577                                           int conv_arg, MonoType **conv_arg_type, 
7578                                           MarshalAction action)
7579 {
7580         MonoMethodBuilder *mb = m->mb;
7581
7582         switch (action) {
7583         case MARSHAL_ACTION_CONV_IN: {
7584                 MonoType *local_type;
7585                 int variant_bool = 0;
7586                 if (!t->byref)
7587                         break;
7588                 if (spec == NULL) {
7589                         local_type = &mono_defaults.int32_class->byval_arg;
7590                 } else {
7591                         switch (spec->native) {
7592                         case MONO_NATIVE_I1:
7593                                 local_type = &mono_defaults.byte_class->byval_arg;
7594                                 break;
7595                         case MONO_NATIVE_VARIANTBOOL:
7596                                 local_type = &mono_defaults.int16_class->byval_arg;
7597                                 variant_bool = 1;
7598                                 break;
7599                         default:
7600                                 g_warning ("marshalling bool as native type %x is currently not supported", spec->native);
7601                                 local_type = &mono_defaults.int32_class->byval_arg;
7602                                 break;
7603                         }
7604                 }
7605                 *conv_arg_type = &mono_defaults.int_class->byval_arg;
7606                 conv_arg = mono_mb_add_local (mb, local_type);
7607                 mono_mb_emit_ldarg (mb, argnum);
7608                 mono_mb_emit_byte (mb, CEE_LDIND_I1);
7609                 if (variant_bool)
7610                         mono_mb_emit_byte (mb, CEE_NEG);
7611                 mono_mb_emit_stloc (mb, conv_arg);
7612                 break;
7613         }
7614
7615         case MARSHAL_ACTION_CONV_OUT:
7616                 if (!t->byref)
7617                         break;
7618                 mono_mb_emit_ldarg (mb, argnum);
7619                 mono_mb_emit_ldloc (mb, conv_arg);
7620                 if (spec != NULL && spec->native == MONO_NATIVE_VARIANTBOOL)
7621                         mono_mb_emit_byte (mb, CEE_NEG);
7622                 mono_mb_emit_byte (mb, CEE_STIND_I1);
7623                 break;
7624
7625         case MARSHAL_ACTION_PUSH:
7626                 if (t->byref)
7627                         mono_mb_emit_ldloc_addr (mb, conv_arg);
7628                 else
7629                         mono_mb_emit_ldarg (mb, argnum);
7630                 break;
7631
7632         case MARSHAL_ACTION_CONV_RESULT:
7633                 /* maybe we need to make sure that it fits within 8 bits */
7634                 mono_mb_emit_stloc (mb, 3);
7635                 break;
7636
7637         default:
7638                 g_assert_not_reached ();
7639         }
7640
7641         return conv_arg;
7642 }
7643
7644 static int
7645 emit_marshal_ptr (EmitMarshalContext *m, int argnum, MonoType *t, 
7646                                   MonoMarshalSpec *spec, int conv_arg, 
7647                                   MonoType **conv_arg_type, MarshalAction action)
7648 {
7649         MonoMethodBuilder *mb = m->mb;
7650
7651         switch (action) {
7652         case MARSHAL_ACTION_CONV_IN:
7653                 if (MONO_TYPE_ISSTRUCT (t->data.type)) {
7654                         char *msg = g_strdup_printf ("Can not marshal 'parameter #%d': Pointers can not reference marshaled structures. Use byref instead.", argnum + 1);
7655                         mono_mb_emit_exception_marshal_directive (m->mb, msg);
7656                 }
7657                 break;
7658
7659         case MARSHAL_ACTION_PUSH:
7660                 mono_mb_emit_ldarg (mb, argnum);
7661                 break;
7662
7663         case MARSHAL_ACTION_CONV_RESULT:
7664                 /* no conversions necessary */
7665                 mono_mb_emit_stloc (mb, 3);
7666                 break;
7667
7668         default:
7669                 break;
7670         }
7671
7672         return conv_arg;
7673 }
7674
7675 static int
7676 emit_marshal_char (EmitMarshalContext *m, int argnum, MonoType *t, 
7677                                    MonoMarshalSpec *spec, int conv_arg, 
7678                                    MonoType **conv_arg_type, MarshalAction action)
7679 {
7680         MonoMethodBuilder *mb = m->mb;
7681
7682         switch (action) {
7683         case MARSHAL_ACTION_PUSH:
7684                 /* fixme: dont know how to marshal that. We cant simply
7685                  * convert it to a one byte UTF8 character, because an
7686                  * unicode character may need more that one byte in UTF8 */
7687                 mono_mb_emit_ldarg (mb, argnum);
7688                 break;
7689
7690         case MARSHAL_ACTION_CONV_RESULT:
7691                 /* fixme: we need conversions here */
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_scalar (EmitMarshalContext *m, int argnum, MonoType *t, 
7704                                          MonoMarshalSpec *spec, int conv_arg, 
7705                                          MonoType **conv_arg_type, MarshalAction action)
7706 {
7707         MonoMethodBuilder *mb = m->mb;
7708
7709         switch (action) {
7710         case MARSHAL_ACTION_PUSH:
7711                 mono_mb_emit_ldarg (mb, argnum);
7712                 break;
7713
7714         case MARSHAL_ACTION_CONV_RESULT:
7715                 /* no conversions necessary */
7716                 mono_mb_emit_stloc (mb, 3);
7717                 break;
7718
7719         default:
7720                 break;
7721         }
7722
7723         return conv_arg;
7724 }
7725
7726 static int
7727 emit_marshal (EmitMarshalContext *m, int argnum, MonoType *t, 
7728                           MonoMarshalSpec *spec, int conv_arg, 
7729                           MonoType **conv_arg_type, MarshalAction action)
7730 {
7731         /* Ensure that we have marshalling info for this param */
7732         mono_marshal_load_type_info (mono_class_from_mono_type (t));
7733
7734         if (spec && spec->native == MONO_NATIVE_CUSTOM)
7735                 return emit_marshal_custom (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7736
7737         if (spec && spec->native == MONO_NATIVE_ASANY)
7738                 return emit_marshal_asany (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7739                         
7740         switch (t->type) {
7741         case MONO_TYPE_VALUETYPE:
7742                 return emit_marshal_vtype (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7743         case MONO_TYPE_STRING:
7744                 return emit_marshal_string (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7745         case MONO_TYPE_CLASS:
7746         case MONO_TYPE_OBJECT:
7747                 if (spec && spec->native == MONO_NATIVE_STRUCT)
7748                         return emit_marshal_variant (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7749
7750                 if (spec && (spec->native == MONO_NATIVE_IUNKNOWN ||
7751                         spec->native == MONO_NATIVE_IDISPATCH ||
7752                         spec->native == MONO_NATIVE_INTERFACE))
7753                         return emit_marshal_com_interface (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7754
7755                 if (mono_defaults.safehandle_class != NULL &&
7756                     mono_class_is_subclass_of (t->data.klass,  mono_defaults.safehandle_class, FALSE))
7757                         return emit_marshal_safehandle (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7758                 
7759                 return emit_marshal_object (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7760         case MONO_TYPE_ARRAY:
7761         case MONO_TYPE_SZARRAY:
7762                 return emit_marshal_array (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7763         case MONO_TYPE_BOOLEAN:
7764                 return emit_marshal_boolean (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7765         case MONO_TYPE_PTR:
7766                 return emit_marshal_ptr (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7767         case MONO_TYPE_CHAR:
7768                 return emit_marshal_char (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7769         case MONO_TYPE_I1:
7770         case MONO_TYPE_U1:
7771         case MONO_TYPE_I2:
7772         case MONO_TYPE_U2:
7773         case MONO_TYPE_I4:
7774         case MONO_TYPE_U4:
7775         case MONO_TYPE_I:
7776         case MONO_TYPE_U:
7777         case MONO_TYPE_R4:
7778         case MONO_TYPE_R8:
7779         case MONO_TYPE_I8:
7780         case MONO_TYPE_U8:
7781         case MONO_TYPE_FNPTR:
7782                 return emit_marshal_scalar (m, argnum, t, spec, conv_arg, conv_arg_type, action);
7783         }
7784
7785         return conv_arg;
7786 }
7787
7788 /**
7789  * mono_marshal_emit_native_wrapper:
7790  * @image: the image to use for looking up custom marshallers
7791  * @sig: The signature of the native function
7792  * @piinfo: Marshalling information
7793  * @mspecs: Marshalling information
7794  * @func: the native function to call
7795  *
7796  * generates IL code for the pinvoke wrapper, the generated code calls @func.
7797  */
7798 static void
7799 mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoMethodSignature *sig, MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
7800 {
7801         EmitMarshalContext m;
7802         MonoMethodSignature *csig;
7803         MonoClass *klass;
7804         int i, argnum, *tmp_locals;
7805         int type;
7806         static MonoMethodSignature *get_last_error_sig = NULL;
7807
7808         m.mb = mb;
7809         m.piinfo = piinfo;
7810
7811         /* we copy the signature, so that we can set pinvoke to 0 */
7812         csig = signature_dup (mb->method->klass->image, sig);
7813         csig->pinvoke = 1;
7814         m.csig = csig;
7815         m.image = image;
7816
7817         /* we allocate local for use with emit_struct_conv() */
7818         /* allocate local 0 (pointer) src_ptr */
7819         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7820         /* allocate local 1 (pointer) dst_ptr */
7821         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
7822         /* allocate local 2 (boolean) delete_old */
7823         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
7824
7825         /* delete_old = FALSE */
7826         mono_mb_emit_icon (mb, 0);
7827         mono_mb_emit_stloc (mb, 2);
7828
7829         if (!MONO_TYPE_IS_VOID(sig->ret)) {
7830                 /* allocate local 3 to store the return value */
7831                 mono_mb_add_local (mb, sig->ret);
7832         }
7833
7834         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
7835                 /* Return type custom marshaling */
7836                 /*
7837                  * Since we can't determine the return type of the unmanaged function,
7838                  * we assume it returns a pointer, and pass that pointer to
7839                  * MarshalNativeToManaged.
7840                  */
7841                 csig->ret = &mono_defaults.int_class->byval_arg;
7842         }
7843
7844         /* we first do all conversions */
7845         tmp_locals = alloca (sizeof (int) * sig->param_count);
7846         m.orig_conv_args = alloca (sizeof (int) * (sig->param_count + 1));
7847
7848         for (i = 0; i < sig->param_count; i ++) {
7849                 tmp_locals [i] = emit_marshal (&m, i + sig->hasthis, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_CONV_IN);
7850         }
7851
7852         /* push all arguments */
7853
7854         if (sig->hasthis)
7855                 mono_mb_emit_byte (mb, CEE_LDARG_0);
7856
7857
7858         for (i = 0; i < sig->param_count; i++) {
7859                 emit_marshal (&m, i + sig->hasthis, sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_PUSH);
7860         }                       
7861
7862         /* call the native method */
7863         if (MONO_CLASS_IS_IMPORT (mb->method->klass)) {
7864                 mono_mb_emit_cominterop_call (mb, csig, &piinfo->method);
7865         }
7866         else {
7867                 mono_mb_emit_native_call (mb, csig, func);
7868         }
7869
7870         /* Set LastError if needed */
7871         if (piinfo->piflags & PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR) {
7872                 if (!get_last_error_sig) {
7873                         get_last_error_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
7874                         get_last_error_sig->ret = &mono_defaults.int_class->byval_arg;
7875                         get_last_error_sig->pinvoke = 1;
7876                 }
7877
7878 #ifdef PLATFORM_WIN32
7879                 /* 
7880                  * Have to call GetLastError () early and without a wrapper, since various runtime components could
7881                  * clobber its value.
7882                  */
7883                 mono_mb_emit_native_call (mb, get_last_error_sig, GetLastError);
7884                 mono_mb_emit_icall (mb, mono_marshal_set_last_error_windows);
7885 #else
7886                 mono_mb_emit_icall (mb, mono_marshal_set_last_error);
7887 #endif
7888         }               
7889
7890         /* convert the result */
7891         if (!sig->ret->byref) {
7892                 MonoMarshalSpec *spec = mspecs [0];
7893                 type = sig->ret->type;
7894
7895                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
7896                         emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7897                 } else {
7898
7899                 handle_enum:
7900                         switch (type) {
7901                         case MONO_TYPE_VOID:
7902                                 break;
7903                         case MONO_TYPE_VALUETYPE:
7904                                 klass = sig->ret->data.klass;
7905                                 if (klass->enumtype) {
7906                                         type = sig->ret->data.klass->enum_basetype->type;
7907                                         goto handle_enum;
7908                                 }
7909                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7910                                 break;
7911                         case MONO_TYPE_I1:
7912                         case MONO_TYPE_U1:
7913                         case MONO_TYPE_I2:
7914                         case MONO_TYPE_U2:
7915                         case MONO_TYPE_I4:
7916                         case MONO_TYPE_U4:
7917                         case MONO_TYPE_I:
7918                         case MONO_TYPE_U:
7919                         case MONO_TYPE_R4:
7920                         case MONO_TYPE_R8:
7921                         case MONO_TYPE_I8:
7922                         case MONO_TYPE_U8:
7923                         case MONO_TYPE_FNPTR:
7924                         case MONO_TYPE_STRING:
7925                         case MONO_TYPE_CLASS:
7926                         case MONO_TYPE_OBJECT:
7927                         case MONO_TYPE_BOOLEAN:
7928                         case MONO_TYPE_ARRAY:
7929                         case MONO_TYPE_SZARRAY:
7930                         case MONO_TYPE_CHAR:
7931                         case MONO_TYPE_PTR:
7932                                 emit_marshal (&m, 0, sig->ret, spec, 0, NULL, MARSHAL_ACTION_CONV_RESULT);
7933                                 break;
7934                         case MONO_TYPE_TYPEDBYREF:
7935                         default:
7936                                 g_warning ("return type 0x%02x unknown", sig->ret->type);       
7937                                 g_assert_not_reached ();
7938                         }
7939                 }
7940         } else {
7941                 mono_mb_emit_stloc (mb, 3);
7942         }
7943
7944         /* 
7945          * Need to call this after converting the result since MONO_VTADDR needs 
7946          * to be adjacent to the call instruction.
7947          */
7948         emit_thread_interrupt_checkpoint (mb);
7949
7950         /* we need to convert byref arguments back and free string arrays */
7951         for (i = 0; i < sig->param_count; i++) {
7952                 MonoType *t = sig->params [i];
7953                 MonoMarshalSpec *spec = mspecs [i + 1];
7954
7955                 argnum = i + sig->hasthis;
7956
7957                 if (spec && ((spec->native == MONO_NATIVE_CUSTOM) || (spec->native == MONO_NATIVE_ASANY))) {
7958                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7959                         continue;
7960                 }
7961
7962                 switch (t->type) {
7963                 case MONO_TYPE_STRING:
7964                 case MONO_TYPE_VALUETYPE:
7965                 case MONO_TYPE_CLASS:
7966                 case MONO_TYPE_OBJECT:
7967                 case MONO_TYPE_SZARRAY:
7968                 case MONO_TYPE_BOOLEAN:
7969                         emit_marshal (&m, argnum, t, spec, tmp_locals [i], NULL, MARSHAL_ACTION_CONV_OUT);
7970                         break;
7971                 }
7972         }
7973
7974         if (!MONO_TYPE_IS_VOID(sig->ret))
7975                 mono_mb_emit_ldloc (mb, 3);
7976
7977         mono_mb_emit_byte (mb, CEE_RET);
7978 }
7979
7980 /**
7981  * mono_marshal_get_native_wrapper:
7982  * @method: The MonoMethod to wrap.
7983  *
7984  * generates IL code for the pinvoke wrapper (the generated method
7985  * calls the unmanaged code in piinfo->addr)
7986  */
7987 MonoMethod *
7988 mono_marshal_get_native_wrapper (MonoMethod *method)
7989 {
7990         MonoMethodSignature *sig, *csig;
7991         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
7992         MonoMethodBuilder *mb;
7993         MonoMarshalSpec **mspecs;
7994         MonoMethod *res;
7995         GHashTable *cache;
7996         gboolean pinvoke = FALSE;
7997         gpointer iter;
7998         int i;
7999         const char *exc_class = "MissingMethodException";
8000         const char *exc_arg = NULL;
8001
8002         g_assert (method != NULL);
8003         g_assert (mono_method_signature (method)->pinvoke);
8004
8005         cache = method->klass->image->native_wrapper_cache;
8006         if ((res = mono_marshal_find_in_cache (cache, method)))
8007                 return res;
8008
8009         if (MONO_CLASS_IS_IMPORT (method->klass))
8010                 return cominterop_get_native_wrapper (method);
8011
8012         sig = mono_method_signature (method);
8013
8014         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
8015             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8016                 pinvoke = TRUE;
8017
8018         if (!piinfo->addr) {
8019                 if (pinvoke)
8020                         mono_lookup_pinvoke_call (method, &exc_class, &exc_arg);
8021                 else
8022                         piinfo->addr = mono_lookup_internal_call (method);
8023         }
8024
8025         /* hack - redirect certain string constructors to CreateString */
8026         if (piinfo->addr == ves_icall_System_String_ctor_RedirectToCreateString) {
8027                 g_assert (!pinvoke);
8028                 g_assert (method->string_ctor);
8029                 g_assert (sig->hasthis);
8030
8031                 /* CreateString returns a value */
8032                 csig = signature_dup (method->klass->image, sig);
8033                 csig->ret = &mono_defaults.string_class->byval_arg;
8034                 csig->pinvoke = 0;
8035
8036                 iter = NULL;
8037                 while ((res = mono_class_get_methods (mono_defaults.string_class, &iter))) {
8038                         if (!strcmp ("CreateString", res->name) &&
8039                                 mono_metadata_signature_equal (csig, mono_method_signature (res))) {
8040
8041                                 g_assert (!(res->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
8042                                 g_assert (!(res->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
8043
8044                                 /* create a wrapper to preserve .ctor in stack trace */
8045                                 mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_MANAGED);
8046
8047                                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8048                                 for (i = 1; i <= csig->param_count; i++)
8049                                         mono_mb_emit_ldarg (mb, i);
8050                                 mono_mb_emit_managed_call (mb, res, NULL);
8051                                 mono_mb_emit_byte (mb, CEE_RET);
8052
8053                                 /* use native_wrapper_cache because internal calls are looked up there */
8054                                 res = mono_mb_create_and_cache (cache, method,
8055                                         mb, csig, csig->param_count + 1);
8056
8057                                 mono_mb_free (mb);
8058
8059                                 return res;
8060                         }
8061                 }
8062
8063                 /* exception will be thrown */
8064                 piinfo->addr = NULL;
8065                 g_warning ("cannot find CreateString for .ctor");
8066         }
8067
8068         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8069
8070         mb->method->save_lmf = 1;
8071         
8072         if (!piinfo->addr) {
8073                 mono_mb_emit_exception (mb, exc_class, exc_arg);
8074                 csig = signature_dup (method->klass->image, sig);
8075                 csig->pinvoke = 0;
8076                 res = mono_mb_create_and_cache (cache, method,
8077                                                                                 mb, csig, csig->param_count + 16);
8078                 mono_mb_free (mb);
8079                 return res;
8080         }
8081
8082         /* internal calls: we simply push all arguments and call the method (no conversions) */
8083         if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
8084
8085                 /* hack - string constructors returns a value */
8086                 if (method->string_ctor) {
8087                         csig = signature_dup (method->klass->image, sig);
8088                         csig->ret = &mono_defaults.string_class->byval_arg;
8089                 } else
8090                         csig = sig;
8091
8092                 if (sig->hasthis)
8093                         mono_mb_emit_byte (mb, CEE_LDARG_0);
8094
8095                 for (i = 0; i < sig->param_count; i++)
8096                         mono_mb_emit_ldarg (mb, i + sig->hasthis);
8097
8098                 g_assert (piinfo->addr);
8099                 mono_mb_emit_native_call (mb, csig, piinfo->addr);
8100                 emit_thread_interrupt_checkpoint (mb);
8101                 mono_mb_emit_byte (mb, CEE_RET);
8102
8103                 csig = signature_dup (method->klass->image, csig);
8104                 csig->pinvoke = 0;
8105                 res = mono_mb_create_and_cache (cache, method,
8106                                                                                 mb, csig, csig->param_count + 16);
8107                 mono_mb_free (mb);
8108                 return res;
8109         }
8110
8111         g_assert (pinvoke);
8112
8113         mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
8114         mono_method_get_marshal_info (method, mspecs);
8115
8116         mono_marshal_emit_native_wrapper (mb->method->klass->image, mb, sig, piinfo, mspecs, piinfo->addr);
8117
8118         csig = signature_dup (method->klass->image, sig);
8119         csig->pinvoke = 0;
8120         res = mono_mb_create_and_cache (cache, method,
8121                                                                         mb, csig, csig->param_count + 16);
8122         mono_mb_free (mb);
8123
8124         for (i = sig->param_count; i >= 0; i--)
8125                 if (mspecs [i])
8126                         mono_metadata_free_marshal_spec (mspecs [i]);
8127         g_free (mspecs);
8128
8129         /* 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)); */ 
8130
8131         return res;
8132 }
8133
8134 /**
8135  * mono_marshal_get_native_func_wrapper:
8136  * @image: The image to use for memory allocation and for looking up custom marshallers.
8137  * @sig: The signature of the function
8138  * @func: The native function to wrap
8139  *
8140  *   Returns a wrapper method around native functions, similar to the pinvoke
8141  * wrapper.
8142  */
8143 MonoMethod *
8144 mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig, 
8145                                                                           MonoMethodPInvoke *piinfo, MonoMarshalSpec **mspecs, gpointer func)
8146 {
8147         MonoMethodSignature *csig;
8148
8149         MonoMethodBuilder *mb;
8150         MonoMethod *res;
8151         GHashTable *cache;
8152         char *name;
8153
8154         cache = image->native_wrapper_cache;
8155         if ((res = mono_marshal_find_in_cache (cache, func)))
8156                 return res;
8157
8158         name = g_strdup_printf ("wrapper_native_%p", func);
8159         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_MANAGED_TO_NATIVE);
8160         mb->method->save_lmf = 1;
8161
8162         mono_marshal_emit_native_wrapper (image, mb, sig, piinfo, mspecs, func);
8163
8164         csig = signature_dup (image, sig);
8165         csig->pinvoke = 0;
8166         res = mono_mb_create_and_cache (cache, func,
8167                                                                         mb, csig, csig->param_count + 16);
8168         mono_mb_free (mb);
8169
8170         /* 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)); */ 
8171
8172         return res;
8173 }
8174                             
8175 /* FIXME: moving GC */
8176 static void
8177 mono_marshal_emit_managed_wrapper (MonoMethodBuilder *mb, MonoMethodSignature *invoke_sig, MonoMarshalSpec **mspecs, EmitMarshalContext* m, MonoMethod *method, MonoObject* this)
8178 {
8179         MonoMethodSignature *sig, *csig;
8180         int i, *tmp_locals;
8181
8182         sig = m->sig;
8183         csig = m->csig;
8184
8185         /* allocate local 0 (pointer) src_ptr */
8186         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8187         /* allocate local 1 (pointer) dst_ptr */
8188         mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8189         /* allocate local 2 (boolean) delete_old */
8190         mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8191
8192         if (!MONO_TYPE_IS_VOID(sig->ret)) {
8193                 /* allocate local 3 to store the return value */
8194                 mono_mb_add_local (mb, sig->ret);
8195         }
8196
8197         mono_mb_emit_icon (mb, 0);
8198         mono_mb_emit_stloc (mb, 2);
8199
8200         /* fixme: howto handle this ? */
8201         if (sig->hasthis) {
8202                 if (this) {
8203                         /* FIXME: need a solution for the moving GC here */
8204                         mono_mb_emit_ptr (mb, this);
8205                 } else {
8206                         /* fixme: */
8207                         g_assert_not_reached ();
8208                 }
8209         } 
8210
8211         /* we first do all conversions */
8212         tmp_locals = alloca (sizeof (int) * sig->param_count);
8213         for (i = 0; i < sig->param_count; i ++) {
8214                 MonoType *t = sig->params [i];
8215                 
8216                 switch (t->type) {
8217                 case MONO_TYPE_OBJECT:
8218                 case MONO_TYPE_CLASS:
8219                 case MONO_TYPE_VALUETYPE:
8220                 case MONO_TYPE_ARRAY:
8221                 case MONO_TYPE_SZARRAY:
8222                 case MONO_TYPE_STRING:
8223                         tmp_locals [i] = emit_marshal (m, i, sig->params [i], mspecs [i + 1], 0, &csig->params [i], MARSHAL_ACTION_MANAGED_CONV_IN);
8224
8225                         break;
8226                 default:
8227                         tmp_locals [i] = 0;
8228                         break;
8229                 }
8230         }
8231
8232         emit_thread_interrupt_checkpoint (mb);
8233
8234         for (i = 0; i < sig->param_count; i++) {
8235                 MonoType *t = sig->params [i];
8236
8237                 if (tmp_locals [i]) {
8238                         if (t->byref)
8239                                 mono_mb_emit_ldloc_addr (mb, tmp_locals [i]);
8240                         else
8241                                 mono_mb_emit_ldloc (mb, tmp_locals [i]);
8242                 }
8243                 else
8244                         mono_mb_emit_ldarg (mb, i);
8245         }
8246
8247         mono_mb_emit_managed_call (mb, method, NULL);
8248
8249         if (mspecs [0] && mspecs [0]->native == MONO_NATIVE_CUSTOM) {
8250                 emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8251         }
8252         else
8253         if (!sig->ret->byref) { 
8254                 switch (sig->ret->type) {
8255                 case MONO_TYPE_VOID:
8256                         break;
8257                 case MONO_TYPE_BOOLEAN:
8258                 case MONO_TYPE_I1:
8259                 case MONO_TYPE_U1:
8260                 case MONO_TYPE_I2:
8261                 case MONO_TYPE_U2:
8262                 case MONO_TYPE_I4:
8263                 case MONO_TYPE_U4:
8264                 case MONO_TYPE_I:
8265                 case MONO_TYPE_U:
8266                 case MONO_TYPE_PTR:
8267                 case MONO_TYPE_R4:
8268                 case MONO_TYPE_R8:
8269                 case MONO_TYPE_I8:
8270                 case MONO_TYPE_U8:
8271                 case MONO_TYPE_OBJECT:
8272                         mono_mb_emit_stloc (mb, 3);
8273                         break;
8274                 case MONO_TYPE_STRING:
8275                         csig->ret = &mono_defaults.int_class->byval_arg;
8276                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8277                         break;
8278                 case MONO_TYPE_VALUETYPE:
8279                 case MONO_TYPE_CLASS:
8280                 case MONO_TYPE_SZARRAY:
8281                         emit_marshal (m, 0, sig->ret, mspecs [0], 0, NULL, MARSHAL_ACTION_MANAGED_CONV_RESULT);
8282                         break;
8283                 default:
8284                         g_warning ("return type 0x%02x unknown", sig->ret->type);       
8285                         g_assert_not_reached ();
8286                 }
8287         } else {
8288                 mono_mb_emit_stloc (mb, 3);
8289         }
8290
8291         /* Convert byref arguments back */
8292         for (i = 0; i < sig->param_count; i ++) {
8293                 MonoType *t = sig->params [i];
8294                 MonoMarshalSpec *spec = mspecs [i + 1];
8295
8296                 if (spec && spec->native == MONO_NATIVE_CUSTOM) {
8297                         emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8298                 }
8299                 else if (t->byref) {
8300                         switch (t->type) {
8301                         case MONO_TYPE_CLASS:
8302                         case MONO_TYPE_VALUETYPE:
8303                         case MONO_TYPE_OBJECT:
8304                                 emit_marshal (m, i, t, mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8305                                 break;
8306                         }
8307                 }
8308                 else if (invoke_sig->params [i]->attrs & PARAM_ATTRIBUTE_OUT) {
8309                         /* The [Out] information is encoded in the delegate signature */
8310                         switch (t->type) {
8311                         case MONO_TYPE_SZARRAY:
8312                         case MONO_TYPE_CLASS:
8313                         case MONO_TYPE_VALUETYPE:
8314                                 emit_marshal (m, i, invoke_sig->params [i], mspecs [i + 1], tmp_locals [i], NULL, MARSHAL_ACTION_MANAGED_CONV_OUT);
8315                                 break;
8316                         default:
8317                                 g_assert_not_reached ();
8318                         }
8319                 }
8320         }
8321
8322         if (m->retobj_var) {
8323                 mono_mb_emit_ldloc (mb, m->retobj_var);
8324                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8325                 mono_mb_emit_op (mb, CEE_MONO_RETOBJ, m->retobj_class);
8326         }
8327         else {
8328                 if (!MONO_TYPE_IS_VOID(sig->ret))
8329                         mono_mb_emit_ldloc (mb, 3);
8330                 mono_mb_emit_byte (mb, CEE_RET);
8331         }
8332 }
8333
8334
8335 /*
8336  * generates IL code to call managed methods from unmanaged code 
8337  */
8338 MonoMethod *
8339 mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass, MonoObject *this)
8340 {
8341         static MonoClass *UnmanagedFunctionPointerAttribute;
8342         MonoMethodSignature *sig, *csig, *invoke_sig;
8343         MonoMethodBuilder *mb;
8344         MonoMethod *res, *invoke;
8345         MonoMarshalSpec **mspecs;
8346         MonoMethodPInvoke piinfo;
8347         GHashTable *cache;
8348         int i;
8349         EmitMarshalContext m;
8350
8351         g_assert (method != NULL);
8352         g_assert (!mono_method_signature (method)->pinvoke);
8353
8354         /* 
8355          * FIXME: Should cache the method+delegate type pair, since the same method
8356          * could be called with different delegates, thus different marshalling
8357          * options.
8358          */
8359         cache = method->klass->image->managed_wrapper_cache;
8360         if (!this && (res = mono_marshal_find_in_cache (cache, method)))
8361                 return res;
8362
8363         invoke = mono_class_get_method_from_name (delegate_klass, "Invoke", mono_method_signature (method)->param_count);
8364         invoke_sig = mono_method_signature (invoke);
8365
8366         mspecs = g_new0 (MonoMarshalSpec*, mono_method_signature (invoke)->param_count + 1);
8367         mono_method_get_marshal_info (invoke, mspecs);
8368
8369         sig = mono_method_signature (method);
8370
8371         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_NATIVE_TO_MANAGED);
8372
8373
8374         /* we copy the signature, so that we can modify it */
8375         csig = signature_dup (method->klass->image, sig);
8376         csig->hasthis = 0;
8377         csig->pinvoke = 1;
8378
8379         m.mb = mb;
8380         m.sig = sig;
8381         m.piinfo = NULL;
8382         m.retobj_var = 0;
8383         m.csig = csig;
8384         m.image = method->klass->image;
8385
8386 #ifdef PLATFORM_WIN32
8387         /* 
8388          * Under windows, delegates passed to native code must use the STDCALL
8389          * calling convention.
8390          */
8391         csig->call_convention = MONO_CALL_STDCALL;
8392 #endif
8393
8394         /* Change default calling convention if needed */
8395         /* Why is this a modopt ? */
8396         if (invoke_sig->ret && invoke_sig->ret->num_mods) {
8397                 for (i = 0; i < invoke_sig->ret->num_mods; ++i) {
8398                         MonoClass *cmod_class = mono_class_get (delegate_klass->image, invoke_sig->ret->modifiers [i].token);
8399                         g_assert (cmod_class);
8400                         if ((cmod_class->image == mono_defaults.corlib) && !strcmp (cmod_class->name_space, "System.Runtime.CompilerServices")) {
8401                                 if (!strcmp (cmod_class->name, "CallConvCdecl"))
8402                                         csig->call_convention = MONO_CALL_C;
8403                                 else if (!strcmp (cmod_class->name, "CallConvStdcall"))
8404                                         csig->call_convention = MONO_CALL_STDCALL;
8405                                 else if (!strcmp (cmod_class->name, "CallConvFastcall"))
8406                                         csig->call_convention = MONO_CALL_FASTCALL;
8407                                 else if (!strcmp (cmod_class->name, "CallConvThiscall"))
8408                                         csig->call_convention = MONO_CALL_THISCALL;
8409                         }
8410                 }
8411         }
8412
8413         /* Handle the UnmanagedFunctionPointerAttribute */
8414         if (!UnmanagedFunctionPointerAttribute)
8415                 UnmanagedFunctionPointerAttribute = mono_class_from_name (mono_defaults.corlib, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
8416
8417         /* The attribute is only available in Net 2.0 */
8418         if (UnmanagedFunctionPointerAttribute) {
8419                 MonoReflectionUnmanagedFunctionPointerAttribute *attr;
8420                 MonoCustomAttrInfo *cinfo;
8421
8422                 /* 
8423                  * The pinvoke attributes are stored in a real custom attribute so we have to
8424                  * construct it.
8425                  */
8426                 cinfo = mono_custom_attrs_from_class (delegate_klass);
8427                 if (cinfo) {
8428                         attr = (MonoReflectionUnmanagedFunctionPointerAttribute*)mono_custom_attrs_get_attr (cinfo, UnmanagedFunctionPointerAttribute);
8429                         if (attr) {
8430                                 memset (&piinfo, 0, sizeof (piinfo));
8431                                 m.piinfo = &piinfo;
8432                                 piinfo.piflags = (attr->call_conv << 8) | (attr->charset ? (attr->charset - 1) * 2 : 1) | attr->set_last_error;
8433
8434                                 csig->call_convention = attr->call_conv - 1;
8435                         }
8436                         if (!cinfo->cached)
8437                                 mono_custom_attrs_free (cinfo);
8438                 }
8439         }
8440
8441         mono_marshal_emit_managed_wrapper (mb, invoke_sig, mspecs, &m, method, this);
8442
8443         if (!this)
8444                 res = mono_mb_create_and_cache (cache, method,
8445                                                                                          mb, csig, sig->param_count + 16);
8446         else {
8447                 mb->dynamic = 1;
8448                 res = mono_mb_create_method (mb, csig, sig->param_count + 16);
8449         }
8450         mono_mb_free (mb);
8451
8452         for (i = mono_method_signature (invoke)->param_count; i >= 0; i--)
8453                 if (mspecs [i])
8454                         mono_metadata_free_marshal_spec (mspecs [i]);
8455         g_free (mspecs);
8456
8457         /* 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)); */
8458
8459         return res;
8460 }
8461
8462 static MonoReflectionType *
8463 type_from_handle (MonoType *handle)
8464 {
8465         MonoDomain *domain = mono_domain_get (); 
8466         MonoClass *klass = mono_class_from_mono_type (handle);
8467
8468         MONO_ARCH_SAVE_REGS;
8469
8470         mono_class_init (klass);
8471         return mono_type_get_object (domain, handle);
8472 }
8473
8474 /*
8475  * mono_marshal_get_isinst:
8476  * @klass: the type of the field
8477  *
8478  * This method generates a function which can be used to check if an object is
8479  * an instance of the given type, icluding the case where the object is a proxy.
8480  * The generated function has the following signature:
8481  * MonoObject* __isinst_wrapper_ (MonoObject *obj)
8482  */
8483 MonoMethod *
8484 mono_marshal_get_isinst (MonoClass *klass)
8485 {
8486         static MonoMethodSignature *isint_sig = NULL;
8487         GHashTable *cache;
8488         MonoMethod *res;
8489         int pos_was_ok, pos_failed, pos_end, pos_end2;
8490         char *name;
8491         MonoMethodBuilder *mb;
8492
8493         cache = klass->image->isinst_cache;
8494         if ((res = mono_marshal_find_in_cache (cache, klass)))
8495                 return res;
8496
8497         if (!isint_sig) {
8498                 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8499                 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
8500                 isint_sig->ret = &mono_defaults.object_class->byval_arg;
8501                 isint_sig->pinvoke = 0;
8502         }
8503         
8504         name = g_strdup_printf ("__isinst_wrapper_%s", klass->name); 
8505         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ISINST);
8506         g_free (name);
8507         
8508         mb->method->save_lmf = 1;
8509
8510         /* check if the object is a proxy that needs special cast */
8511         mono_mb_emit_ldarg (mb, 0);
8512         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8513         mono_mb_emit_op (mb, CEE_MONO_CISINST, klass);
8514
8515         /* The result of MONO_ISINST can be:
8516                 0) the type check succeeded
8517                 1) the type check did not succeed
8518                 2) a CanCastTo call is needed */
8519         
8520         mono_mb_emit_byte (mb, CEE_DUP);
8521         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8522
8523         mono_mb_emit_byte (mb, CEE_LDC_I4_2);
8524         pos_failed = mono_mb_emit_branch (mb, CEE_BNE_UN);
8525         
8526         /* get the real proxy from the transparent proxy*/
8527
8528         mono_mb_emit_ldarg (mb, 0);
8529         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8530         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8531         
8532         /* fail */
8533         
8534         mono_mb_patch_addr (mb, pos_failed, mb->pos - (pos_failed + 4));
8535         mono_mb_emit_byte (mb, CEE_LDNULL);
8536         pos_end2 = mono_mb_emit_branch (mb, CEE_BR);
8537         
8538         /* success */
8539         
8540         mono_mb_patch_addr (mb, pos_was_ok, mb->pos - (pos_was_ok + 4));
8541         mono_mb_emit_byte (mb, CEE_POP);
8542         mono_mb_emit_ldarg (mb, 0);
8543         
8544         /* the end */
8545         
8546         mono_mb_patch_addr (mb, pos_end, mb->pos - (pos_end + 4));
8547         mono_mb_patch_addr (mb, pos_end2, mb->pos - (pos_end2 + 4));
8548         mono_mb_emit_byte (mb, CEE_RET);
8549
8550         res = mono_mb_create_and_cache (cache, klass, mb, isint_sig, isint_sig->param_count + 16);
8551         mono_mb_free (mb);
8552
8553         return res;
8554 }
8555
8556 /*
8557  * mono_marshal_get_castclass:
8558  * @klass: the type of the field
8559  *
8560  * This method generates a function which can be used to cast an object to
8561  * an instance of the given type, icluding the case where the object is a proxy.
8562  * The generated function has the following signature:
8563  * MonoObject* __castclass_wrapper_ (MonoObject *obj)
8564  */
8565 MonoMethod *
8566 mono_marshal_get_castclass (MonoClass *klass)
8567 {
8568         static MonoMethodSignature *castclass_sig = NULL;
8569         GHashTable *cache;
8570         MonoMethod *res;
8571         int pos_was_ok, pos_was_ok2;
8572         char *name;
8573         MonoMethodBuilder *mb;
8574
8575         cache = klass->image->castclass_cache;
8576         if ((res = mono_marshal_find_in_cache (cache, klass)))
8577                 return res;
8578
8579         if (!castclass_sig) {
8580                 castclass_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8581                 castclass_sig->params [0] = &mono_defaults.object_class->byval_arg;
8582                 castclass_sig->ret = &mono_defaults.object_class->byval_arg;
8583                 castclass_sig->pinvoke = 0;
8584         }
8585         
8586         name = g_strdup_printf ("__castclass_wrapper_%s", klass->name); 
8587         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_CASTCLASS);
8588         g_free (name);
8589         
8590         mb->method->save_lmf = 1;
8591
8592         /* check if the object is a proxy that needs special cast */
8593         mono_mb_emit_ldarg (mb, 0);
8594         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
8595         mono_mb_emit_op (mb, CEE_MONO_CCASTCLASS, klass);
8596
8597         /* The result of MONO_ISINST can be:
8598                 0) the cast is valid
8599                 1) cast of unknown proxy type
8600                 or an exception if the cast is is invalid
8601         */
8602         
8603         pos_was_ok = mono_mb_emit_branch (mb, CEE_BRFALSE);
8604
8605         /* get the real proxy from the transparent proxy*/
8606
8607         mono_mb_emit_ldarg (mb, 0);
8608         mono_mb_emit_managed_call (mb, mono_marshal_get_proxy_cancast (klass), NULL);
8609         pos_was_ok2 = mono_mb_emit_branch (mb, CEE_BRTRUE);
8610         
8611         /* fail */
8612         mono_mb_emit_exception (mb, "InvalidCastException", NULL);
8613         
8614         /* success */
8615         mono_mb_patch_addr (mb, pos_was_ok, mb->pos - (pos_was_ok + 4));
8616         mono_mb_patch_addr (mb, pos_was_ok2, mb->pos - (pos_was_ok2 + 4));
8617         mono_mb_emit_ldarg (mb, 0);
8618         
8619         /* the end */
8620         mono_mb_emit_byte (mb, CEE_RET);
8621
8622         res = mono_mb_create_and_cache (cache, klass, mb, castclass_sig, castclass_sig->param_count + 16);
8623         mono_mb_free (mb);
8624
8625         return res;
8626 }
8627
8628 MonoMethod *
8629 mono_marshal_get_proxy_cancast (MonoClass *klass)
8630 {
8631         static MonoMethodSignature *isint_sig = NULL;
8632         GHashTable *cache;
8633         MonoMethod *res;
8634         int pos_failed, pos_end;
8635         char *name;
8636         MonoMethod *can_cast_to;
8637         MonoMethodDesc *desc;
8638         MonoMethodBuilder *mb;
8639
8640         cache = klass->image->proxy_isinst_cache;
8641         if ((res = mono_marshal_find_in_cache (cache, klass)))
8642                 return res;
8643
8644         if (!isint_sig) {
8645                 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
8646                 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
8647                 isint_sig->ret = &mono_defaults.object_class->byval_arg;
8648                 isint_sig->pinvoke = 0;
8649         }
8650         
8651         name = g_strdup_printf ("__proxy_isinst_wrapper_%s", klass->name); 
8652         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_PROXY_ISINST);
8653         g_free (name);
8654         
8655         mb->method->save_lmf = 1;
8656
8657         /* get the real proxy from the transparent proxy*/
8658         mono_mb_emit_ldarg (mb, 0);
8659         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoTransparentProxy, rp));
8660         mono_mb_emit_byte (mb, CEE_LDIND_REF);
8661         
8662         /* get the reflection type from the type handle */
8663         mono_mb_emit_ptr (mb, &klass->byval_arg);
8664         mono_mb_emit_icall (mb, type_from_handle);
8665         
8666         mono_mb_emit_ldarg (mb, 0);
8667         
8668         /* make the call to CanCastTo (type, ob) */
8669         desc = mono_method_desc_new ("IRemotingTypeInfo:CanCastTo", FALSE);
8670         can_cast_to = mono_method_desc_search_in_class (desc, mono_defaults.iremotingtypeinfo_class);
8671         g_assert (can_cast_to);
8672         mono_method_desc_free (desc);
8673         mono_mb_emit_op (mb, CEE_CALLVIRT, can_cast_to);
8674         
8675         pos_failed = mono_mb_emit_branch (mb, CEE_BRFALSE);
8676
8677         /* Upgrade the proxy vtable by calling: mono_upgrade_remote_class_wrapper (type, ob)*/
8678         mono_mb_emit_ptr (mb, &klass->byval_arg);
8679         mono_mb_emit_icall (mb, type_from_handle);
8680         mono_mb_emit_ldarg (mb, 0);
8681         
8682         mono_mb_emit_icall (mb, mono_upgrade_remote_class_wrapper);
8683         emit_thread_interrupt_checkpoint (mb);
8684         
8685         mono_mb_emit_ldarg (mb, 0);
8686         pos_end = mono_mb_emit_branch (mb, CEE_BR);
8687         
8688         /* fail */
8689         
8690         mono_mb_patch_addr (mb, pos_failed, mb->pos - (pos_failed + 4));
8691         mono_mb_emit_byte (mb, CEE_LDNULL);
8692         
8693         /* the end */
8694         
8695         mono_mb_patch_addr (mb, pos_end, mb->pos - (pos_end + 4));
8696         mono_mb_emit_byte (mb, CEE_RET);
8697
8698         res = mono_mb_create_and_cache (cache, klass, mb, isint_sig, isint_sig->param_count + 16);
8699         mono_mb_free (mb);
8700
8701         return res;
8702 }
8703
8704 void
8705 mono_upgrade_remote_class_wrapper (MonoReflectionType *rtype, MonoTransparentProxy *tproxy)
8706 {
8707         MonoClass *klass;
8708         MonoDomain *domain = ((MonoObject*)tproxy)->vtable->domain;
8709         klass = mono_class_from_mono_type (rtype->type);
8710         mono_upgrade_remote_class (domain, (MonoObject*)tproxy, klass);
8711 }
8712
8713 /**
8714  * mono_marshal_get_struct_to_ptr:
8715  * @klass:
8716  *
8717  * generates IL code for StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)
8718  */
8719 MonoMethod *
8720 mono_marshal_get_struct_to_ptr (MonoClass *klass)
8721 {
8722         MonoMethodBuilder *mb;
8723         static MonoMethod *stoptr = NULL;
8724         MonoMethod *res;
8725
8726         g_assert (klass != NULL);
8727
8728         mono_marshal_load_type_info (klass);
8729
8730         if (klass->marshal_info->str_to_ptr)
8731                 return klass->marshal_info->str_to_ptr;
8732
8733         if (!stoptr) 
8734                 stoptr = mono_class_get_method_from_name (mono_defaults.marshal_class, "StructureToPtr", 3);
8735         g_assert (stoptr);
8736
8737         mb = mono_mb_new (klass, stoptr->name, MONO_WRAPPER_UNKNOWN);
8738
8739         if (klass->blittable) {
8740                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8741                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8742                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8743                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8744                 mono_mb_emit_byte (mb, CEE_PREFIX1);
8745                 mono_mb_emit_byte (mb, CEE_CPBLK);
8746         } else {
8747
8748                 /* allocate local 0 (pointer) src_ptr */
8749                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8750                 /* allocate local 1 (pointer) dst_ptr */
8751                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8752                 /* allocate local 2 (boolean) delete_old */
8753                 mono_mb_add_local (mb, &mono_defaults.boolean_class->byval_arg);
8754                 mono_mb_emit_byte (mb, CEE_LDARG_2);
8755                 mono_mb_emit_stloc (mb, 2);
8756
8757                 /* initialize src_ptr to point to the start of object data */
8758                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8759                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8760                 mono_mb_emit_stloc (mb, 0);
8761
8762                 /* initialize dst_ptr */
8763                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8764                 mono_mb_emit_stloc (mb, 1);
8765
8766                 emit_struct_conv (mb, klass, FALSE);
8767         }
8768
8769         mono_mb_emit_byte (mb, CEE_RET);
8770
8771         res = mono_mb_create_method (mb, mono_method_signature (stoptr), 0);
8772         mono_mb_free (mb);
8773
8774         klass->marshal_info->str_to_ptr = res;
8775         return res;
8776 }
8777
8778 /**
8779  * mono_marshal_get_ptr_to_struct:
8780  * @klass:
8781  *
8782  * generates IL code for PtrToStructure (IntPtr src, object structure)
8783  */
8784 MonoMethod *
8785 mono_marshal_get_ptr_to_struct (MonoClass *klass)
8786 {
8787         MonoMethodBuilder *mb;
8788         static MonoMethodSignature *ptostr = NULL;
8789         MonoMethod *res;
8790
8791         g_assert (klass != NULL);
8792
8793         mono_marshal_load_type_info (klass);
8794
8795         if (klass->marshal_info->ptr_to_str)
8796                 return klass->marshal_info->ptr_to_str;
8797
8798         if (!ptostr)
8799                 /* Create the signature corresponding to
8800                           static void PtrToStructure (IntPtr ptr, object structure);
8801                    defined in class/corlib/System.Runtime.InteropServices/Marshal.cs */
8802                 ptostr = mono_create_icall_signature ("void ptr object");
8803
8804         mb = mono_mb_new (klass, "PtrToStructure", MONO_WRAPPER_UNKNOWN);
8805
8806         if (klass->blittable) {
8807                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8808                 mono_mb_emit_ldflda (mb, sizeof (MonoObject));
8809                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8810                 mono_mb_emit_icon (mb, mono_class_value_size (klass, NULL));
8811                 mono_mb_emit_byte (mb, CEE_PREFIX1);
8812                 mono_mb_emit_byte (mb, CEE_CPBLK);
8813         } else {
8814
8815                 /* allocate local 0 (pointer) src_ptr */
8816                 mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
8817                 /* allocate local 1 (pointer) dst_ptr */
8818                 mono_mb_add_local (mb, &klass->this_arg);
8819                 
8820                 /* initialize src_ptr to point to the start of object data */
8821                 mono_mb_emit_byte (mb, CEE_LDARG_0);
8822                 mono_mb_emit_stloc (mb, 0);
8823
8824                 /* initialize dst_ptr */
8825                 mono_mb_emit_byte (mb, CEE_LDARG_1);
8826                 mono_mb_emit_op (mb, CEE_UNBOX, klass);
8827                 mono_mb_emit_stloc (mb, 1);
8828
8829                 emit_struct_conv (mb, klass, TRUE);
8830         }
8831
8832         mono_mb_emit_byte (mb, CEE_RET);
8833
8834         res = mono_mb_create_method (mb, ptostr, 0);
8835         mono_mb_free (mb);
8836
8837         klass->marshal_info->ptr_to_str = res;
8838         return res;
8839 }
8840
8841 /*
8842  * generates IL code for the synchronized wrapper: the generated method
8843  * calls METHOD while locking 'this' or the parent type.
8844  */
8845 MonoMethod *
8846 mono_marshal_get_synchronized_wrapper (MonoMethod *method)
8847 {
8848         static MonoMethod *enter_method, *exit_method;
8849         MonoMethodSignature *sig;
8850         MonoExceptionClause *clause;
8851         MonoMethodHeader *header;
8852         MonoMethodBuilder *mb;
8853         MonoMethod *res;
8854         GHashTable *cache;
8855         int i, pos, this_local, ret_local = 0;
8856
8857         g_assert (method);
8858
8859         if (method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED)
8860                 return method;
8861
8862         cache = method->klass->image->synchronized_cache;
8863         if ((res = mono_marshal_find_in_cache (cache, method)))
8864                 return res;
8865
8866         sig = signature_dup (method->klass->image, mono_method_signature (method));
8867         sig->pinvoke = 0;
8868
8869         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_SYNCHRONIZED);
8870
8871         /* result */
8872         if (!MONO_TYPE_IS_VOID (sig->ret))
8873                 ret_local = mono_mb_add_local (mb, sig->ret);
8874
8875         /* this */
8876         this_local = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
8877
8878         mono_loader_lock ();
8879         clause = mono_mempool_alloc0 (method->klass->image->mempool, sizeof (MonoExceptionClause));
8880         mono_loader_unlock ();
8881         clause->flags = MONO_EXCEPTION_CLAUSE_FINALLY;
8882
8883         if (!enter_method) {
8884                 MonoMethodDesc *desc;
8885
8886                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
8887                 enter_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
8888                 g_assert (enter_method);
8889                 mono_method_desc_free (desc);
8890                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
8891                 exit_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
8892                 g_assert (exit_method);
8893                 mono_method_desc_free (desc);
8894         }
8895
8896         /* Push this or the type object */
8897         if (method->flags & METHOD_ATTRIBUTE_STATIC) {
8898                 /*
8899                  * GetTypeFromHandle isn't called as a managed method because it has
8900                  * a funky calling sequence, e.g. ldtoken+GetTypeFromHandle gets
8901                  * transformed into something else by the JIT.
8902                  */
8903                 mono_mb_emit_ptr (mb, &method->klass->byval_arg);
8904                 mono_mb_emit_icall (mb, type_from_handle);
8905         }
8906         else
8907                 mono_mb_emit_ldarg (mb, 0);
8908         mono_mb_emit_stloc (mb, this_local);
8909
8910         /* Call Monitor::Enter() */
8911         mono_mb_emit_ldloc (mb, this_local);
8912         mono_mb_emit_managed_call (mb, enter_method, NULL);
8913
8914         clause->try_offset = mb->pos;
8915
8916         /* Call the method */
8917         if (sig->hasthis)
8918                 mono_mb_emit_ldarg (mb, 0);
8919         for (i = 0; i < sig->param_count; i++)
8920                 mono_mb_emit_ldarg (mb, i + (sig->hasthis == TRUE));
8921         
8922         /* this is needed to avoid recursion */
8923         mono_mb_emit_byte (mb, CEE_PREFIX1);
8924         mono_mb_emit_op (mb, CEE_LDFTN, method);
8925         mono_mb_emit_calli (mb, mono_method_signature (method));
8926
8927         if (!MONO_TYPE_IS_VOID (sig->ret))
8928                 mono_mb_emit_stloc (mb, ret_local);
8929
8930         pos = mono_mb_emit_branch (mb, CEE_LEAVE);
8931
8932         clause->try_len = mb->pos - clause->try_offset;
8933         clause->handler_offset = mb->pos;
8934
8935         /* Call Monitor::Exit() */
8936         mono_mb_emit_ldloc (mb, this_local);
8937 /*      mono_mb_emit_native_call (mb, exit_sig, mono_monitor_exit); */
8938         mono_mb_emit_managed_call (mb, exit_method, NULL);
8939         mono_mb_emit_byte (mb, CEE_ENDFINALLY);
8940
8941         clause->handler_len = mb->pos - clause->handler_offset;
8942
8943         mono_mb_patch_branch (mb, pos);
8944         if (!MONO_TYPE_IS_VOID (sig->ret))
8945                 mono_mb_emit_ldloc (mb, ret_local);
8946         mono_mb_emit_byte (mb, CEE_RET);
8947
8948         res = mono_mb_create_and_cache (cache, method,
8949                                                                         mb, sig, sig->param_count + 16);
8950         mono_mb_free (mb);
8951
8952         header = ((MonoMethodNormal *)res)->header;
8953         header->num_clauses = 1;
8954         header->clauses = clause;
8955
8956         return res;     
8957 }
8958
8959
8960 /*
8961  * the returned method calls 'method' unboxing the this argument
8962  */
8963 MonoMethod *
8964 mono_marshal_get_unbox_wrapper (MonoMethod *method)
8965 {
8966         MonoMethodSignature *sig = mono_method_signature (method);
8967         int i;
8968         MonoMethodBuilder *mb;
8969         MonoMethod *res;
8970         GHashTable *cache;
8971
8972         cache = method->klass->image->unbox_wrapper_cache;
8973         if ((res = mono_marshal_find_in_cache (cache, method)))
8974                 return res;
8975
8976         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_UNBOX);
8977
8978         g_assert (sig->hasthis);
8979         
8980         mono_mb_emit_ldarg (mb, 0); 
8981         mono_mb_emit_icon (mb, sizeof (MonoObject));
8982         mono_mb_emit_byte (mb, CEE_ADD);
8983         for (i = 0; i < sig->param_count; ++i)
8984                 mono_mb_emit_ldarg (mb, i + 1);
8985         mono_mb_emit_managed_call (mb, method, NULL);
8986         mono_mb_emit_byte (mb, CEE_RET);
8987
8988         res = mono_mb_create_and_cache (cache, method,
8989                                                                                  mb, sig, sig->param_count + 16);
8990         mono_mb_free (mb);
8991
8992         /* 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)); */
8993
8994         return res;     
8995 }
8996
8997 MonoMethod*
8998 mono_marshal_get_stelemref ()
8999 {
9000         static MonoMethod* ret = NULL;
9001         MonoMethodSignature *sig;
9002         MonoMethodBuilder *mb;
9003         
9004         guint32 b1, b2, b3, b4;
9005         guint32 copy_pos;
9006         int aklass, vklass;
9007         int array_slot_addr;
9008         
9009         if (ret)
9010                 return ret;
9011         
9012         mb = mono_mb_new (mono_defaults.object_class, "stelemref", MONO_WRAPPER_STELEMREF);
9013         
9014
9015         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
9016
9017         /* void stelemref (void* array, int idx, void* value) */
9018         sig->ret = &mono_defaults.void_class->byval_arg;
9019         sig->params [0] = &mono_defaults.object_class->byval_arg;
9020         sig->params [1] = &mono_defaults.int_class->byval_arg; /* this is a natural sized int */
9021         sig->params [2] = &mono_defaults.object_class->byval_arg;
9022                 
9023         aklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9024         vklass = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9025         array_slot_addr = mono_mb_add_local (mb, &mono_defaults.object_class->this_arg);
9026         
9027         /*
9028         the method:
9029         <ldelema (bound check)>
9030         if (!value)
9031                 goto store;
9032         
9033         aklass = array->vtable->klass->element_class;
9034         vklass = value->vtable->klass;
9035         
9036         if (vklass->idepth < aklass->idepth)
9037                 goto long;
9038         
9039         if (vklass->supertypes [aklass->idepth - 1] != aklass)
9040                 goto long;
9041         
9042         store:
9043                 *array_slot_addr = value;
9044                 return;
9045         
9046         long:
9047                 if (mono_object_isinst (value, aklass))
9048                         goto store;
9049                 
9050                 throw new ArrayTypeMismatchException ();
9051         */
9052         
9053         /* ldelema (implicit bound check) */
9054         mono_mb_emit_ldarg (mb, 0);
9055         mono_mb_emit_ldarg (mb, 1);
9056         mono_mb_emit_op (mb, CEE_LDELEMA, mono_defaults.object_class);
9057         mono_mb_emit_stloc (mb, array_slot_addr);
9058                 
9059         /* if (!value) goto do_store */
9060         mono_mb_emit_ldarg (mb, 2);
9061         b1 = mono_mb_emit_branch (mb, CEE_BRFALSE);
9062         
9063         /* aklass = array->vtable->klass->element_class */
9064         mono_mb_emit_ldarg (mb, 0);
9065         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoObject, vtable));
9066         mono_mb_emit_byte (mb, CEE_LDIND_I);
9067         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoVTable, klass));
9068         mono_mb_emit_byte (mb, CEE_LDIND_I);
9069         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, element_class));
9070         mono_mb_emit_byte (mb, CEE_LDIND_I);
9071         mono_mb_emit_stloc (mb, aklass);
9072         
9073         /* vklass = value->vtable->klass */
9074         mono_mb_emit_ldarg (mb, 2);
9075         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoObject, vtable));
9076         mono_mb_emit_byte (mb, CEE_LDIND_I);
9077         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoVTable, klass));
9078         mono_mb_emit_byte (mb, CEE_LDIND_I);
9079         mono_mb_emit_stloc (mb, vklass);
9080         
9081         /* if (vklass->idepth < aklass->idepth) goto failue */
9082         mono_mb_emit_ldloc (mb, vklass);
9083         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, idepth));
9084         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9085         
9086         mono_mb_emit_ldloc (mb, aklass);
9087         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, idepth));
9088         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9089         
9090         b2 = mono_mb_emit_branch (mb, CEE_BLT_UN);
9091         
9092         /* if (vklass->supertypes [aklass->idepth - 1] != aklass) goto failure */
9093         mono_mb_emit_ldloc (mb, vklass);
9094         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, supertypes));
9095         mono_mb_emit_byte (mb, CEE_LDIND_I);
9096         
9097         mono_mb_emit_ldloc (mb, aklass);
9098         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoClass, idepth));
9099         mono_mb_emit_byte (mb, CEE_LDIND_U2);
9100         mono_mb_emit_icon (mb, 1);
9101         mono_mb_emit_byte (mb, CEE_SUB);
9102         mono_mb_emit_icon (mb, sizeof (void*));
9103         mono_mb_emit_byte (mb, CEE_MUL);
9104         mono_mb_emit_byte (mb, CEE_ADD);
9105         mono_mb_emit_byte (mb, CEE_LDIND_I);
9106         
9107         mono_mb_emit_ldloc (mb, aklass);
9108         
9109         b3 = mono_mb_emit_branch (mb, CEE_BNE_UN);
9110         
9111         copy_pos = mb->pos;
9112         /* do_store */
9113         mono_mb_patch_branch (mb, b1);
9114         mono_mb_emit_ldloc (mb, array_slot_addr);
9115         mono_mb_emit_ldarg (mb, 2);
9116         mono_mb_emit_byte (mb, CEE_STIND_REF);
9117         
9118         mono_mb_emit_byte (mb, CEE_RET);
9119         
9120         /* the hard way */
9121         mono_mb_patch_branch (mb, b2);
9122         mono_mb_patch_branch (mb, b3);
9123         
9124         mono_mb_emit_ldarg (mb, 2);
9125         mono_mb_emit_ldloc (mb, aklass);
9126         mono_mb_emit_icall (mb, mono_object_isinst);
9127         
9128         b4 = mono_mb_emit_branch (mb, CEE_BRTRUE);
9129         mono_mb_patch_addr (mb, b4, copy_pos - (b4 + 4));
9130         mono_mb_emit_exception (mb, "ArrayTypeMismatchException", NULL);
9131         
9132         mono_mb_emit_byte (mb, CEE_RET);
9133         ret = mono_mb_create_method (mb, sig, 4);
9134         mono_mb_free (mb);
9135         return ret;
9136 }
9137
9138 typedef struct {
9139         int rank;
9140         int elem_size;
9141         MonoMethod *method;
9142 } ArrayElemAddr;
9143
9144 /* LOCKING: vars accessed under the marshal lock */
9145 static ArrayElemAddr *elem_addr_cache = NULL;
9146 static int elem_addr_cache_size = 0;
9147 static int elem_addr_cache_next = 0;
9148
9149 /**
9150  * mono_marshal_get_array_address:
9151  * @rank: rank of the array type
9152  * @elem_size: size in bytes of an element of an array.
9153  *
9154  * Returns a MonoMethd that implements the code to get the address
9155  * of an element in a multi-dimenasional array of @rank dimensions.
9156  * The returned method takes an array as the first argument and then
9157  * @rank indexes for the @rank dimensions.
9158  */
9159 MonoMethod*
9160 mono_marshal_get_array_address (int rank, int elem_size)
9161 {
9162         MonoMethod *ret;
9163         MonoMethodBuilder *mb;
9164         MonoMethodSignature *sig;
9165         int i, bounds, ind, realidx;
9166         int branch_pos, *branch_positions;
9167         int cached;
9168
9169         ret = NULL;
9170         mono_marshal_lock ();
9171         for (i = 0; i < elem_addr_cache_next; ++i) {
9172                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
9173                         ret = elem_addr_cache [i].method;
9174                         break;
9175                 }
9176         }
9177         mono_marshal_unlock ();
9178         if (ret)
9179                 return ret;
9180
9181         branch_positions = g_new0 (int, rank);
9182
9183         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1 + rank);
9184
9185         /* void* address (void* array, int idx0, int idx1, int idx2, ...) */
9186         sig->ret = &mono_defaults.int_class->byval_arg;
9187         sig->params [0] = &mono_defaults.object_class->byval_arg;
9188         for (i = 0; i < rank; ++i) {
9189                 sig->params [i + 1] = &mono_defaults.int32_class->byval_arg;
9190         }
9191
9192         mb = mono_mb_new (mono_defaults.object_class, "ElementAddr", MONO_WRAPPER_MANAGED_TO_MANAGED);
9193         
9194         bounds = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
9195         ind = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9196         realidx = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
9197
9198         /* bounds = array->bounds; */
9199         mono_mb_emit_ldarg (mb, 0);
9200         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoArray, bounds));
9201         mono_mb_emit_byte (mb, CEE_LDIND_I);
9202         mono_mb_emit_stloc (mb, bounds);
9203
9204         /* ind is the overall element index, realidx is the partial index in a single dimension */
9205         /* ind = idx0 - bounds [0].lower_bound */
9206         mono_mb_emit_ldarg (mb, 1);
9207         mono_mb_emit_ldloc (mb, bounds);
9208         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
9209         mono_mb_emit_byte (mb, CEE_ADD);
9210         mono_mb_emit_byte (mb, CEE_LDIND_I4);
9211         mono_mb_emit_byte (mb, CEE_SUB);
9212         mono_mb_emit_stloc (mb, ind);
9213         /* if (ind >= bounds [0].length) goto exeception; */
9214         mono_mb_emit_ldloc (mb, ind);
9215         mono_mb_emit_ldloc (mb, bounds);
9216         mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoArrayBounds, length));
9217         mono_mb_emit_byte (mb, CEE_ADD);
9218         mono_mb_emit_byte (mb, CEE_LDIND_I4);
9219         /* note that we use unsigned comparison */
9220         branch_pos = mono_mb_emit_branch (mb, CEE_BGE_UN);
9221
9222         /* For large ranks (> 4?) use a loop n IL later to reduce code size.
9223          * We could also decide to ignore the passed elem_size and get it
9224          * from the array object, to reduce the number of methods we generate:
9225          * the additional cost is 3 memory loads and a non-immediate mul.
9226          */
9227         for (i = 1; i < rank; ++i) {
9228                 /* realidx = idxi - bounds [i].lower_bound */
9229                 mono_mb_emit_ldarg (mb, 1 + i);
9230                 mono_mb_emit_ldloc (mb, bounds);
9231                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + G_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
9232                 mono_mb_emit_byte (mb, CEE_ADD);
9233                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9234                 mono_mb_emit_byte (mb, CEE_SUB);
9235                 mono_mb_emit_stloc (mb, realidx);
9236                 /* if (realidx >= bounds [i].length) goto exeception; */
9237                 mono_mb_emit_ldloc (mb, realidx);
9238                 mono_mb_emit_ldloc (mb, bounds);
9239                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + G_STRUCT_OFFSET (MonoArrayBounds, length));
9240                 mono_mb_emit_byte (mb, CEE_ADD);
9241                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9242                 branch_positions [i] = mono_mb_emit_branch (mb, CEE_BGE_UN);
9243                 /* ind = ind * bounds [i].length + realidx */
9244                 mono_mb_emit_ldloc (mb, ind);
9245                 mono_mb_emit_ldloc (mb, bounds);
9246                 mono_mb_emit_icon (mb, (i * sizeof (MonoArrayBounds)) + G_STRUCT_OFFSET (MonoArrayBounds, length));
9247                 mono_mb_emit_byte (mb, CEE_ADD);
9248                 mono_mb_emit_byte (mb, CEE_LDIND_I4);
9249                 mono_mb_emit_byte (mb, CEE_MUL);
9250                 mono_mb_emit_ldloc (mb, realidx);
9251                 mono_mb_emit_byte (mb, CEE_ADD);
9252                 mono_mb_emit_stloc (mb, ind);
9253         }
9254
9255         /* return array->vector + ind * element_size */
9256         mono_mb_emit_ldarg (mb, 0);
9257         mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoArray, vector));
9258         mono_mb_emit_ldloc (mb, ind);
9259         mono_mb_emit_icon (mb, elem_size);
9260         mono_mb_emit_byte (mb, CEE_MUL);
9261         mono_mb_emit_byte (mb, CEE_ADD);
9262         mono_mb_emit_byte (mb, CEE_RET);
9263
9264         /* patch the branches to get here and throw */
9265         for (i = 1; i < rank; ++i) {
9266                 mono_mb_patch_branch (mb, branch_positions [i]);
9267         }
9268         mono_mb_patch_branch (mb, branch_pos);
9269         /* throw exception */
9270         mono_mb_emit_exception (mb, "IndexOutOfRangeException", NULL);
9271
9272         g_free (branch_positions);
9273         mono_loader_lock ();
9274         ret = mono_mb_create_method (mb, sig, 4);
9275         mono_loader_unlock ();
9276         mono_mb_free (mb);
9277
9278         /* cache the result */
9279         cached = 0;
9280         mono_marshal_lock ();
9281         for (i = 0; i < elem_addr_cache_next; ++i) {
9282                 if (elem_addr_cache [i].rank == rank && elem_addr_cache [i].elem_size == elem_size) {
9283                         /* FIXME: free ret */
9284                         ret = elem_addr_cache [i].method;
9285                         cached = TRUE;
9286                         break;
9287                 }
9288         }
9289         if (!cached) {
9290                 if (elem_addr_cache_next >= elem_addr_cache_size) {
9291                         int new_size = elem_addr_cache_size + 4;
9292                         ArrayElemAddr *new_array = g_new0 (ArrayElemAddr, new_size);
9293                         memcpy (new_array, elem_addr_cache, elem_addr_cache_size * sizeof (ArrayElemAddr));
9294                         g_free (elem_addr_cache);
9295                         elem_addr_cache = new_array;
9296                         elem_addr_cache_size = new_size;
9297                 }
9298                 elem_addr_cache [elem_addr_cache_next].rank = rank;
9299                 elem_addr_cache [elem_addr_cache_next].elem_size = elem_size;
9300                 elem_addr_cache [elem_addr_cache_next].method = ret;
9301         }
9302         mono_marshal_unlock ();
9303         return ret;
9304 }
9305
9306 MonoMethod*
9307 mono_marshal_get_write_barrier (void)
9308 {
9309         static MonoMethod* ret = NULL;
9310         MonoMethodSignature *sig;
9311         MonoMethodBuilder *mb;
9312         int max_stack = 2;
9313
9314         if (ret)
9315                 return ret;
9316         
9317         mb = mono_mb_new (mono_defaults.object_class, "writebarrier", MONO_WRAPPER_WRITE_BARRIER);
9318
9319         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
9320
9321         /* void writebarrier (MonoObject** addr, MonoObject* obj) */
9322         sig->ret = &mono_defaults.void_class->byval_arg;
9323         sig->params [0] = &mono_defaults.object_class->this_arg;
9324         sig->params [1] = &mono_defaults.object_class->byval_arg;
9325
9326         /* just the store right now: add an hook for the GC to use, maybe something
9327          * that can be used for stelemref as well
9328          * We need a write barrier variant to be used with struct copies as well, though
9329          * there are also other approaches possible, like writing a wrapper specific to
9330          * the struct or to the reference pattern in the struct...
9331          * Depending on the GC, we may want variants that take the object we store to
9332          * when it is available.
9333          */
9334         mono_mb_emit_ldarg (mb, 0);
9335         mono_mb_emit_ldarg (mb, 1);
9336         mono_mb_emit_icall (mb, mono_gc_wbarrier_generic_store);
9337         /*mono_mb_emit_byte (mb, CEE_STIND_REF);*/
9338
9339         mono_mb_emit_byte (mb, CEE_RET);
9340
9341         ret = mono_mb_create_method (mb, sig, max_stack);
9342         mono_mb_free (mb);
9343         return ret;
9344 }
9345
9346 void*
9347 mono_marshal_alloc (gulong size)
9348 {
9349         gpointer res;
9350
9351 #ifdef PLATFORM_WIN32
9352         res = CoTaskMemAlloc (size);
9353 #else
9354         res = g_try_malloc ((gulong)size);
9355         if (!res)
9356                 mono_gc_out_of_memory ((gulong)size);
9357 #endif
9358         return res;
9359 }
9360
9361 void
9362 mono_marshal_free (gpointer ptr)
9363 {
9364 #ifdef PLATFORM_WIN32
9365         CoTaskMemFree (ptr);
9366 #else
9367         g_free (ptr);
9368 #endif
9369 }
9370
9371 void
9372 mono_marshal_free_array (gpointer *ptr, int size) 
9373 {
9374         int i;
9375
9376         if (!ptr)
9377                 return;
9378
9379         for (i = 0; i < size; i++)
9380                 if (ptr [i])
9381                         g_free (ptr [i]);
9382 }
9383
9384 void *
9385 mono_marshal_realloc (gpointer ptr, gpointer size) 
9386 {
9387         MONO_ARCH_SAVE_REGS;
9388
9389         return g_try_realloc (ptr, (gulong)size);
9390 }
9391
9392 void *
9393 mono_marshal_string_to_utf16 (MonoString *s)
9394 {
9395         return s ? mono_string_chars (s) : NULL;
9396 }
9397
9398 /**
9399  * mono_marshal_set_last_error:
9400  *
9401  * This function is invoked to set the last error value from a P/Invoke call
9402  * which has SetLastError set.
9403  */
9404 void
9405 mono_marshal_set_last_error (void)
9406 {
9407 #ifdef WIN32
9408         TlsSetValue (last_error_tls_id, GINT_TO_POINTER (GetLastError ()));
9409 #else
9410         TlsSetValue (last_error_tls_id, GINT_TO_POINTER (errno));
9411 #endif
9412 }
9413
9414 static void
9415 mono_marshal_set_last_error_windows (int error)
9416 {
9417 #ifdef WIN32
9418         TlsSetValue (last_error_tls_id, GINT_TO_POINTER (error));
9419 #endif
9420 }
9421
9422 void
9423 ves_icall_System_Runtime_InteropServices_Marshal_copy_to_unmanaged (MonoArray *src, gint32 start_index,
9424                                                                     gpointer dest, gint32 length)
9425 {
9426         int element_size;
9427         void *source_addr;
9428
9429         MONO_ARCH_SAVE_REGS;
9430
9431         MONO_CHECK_ARG_NULL (src);
9432         MONO_CHECK_ARG_NULL (dest);
9433
9434         if (src->obj.vtable->klass->rank != 1)
9435                 mono_raise_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
9436         if (start_index < 0)
9437                 mono_raise_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
9438         if (length < 0)
9439                 mono_raise_exception (mono_get_exception_argument ("length", "Must be >= 0"));
9440         if (start_index + length > mono_array_length (src))
9441                 mono_raise_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
9442
9443         element_size = mono_array_element_size (src->obj.vtable->klass);
9444
9445         /* no references should be involved */
9446         source_addr = mono_array_addr_with_size (src, element_size, start_index);
9447
9448         memcpy (dest, source_addr, length * element_size);
9449 }
9450
9451 void
9452 ves_icall_System_Runtime_InteropServices_Marshal_copy_from_unmanaged (gpointer src, gint32 start_index,
9453                                                                       MonoArray *dest, gint32 length)
9454 {
9455         int element_size;
9456         void *dest_addr;
9457
9458         MONO_ARCH_SAVE_REGS;
9459
9460         MONO_CHECK_ARG_NULL (src);
9461         MONO_CHECK_ARG_NULL (dest);
9462
9463         if (dest->obj.vtable->klass->rank != 1)
9464                 mono_raise_exception (mono_get_exception_argument ("array", "array is multi-dimensional"));
9465         if (start_index < 0)
9466                 mono_raise_exception (mono_get_exception_argument ("startIndex", "Must be >= 0"));
9467         if (length < 0)
9468                 mono_raise_exception (mono_get_exception_argument ("length", "Must be >= 0"));
9469         if (start_index + length > mono_array_length (dest))
9470                 mono_raise_exception (mono_get_exception_argument ("length", "start_index + length > array length"));
9471
9472         element_size = mono_array_element_size (dest->obj.vtable->klass);
9473           
9474         /* no references should be involved */
9475         dest_addr = mono_array_addr_with_size (dest, element_size, start_index);
9476
9477         memcpy (dest_addr, src, length * element_size);
9478 }
9479
9480 #if NO_UNALIGNED_ACCESS
9481 #define RETURN_UNALIGNED(type, addr) \
9482         { \
9483                 type val; \
9484                 memcpy(&val, p + offset, sizeof(val)); \
9485                 return val; \
9486         }
9487 #define WRITE_UNALIGNED(type, addr, val) \
9488         memcpy(addr, &val, sizeof(type))
9489 #else
9490 #define RETURN_UNALIGNED(type, addr) \
9491         return *(type*)(p + offset);
9492 #define WRITE_UNALIGNED(type, addr, val) \
9493         (*(type *)(addr) = (val))
9494 #endif
9495
9496 gpointer
9497 ves_icall_System_Runtime_InteropServices_Marshal_ReadIntPtr (gpointer ptr, gint32 offset)
9498 {
9499         char *p = ptr;
9500
9501         MONO_ARCH_SAVE_REGS;
9502
9503         RETURN_UNALIGNED(gpointer, p + offset);
9504 }
9505
9506 unsigned char
9507 ves_icall_System_Runtime_InteropServices_Marshal_ReadByte (gpointer ptr, gint32 offset)
9508 {
9509         char *p = ptr;
9510
9511         MONO_ARCH_SAVE_REGS;
9512
9513         return *(unsigned char*)(p + offset);
9514 }
9515
9516 gint16
9517 ves_icall_System_Runtime_InteropServices_Marshal_ReadInt16 (gpointer ptr, gint32 offset)
9518 {
9519         char *p = ptr;
9520
9521         MONO_ARCH_SAVE_REGS;
9522
9523         RETURN_UNALIGNED(gint16, p + offset);
9524 }
9525
9526 gint32
9527 ves_icall_System_Runtime_InteropServices_Marshal_ReadInt32 (gpointer ptr, gint32 offset)
9528 {
9529         char *p = ptr;
9530
9531         MONO_ARCH_SAVE_REGS;
9532
9533         RETURN_UNALIGNED(gint32, p + offset);
9534 }
9535
9536 gint64
9537 ves_icall_System_Runtime_InteropServices_Marshal_ReadInt64 (gpointer ptr, gint32 offset)
9538 {
9539         char *p = ptr;
9540
9541         MONO_ARCH_SAVE_REGS;
9542
9543         RETURN_UNALIGNED(gint64, p + offset);
9544 }
9545
9546 void
9547 ves_icall_System_Runtime_InteropServices_Marshal_WriteByte (gpointer ptr, gint32 offset, unsigned char val)
9548 {
9549         char *p = ptr;
9550
9551         MONO_ARCH_SAVE_REGS;
9552
9553         *(unsigned char*)(p + offset) = val;
9554 }
9555
9556 void
9557 ves_icall_System_Runtime_InteropServices_Marshal_WriteIntPtr (gpointer ptr, gint32 offset, gpointer val)
9558 {
9559         char *p = ptr;
9560
9561         MONO_ARCH_SAVE_REGS;
9562
9563         WRITE_UNALIGNED(gpointer, p + offset, val);
9564 }
9565
9566 void
9567 ves_icall_System_Runtime_InteropServices_Marshal_WriteInt16 (gpointer ptr, gint32 offset, gint16 val)
9568 {
9569         char *p = ptr;
9570
9571         MONO_ARCH_SAVE_REGS;
9572
9573         WRITE_UNALIGNED(gint16, p + offset, val);
9574 }
9575
9576 void
9577 ves_icall_System_Runtime_InteropServices_Marshal_WriteInt32 (gpointer ptr, gint32 offset, gint32 val)
9578 {
9579         char *p = ptr;
9580
9581         MONO_ARCH_SAVE_REGS;
9582
9583         WRITE_UNALIGNED(gint32, p + offset, val);
9584 }
9585
9586 void
9587 ves_icall_System_Runtime_InteropServices_Marshal_WriteInt64 (gpointer ptr, gint32 offset, gint64 val)
9588 {
9589         char *p = ptr;
9590
9591         MONO_ARCH_SAVE_REGS;
9592
9593         WRITE_UNALIGNED(gint64, p + offset, val);
9594 }
9595
9596 MonoString *
9597 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi (char *ptr)
9598 {
9599         MONO_ARCH_SAVE_REGS;
9600
9601         if (ptr == NULL)
9602                 return NULL;
9603         else
9604                 return mono_string_new (mono_domain_get (), ptr);
9605 }
9606
9607 MonoString *
9608 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringAnsi_len (char *ptr, gint32 len)
9609 {
9610         MONO_ARCH_SAVE_REGS;
9611
9612         if (ptr == NULL) {
9613                 mono_raise_exception (mono_get_exception_argument_null ("ptr"));
9614                 g_assert_not_reached ();
9615                 return NULL;
9616         } else {
9617                 return mono_string_new_len (mono_domain_get (), ptr, len);
9618         }
9619 }
9620
9621 MonoString *
9622 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni (guint16 *ptr)
9623 {
9624         MonoDomain *domain = mono_domain_get (); 
9625         int len = 0;
9626         guint16 *t = ptr;
9627
9628         MONO_ARCH_SAVE_REGS;
9629
9630         if (ptr == NULL)
9631                 return NULL;
9632
9633         while (*t++)
9634                 len++;
9635
9636         return mono_string_new_utf16 (domain, ptr, len);
9637 }
9638
9639 MonoString *
9640 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringUni_len (guint16 *ptr, gint32 len)
9641 {
9642         MonoDomain *domain = mono_domain_get (); 
9643
9644         MONO_ARCH_SAVE_REGS;
9645
9646         if (ptr == NULL) {
9647                 mono_raise_exception (mono_get_exception_argument_null ("ptr"));
9648                 g_assert_not_reached ();
9649                 return NULL;
9650         } else {
9651                 return mono_string_new_utf16 (domain, ptr, len);
9652         }
9653 }
9654
9655 MonoString *
9656 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStringBSTR (gpointer ptr)
9657 {
9658         MONO_ARCH_SAVE_REGS;
9659
9660         return mono_string_from_bstr(ptr);
9661 }
9662
9663 gpointer
9664 ves_icall_System_Runtime_InteropServices_Marshal_StringToBSTR (MonoString* ptr)
9665 {
9666         MONO_ARCH_SAVE_REGS;
9667
9668         return mono_string_to_bstr(ptr);
9669 }
9670
9671 // STDCALL on windows, CDECL everywhere else to work with XPCOM and MainWin COM
9672 #ifdef  PLATFORM_WIN32
9673 #ifdef _MSC_VER
9674 #define STDCALL __stdcall
9675 #else
9676 #define STDCALL __attribute__((stdcall))
9677 #endif
9678 #else
9679 #define STDCALL
9680 #endif
9681
9682 typedef struct
9683 {
9684         int (STDCALL *QueryInterface)(gpointer pUnk, gpointer riid, gpointer* ppv);
9685         int (STDCALL *AddRef)(gpointer pUnk);
9686         int (STDCALL *Release)(gpointer pUnk);
9687 } MonoIUnknown;
9688
9689 void
9690 ves_icall_System_Runtime_InteropServices_Marshal_FreeBSTR (gpointer ptr)
9691 {
9692         MONO_ARCH_SAVE_REGS;
9693
9694         mono_free_bstr (ptr);
9695 }
9696
9697 int
9698 ves_icall_System_Runtime_InteropServices_Marshal_AddRef (gpointer pUnk)
9699 {
9700         MONO_ARCH_SAVE_REGS;
9701
9702         return (*(MonoIUnknown**)pUnk)->AddRef(pUnk);
9703 }
9704
9705 int
9706 ves_icall_System_Runtime_InteropServices_Marshal_QueryInterface (gpointer pUnk, gpointer riid, gpointer* ppv)
9707 {
9708         MONO_ARCH_SAVE_REGS;
9709
9710         return (*(MonoIUnknown**)pUnk)->QueryInterface(pUnk, riid, ppv);
9711 }
9712
9713 int
9714 ves_icall_System_Runtime_InteropServices_Marshal_Release (gpointer pUnk)
9715 {
9716         MONO_ARCH_SAVE_REGS;
9717
9718         return (*(MonoIUnknown**)pUnk)->Release(pUnk);
9719 }
9720
9721 guint32
9722 ves_icall_System_Runtime_InteropServices_Marshal_GetComSlotForMethodInfoInternal (MonoReflectionMethod *m)
9723 {
9724         MONO_ARCH_SAVE_REGS;
9725
9726         return cominterop_get_com_slot_for_method (m->method);
9727 }
9728
9729 guint32 
9730 ves_icall_System_Runtime_InteropServices_Marshal_GetLastWin32Error (void)
9731 {
9732         MONO_ARCH_SAVE_REGS;
9733
9734         return (GPOINTER_TO_INT (TlsGetValue (last_error_tls_id)));
9735 }
9736
9737 guint32 
9738 ves_icall_System_Runtime_InteropServices_Marshal_SizeOf (MonoReflectionType *rtype)
9739 {
9740         MonoClass *klass;
9741         MonoType *type;
9742         guint32 layout;
9743
9744         MONO_ARCH_SAVE_REGS;
9745
9746         MONO_CHECK_ARG_NULL (rtype);
9747
9748         type = rtype->type;
9749         klass = mono_class_from_mono_type (type);
9750         layout = (klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK);
9751
9752         if (layout == TYPE_ATTRIBUTE_AUTO_LAYOUT) {
9753                 gchar *msg;
9754                 MonoException *exc;
9755
9756                 msg = g_strdup_printf ("Type %s cannot be marshaled as an unmanaged structure.", klass->name);
9757                 exc = mono_get_exception_argument ("t", msg);
9758                 g_free (msg);
9759                 mono_raise_exception (exc);
9760         }
9761
9762
9763         return mono_class_native_size (klass, NULL);
9764 }
9765
9766 void
9767 ves_icall_System_Runtime_InteropServices_Marshal_StructureToPtr (MonoObject *obj, gpointer dst, MonoBoolean delete_old)
9768 {
9769         MonoMethod *method;
9770         gpointer pa [3];
9771
9772         MONO_ARCH_SAVE_REGS;
9773
9774         MONO_CHECK_ARG_NULL (obj);
9775         MONO_CHECK_ARG_NULL (dst);
9776
9777         method = mono_marshal_get_struct_to_ptr (obj->vtable->klass);
9778
9779         pa [0] = obj;
9780         pa [1] = &dst;
9781         pa [2] = &delete_old;
9782
9783         mono_runtime_invoke (method, NULL, pa, NULL);
9784 }
9785
9786 static void
9787 ptr_to_structure (gpointer src, MonoObject *dst)
9788 {
9789         MonoMethod *method;
9790         gpointer pa [2];
9791
9792         method = mono_marshal_get_ptr_to_struct (dst->vtable->klass);
9793
9794         pa [0] = &src;
9795         pa [1] = dst;
9796
9797         mono_runtime_invoke (method, NULL, pa, NULL);
9798 }
9799
9800 void
9801 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure (gpointer src, MonoObject *dst)
9802 {
9803         MonoType *t;
9804
9805         MONO_ARCH_SAVE_REGS;
9806
9807         MONO_CHECK_ARG_NULL (src);
9808         MONO_CHECK_ARG_NULL (dst);
9809         
9810         t = mono_type_get_underlying_type (mono_class_get_type (dst->vtable->klass));
9811
9812         if (t->type == MONO_TYPE_VALUETYPE) {
9813                 MonoException *exc;
9814                 gchar *tmp;
9815
9816                 tmp = g_strdup_printf ("Destination is a boxed value type.");
9817                 exc = mono_get_exception_argument ("dst", tmp);
9818                 g_free (tmp);  
9819
9820                 mono_raise_exception (exc);
9821                 return;
9822         }
9823
9824         ptr_to_structure (src, dst);
9825 }
9826
9827 MonoObject *
9828 ves_icall_System_Runtime_InteropServices_Marshal_PtrToStructure_type (gpointer src, MonoReflectionType *type)
9829 {
9830         MonoDomain *domain = mono_domain_get (); 
9831         MonoObject *res;
9832
9833         MONO_ARCH_SAVE_REGS;
9834
9835         MONO_CHECK_ARG_NULL (src);
9836         MONO_CHECK_ARG_NULL (type);
9837
9838         res = mono_object_new (domain, mono_class_from_mono_type (type->type));
9839
9840         ptr_to_structure (src, res);
9841
9842         return res;
9843 }
9844
9845 int
9846 ves_icall_System_Runtime_InteropServices_Marshal_OffsetOf (MonoReflectionType *type, MonoString *field_name)
9847 {
9848         MonoMarshalType *info;
9849         MonoClass *klass;
9850         char *fname;
9851         int match_index = -1;
9852         
9853         MONO_ARCH_SAVE_REGS;
9854
9855         MONO_CHECK_ARG_NULL (type);
9856         MONO_CHECK_ARG_NULL (field_name);
9857
9858         fname = mono_string_to_utf8 (field_name);
9859         klass = mono_class_from_mono_type (type->type);
9860
9861         while (klass && match_index == -1) {
9862                 MonoClassField* field;
9863                 int i = 0;
9864                 gpointer iter = NULL;
9865                 while ((field = mono_class_get_fields (klass, &iter))) {
9866                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
9867                                 continue;
9868                         if (!strcmp (fname, field->name)) {
9869                                 match_index = i;
9870                                 break;
9871                         }
9872                         i ++;
9873                 }
9874
9875                 if (match_index == -1)
9876                         klass = klass->parent;
9877         }
9878
9879         g_free (fname);
9880
9881         if(match_index == -1) {
9882                 MonoException* exc;
9883                 gchar *tmp;
9884
9885                 /* Get back original class instance */
9886                 klass = mono_class_from_mono_type (type->type);
9887
9888                 tmp = g_strdup_printf ("Field passed in is not a marshaled member of the type %s", klass->name);
9889                 exc = mono_get_exception_argument ("fieldName", tmp);
9890                 g_free (tmp);
9891  
9892                 mono_raise_exception ((MonoException*)exc);
9893         }
9894
9895         info = mono_marshal_load_type_info (klass);     
9896         return info->fields [match_index].offset;
9897 }
9898
9899 gpointer
9900 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalAnsi (MonoString *string)
9901 {
9902         MONO_ARCH_SAVE_REGS;
9903
9904         return mono_string_to_utf8 (string);
9905 }
9906
9907 gpointer
9908 ves_icall_System_Runtime_InteropServices_Marshal_StringToHGlobalUni (MonoString *string)
9909 {
9910         MONO_ARCH_SAVE_REGS;
9911
9912         if (string == NULL)
9913                 return NULL;
9914         else {
9915                 gunichar2 *res = g_malloc ((mono_string_length (string) + 1) * 2);
9916                 memcpy (res, mono_string_chars (string), mono_string_length (string) * 2);
9917                 res [mono_string_length (string)] = 0;
9918                 return res;
9919         }
9920 }
9921
9922 static void
9923 mono_struct_delete_old (MonoClass *klass, char *ptr)
9924 {
9925         MonoMarshalType *info;
9926         int i;
9927
9928         info = mono_marshal_load_type_info (klass);
9929
9930         for (i = 0; i < info->num_fields; i++) {
9931                 MonoMarshalNative ntype;
9932                 MonoMarshalConv conv;
9933                 MonoType *ftype = info->fields [i].field->type;
9934                 char *cpos;
9935
9936                 if (ftype->attrs & FIELD_ATTRIBUTE_STATIC)
9937                         continue;
9938
9939                 ntype = mono_type_to_unmanaged (ftype, info->fields [i].mspec, TRUE, 
9940                                                 klass->unicode, &conv);
9941                         
9942                 cpos = ptr + info->fields [i].offset;
9943
9944                 switch (conv) {
9945                 case MONO_MARSHAL_CONV_NONE:
9946                         if (MONO_TYPE_ISSTRUCT (ftype)) {
9947                                 mono_struct_delete_old (ftype->data.klass, cpos);
9948                                 continue;
9949                         }
9950                         break;
9951                 case MONO_MARSHAL_CONV_STR_LPWSTR:
9952                         /* We assume this field points inside a MonoString */
9953                         break;
9954                 case MONO_MARSHAL_CONV_STR_LPSTR:
9955                 case MONO_MARSHAL_CONV_STR_LPTSTR:
9956                 case MONO_MARSHAL_CONV_STR_BSTR:
9957                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
9958                 case MONO_MARSHAL_CONV_STR_TBSTR:
9959                         mono_marshal_free (*(gpointer *)cpos);
9960                         break;
9961
9962                 default:
9963                         continue;
9964                 }
9965         }
9966 }
9967
9968 void
9969 ves_icall_System_Runtime_InteropServices_Marshal_DestroyStructure (gpointer src, MonoReflectionType *type)
9970 {
9971         MonoClass *klass;
9972
9973         MONO_ARCH_SAVE_REGS;
9974
9975         MONO_CHECK_ARG_NULL (src);
9976         MONO_CHECK_ARG_NULL (type);
9977
9978         klass = mono_class_from_mono_type (type->type);
9979
9980         mono_struct_delete_old (klass, (char *)src);
9981 }
9982
9983 void*
9984 ves_icall_System_Runtime_InteropServices_Marshal_AllocHGlobal (int size)
9985 {
9986         gpointer res;
9987
9988         MONO_ARCH_SAVE_REGS;
9989
9990         if ((gulong)size == 0)
9991                 /* This returns a valid pointer for size 0 on MS.NET */
9992                 size = 4;
9993
9994 #ifdef PLATFORM_WIN32
9995         res = GlobalAlloc (GMEM_FIXED, (gulong)size);
9996 #else
9997         res = g_try_malloc ((gulong)size);
9998 #endif
9999         if (!res)
10000                 mono_gc_out_of_memory ((gulong)size);
10001
10002         return res;
10003 }
10004
10005 void
10006 ves_icall_System_Runtime_InteropServices_Marshal_FreeHGlobal (void *ptr)
10007 {
10008         MONO_ARCH_SAVE_REGS;
10009
10010 #ifdef PLATFORM_WIN32
10011         GlobalFree (ptr);
10012 #else
10013         g_free (ptr);
10014 #endif
10015 }
10016
10017 void*
10018 ves_icall_System_Runtime_InteropServices_Marshal_AllocCoTaskMem (int size)
10019 {
10020         MONO_ARCH_SAVE_REGS;
10021
10022 #ifdef PLATFORM_WIN32
10023         return CoTaskMemAlloc (size);
10024 #else
10025         return g_try_malloc ((gulong)size);
10026 #endif
10027 }
10028
10029 void
10030 ves_icall_System_Runtime_InteropServices_Marshal_FreeCoTaskMem (void *ptr)
10031 {
10032         MONO_ARCH_SAVE_REGS;
10033
10034 #ifdef PLATFORM_WIN32
10035         CoTaskMemFree (ptr);
10036 #else
10037         g_free (ptr);
10038 #endif
10039 }
10040
10041 gpointer
10042 ves_icall_System_Runtime_InteropServices_Marshal_ReAllocCoTaskMem (gpointer ptr, int size)
10043 {
10044         MONO_ARCH_SAVE_REGS;
10045
10046 #ifdef PLATFORM_WIN32
10047         return CoTaskMemRealloc (ptr, size);
10048 #else
10049         return g_try_realloc (ptr, (gulong)size);
10050 #endif
10051 }
10052
10053 void*
10054 ves_icall_System_Runtime_InteropServices_Marshal_UnsafeAddrOfPinnedArrayElement (MonoArray *arrayobj, int index)
10055 {
10056         return mono_array_addr_with_size (arrayobj, mono_array_element_size (arrayobj->obj.vtable->klass), index);
10057 }
10058
10059 MonoDelegate*
10060 ves_icall_System_Runtime_InteropServices_Marshal_GetDelegateForFunctionPointerInternal (void *ftn, MonoReflectionType *type)
10061 {
10062         return mono_ftnptr_to_delegate (mono_type_get_class (type->type), ftn);
10063 }
10064
10065 /* Only used for COM RCWs */
10066 MonoObject *
10067 ves_icall_System_ComObject_CreateRCW (MonoReflectionType *type)
10068 {
10069         MonoClass *klass;
10070         MonoDomain *domain;
10071         MonoObject *obj;
10072         
10073         MONO_ARCH_SAVE_REGS;
10074
10075         domain = mono_object_domain (type);
10076         klass = mono_class_from_mono_type (type->type);
10077
10078         /* call mono_object_new_alloc_specific instead of mono_object_new
10079          * because we want to actually create object. mono_object_new checks
10080          * to see if type is import and creates transparent proxy. this method
10081          * is called by the corresponding real proxy to create the real RCW.
10082          * Constructor does not need to be called. Will be called later.
10083         */
10084         obj = mono_object_new_alloc_specific (mono_class_vtable (domain, klass));
10085         return obj;
10086 }
10087
10088 static gboolean    
10089 cominterop_finalizer (gpointer key, gpointer value, gpointer user_data)
10090 {
10091         ves_icall_System_Runtime_InteropServices_Marshal_Release (value);
10092         return TRUE;
10093 }
10094
10095 void
10096 ves_icall_System_ComObject_Finalizer(MonoComObject* obj)
10097 {
10098         g_assert(obj);
10099         if (obj->itf_hash)
10100                 g_hash_table_foreach_remove (obj->itf_hash, cominterop_finalizer, NULL);
10101         obj->itf_hash = NULL;
10102 }
10103
10104 #define MONO_IUNKNOWN_INTERFACE_SLOT 0
10105
10106 gpointer
10107 ves_icall_System_ComObject_FindInterface (MonoComObject* obj, MonoReflectionType* type)
10108 {
10109         MonoClass* klass;
10110         g_assert(obj);
10111         g_assert(obj->itf_hash);
10112
10113         klass = mono_class_from_mono_type (type->type);
10114
10115         return g_hash_table_lookup (obj->itf_hash, GUINT_TO_POINTER ((guint)klass->interface_id));
10116 }
10117
10118 void
10119 ves_icall_System_ComObject_CacheInterface (MonoComObject* obj, MonoReflectionType* type, gpointer pItf)
10120 {
10121         MonoClass* klass;
10122         g_assert(obj);
10123         g_assert(obj->itf_hash);
10124
10125         klass = mono_class_from_mono_type (type->type);
10126
10127         g_hash_table_insert (obj->itf_hash, GUINT_TO_POINTER ((guint)klass->interface_id), pItf);
10128 }
10129
10130 gpointer
10131 ves_icall_System_ComObject_GetIUnknown (MonoComObject* obj)
10132 {
10133         g_assert(obj);
10134         if (!obj->itf_hash)
10135                 return NULL;
10136         return g_hash_table_lookup (obj->itf_hash, MONO_IUNKNOWN_INTERFACE_SLOT);
10137 }
10138
10139 void
10140 ves_icall_System_ComObject_SetIUnknown (MonoComObject* obj, gpointer pUnk)
10141 {
10142         g_assert(obj);
10143         g_assert(!obj->itf_hash);
10144         obj->itf_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
10145         g_hash_table_insert (obj->itf_hash, MONO_IUNKNOWN_INTERFACE_SLOT, pUnk);
10146 }
10147
10148 /**
10149  * mono_marshal_is_loading_type_info:
10150  *
10151  *  Return whenever mono_marshal_load_type_info () is being executed for KLASS by this
10152  * thread.
10153  */
10154 static gboolean
10155 mono_marshal_is_loading_type_info (MonoClass *klass)
10156 {
10157         GSList *loads_list = TlsGetValue (load_type_info_tls_id);
10158
10159         return g_slist_find (loads_list, klass) != NULL;
10160 }
10161
10162 /**
10163  * mono_marshal_load_type_info:
10164  *
10165  *  Initialize klass->marshal_info using information from metadata. This function can
10166  * recursively call itself, and the caller is responsible to avoid that by calling 
10167  * mono_marshal_is_loading_type_info () beforehand.
10168  *
10169  * LOCKING: Acquires the loader lock.
10170  */
10171 MonoMarshalType *
10172 mono_marshal_load_type_info (MonoClass* klass)
10173 {
10174         int j, count = 0;
10175         guint32 native_size = 0, min_align = 1;
10176         MonoMarshalType *info;
10177         MonoClassField* field;
10178         gpointer iter;
10179         guint32 layout;
10180         GSList *loads_list;
10181
10182         g_assert (klass != NULL);
10183
10184         if (klass->marshal_info)
10185                 return klass->marshal_info;
10186
10187         if (!klass->inited)
10188                 mono_class_init (klass);
10189
10190         mono_loader_lock ();
10191
10192         if (klass->marshal_info) {
10193                 mono_loader_unlock ();
10194                 return klass->marshal_info;
10195         }
10196
10197         /*
10198          * This function can recursively call itself, so we keep the list of classes which are
10199          * under initialization in a TLS list.
10200          */
10201         g_assert (!mono_marshal_is_loading_type_info (klass));
10202         loads_list = TlsGetValue (load_type_info_tls_id);
10203         loads_list = g_slist_prepend (loads_list, klass);
10204         TlsSetValue (load_type_info_tls_id, loads_list);
10205         
10206         iter = NULL;
10207         while ((field = mono_class_get_fields (klass, &iter))) {
10208                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10209                         continue;
10210                 if (mono_field_is_deleted (field))
10211                         continue;
10212                 count++;
10213         }
10214
10215         layout = klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
10216
10217         /* The mempool is protected by the loader lock */
10218         info = mono_mempool_alloc0 (klass->image->mempool, sizeof (MonoMarshalType) + sizeof (MonoMarshalField) * count);
10219         info->num_fields = count;
10220         
10221         /* Try to find a size for this type in metadata */
10222         mono_metadata_packing_from_typedef (klass->image, klass->type_token, NULL, &native_size);
10223
10224         if (klass->parent) {
10225                 int parent_size = mono_class_native_size (klass->parent, NULL);
10226
10227                 /* Add parent size to real size */
10228                 native_size += parent_size;
10229                 info->native_size = parent_size;
10230         }
10231         
10232         iter = NULL;
10233         j = 0;
10234         while ((field = mono_class_get_fields (klass, &iter))) {
10235                 int size;
10236                 guint32 align;
10237                 
10238                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
10239                         continue;
10240
10241                 if (mono_field_is_deleted (field))
10242                         continue;
10243                 if (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
10244                         mono_metadata_field_info (klass->image, mono_metadata_token_index (mono_class_get_field_token (field)) - 1, 
10245                                                   NULL, NULL, &info->fields [j].mspec);
10246
10247                 info->fields [j].field = field;
10248
10249                 if ((mono_class_num_fields (klass) == 1) && (klass->instance_size == sizeof (MonoObject)) &&
10250                         (strcmp (field->name, "$PRIVATE$") == 0)) {
10251                         /* This field is a hack inserted by MCS to empty structures */
10252                         continue;
10253                 }
10254
10255                 switch (layout) {
10256                 case TYPE_ATTRIBUTE_AUTO_LAYOUT:
10257                 case TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT:
10258                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
10259                                                        &align, TRUE, klass->unicode);
10260                         align = klass->packing_size ? MIN (klass->packing_size, align): align;
10261                         min_align = MAX (align, min_align);
10262                         info->fields [j].offset = info->native_size;
10263                         info->fields [j].offset += align - 1;
10264                         info->fields [j].offset &= ~(align - 1);
10265                         info->native_size = info->fields [j].offset + size;
10266                         break;
10267                 case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
10268                         size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
10269                                                        &align, TRUE, klass->unicode);
10270                         align = klass->packing_size ? MIN (klass->packing_size, align): align;
10271                         min_align = MAX (align, min_align);
10272                         info->fields [j].offset = field->offset - sizeof (MonoObject);
10273                         info->native_size = MAX (info->native_size, info->fields [j].offset + size);
10274                         break;
10275                 }       
10276                 j++;
10277         }
10278
10279         if(layout != TYPE_ATTRIBUTE_AUTO_LAYOUT) {
10280                 info->native_size = MAX (native_size, info->native_size);
10281         }
10282
10283         if (info->native_size & (min_align - 1)) {
10284                 info->native_size += min_align - 1;
10285                 info->native_size &= ~(min_align - 1);
10286         }
10287
10288         /* Update the class's blittable info, if the layouts don't match */
10289         if (info->native_size != mono_class_value_size (klass, NULL))
10290                 klass->blittable = FALSE;
10291
10292         /* If this is an array type, ensure that we have element info */
10293         if (klass->element_class && !mono_marshal_is_loading_type_info (klass->element_class)) {
10294                 mono_marshal_load_type_info (klass->element_class);
10295         }
10296
10297         loads_list = TlsGetValue (load_type_info_tls_id);
10298         loads_list = g_slist_remove (loads_list, klass);
10299         TlsSetValue (load_type_info_tls_id, loads_list);
10300
10301         klass->marshal_info = info;
10302
10303         mono_loader_unlock ();
10304
10305         return klass->marshal_info;
10306 }
10307
10308 /**
10309  * mono_class_native_size:
10310  * @klass: a class 
10311  * 
10312  * Returns: the native size of an object instance (when marshaled 
10313  * to unmanaged code) 
10314  */
10315 gint32
10316 mono_class_native_size (MonoClass *klass, guint32 *align)
10317 {       
10318         if (!klass->marshal_info) {
10319                 if (mono_marshal_is_loading_type_info (klass))
10320                         return 0;
10321                 else
10322                         mono_marshal_load_type_info (klass);
10323         }
10324
10325         if (align)
10326                 *align = klass->min_align;
10327
10328         return klass->marshal_info->native_size;
10329 }
10330
10331 /*
10332  * mono_type_native_stack_size:
10333  * @t: the type to return the size it uses on the stack
10334  *
10335  * Returns: the number of bytes required to hold an instance of this
10336  * type on the native stack
10337  */
10338 int
10339 mono_type_native_stack_size (MonoType *t, guint32 *align)
10340 {
10341         guint32 tmp;
10342
10343         g_assert (t != NULL);
10344
10345         if (!align)
10346                 align = &tmp;
10347
10348         if (t->byref) {
10349                 *align = 4;
10350                 return 4;
10351         }
10352
10353         switch (t->type){
10354         case MONO_TYPE_BOOLEAN:
10355         case MONO_TYPE_CHAR:
10356         case MONO_TYPE_I1:
10357         case MONO_TYPE_U1:
10358         case MONO_TYPE_I2:
10359         case MONO_TYPE_U2:
10360         case MONO_TYPE_I4:
10361         case MONO_TYPE_U4:
10362         case MONO_TYPE_I:
10363         case MONO_TYPE_U:
10364         case MONO_TYPE_STRING:
10365         case MONO_TYPE_OBJECT:
10366         case MONO_TYPE_CLASS:
10367         case MONO_TYPE_SZARRAY:
10368         case MONO_TYPE_PTR:
10369         case MONO_TYPE_FNPTR:
10370         case MONO_TYPE_ARRAY:
10371         case MONO_TYPE_TYPEDBYREF:
10372                 *align = 4;
10373                 return 4;
10374         case MONO_TYPE_R4:
10375                 *align = 4;
10376                 return 4;
10377         case MONO_TYPE_I8:
10378         case MONO_TYPE_U8:
10379         case MONO_TYPE_R8:
10380                 *align = 4;
10381                 return 8;
10382         case MONO_TYPE_VALUETYPE: {
10383                 guint32 size;
10384
10385                 if (t->data.klass->enumtype)
10386                         return mono_type_native_stack_size (t->data.klass->enum_basetype, align);
10387                 else {
10388                         size = mono_class_native_size (t->data.klass, align);
10389                         *align = *align + 3;
10390                         *align &= ~3;
10391                         
10392                         size +=  3;
10393                         size &= ~3;
10394
10395                         return size;
10396                 }
10397         }
10398         default:
10399                 g_error ("type 0x%02x unknown", t->type);
10400         }
10401         return 0;
10402 }
10403
10404 /* __alignof__ returns the preferred alignment of values not the actual alignment used by
10405    the compiler so is wrong e.g. for Linux where doubles are aligned on a 4 byte boundary
10406    but __alignof__ returns 8 - using G_STRUCT_OFFSET works better */
10407 #define ALIGNMENT(type) G_STRUCT_OFFSET(struct { char c; type x; }, x)
10408
10409 gint32
10410 mono_marshal_type_size (MonoType *type, MonoMarshalSpec *mspec, guint32 *align,
10411                         gboolean as_field, gboolean unicode)
10412 {
10413         MonoMarshalNative native_type = mono_type_to_unmanaged (type, mspec, as_field, unicode, NULL);
10414         MonoClass *klass;
10415
10416         switch (native_type) {
10417         case MONO_NATIVE_BOOLEAN:
10418                 *align = 4;
10419                 return 4;
10420         case MONO_NATIVE_I1:
10421         case MONO_NATIVE_U1:
10422                 *align = 1;
10423                 return 1;
10424         case MONO_NATIVE_I2:
10425         case MONO_NATIVE_U2:
10426         case MONO_NATIVE_VARIANTBOOL:
10427                 *align = 2;
10428                 return 2;
10429         case MONO_NATIVE_I4:
10430         case MONO_NATIVE_U4:
10431         case MONO_NATIVE_ERROR:
10432                 *align = 4;
10433                 return 4;
10434         case MONO_NATIVE_I8:
10435         case MONO_NATIVE_U8:
10436                 *align = ALIGNMENT(guint64);
10437                 return 8;
10438         case MONO_NATIVE_R4:
10439                 *align = 4;
10440                 return 4;
10441         case MONO_NATIVE_R8:
10442                 *align = ALIGNMENT(double);
10443                 return 8;
10444         case MONO_NATIVE_INT:
10445         case MONO_NATIVE_UINT:
10446         case MONO_NATIVE_LPSTR:
10447         case MONO_NATIVE_LPWSTR:
10448         case MONO_NATIVE_LPTSTR:
10449         case MONO_NATIVE_BSTR:
10450         case MONO_NATIVE_ANSIBSTR:
10451         case MONO_NATIVE_TBSTR:
10452         case MONO_NATIVE_LPARRAY:
10453         case MONO_NATIVE_SAFEARRAY:
10454         case MONO_NATIVE_IUNKNOWN:
10455         case MONO_NATIVE_IDISPATCH:
10456         case MONO_NATIVE_INTERFACE:
10457         case MONO_NATIVE_ASANY:
10458         case MONO_NATIVE_FUNC:
10459         case MONO_NATIVE_LPSTRUCT:
10460                 *align = ALIGNMENT(gpointer);
10461                 return sizeof (gpointer);
10462         case MONO_NATIVE_STRUCT: 
10463                 klass = mono_class_from_mono_type (type);
10464                 if (klass == mono_defaults.object_class &&
10465                         (mspec && mspec->native == MONO_NATIVE_STRUCT)) {
10466                 *align = 16;
10467                 return 16;
10468                 }
10469                 return mono_class_native_size (klass, align);
10470         case MONO_NATIVE_BYVALTSTR: {
10471                 int esize = unicode ? 2: 1;
10472                 g_assert (mspec);
10473                 *align = esize;
10474                 return mspec->data.array_data.num_elem * esize;
10475         }
10476         case MONO_NATIVE_BYVALARRAY: {
10477                 // FIXME: Have to consider ArraySubType
10478                 int esize;
10479                 klass = mono_class_from_mono_type (type);
10480                 if (klass->element_class == mono_defaults.char_class) {
10481                         esize = unicode ? 2 : 1;
10482                         *align = esize;
10483                 } else {
10484                         esize = mono_class_native_size (klass->element_class, align);
10485                 }
10486                 g_assert (mspec);
10487                 return mspec->data.array_data.num_elem * esize;
10488         }
10489         case MONO_NATIVE_CUSTOM:
10490                 g_assert_not_reached ();
10491                 break;
10492         case MONO_NATIVE_CURRENCY:
10493         case MONO_NATIVE_VBBYREFSTR:
10494         default:
10495                 g_error ("native type %02x not implemented", native_type); 
10496                 break;
10497         }
10498         g_assert_not_reached ();
10499         return 0;
10500 }
10501
10502 gpointer
10503 mono_marshal_asany (MonoObject *o, MonoMarshalNative string_encoding, int param_attrs)
10504 {
10505         MonoType *t;
10506         MonoClass *klass;
10507
10508         if (o == NULL)
10509                 return NULL;
10510
10511         t = &o->vtable->klass->byval_arg;
10512         switch (t->type) {
10513         case MONO_TYPE_I4:
10514         case MONO_TYPE_U4:
10515         case MONO_TYPE_PTR:
10516         case MONO_TYPE_I1:
10517         case MONO_TYPE_U1:
10518         case MONO_TYPE_BOOLEAN:
10519         case MONO_TYPE_I2:
10520         case MONO_TYPE_U2:
10521         case MONO_TYPE_CHAR:
10522         case MONO_TYPE_I8:
10523         case MONO_TYPE_U8:
10524         case MONO_TYPE_R4:
10525         case MONO_TYPE_R8:
10526                 return mono_object_unbox (o);
10527                 break;
10528         case MONO_TYPE_STRING:
10529                 switch (string_encoding) {
10530                 case MONO_NATIVE_LPWSTR:
10531                         return mono_string_to_utf16 ((MonoString*)o);
10532                         break;
10533                 case MONO_NATIVE_LPSTR:
10534                         return mono_string_to_lpstr ((MonoString*)o);
10535                         break;
10536                 default:
10537                         g_warning ("marshaling conversion %d not implemented", string_encoding);
10538                         g_assert_not_reached ();
10539                 }
10540                 break;
10541         case MONO_TYPE_CLASS:
10542         case MONO_TYPE_VALUETYPE: {
10543                 MonoMethod *method;
10544                 gpointer pa [3];
10545                 gpointer res;
10546                 MonoBoolean delete_old = FALSE;
10547
10548                 klass = t->data.klass;
10549
10550                 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
10551                         break;
10552
10553                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
10554                         klass->blittable || klass->enumtype))
10555                         return mono_object_unbox (o);
10556
10557                 res = mono_marshal_alloc (mono_class_native_size (klass, NULL));
10558
10559                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
10560                         method = mono_marshal_get_struct_to_ptr (o->vtable->klass);
10561
10562                         pa [0] = o;
10563                         pa [1] = &res;
10564                         pa [2] = &delete_old;
10565
10566                         mono_runtime_invoke (method, NULL, pa, NULL);
10567                 }
10568
10569                 return res;
10570         }
10571         }
10572
10573         mono_raise_exception (mono_get_exception_argument ("", "No PInvoke conversion exists for value passed to Object-typed parameter."));
10574
10575         return NULL;
10576 }
10577
10578 void
10579 mono_marshal_free_asany (MonoObject *o, gpointer ptr, MonoMarshalNative string_encoding, int param_attrs)
10580 {
10581         MonoType *t;
10582         MonoClass *klass;
10583
10584         if (o == NULL)
10585                 return;
10586
10587         t = &o->vtable->klass->byval_arg;
10588         switch (t->type) {
10589         case MONO_TYPE_STRING:
10590                 switch (string_encoding) {
10591                 case MONO_NATIVE_LPWSTR:
10592                 case MONO_NATIVE_LPSTR:
10593                         mono_marshal_free (ptr);
10594                         break;
10595                 default:
10596                         g_warning ("marshaling conversion %d not implemented", string_encoding);
10597                         g_assert_not_reached ();
10598                 }
10599                 break;
10600         case MONO_TYPE_CLASS:
10601         case MONO_TYPE_VALUETYPE: {
10602                 klass = t->data.klass;
10603
10604                 if (klass->valuetype && (((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) ||
10605                                                                  klass->blittable || klass->enumtype))
10606                         break;
10607
10608                 if (param_attrs & PARAM_ATTRIBUTE_OUT) {
10609                         MonoMethod *method = mono_marshal_get_ptr_to_struct (o->vtable->klass);
10610                         gpointer pa [2];
10611
10612                         pa [0] = &ptr;
10613                         pa [1] = o;
10614
10615                         mono_runtime_invoke (method, NULL, pa, NULL);
10616                 }
10617
10618                 if (!((param_attrs & PARAM_ATTRIBUTE_OUT) && !(param_attrs & PARAM_ATTRIBUTE_IN))) {
10619                         mono_struct_delete_old (klass, ptr);
10620                 }
10621
10622                 mono_marshal_free (ptr);
10623                 break;
10624         }
10625         default:
10626                 break;
10627         }
10628 }
10629
10630 MonoMethod *
10631 mono_marshal_get_generic_array_helper (MonoClass *class, MonoClass *iface, gchar *name, MonoMethod *method)
10632 {
10633         MonoMethodSignature *sig, *csig;
10634         MonoMethodBuilder *mb;
10635         MonoMethod *res;
10636         int i;
10637
10638         mb = mono_mb_new (class, name, MONO_WRAPPER_MANAGED_TO_MANAGED);
10639         mb->method->slot = -1;
10640
10641         mb->method->flags = METHOD_ATTRIBUTE_PRIVATE | METHOD_ATTRIBUTE_VIRTUAL |
10642                 METHOD_ATTRIBUTE_NEW_SLOT | METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
10643
10644         sig = mono_method_signature (method);
10645         csig = signature_dup (method->klass->image, sig);
10646         csig->generic_param_count = 0;
10647
10648         mono_mb_emit_ldarg (mb, 0);
10649         for (i = 0; i < csig->param_count; i++)
10650                 mono_mb_emit_ldarg (mb, i + 1);
10651         mono_mb_emit_managed_call (mb, method, NULL);
10652         mono_mb_emit_byte (mb, CEE_RET);
10653
10654         res = mono_mb_create_method (mb, csig, csig->param_count + 16);
10655
10656         mono_mb_free (mb);
10657
10658         return res;
10659 }