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