Merge pull request #2626 from lewurm/jit-time-track
[mono.git] / mono / metadata / remoting.c
1 /*
2  * remoting.c: Remoting support
3  * 
4  * Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
5  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
6  * Copyright 2011-2014 Xamarin, Inc (http://www.xamarin.com)
7  *
8  */
9
10 #include "config.h"
11
12 #include "mono/metadata/remoting.h"
13 #include "mono/metadata/marshal.h"
14 #include "mono/metadata/abi-details.h"
15 #include "mono/metadata/cominterop.h"
16 #include "mono/metadata/tabledefs.h"
17 #include "mono/metadata/exception.h"
18 #include "mono/metadata/debug-helpers.h"
19 #include "mono/metadata/reflection-internals.h"
20
21 typedef enum {
22         MONO_MARSHAL_NONE,                      /* No marshalling needed */
23         MONO_MARSHAL_COPY,                      /* Can be copied by value to the new domain */
24         MONO_MARSHAL_COPY_OUT,          /* out parameter that needs to be copied back to the original instance */
25         MONO_MARSHAL_SERIALIZE          /* Value needs to be serialized into the new domain */
26 } MonoXDomainMarshalType;
27
28 #ifndef DISABLE_REMOTING
29
30 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
31         a = i,
32
33 enum {
34 #include "mono/cil/opcode.def"
35         LAST = 0xff
36 };
37 #undef OPDEF
38
39 struct _MonoRemotingMethods {
40         MonoMethod *invoke;
41         MonoMethod *invoke_with_check;
42         MonoMethod *xdomain_invoke;
43         MonoMethod *xdomain_dispatch;
44 };
45
46 typedef struct _MonoRemotingMethods MonoRemotingMethods;
47
48 static MonoObject *
49 mono_remoting_wrapper (MonoMethod *method, gpointer *params);
50
51 static gint32
52 mono_marshal_set_domain_by_id (gint32 id, MonoBoolean push);
53
54 static gboolean
55 mono_marshal_check_domain_image (gint32 domain_id, MonoImage *image);
56
57 MONO_API void
58 mono_upgrade_remote_class_wrapper (MonoReflectionType *rtype, MonoTransparentProxy *tproxy);
59
60 static MonoXDomainMarshalType
61 mono_get_xdomain_marshal_type (MonoType *t);
62
63 static void
64 mono_marshal_xdomain_copy_out_value (MonoObject *src, MonoObject *dst);
65
66 static MonoReflectionType *
67 type_from_handle (MonoType *handle);
68
69 /* Class lazy loading functions */
70 static GENERATE_GET_CLASS_WITH_CACHE (remoting_services, System.Runtime.Remoting, RemotingServices)
71 static GENERATE_GET_CLASS_WITH_CACHE (call_context, System.Runtime.Remoting.Messaging, CallContext)
72 static GENERATE_GET_CLASS_WITH_CACHE (context, System.Runtime.Remoting.Contexts, Context)
73
74 static mono_mutex_t remoting_mutex;
75 static gboolean remoting_mutex_inited;
76
77 static MonoClass *byte_array_class;
78 #ifndef DISABLE_JIT
79 static MonoMethod *method_rs_serialize, *method_rs_deserialize, *method_exc_fixexc, *method_rs_appdomain_target;
80 static MonoMethod *method_set_call_context, *method_needs_context_sink, *method_rs_serialize_exc;
81 #endif
82
83 static void
84 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
85 {
86         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
87
88         mono_register_jit_icall (func, name, sig, save);
89 }
90
91 static inline void
92 remoting_lock (void)
93 {
94         g_assert (remoting_mutex_inited);
95         mono_os_mutex_lock (&remoting_mutex);
96 }
97
98 static inline void
99 remoting_unlock (void)
100 {
101         g_assert (remoting_mutex_inited);
102         mono_os_mutex_unlock (&remoting_mutex);
103 }
104
105 /*
106  * Return the hash table pointed to by VAR, lazily creating it if neccesary.
107  */
108 static GHashTable*
109 get_cache (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func)
110 {
111         if (!(*var)) {
112                 remoting_lock ();
113                 if (!(*var)) {
114                         GHashTable *cache = 
115                                 g_hash_table_new (hash_func, equal_func);
116                         mono_memory_barrier ();
117                         *var = cache;
118                 }
119                 remoting_unlock ();
120         }
121         return *var;
122 }
123
124 static GHashTable*
125 get_cache_full (GHashTable **var, GHashFunc hash_func, GCompareFunc equal_func, GDestroyNotify key_destroy_func, GDestroyNotify value_destroy_func)
126 {
127         if (!(*var)) {
128                 remoting_lock ();
129                 if (!(*var)) {
130                         GHashTable *cache = 
131                                 g_hash_table_new_full (hash_func, equal_func, key_destroy_func, value_destroy_func);
132                         mono_memory_barrier ();
133                         *var = cache;
134                 }
135                 remoting_unlock ();
136         }
137         return *var;
138 }
139
140 void
141 mono_remoting_init (void)
142 {
143         mono_os_mutex_init (&remoting_mutex);
144         remoting_mutex_inited = TRUE;
145 }
146
147 static void
148 mono_remoting_marshal_init (void)
149 {
150         MonoClass *klass;
151
152         static gboolean module_initialized = FALSE;
153         static gboolean icalls_registered = FALSE;
154
155         if (module_initialized)
156                 return;
157
158         byte_array_class = mono_array_class_get (mono_defaults.byte_class, 1);
159
160 #ifndef DISABLE_JIT
161         klass = mono_class_get_remoting_services_class ();
162         method_rs_serialize = mono_class_get_method_from_name (klass, "SerializeCallData", -1);
163         g_assert (method_rs_serialize);
164         method_rs_deserialize = mono_class_get_method_from_name (klass, "DeserializeCallData", -1);
165         g_assert (method_rs_deserialize);
166         method_rs_serialize_exc = mono_class_get_method_from_name (klass, "SerializeExceptionData", -1);
167         g_assert (method_rs_serialize_exc);
168         
169         klass = mono_defaults.real_proxy_class;
170         method_rs_appdomain_target = mono_class_get_method_from_name (klass, "GetAppDomainTarget", -1);
171         g_assert (method_rs_appdomain_target);
172         
173         klass = mono_defaults.exception_class;
174         method_exc_fixexc = mono_class_get_method_from_name (klass, "FixRemotingException", -1);
175         g_assert (method_exc_fixexc);
176
177         klass = mono_class_get_call_context_class ();
178         method_set_call_context = mono_class_get_method_from_name (klass, "SetCurrentCallContext", -1);
179         g_assert (method_set_call_context);
180
181         klass = mono_class_get_context_class ();
182         method_needs_context_sink = mono_class_get_method_from_name (klass, "get_NeedsContextSink", -1);
183         g_assert (method_needs_context_sink);
184 #endif  
185
186         mono_loader_lock ();
187
188         if (!icalls_registered) {
189                 register_icall (type_from_handle, "type_from_handle", "object ptr", FALSE);
190                 register_icall (mono_marshal_set_domain_by_id, "mono_marshal_set_domain_by_id", "int32 int32 int32", FALSE);
191                 register_icall (mono_marshal_check_domain_image, "mono_marshal_check_domain_image", "int32 int32 ptr", FALSE);
192                 register_icall (mono_marshal_xdomain_copy_value, "mono_marshal_xdomain_copy_value", "object object", FALSE);
193                 register_icall (mono_marshal_xdomain_copy_out_value, "mono_marshal_xdomain_copy_out_value", "void object object", FALSE);
194                 register_icall (mono_remoting_wrapper, "mono_remoting_wrapper", "object ptr ptr", FALSE);
195                 register_icall (mono_upgrade_remote_class_wrapper, "mono_upgrade_remote_class_wrapper", "void object object", FALSE);
196         }
197
198         icalls_registered = TRUE;
199
200         mono_loader_unlock ();
201
202         module_initialized = TRUE;
203 }
204
205 static MonoReflectionType *
206 type_from_handle (MonoType *handle)
207 {
208         MonoError error;
209         MonoReflectionType *ret;
210         MonoDomain *domain = mono_domain_get (); 
211         MonoClass *klass = mono_class_from_mono_type (handle);
212
213         mono_class_init (klass);
214
215         ret = mono_type_get_object_checked (domain, handle, &error);
216         mono_error_raise_exception (&error); /* FIXME don't raise here */
217
218         return ret;
219 }
220
221 #ifndef DISABLE_JIT
222 static int
223 mono_mb_emit_proxy_check (MonoMethodBuilder *mb, int branch_code)
224 {
225         int pos;
226         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoObject, vtable));
227         mono_mb_emit_byte (mb, CEE_LDIND_I);
228         mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
229         mono_mb_emit_byte (mb, CEE_ADD);
230         mono_mb_emit_byte (mb, CEE_LDIND_I);
231         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
232         mono_mb_emit_byte (mb, CEE_MONO_CLASSCONST);
233         mono_mb_emit_i4 (mb, mono_mb_add_data (mb, mono_defaults.transparent_proxy_class));
234         pos = mono_mb_emit_branch (mb, branch_code);
235         return pos;
236 }
237
238 static int
239 mono_mb_emit_xdomain_check (MonoMethodBuilder *mb, int branch_code)
240 {
241         int pos;
242         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoTransparentProxy, rp));
243         mono_mb_emit_byte (mb, CEE_LDIND_REF);
244         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoRealProxy, target_domain_id));
245         mono_mb_emit_byte (mb, CEE_LDIND_I4);
246         mono_mb_emit_icon (mb, -1);
247         pos = mono_mb_emit_branch (mb, branch_code);
248         return pos;
249 }
250
251 static int
252 mono_mb_emit_contextbound_check (MonoMethodBuilder *mb, int branch_code)
253 {
254         static int offset = -1;
255         static guint8 mask;
256
257         if (offset < 0)
258                 mono_marshal_find_bitfield_offset (MonoClass, contextbound, &offset, &mask);
259
260         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoTransparentProxy, remote_class));
261         mono_mb_emit_byte (mb, CEE_LDIND_REF);
262         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoRemoteClass, proxy_class));
263         mono_mb_emit_byte (mb, CEE_LDIND_REF);
264         mono_mb_emit_ldflda (mb, offset);
265         mono_mb_emit_byte (mb, CEE_LDIND_U1);
266         mono_mb_emit_icon (mb, mask);
267         mono_mb_emit_byte (mb, CEE_AND);
268         mono_mb_emit_icon (mb, 0);
269         return mono_mb_emit_branch (mb, branch_code);
270 }
271 #endif /* !DISABLE_JIT */
272
273 static inline MonoMethod*
274 mono_marshal_remoting_find_in_cache (MonoMethod *method, int wrapper_type)
275 {
276         MonoMethod *res = NULL;
277         MonoRemotingMethods *wrps = NULL;
278
279         mono_marshal_lock_internal ();
280         if (mono_method_get_wrapper_cache (method)->remoting_invoke_cache)
281                 wrps = (MonoRemotingMethods *)g_hash_table_lookup (mono_method_get_wrapper_cache (method)->remoting_invoke_cache, method);
282
283         if (wrps) {
284                 switch (wrapper_type) {
285                 case MONO_WRAPPER_REMOTING_INVOKE: res = wrps->invoke; break;
286                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: res = wrps->invoke_with_check; break;
287                 case MONO_WRAPPER_XDOMAIN_INVOKE: res = wrps->xdomain_invoke; break;
288                 case MONO_WRAPPER_XDOMAIN_DISPATCH: res = wrps->xdomain_dispatch; break;
289                 }
290         }
291         
292         /* it is important to do the unlock after the load from wrps, since in
293          * mono_remoting_mb_create_and_cache () we drop the marshal lock to be able
294          * to take the loader lock and some other thread may set the fields.
295          */
296         mono_marshal_unlock_internal ();
297         return res;
298 }
299
300 /* Create the method from the builder and place it in the cache */
301 static inline MonoMethod*
302 mono_remoting_mb_create_and_cache (MonoMethod *key, MonoMethodBuilder *mb, 
303                                                                    MonoMethodSignature *sig, int max_stack, WrapperInfo *info)
304 {
305         MonoMethod **res = NULL;
306         MonoRemotingMethods *wrps;
307         GHashTable *cache;
308
309         cache = get_cache_full (&mono_method_get_wrapper_cache (key)->remoting_invoke_cache, mono_aligned_addr_hash, NULL, NULL, g_free);
310
311         mono_marshal_lock_internal ();
312         wrps = (MonoRemotingMethods *)g_hash_table_lookup (cache, key);
313         if (!wrps) {
314                 wrps = g_new0 (MonoRemotingMethods, 1);
315                 g_hash_table_insert (cache, key, wrps);
316         }
317
318         switch (mb->method->wrapper_type) {
319         case MONO_WRAPPER_REMOTING_INVOKE: res = &wrps->invoke; break;
320         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK: res = &wrps->invoke_with_check; break;
321         case MONO_WRAPPER_XDOMAIN_INVOKE: res = &wrps->xdomain_invoke; break;
322         case MONO_WRAPPER_XDOMAIN_DISPATCH: res = &wrps->xdomain_dispatch; break;
323         default: g_assert_not_reached (); break;
324         }
325         mono_marshal_unlock_internal ();
326
327         if (*res == NULL) {
328                 MonoMethod *newm;
329                 newm = mono_mb_create_method (mb, sig, max_stack);
330
331                 mono_marshal_lock_internal ();
332                 if (!*res) {
333                         *res = newm;
334                         mono_marshal_set_wrapper_info (*res, info);
335                         mono_marshal_unlock_internal ();
336                 } else {
337                         mono_marshal_unlock_internal ();
338                         mono_free_method (newm);
339                 }
340         }
341
342         return *res;
343 }               
344
345 static MonoObject *
346 mono_remoting_wrapper (MonoMethod *method, gpointer *params)
347 {
348         MonoError error;
349         MonoMethodMessage *msg;
350         MonoTransparentProxy *this_obj;
351         MonoObject *res, *exc;
352         MonoArray *out_args;
353
354         this_obj = *((MonoTransparentProxy **)params [0]);
355
356         g_assert (this_obj);
357         g_assert (((MonoObject *)this_obj)->vtable->klass == mono_defaults.transparent_proxy_class);
358         
359         /* skip the this pointer */
360         params++;
361
362         if (mono_class_is_contextbound (this_obj->remote_class->proxy_class) && this_obj->rp->context == (MonoObject *) mono_context_get ())
363         {
364                 int i;
365                 MonoMethodSignature *sig = mono_method_signature (method);
366                 int count = sig->param_count;
367                 gpointer* mparams = (gpointer*) alloca(count*sizeof(gpointer));
368
369                 for (i=0; i<count; i++) {
370                         MonoClass *klass = mono_class_from_mono_type (sig->params [i]);
371                         if (klass->valuetype) {
372                                 if (sig->params [i]->byref) {
373                                         mparams[i] = *((gpointer *)params [i]);
374                                 } else {
375                                         /* runtime_invoke expects a boxed instance */
376                                         if (mono_class_is_nullable (mono_class_from_mono_type (sig->params [i])))
377                                                 mparams[i] = mono_nullable_box ((guint8 *)params [i], klass);
378                                         else
379                                                 mparams[i] = params [i];
380                                 }
381                         } else {
382                                 mparams[i] = *((gpointer**)params [i]);
383                         }
384                 }
385
386                 res = mono_runtime_invoke_checked (method, method->klass->valuetype? mono_object_unbox ((MonoObject*)this_obj): this_obj, mparams, &error);
387                 mono_error_raise_exception (&error); /* FIXME don't raise here */
388
389                 return res;
390         }
391
392         msg = mono_method_call_message_new (method, params, NULL, NULL, NULL);
393
394         res = mono_remoting_invoke ((MonoObject *)this_obj->rp, msg, &exc, &out_args);
395
396         if (exc)
397                 mono_raise_exception ((MonoException *)exc);
398
399         mono_method_return_message_restore (method, params, out_args);
400
401         return res;
402
403
404 MonoMethod *
405 mono_marshal_get_remoting_invoke (MonoMethod *method)
406 {
407         MonoMethodSignature *sig;
408         MonoMethodBuilder *mb;
409         MonoMethod *res;
410         int params_var;
411         WrapperInfo *info;
412
413         g_assert (method);
414
415         if (method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE || method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE)
416                 return method;
417
418         /* this seems to be the best plase to put this, as all remoting invokes seem to get filtered through here */
419 #ifndef DISABLE_COM
420         if (mono_class_is_com_object (method->klass) || method->klass == mono_class_try_get_com_object_class ()) {
421                 MonoVTable *vtable = mono_class_vtable (mono_domain_get (), method->klass);
422                 g_assert (vtable); /*FIXME do proper error handling*/
423
424                 if (!mono_vtable_is_remote (vtable)) {
425                         return mono_cominterop_get_invoke (method);
426                 }
427         }
428 #endif
429
430         sig = mono_signature_no_pinvoke (method);
431
432         /* we cant remote methods without this pointer */
433         if (!sig->hasthis)
434                 return method;
435
436         if ((res = mono_marshal_remoting_find_in_cache (method, MONO_WRAPPER_REMOTING_INVOKE)))
437                 return res;
438
439         mono_remoting_marshal_init ();
440
441         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_REMOTING_INVOKE);
442
443 #ifndef DISABLE_JIT
444         mb->method->save_lmf = 1;
445
446         params_var = mono_mb_emit_save_args (mb, sig, TRUE);
447
448         mono_mb_emit_ptr (mb, method);
449         mono_mb_emit_ldloc (mb, params_var);
450         mono_mb_emit_icall (mb, mono_remoting_wrapper);
451         mono_marshal_emit_thread_interrupt_checkpoint (mb);
452
453         if (sig->ret->type == MONO_TYPE_VOID) {
454                 mono_mb_emit_byte (mb, CEE_POP);
455                 mono_mb_emit_byte (mb, CEE_RET);
456         } else {
457                  mono_mb_emit_restore_result (mb, sig->ret);
458         }
459 #endif
460
461         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
462         info->d.remoting.method = method;
463         res = mono_remoting_mb_create_and_cache (method, mb, sig, sig->param_count + 16, info);
464         mono_mb_free (mb);
465
466         return res;
467 }
468
469 /* mono_marshal_xdomain_copy_out_value()
470  * Copies the contents of the src instance into the dst instance. src and dst
471  * must have the same type, and if they are arrays, the same size.
472  */
473 static void
474 mono_marshal_xdomain_copy_out_value (MonoObject *src, MonoObject *dst)
475 {
476         if (src == NULL || dst == NULL) return;
477         
478         g_assert (mono_object_class (src) == mono_object_class (dst));
479
480         switch (mono_object_class (src)->byval_arg.type) {
481         case MONO_TYPE_ARRAY:
482         case MONO_TYPE_SZARRAY: {
483                 int mt = mono_get_xdomain_marshal_type (&(mono_object_class (src)->element_class->byval_arg));
484                 if (mt == MONO_MARSHAL_SERIALIZE) return;
485                 if (mt == MONO_MARSHAL_COPY) {
486                         int i, len = mono_array_length ((MonoArray *)dst);
487                         for (i = 0; i < len; i++) {
488                                 MonoObject *item = (MonoObject *)mono_array_get ((MonoArray *)src, gpointer, i);
489                                 mono_array_setref ((MonoArray *)dst, i, mono_marshal_xdomain_copy_value (item));
490                         }
491                 } else {
492                         mono_array_full_copy ((MonoArray *)src, (MonoArray *)dst);
493                 }
494                 return;
495         }
496         default:
497                 break;
498         }
499
500 }
501
502
503 #if !defined (DISABLE_JIT)
504 static void
505 mono_marshal_emit_xdomain_copy_value (MonoMethodBuilder *mb, MonoClass *pclass)
506 {
507         mono_mb_emit_icall (mb, mono_marshal_xdomain_copy_value);
508         mono_mb_emit_op (mb, CEE_CASTCLASS, pclass);
509 }
510
511 static void
512 mono_marshal_emit_xdomain_copy_out_value (MonoMethodBuilder *mb, MonoClass *pclass)
513 {
514         mono_mb_emit_icall (mb, mono_marshal_xdomain_copy_out_value);
515 }
516 #endif
517
518 /* mono_marshal_supports_fast_xdomain()
519  * Returns TRUE if the method can use the fast xdomain wrapper.
520  */
521 static gboolean
522 mono_marshal_supports_fast_xdomain (MonoMethod *method)
523 {
524         return !mono_class_is_contextbound (method->klass) &&
525                    !((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) && (strcmp (".ctor", method->name) == 0));
526 }
527
528 static gint32
529 mono_marshal_set_domain_by_id (gint32 id, MonoBoolean push)
530 {
531         MonoDomain *current_domain = mono_domain_get ();
532         MonoDomain *domain = mono_domain_get_by_id (id);
533
534         if (!domain || !mono_domain_set (domain, FALSE))        
535                 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
536
537         if (push)
538                 mono_thread_push_appdomain_ref (domain);
539         else
540                 mono_thread_pop_appdomain_ref ();
541
542         return current_domain->domain_id;
543 }
544
545 #if !defined (DISABLE_JIT)
546 static void
547 mono_marshal_emit_switch_domain (MonoMethodBuilder *mb)
548 {
549         mono_mb_emit_icall (mb, mono_marshal_set_domain_by_id);
550 }
551
552 /* mono_marshal_emit_load_domain_method ()
553  * Loads into the stack a pointer to the code of the provided method for
554  * the current domain.
555  */
556 static void
557 mono_marshal_emit_load_domain_method (MonoMethodBuilder *mb, MonoMethod *method)
558 {
559         /* We need a pointer to the method for the running domain (not the domain
560          * that compiles the method).
561          */
562         mono_mb_emit_ptr (mb, method);
563         mono_mb_emit_icall (mb, mono_compile_method);
564 }
565 #endif
566
567 /* mono_marshal_check_domain_image ()
568  * Returns TRUE if the image is loaded in the specified
569  * application domain.
570  */
571 static gboolean
572 mono_marshal_check_domain_image (gint32 domain_id, MonoImage *image)
573 {
574         MonoAssembly* ass;
575         GSList *tmp;
576         
577         MonoDomain *domain = mono_domain_get_by_id (domain_id);
578         if (!domain)
579                 return FALSE;
580         
581         mono_domain_assemblies_lock (domain);
582         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
583                 ass = (MonoAssembly *)tmp->data;
584                 if (ass->image == image)
585                         break;
586         }
587         mono_domain_assemblies_unlock (domain);
588         
589         return tmp != NULL;
590 }
591
592 /* mono_marshal_get_xappdomain_dispatch ()
593  * Generates a method that dispatches a method call from another domain into
594  * the current domain.
595  */
596 static MonoMethod *
597 mono_marshal_get_xappdomain_dispatch (MonoMethod *method, int *marshal_types, int complex_count, int complex_out_count, int ret_marshal_type)
598 {
599         MonoMethodSignature *sig, *csig;
600         MonoMethodBuilder *mb;
601         MonoMethod *res;
602         int i, j, param_index, copy_locals_base;
603         MonoClass *ret_class = NULL;
604         int loc_array=0, loc_return=0, loc_serialized_exc=0;
605         MonoExceptionClause *main_clause;
606         int pos, pos_leave;
607         gboolean copy_return;
608         WrapperInfo *info;
609
610         if ((res = mono_marshal_remoting_find_in_cache (method, MONO_WRAPPER_XDOMAIN_DISPATCH)))
611                 return res;
612
613         sig = mono_method_signature (method);
614         copy_return = (sig->ret->type != MONO_TYPE_VOID && ret_marshal_type != MONO_MARSHAL_SERIALIZE);
615
616         j = 0;
617         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3 + sig->param_count - complex_count);
618         csig->params [j++] = &mono_defaults.object_class->byval_arg;
619         csig->params [j++] = &byte_array_class->this_arg;
620         csig->params [j++] = &byte_array_class->this_arg;
621         for (i = 0; i < sig->param_count; i++) {
622                 if (marshal_types [i] != MONO_MARSHAL_SERIALIZE)
623                         csig->params [j++] = sig->params [i];
624         }
625         if (copy_return)
626                 csig->ret = sig->ret;
627         else
628                 csig->ret = &mono_defaults.void_class->byval_arg;
629         csig->pinvoke = 1;
630         csig->hasthis = FALSE;
631
632         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_XDOMAIN_DISPATCH);
633         mb->method->save_lmf = 1;
634
635 #ifndef DISABLE_JIT
636         /* Locals */
637
638         loc_serialized_exc = mono_mb_add_local (mb, &byte_array_class->byval_arg);
639         if (complex_count > 0)
640                 loc_array = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
641         if (sig->ret->type != MONO_TYPE_VOID) {
642                 loc_return = mono_mb_add_local (mb, sig->ret);
643                 ret_class = mono_class_from_mono_type (sig->ret);
644         }
645
646         /* try */
647
648         main_clause = (MonoExceptionClause *)mono_image_alloc0 (method->klass->image, sizeof (MonoExceptionClause));
649         main_clause->try_offset = mono_mb_get_label (mb);
650
651         /* Clean the call context */
652
653         mono_mb_emit_byte (mb, CEE_LDNULL);
654         mono_mb_emit_managed_call (mb, method_set_call_context, NULL);
655         mono_mb_emit_byte (mb, CEE_POP);
656
657         /* Deserialize call data */
658
659         mono_mb_emit_ldarg (mb, 1);
660         mono_mb_emit_byte (mb, CEE_LDIND_REF);
661         mono_mb_emit_byte (mb, CEE_DUP);
662         pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
663         
664         mono_marshal_emit_xdomain_copy_value (mb, byte_array_class);
665         mono_mb_emit_managed_call (mb, method_rs_deserialize, NULL);
666         
667         if (complex_count > 0)
668                 mono_mb_emit_stloc (mb, loc_array);
669         else
670                 mono_mb_emit_byte (mb, CEE_POP);
671
672         mono_mb_patch_short_branch (mb, pos);
673
674         /* Get the target object */
675         
676         mono_mb_emit_ldarg (mb, 0);
677         mono_mb_emit_managed_call (mb, method_rs_appdomain_target, NULL);
678
679         /* Load the arguments */
680         
681         copy_locals_base = mb->locals;
682         param_index = 3;        // Index of the first non-serialized parameter of this wrapper
683         j = 0;
684         for (i = 0; i < sig->param_count; i++) {
685                 MonoType *pt = sig->params [i];
686                 MonoClass *pclass = mono_class_from_mono_type (pt);
687                 switch (marshal_types [i]) {
688                 case MONO_MARSHAL_SERIALIZE: {
689                         /* take the value from the serialized array */
690                         mono_mb_emit_ldloc (mb, loc_array);
691                         mono_mb_emit_icon (mb, j++);
692                         if (pt->byref) {
693                                 if (pclass->valuetype) {
694                                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
695                                         mono_mb_emit_op (mb, CEE_UNBOX, pclass);
696                                 } else {
697                                         mono_mb_emit_op (mb, CEE_LDELEMA, pclass);
698                                 }
699                         } else {
700                                 if (pclass->valuetype) {
701                                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
702                                         mono_mb_emit_op (mb, CEE_UNBOX, pclass);
703                                         mono_mb_emit_op (mb, CEE_LDOBJ, pclass);
704                                 } else {
705                                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
706                                         if (pclass != mono_defaults.object_class) {
707                                                 mono_mb_emit_op (mb, CEE_CASTCLASS, pclass);
708                                         }
709                                 }
710                         }
711                         break;
712                 }
713                 case MONO_MARSHAL_COPY_OUT: {
714                         /* Keep a local copy of the value since we need to copy it back after the call */
715                         int copy_local = mono_mb_add_local (mb, &(pclass->byval_arg));
716                         mono_mb_emit_ldarg (mb, param_index++);
717                         mono_marshal_emit_xdomain_copy_value (mb, pclass);
718                         mono_mb_emit_byte (mb, CEE_DUP);
719                         mono_mb_emit_stloc (mb, copy_local);
720                         break;
721                 }
722                 case MONO_MARSHAL_COPY: {
723                         mono_mb_emit_ldarg (mb, param_index);
724                         if (pt->byref) {
725                                 mono_mb_emit_byte (mb, CEE_DUP);
726                                 mono_mb_emit_byte (mb, CEE_DUP);
727                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
728                                 mono_marshal_emit_xdomain_copy_value (mb, pclass);
729                                 mono_mb_emit_byte (mb, CEE_STIND_REF);
730                         } else {
731                                 mono_marshal_emit_xdomain_copy_value (mb, pclass);
732                         }
733                         param_index++;
734                         break;
735                 }
736                 case MONO_MARSHAL_NONE:
737                         mono_mb_emit_ldarg (mb, param_index++);
738                         break;
739                 }
740         }
741
742         /* Make the call to the real object */
743
744         mono_marshal_emit_thread_force_interrupt_checkpoint (mb);
745         
746         mono_mb_emit_op (mb, CEE_CALLVIRT, method);
747
748         if (sig->ret->type != MONO_TYPE_VOID)
749                 mono_mb_emit_stloc (mb, loc_return);
750
751         /* copy back MONO_MARSHAL_COPY_OUT parameters */
752
753         j = 0;
754         param_index = 3;
755         for (i = 0; i < sig->param_count; i++) {
756                 if (marshal_types [i] == MONO_MARSHAL_SERIALIZE) continue;
757                 if (marshal_types [i] == MONO_MARSHAL_COPY_OUT) {
758                         mono_mb_emit_ldloc (mb, copy_locals_base + (j++));
759                         mono_mb_emit_ldarg (mb, param_index);
760                         mono_marshal_emit_xdomain_copy_out_value (mb, mono_class_from_mono_type (sig->params [i]));
761                 }
762                 param_index++;
763         }
764
765         /* Serialize the return values */
766         
767         if (complex_out_count > 0) {
768                 /* Reset parameters in the array that don't need to be serialized back */
769                 j = 0;
770                 for (i = 0; i < sig->param_count; i++) {
771                         if (marshal_types[i] != MONO_MARSHAL_SERIALIZE) continue;
772                         if (!sig->params [i]->byref) {
773                                 mono_mb_emit_ldloc (mb, loc_array);
774                                 mono_mb_emit_icon (mb, j);
775                                 mono_mb_emit_byte (mb, CEE_LDNULL);
776                                 mono_mb_emit_byte (mb, CEE_STELEM_REF);
777                         }
778                         j++;
779                 }
780         
781                 /* Add the return value to the array */
782         
783                 if (ret_marshal_type == MONO_MARSHAL_SERIALIZE) {
784                         mono_mb_emit_ldloc (mb, loc_array);
785                         mono_mb_emit_icon (mb, complex_count);  /* The array has an additional slot to hold the ret value */
786                         mono_mb_emit_ldloc (mb, loc_return);
787
788                         g_assert (ret_class); /*FIXME properly fail here*/
789                         if (ret_class->valuetype) {
790                                 mono_mb_emit_op (mb, CEE_BOX, ret_class);
791                         }
792                         mono_mb_emit_byte (mb, CEE_STELEM_REF);
793                 }
794         
795                 /* Serialize */
796         
797                 mono_mb_emit_ldarg (mb, 1);
798                 mono_mb_emit_ldloc (mb, loc_array);
799                 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
800                 mono_mb_emit_byte (mb, CEE_STIND_REF);
801         } else if (ret_marshal_type == MONO_MARSHAL_SERIALIZE) {
802                 mono_mb_emit_ldarg (mb, 1);
803                 mono_mb_emit_ldloc (mb, loc_return);
804                 if (ret_class->valuetype) {
805                         mono_mb_emit_op (mb, CEE_BOX, ret_class);
806                 }
807                 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
808                 mono_mb_emit_byte (mb, CEE_STIND_REF);
809         } else {
810                 mono_mb_emit_ldarg (mb, 1);
811                 mono_mb_emit_byte (mb, CEE_LDNULL);
812                 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
813                 mono_mb_emit_byte (mb, CEE_STIND_REF);
814         }
815
816         mono_mb_emit_ldarg (mb, 2);
817         mono_mb_emit_byte (mb, CEE_LDNULL);
818         mono_mb_emit_byte (mb, CEE_STIND_REF);
819         pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
820
821         /* Main exception catch */
822         main_clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
823         main_clause->try_len = mono_mb_get_pos (mb) - main_clause->try_offset;
824         main_clause->data.catch_class = mono_defaults.object_class;
825         
826         /* handler code */
827         main_clause->handler_offset = mono_mb_get_label (mb);
828         mono_mb_emit_managed_call (mb, method_rs_serialize_exc, NULL);
829         mono_mb_emit_stloc (mb, loc_serialized_exc);
830         mono_mb_emit_ldarg (mb, 2);
831         mono_mb_emit_ldloc (mb, loc_serialized_exc);
832         mono_mb_emit_byte (mb, CEE_STIND_REF);
833         mono_mb_emit_branch (mb, CEE_LEAVE);
834         main_clause->handler_len = mono_mb_get_pos (mb) - main_clause->handler_offset;
835         /* end catch */
836
837         mono_mb_patch_branch (mb, pos_leave);
838         
839         if (copy_return)
840                 mono_mb_emit_ldloc (mb, loc_return);
841
842         mono_mb_emit_byte (mb, CEE_RET);
843
844         mono_mb_set_clauses (mb, 1, main_clause);
845 #endif
846
847         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
848         info->d.remoting.method = method;
849         res = mono_remoting_mb_create_and_cache (method, mb, csig, csig->param_count + 16, info);
850         mono_mb_free (mb);
851
852         return res;
853 }
854
855 /* mono_marshal_get_xappdomain_invoke ()
856  * Generates a fast remoting wrapper for cross app domain calls.
857  */
858 MonoMethod *
859 mono_marshal_get_xappdomain_invoke (MonoMethod *method)
860 {
861         MonoMethodSignature *sig;
862         MonoMethodBuilder *mb;
863         MonoMethod *res;
864         int i, j, complex_count, complex_out_count, copy_locals_base;
865         int *marshal_types;
866         MonoClass *ret_class = NULL;
867         MonoMethod *xdomain_method;
868         int ret_marshal_type = MONO_MARSHAL_NONE;
869         int loc_array=0, loc_serialized_data=-1, loc_real_proxy;
870         int loc_old_domainid, loc_domainid, loc_return=0, loc_serialized_exc=0, loc_context;
871         int pos, pos_dispatch, pos_noex;
872         gboolean copy_return = FALSE;
873         WrapperInfo *info;
874
875         g_assert (method);
876         
877         if (method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE || method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE)
878                 return method;
879
880         /* we cant remote methods without this pointer */
881         if (!mono_method_signature (method)->hasthis)
882                 return method;
883
884         mono_remoting_marshal_init ();
885
886         if (!mono_marshal_supports_fast_xdomain (method))
887                 return mono_marshal_get_remoting_invoke (method);
888         
889         if ((res = mono_marshal_remoting_find_in_cache (method, MONO_WRAPPER_XDOMAIN_INVOKE)))
890                 return res;
891         
892         sig = mono_signature_no_pinvoke (method);
893
894         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_XDOMAIN_INVOKE);
895         mb->method->save_lmf = 1;
896
897         /* Count the number of parameters that need to be serialized */
898
899         marshal_types = (int *)alloca (sizeof (int) * sig->param_count);
900         complex_count = complex_out_count = 0;
901         for (i = 0; i < sig->param_count; i++) {
902                 MonoType *ptype = sig->params[i];
903                 int mt = mono_get_xdomain_marshal_type (ptype);
904                 
905                 /* If the [Out] attribute is applied to a parameter that can be internally copied,
906                  * the copy will be made by reusing the original object instance
907                  */
908                 if ((ptype->attrs & PARAM_ATTRIBUTE_OUT) != 0 && mt == MONO_MARSHAL_COPY && !ptype->byref)
909                         mt = MONO_MARSHAL_COPY_OUT;
910                 else if (mt == MONO_MARSHAL_SERIALIZE) {
911                         complex_count++;
912                         if (ptype->byref) complex_out_count++;
913                 }
914                 marshal_types [i] = mt;
915         }
916
917         if (sig->ret->type != MONO_TYPE_VOID) {
918                 ret_marshal_type = mono_get_xdomain_marshal_type (sig->ret);
919                 ret_class = mono_class_from_mono_type (sig->ret);
920                 copy_return = ret_marshal_type != MONO_MARSHAL_SERIALIZE;
921         }
922         
923         /* Locals */
924
925 #ifndef DISABLE_JIT
926         if (complex_count > 0)
927                 loc_array = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
928         loc_serialized_data = mono_mb_add_local (mb, &byte_array_class->byval_arg);
929         loc_real_proxy = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
930         if (copy_return)
931                 loc_return = mono_mb_add_local (mb, sig->ret);
932         loc_old_domainid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
933         loc_domainid = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
934         loc_serialized_exc = mono_mb_add_local (mb, &byte_array_class->byval_arg);
935         loc_context = mono_mb_add_local (mb, &mono_defaults.object_class->byval_arg);
936
937         /* Save thread domain data */
938
939         mono_mb_emit_icall (mb, mono_context_get);
940         mono_mb_emit_byte (mb, CEE_DUP);
941         mono_mb_emit_stloc (mb, loc_context);
942
943         /* If the thread is not running in the default context, it needs to go
944          * through the whole remoting sink, since the context is going to change
945          */
946         mono_mb_emit_managed_call (mb, method_needs_context_sink, NULL);
947         pos = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
948         
949         /* Another case in which the fast path can't be used: when the target domain
950          * has a different image for the same assembly.
951          */
952
953         /* Get the target domain id */
954
955         mono_mb_emit_ldarg (mb, 0);
956         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoTransparentProxy, rp));
957         mono_mb_emit_byte (mb, CEE_LDIND_REF);
958         mono_mb_emit_byte (mb, CEE_DUP);
959         mono_mb_emit_stloc (mb, loc_real_proxy);
960
961         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoRealProxy, target_domain_id));
962         mono_mb_emit_byte (mb, CEE_LDIND_I4);
963         mono_mb_emit_stloc (mb, loc_domainid);
964
965         /* Check if the target domain has the same image for the required assembly */
966
967         mono_mb_emit_ldloc (mb, loc_domainid);
968         mono_mb_emit_ptr (mb, method->klass->image);
969         mono_mb_emit_icall (mb, mono_marshal_check_domain_image);
970         pos_dispatch = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
971
972         /* Use the whole remoting sink to dispatch this message */
973
974         mono_mb_patch_short_branch (mb, pos);
975
976         mono_mb_emit_ldarg (mb, 0);
977         for (i = 0; i < sig->param_count; i++)
978                 mono_mb_emit_ldarg (mb, i + 1);
979         
980         mono_mb_emit_managed_call (mb, mono_marshal_get_remoting_invoke (method), NULL);
981         mono_mb_emit_byte (mb, CEE_RET);
982         mono_mb_patch_short_branch (mb, pos_dispatch);
983
984         /* Create the array that will hold the parameters to be serialized */
985
986         if (complex_count > 0) {
987                 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 */
988                 mono_mb_emit_op (mb, CEE_NEWARR, mono_defaults.object_class);
989         
990                 j = 0;
991                 for (i = 0; i < sig->param_count; i++) {
992                         MonoClass *pclass;
993                         if (marshal_types [i] != MONO_MARSHAL_SERIALIZE) continue;
994                         pclass = mono_class_from_mono_type (sig->params[i]);
995                         mono_mb_emit_byte (mb, CEE_DUP);
996                         mono_mb_emit_icon (mb, j);
997                         mono_mb_emit_ldarg (mb, i + 1);         /* 0=this */
998                         if (sig->params[i]->byref) {
999                                 if (pclass->valuetype)
1000                                         mono_mb_emit_op (mb, CEE_LDOBJ, pclass);
1001                                 else
1002                                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
1003                         }
1004                         if (pclass->valuetype)
1005                                 mono_mb_emit_op (mb, CEE_BOX, pclass);
1006                         mono_mb_emit_byte (mb, CEE_STELEM_REF);
1007                         j++;
1008                 }
1009                 mono_mb_emit_stloc (mb, loc_array);
1010
1011                 /* Serialize parameters */
1012         
1013                 mono_mb_emit_ldloc (mb, loc_array);
1014                 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
1015                 mono_mb_emit_stloc (mb, loc_serialized_data);
1016         } else {
1017                 mono_mb_emit_byte (mb, CEE_LDNULL);
1018                 mono_mb_emit_managed_call (mb, method_rs_serialize, NULL);
1019                 mono_mb_emit_stloc (mb, loc_serialized_data);
1020         }
1021
1022         /* switch domain */
1023
1024         mono_mb_emit_ldloc (mb, loc_domainid);
1025         mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1026         mono_marshal_emit_switch_domain (mb);
1027         mono_mb_emit_stloc (mb, loc_old_domainid);
1028
1029         /* Load the arguments */
1030         
1031         mono_mb_emit_ldloc (mb, loc_real_proxy);
1032         mono_mb_emit_ldloc_addr (mb, loc_serialized_data);
1033         mono_mb_emit_ldloc_addr (mb, loc_serialized_exc);
1034
1035         copy_locals_base = mb->locals;
1036         for (i = 0; i < sig->param_count; i++) {
1037                 switch (marshal_types [i]) {
1038                 case MONO_MARSHAL_SERIALIZE:
1039                         continue;
1040                 case MONO_MARSHAL_COPY: {
1041                         mono_mb_emit_ldarg (mb, i+1);
1042                         if (sig->params [i]->byref) {
1043                                 /* make a local copy of the byref parameter. The real parameter
1044                                  * will be updated after the xdomain call
1045                                  */
1046                                 MonoClass *pclass = mono_class_from_mono_type (sig->params [i]);
1047                                 int copy_local = mono_mb_add_local (mb, &(pclass->byval_arg));
1048                                 mono_mb_emit_byte (mb, CEE_LDIND_REF);
1049                                 mono_mb_emit_stloc (mb, copy_local);
1050                                 mono_mb_emit_ldloc_addr (mb, copy_local);
1051                         }
1052                         break;
1053                 }
1054                 case MONO_MARSHAL_COPY_OUT:
1055                 case MONO_MARSHAL_NONE:
1056                         mono_mb_emit_ldarg (mb, i+1);
1057                         break;
1058                 }
1059         }
1060
1061         /* Make the call to the invoke wrapper in the target domain */
1062
1063         xdomain_method = mono_marshal_get_xappdomain_dispatch (method, marshal_types, complex_count, complex_out_count, ret_marshal_type);
1064         mono_marshal_emit_load_domain_method (mb, xdomain_method);
1065         mono_mb_emit_calli (mb, mono_method_signature (xdomain_method));
1066
1067         if (copy_return)
1068                 mono_mb_emit_stloc (mb, loc_return);
1069
1070         /* Switch domain */
1071
1072         mono_mb_emit_ldloc (mb, loc_old_domainid);
1073         mono_mb_emit_byte (mb, CEE_LDC_I4_0);
1074         mono_marshal_emit_switch_domain (mb);
1075         mono_mb_emit_byte (mb, CEE_POP);
1076         
1077         /* Restore thread domain data */
1078         
1079         mono_mb_emit_ldloc (mb, loc_context);
1080         mono_mb_emit_icall (mb, mono_context_set);
1081         
1082         /* if (loc_serialized_exc != null) ... */
1083
1084         mono_mb_emit_ldloc (mb, loc_serialized_exc);
1085         pos_noex = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
1086
1087         mono_mb_emit_ldloc (mb, loc_serialized_exc);
1088         mono_marshal_emit_xdomain_copy_value (mb, byte_array_class);
1089         mono_mb_emit_managed_call (mb, method_rs_deserialize, NULL);
1090         mono_mb_emit_op (mb, CEE_CASTCLASS, mono_defaults.exception_class);
1091         mono_mb_emit_managed_call (mb, method_exc_fixexc, NULL);
1092         mono_mb_emit_byte (mb, CEE_THROW);
1093         mono_mb_patch_short_branch (mb, pos_noex);
1094
1095         /* copy back non-serialized output parameters */
1096
1097         j = 0;
1098         for (i = 0; i < sig->param_count; i++) {
1099                 if (!sig->params [i]->byref || marshal_types [i] != MONO_MARSHAL_COPY) continue;
1100                 mono_mb_emit_ldarg (mb, i + 1);
1101                 mono_mb_emit_ldloc (mb, copy_locals_base + (j++));
1102                 mono_marshal_emit_xdomain_copy_value (mb, mono_class_from_mono_type (sig->params [i]));
1103                 mono_mb_emit_byte (mb, CEE_STIND_REF);
1104         }
1105
1106         /* Deserialize out parameters */
1107
1108         if (complex_out_count > 0) {
1109                 mono_mb_emit_ldloc (mb, loc_serialized_data);
1110                 mono_marshal_emit_xdomain_copy_value (mb, byte_array_class);
1111                 mono_mb_emit_managed_call (mb, method_rs_deserialize, NULL);
1112                 mono_mb_emit_stloc (mb, loc_array);
1113         
1114                 /* Copy back output parameters and return type */
1115                 
1116                 j = 0;
1117                 for (i = 0; i < sig->param_count; i++) {
1118                         if (marshal_types [i] != MONO_MARSHAL_SERIALIZE) continue;
1119                         if (sig->params[i]->byref) {
1120                                 MonoClass *pclass = mono_class_from_mono_type (sig->params [i]);
1121                                 mono_mb_emit_ldarg (mb, i + 1);
1122                                 mono_mb_emit_ldloc (mb, loc_array);
1123                                 mono_mb_emit_icon (mb, j);
1124                                 mono_mb_emit_byte (mb, CEE_LDELEM_REF);
1125                                 if (pclass->valuetype) {
1126                                         mono_mb_emit_op (mb, CEE_UNBOX, pclass);
1127                                         mono_mb_emit_op (mb, CEE_LDOBJ, pclass);
1128                                         mono_mb_emit_op (mb, CEE_STOBJ, pclass);
1129                                 } else {
1130                                         if (pclass != mono_defaults.object_class)
1131                                                 mono_mb_emit_op (mb, CEE_CASTCLASS, pclass);
1132                                         mono_mb_emit_byte (mb, CEE_STIND_REF);
1133                                 }
1134                         }
1135                         j++;
1136                 }
1137         
1138                 if (ret_marshal_type == MONO_MARSHAL_SERIALIZE) {
1139                         mono_mb_emit_ldloc (mb, loc_array);
1140                         mono_mb_emit_icon (mb, complex_count);
1141                         mono_mb_emit_byte (mb, CEE_LDELEM_REF);
1142                         if (ret_class->valuetype) {
1143                                 mono_mb_emit_op (mb, CEE_UNBOX, ret_class);
1144                                 mono_mb_emit_op (mb, CEE_LDOBJ, ret_class);
1145                         }
1146                 }
1147         } else if (ret_marshal_type == MONO_MARSHAL_SERIALIZE) {
1148                 mono_mb_emit_ldloc (mb, loc_serialized_data);
1149                 mono_marshal_emit_xdomain_copy_value (mb, byte_array_class);
1150                 mono_mb_emit_managed_call (mb, method_rs_deserialize, NULL);
1151                 if (ret_class->valuetype) {
1152                         mono_mb_emit_op (mb, CEE_UNBOX, ret_class);
1153                         mono_mb_emit_op (mb, CEE_LDOBJ, ret_class);
1154                 } else if (ret_class != mono_defaults.object_class) {
1155                         mono_mb_emit_op (mb, CEE_CASTCLASS, ret_class);
1156                 }
1157         } else {
1158                 mono_mb_emit_ldloc (mb, loc_serialized_data);
1159                 mono_mb_emit_byte (mb, CEE_DUP);
1160                 pos = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
1161                 mono_marshal_emit_xdomain_copy_value (mb, byte_array_class);
1162         
1163                 mono_mb_patch_short_branch (mb, pos);
1164                 mono_mb_emit_managed_call (mb, method_rs_deserialize, NULL);
1165                 mono_mb_emit_byte (mb, CEE_POP);
1166         }
1167
1168         if (copy_return) {
1169                 mono_mb_emit_ldloc (mb, loc_return);
1170                 if (ret_marshal_type == MONO_MARSHAL_COPY)
1171                         mono_marshal_emit_xdomain_copy_value (mb, ret_class);
1172         }
1173
1174         mono_mb_emit_byte (mb, CEE_RET);
1175 #endif /* DISABLE_JIT */
1176
1177         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
1178         info->d.remoting.method = method;
1179         res = mono_remoting_mb_create_and_cache (method, mb, sig, sig->param_count + 16, info);
1180         mono_mb_free (mb);
1181
1182         return res;
1183 }
1184
1185 MonoMethod *
1186 mono_marshal_get_remoting_invoke_for_target (MonoMethod *method, MonoRemotingTarget target_type)
1187 {
1188         if (target_type == MONO_REMOTING_TARGET_APPDOMAIN) {
1189                 return mono_marshal_get_xappdomain_invoke (method);
1190         } else if (target_type == MONO_REMOTING_TARGET_COMINTEROP) {
1191 #ifndef DISABLE_COM
1192                 return mono_cominterop_get_invoke (method);
1193 #else
1194                 g_assert_not_reached ();
1195 #endif
1196         } else {
1197                 return mono_marshal_get_remoting_invoke (method);
1198         }
1199         /* Not erached */
1200         return NULL;
1201 }
1202
1203 G_GNUC_UNUSED static gpointer
1204 mono_marshal_load_remoting_wrapper (MonoRealProxy *rp, MonoMethod *method)
1205 {
1206         if (rp->target_domain_id != -1)
1207                 return mono_compile_method (mono_marshal_get_xappdomain_invoke (method));
1208         else
1209                 return mono_compile_method (mono_marshal_get_remoting_invoke (method));
1210 }
1211
1212 MonoMethod *
1213 mono_marshal_get_remoting_invoke_with_check (MonoMethod *method)
1214 {
1215         MonoMethodSignature *sig;
1216         MonoMethodBuilder *mb;
1217         MonoMethod *res, *native;
1218         WrapperInfo *info;
1219         int i, pos, pos_rem;
1220
1221         g_assert (method);
1222
1223         if (method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
1224                 return method;
1225
1226         /* we cant remote methods without this pointer */
1227         g_assert (mono_method_signature (method)->hasthis);
1228
1229         if ((res = mono_marshal_remoting_find_in_cache (method, MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)))
1230                 return res;
1231
1232         sig = mono_signature_no_pinvoke (method);
1233         
1234         mb = mono_mb_new (method->klass, method->name, MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK);
1235
1236 #ifndef DISABLE_JIT
1237         for (i = 0; i <= sig->param_count; i++)
1238                 mono_mb_emit_ldarg (mb, i);
1239         
1240         mono_mb_emit_ldarg (mb, 0);
1241         pos = mono_mb_emit_proxy_check (mb, CEE_BNE_UN);
1242
1243         if (mono_marshal_supports_fast_xdomain (method)) {
1244                 mono_mb_emit_ldarg (mb, 0);
1245                 pos_rem = mono_mb_emit_xdomain_check (mb, CEE_BEQ);
1246                 
1247                 /* wrapper for cross app domain calls */
1248                 native = mono_marshal_get_xappdomain_invoke (method);
1249                 mono_mb_emit_managed_call (mb, native, mono_method_signature (native));
1250                 mono_mb_emit_byte (mb, CEE_RET);
1251                 
1252                 mono_mb_patch_branch (mb, pos_rem);
1253         }
1254         /* wrapper for normal remote calls */
1255         native = mono_marshal_get_remoting_invoke (method);
1256         mono_mb_emit_managed_call (mb, native, mono_method_signature (native));
1257         mono_mb_emit_byte (mb, CEE_RET);
1258
1259         /* not a proxy */
1260         mono_mb_patch_branch (mb, pos);
1261         mono_mb_emit_managed_call (mb, method, mono_method_signature (method));
1262         mono_mb_emit_byte (mb, CEE_RET);
1263 #endif
1264
1265         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
1266         info->d.remoting.method = method;
1267         res = mono_remoting_mb_create_and_cache (method, mb, sig, sig->param_count + 16, info);
1268         mono_mb_free (mb);
1269
1270         return res;
1271 }
1272
1273 /*
1274  * mono_marshal_get_ldfld_remote_wrapper:
1275  * @klass: The return type
1276  *
1277  * This method generates a wrapper for calling mono_load_remote_field_new.
1278  * The return type is ignored for now, as mono_load_remote_field_new () always
1279  * returns an object. In the future, to optimize some codepaths, we might
1280  * call a different function that takes a pointer to a valuetype, instead.
1281  */
1282 MonoMethod *
1283 mono_marshal_get_ldfld_remote_wrapper (MonoClass *klass)
1284 {
1285         MonoMethodSignature *sig, *csig;
1286         MonoMethodBuilder *mb;
1287         MonoMethod *res;
1288         static MonoMethod* cached = NULL;
1289
1290         mono_marshal_lock_internal ();
1291         if (cached) {
1292                 mono_marshal_unlock_internal ();
1293                 return cached;
1294         }
1295         mono_marshal_unlock_internal ();
1296
1297         mb = mono_mb_new_no_dup_name (mono_defaults.object_class, "__mono_load_remote_field_new_wrapper", MONO_WRAPPER_LDFLD_REMOTE);
1298
1299         mb->method->save_lmf = 1;
1300
1301         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
1302         sig->params [0] = &mono_defaults.object_class->byval_arg;
1303         sig->params [1] = &mono_defaults.int_class->byval_arg;
1304         sig->params [2] = &mono_defaults.int_class->byval_arg;
1305         sig->ret = &mono_defaults.object_class->byval_arg;
1306
1307 #ifndef DISABLE_JIT
1308         mono_mb_emit_ldarg (mb, 0);
1309         mono_mb_emit_ldarg (mb, 1);
1310         mono_mb_emit_ldarg (mb, 2);
1311
1312         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
1313         csig->params [0] = &mono_defaults.object_class->byval_arg;
1314         csig->params [1] = &mono_defaults.int_class->byval_arg;
1315         csig->params [2] = &mono_defaults.int_class->byval_arg;
1316         csig->ret = &mono_defaults.object_class->byval_arg;
1317         csig->pinvoke = 1;
1318
1319         mono_mb_emit_native_call (mb, csig, mono_load_remote_field_new);
1320         mono_marshal_emit_thread_interrupt_checkpoint (mb);
1321
1322         mono_mb_emit_byte (mb, CEE_RET);
1323 #endif
1324
1325         mono_marshal_lock_internal ();
1326         res = cached;
1327         mono_marshal_unlock_internal ();
1328         if (!res) {
1329                 MonoMethod *newm;
1330                 newm = mono_mb_create (mb, sig, 4, NULL);
1331                 mono_marshal_lock_internal ();
1332                 res = cached;
1333                 if (!res) {
1334                         res = newm;
1335                         cached = res;
1336                         mono_marshal_unlock_internal ();
1337                 } else {
1338                         mono_marshal_unlock_internal ();
1339                         mono_free_method (newm);
1340                 }
1341         }
1342         mono_mb_free (mb);
1343
1344         return res;
1345 }
1346
1347 /*
1348  * mono_marshal_get_ldfld_wrapper:
1349  * @type: the type of the field
1350  *
1351  * This method generates a function which can be use to load a field with type
1352  * @type from an object. The generated function has the following signature:
1353  * <@type> ldfld_wrapper (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, int offset)
1354  */
1355 MonoMethod *
1356 mono_marshal_get_ldfld_wrapper (MonoType *type)
1357 {
1358         MonoMethodSignature *sig;
1359         MonoMethodBuilder *mb;
1360         MonoMethod *res;
1361         MonoClass *klass;
1362         GHashTable *cache;
1363         WrapperInfo *info;
1364         char *name;
1365         int t, pos0, pos1 = 0;
1366
1367         type = mono_type_get_underlying_type (type);
1368
1369         t = type->type;
1370
1371         if (!type->byref) {
1372                 if (type->type == MONO_TYPE_SZARRAY) {
1373                         klass = mono_defaults.array_class;
1374                 } else if (type->type == MONO_TYPE_VALUETYPE) {
1375                         klass = type->data.klass;
1376                 } else if (t == MONO_TYPE_OBJECT || t == MONO_TYPE_CLASS || t == MONO_TYPE_STRING) {
1377                         klass = mono_defaults.object_class;
1378                 } else if (t == MONO_TYPE_PTR || t == MONO_TYPE_FNPTR) {
1379                         klass = mono_defaults.int_class;
1380                 } else if (t == MONO_TYPE_GENERICINST) {
1381                         if (mono_type_generic_inst_is_valuetype (type))
1382                                 klass = mono_class_from_mono_type (type);
1383                         else
1384                                 klass = mono_defaults.object_class;
1385                 } else {
1386                         klass = mono_class_from_mono_type (type);                       
1387                 }
1388         } else {
1389                 klass = mono_defaults.int_class;
1390         }
1391
1392         cache = get_cache (&klass->image->ldfld_wrapper_cache, mono_aligned_addr_hash, NULL);
1393         if ((res = mono_marshal_find_in_cache (cache, klass)))
1394                 return res;
1395
1396         /* we add the %p pointer value of klass because class names are not unique */
1397         name = g_strdup_printf ("__ldfld_wrapper_%p_%s.%s", klass, klass->name_space, klass->name); 
1398         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_LDFLD);
1399         g_free (name);
1400
1401         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
1402         sig->params [0] = &mono_defaults.object_class->byval_arg;
1403         sig->params [1] = &mono_defaults.int_class->byval_arg;
1404         sig->params [2] = &mono_defaults.int_class->byval_arg;
1405         sig->params [3] = &mono_defaults.int_class->byval_arg;
1406         sig->ret = &klass->byval_arg;
1407
1408 #ifndef DISABLE_JIT
1409         mono_mb_emit_ldarg (mb, 0);
1410         pos0 = mono_mb_emit_proxy_check (mb, CEE_BNE_UN);
1411
1412         mono_mb_emit_ldarg (mb, 0);
1413         mono_mb_emit_ldarg (mb, 1);
1414         mono_mb_emit_ldarg (mb, 2);
1415
1416         mono_mb_emit_managed_call (mb, mono_marshal_get_ldfld_remote_wrapper (klass), NULL);
1417
1418         /*
1419         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
1420         csig->params [0] = &mono_defaults.object_class->byval_arg;
1421         csig->params [1] = &mono_defaults.int_class->byval_arg;
1422         csig->params [2] = &mono_defaults.int_class->byval_arg;
1423         csig->ret = &klass->this_arg;
1424         csig->pinvoke = 1;
1425
1426         mono_mb_emit_native_call (mb, csig, mono_load_remote_field_new);
1427         mono_marshal_emit_thread_interrupt_checkpoint (mb);
1428         */
1429
1430         if (klass->valuetype) {
1431                 mono_mb_emit_op (mb, CEE_UNBOX, klass);
1432                 pos1 = mono_mb_emit_branch (mb, CEE_BR);
1433         } else {
1434                 mono_mb_emit_byte (mb, CEE_RET);
1435         }
1436
1437         mono_mb_patch_branch (mb, pos0);
1438
1439         mono_mb_emit_ldarg (mb, 0);
1440         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1441         mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
1442         mono_mb_emit_ldarg (mb, 3);
1443         mono_mb_emit_byte (mb, CEE_ADD);
1444
1445         if (klass->valuetype)
1446                 mono_mb_patch_branch (mb, pos1);
1447
1448         switch (t) {
1449         case MONO_TYPE_I1:
1450         case MONO_TYPE_U1:
1451         case MONO_TYPE_BOOLEAN:
1452         case MONO_TYPE_CHAR:
1453         case MONO_TYPE_I2:
1454         case MONO_TYPE_U2:
1455         case MONO_TYPE_I4:
1456         case MONO_TYPE_U4:
1457         case MONO_TYPE_I8:
1458         case MONO_TYPE_U8:
1459         case MONO_TYPE_R4:
1460         case MONO_TYPE_R8:
1461         case MONO_TYPE_ARRAY:
1462         case MONO_TYPE_SZARRAY:
1463         case MONO_TYPE_OBJECT:
1464         case MONO_TYPE_CLASS:
1465         case MONO_TYPE_STRING:
1466         case MONO_TYPE_I:
1467         case MONO_TYPE_U:
1468         case MONO_TYPE_PTR:
1469         case MONO_TYPE_FNPTR:
1470                 mono_mb_emit_byte (mb, mono_type_to_ldind (type));
1471                 break;
1472         case MONO_TYPE_VALUETYPE:
1473                 g_assert (!klass->enumtype);
1474                 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
1475                 break;
1476         case MONO_TYPE_GENERICINST:
1477                 if (mono_type_generic_inst_is_valuetype (type)) {
1478                         mono_mb_emit_op (mb, CEE_LDOBJ, klass);
1479                 } else {
1480                         mono_mb_emit_byte (mb, CEE_LDIND_REF);
1481                 }
1482                 break;
1483         case MONO_TYPE_VAR:
1484         case MONO_TYPE_MVAR:
1485                 mono_mb_emit_op (mb, CEE_LDOBJ, klass);
1486                 break;
1487         default:
1488                 g_warning ("type %x not implemented", type->type);
1489                 g_assert_not_reached ();
1490         }
1491
1492         mono_mb_emit_byte (mb, CEE_RET);
1493 #endif /* DISABLE_JIT */
1494
1495         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
1496         info->d.proxy.klass = klass;
1497         res = mono_mb_create_and_cache_full (cache, klass,
1498                                                                                  mb, sig, sig->param_count + 16, info, NULL);
1499         mono_mb_free (mb);
1500         
1501         return res;
1502 }
1503
1504 /*
1505  * mono_marshal_get_ldflda_wrapper:
1506  * @type: the type of the field
1507  *
1508  * This method generates a function which can be used to load a field address
1509  * from an object. The generated function has the following signature:
1510  * gpointer ldflda_wrapper (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, int offset);
1511  */
1512 MonoMethod *
1513 mono_marshal_get_ldflda_wrapper (MonoType *type)
1514 {
1515         MonoMethodSignature *sig;
1516         MonoMethodBuilder *mb;
1517         MonoMethod *res;
1518         MonoClass *klass;
1519         GHashTable *cache;
1520         WrapperInfo *info;
1521         char *name;
1522         int t, pos0, pos1, pos2, pos3;
1523
1524         type = mono_type_get_underlying_type (type);
1525         t = type->type;
1526
1527         if (!type->byref) {
1528                 if (type->type == MONO_TYPE_SZARRAY) {
1529                         klass = mono_defaults.array_class;
1530                 } else if (type->type == MONO_TYPE_VALUETYPE) {
1531                         klass = type->data.klass;
1532                 } else if (t == MONO_TYPE_OBJECT || t == MONO_TYPE_CLASS || t == MONO_TYPE_STRING ||
1533                            t == MONO_TYPE_CLASS) { 
1534                         klass = mono_defaults.object_class;
1535                 } else if (t == MONO_TYPE_PTR || t == MONO_TYPE_FNPTR) {
1536                         klass = mono_defaults.int_class;
1537                 } else if (t == MONO_TYPE_GENERICINST) {
1538                         if (mono_type_generic_inst_is_valuetype (type))
1539                                 klass = mono_class_from_mono_type (type);
1540                         else
1541                                 klass = mono_defaults.object_class;
1542                 } else {
1543                         klass = mono_class_from_mono_type (type);                       
1544                 }
1545         } else {
1546                 klass = mono_defaults.int_class;
1547         }
1548
1549         cache = get_cache (&klass->image->ldflda_wrapper_cache, mono_aligned_addr_hash, NULL);
1550         if ((res = mono_marshal_find_in_cache (cache, klass)))
1551                 return res;
1552
1553         /* we add the %p pointer value of klass because class names are not unique */
1554         name = g_strdup_printf ("__ldflda_wrapper_%p_%s.%s", klass, klass->name_space, klass->name); 
1555         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_LDFLDA);
1556         g_free (name);
1557
1558         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
1559         sig->params [0] = &mono_defaults.object_class->byval_arg;
1560         sig->params [1] = &mono_defaults.int_class->byval_arg;
1561         sig->params [2] = &mono_defaults.int_class->byval_arg;
1562         sig->params [3] = &mono_defaults.int_class->byval_arg;
1563         sig->ret = &mono_defaults.int_class->byval_arg;
1564
1565 #ifndef DISABLE_JIT
1566         /* if typeof (this) != transparent_proxy goto pos0 */
1567         mono_mb_emit_ldarg (mb, 0);
1568         pos0 = mono_mb_emit_proxy_check (mb, CEE_BNE_UN);
1569
1570         /* if same_appdomain goto pos1 */
1571         mono_mb_emit_ldarg (mb, 0);
1572         pos1 = mono_mb_emit_xdomain_check (mb, CEE_BEQ);
1573
1574         mono_mb_emit_exception_full (mb, "System", "InvalidOperationException", "Attempt to load field address from object in another appdomain.");
1575
1576         /* same app domain */
1577         mono_mb_patch_branch (mb, pos1);
1578
1579         /* if typeof (this) != contextbound goto pos2 */
1580         mono_mb_emit_ldarg (mb, 0);
1581         pos2 = mono_mb_emit_contextbound_check (mb, CEE_BEQ);
1582
1583         /* if this->rp->context == mono_context_get goto pos3 */
1584         mono_mb_emit_ldarg (mb, 0);
1585         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoTransparentProxy, rp));
1586         mono_mb_emit_byte (mb, CEE_LDIND_REF);
1587         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoRealProxy, context));
1588         mono_mb_emit_byte (mb, CEE_LDIND_REF);
1589         mono_mb_emit_icall (mb, mono_context_get);
1590         pos3 = mono_mb_emit_branch (mb, CEE_BEQ);
1591
1592         mono_mb_emit_exception_full (mb, "System", "InvalidOperationException", "Attempt to load field address from object in another context.");
1593
1594         mono_mb_patch_branch (mb, pos2);
1595         mono_mb_patch_branch (mb, pos3);
1596
1597         /* return the address of the field from this->rp->unwrapped_server */
1598         mono_mb_emit_ldarg (mb, 0);
1599         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoTransparentProxy, rp));
1600         mono_mb_emit_byte (mb, CEE_LDIND_REF);
1601         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoRealProxy, unwrapped_server));
1602         mono_mb_emit_byte (mb, CEE_LDIND_REF);
1603         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1604         mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
1605         mono_mb_emit_ldarg (mb, 3);
1606         mono_mb_emit_byte (mb, CEE_ADD);
1607         mono_mb_emit_byte (mb, CEE_RET);
1608
1609         /* not a proxy: return the address of the field directly */
1610         mono_mb_patch_branch (mb, pos0);
1611
1612         mono_mb_emit_ldarg (mb, 0);
1613         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1614         mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
1615         mono_mb_emit_ldarg (mb, 3);
1616         mono_mb_emit_byte (mb, CEE_ADD);
1617
1618         mono_mb_emit_byte (mb, CEE_RET);
1619 #endif
1620
1621         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
1622         info->d.proxy.klass = klass;
1623         res = mono_mb_create_and_cache_full (cache, klass,
1624                                                                                  mb, sig, sig->param_count + 16,
1625                                                                                  info, NULL);
1626         mono_mb_free (mb);
1627         
1628         return res;
1629 }
1630
1631 /*
1632  * mono_marshal_get_stfld_remote_wrapper:
1633  * klass: The type of the field
1634  *
1635  *  This function generates a wrapper for calling mono_store_remote_field_new
1636  * with the appropriate signature.
1637  * Similarly to mono_marshal_get_ldfld_remote_wrapper () this doesn't depend on the
1638  * klass argument anymore.
1639  */
1640 MonoMethod *
1641 mono_marshal_get_stfld_remote_wrapper (MonoClass *klass)
1642 {
1643         MonoMethodSignature *sig, *csig;
1644         MonoMethodBuilder *mb;
1645         MonoMethod *res;
1646         static MonoMethod *cached = NULL;
1647
1648         mono_marshal_lock_internal ();
1649         if (cached) {
1650                 mono_marshal_unlock_internal ();
1651                 return cached;
1652         }
1653         mono_marshal_unlock_internal ();
1654
1655         mb = mono_mb_new_no_dup_name (mono_defaults.object_class, "__mono_store_remote_field_new_wrapper", MONO_WRAPPER_STFLD_REMOTE);
1656
1657         mb->method->save_lmf = 1;
1658
1659         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
1660         sig->params [0] = &mono_defaults.object_class->byval_arg;
1661         sig->params [1] = &mono_defaults.int_class->byval_arg;
1662         sig->params [2] = &mono_defaults.int_class->byval_arg;
1663         sig->params [3] = &mono_defaults.object_class->byval_arg;
1664         sig->ret = &mono_defaults.void_class->byval_arg;
1665
1666 #ifndef DISABLE_JIT
1667         mono_mb_emit_ldarg (mb, 0);
1668         mono_mb_emit_ldarg (mb, 1);
1669         mono_mb_emit_ldarg (mb, 2);
1670         mono_mb_emit_ldarg (mb, 3);
1671
1672         csig = mono_metadata_signature_alloc (mono_defaults.corlib, 4);
1673         csig->params [0] = &mono_defaults.object_class->byval_arg;
1674         csig->params [1] = &mono_defaults.int_class->byval_arg;
1675         csig->params [2] = &mono_defaults.int_class->byval_arg;
1676         csig->params [3] = &mono_defaults.object_class->byval_arg;
1677         csig->ret = &mono_defaults.void_class->byval_arg;
1678         csig->pinvoke = 1;
1679
1680         mono_mb_emit_native_call (mb, csig, mono_store_remote_field_new);
1681         mono_marshal_emit_thread_interrupt_checkpoint (mb);
1682
1683         mono_mb_emit_byte (mb, CEE_RET);
1684 #endif
1685
1686         mono_marshal_lock_internal ();
1687         res = cached;
1688         mono_marshal_unlock_internal ();
1689         if (!res) {
1690                 MonoMethod *newm;
1691                 newm = mono_mb_create (mb, sig, 6, NULL);
1692                 mono_marshal_lock_internal ();
1693                 res = cached;
1694                 if (!res) {
1695                         res = newm;
1696                         cached = res;
1697                         mono_marshal_unlock_internal ();
1698                 } else {
1699                         mono_marshal_unlock_internal ();
1700                         mono_free_method (newm);
1701                 }
1702         }
1703         mono_mb_free (mb);
1704         
1705         return res;
1706 }
1707
1708 /*
1709  * mono_marshal_get_stfld_wrapper:
1710  * @type: the type of the field
1711  *
1712  * This method generates a function which can be use to store a field with type
1713  * @type. The generated function has the following signature:
1714  * void stfld_wrapper (MonoObject *this_obj, MonoClass *klass, MonoClassField *field, int offset, <@type> val)
1715  */
1716 MonoMethod *
1717 mono_marshal_get_stfld_wrapper (MonoType *type)
1718 {
1719         MonoMethodSignature *sig;
1720         MonoMethodBuilder *mb;
1721         MonoMethod *res;
1722         MonoClass *klass;
1723         GHashTable *cache;
1724         WrapperInfo *info;
1725         char *name;
1726         int t, pos;
1727
1728         type = mono_type_get_underlying_type (type);
1729         t = type->type;
1730
1731         if (!type->byref) {
1732                 if (type->type == MONO_TYPE_SZARRAY) {
1733                         klass = mono_defaults.array_class;
1734                 } else if (type->type == MONO_TYPE_VALUETYPE) {
1735                         klass = type->data.klass;
1736                 } else if (t == MONO_TYPE_OBJECT || t == MONO_TYPE_CLASS || t == MONO_TYPE_STRING) {
1737                         klass = mono_defaults.object_class;
1738                 } else if (t == MONO_TYPE_PTR || t == MONO_TYPE_FNPTR) {
1739                         klass = mono_defaults.int_class;
1740                 } else if (t == MONO_TYPE_GENERICINST) {
1741                         if (mono_type_generic_inst_is_valuetype (type))
1742                                 klass = mono_class_from_mono_type (type);
1743                         else
1744                                 klass = mono_defaults.object_class;
1745                 } else {
1746                         klass = mono_class_from_mono_type (type);                       
1747                 }
1748         } else {
1749                 klass = mono_defaults.int_class;
1750         }
1751
1752         cache = get_cache (&klass->image->stfld_wrapper_cache, mono_aligned_addr_hash, NULL);
1753         if ((res = mono_marshal_find_in_cache (cache, klass)))
1754                 return res;
1755
1756         /* we add the %p pointer value of klass because class names are not unique */
1757         name = g_strdup_printf ("__stfld_wrapper_%p_%s.%s", klass, klass->name_space, klass->name); 
1758         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_STFLD);
1759         g_free (name);
1760
1761         sig = mono_metadata_signature_alloc (mono_defaults.corlib, 5);
1762         sig->params [0] = &mono_defaults.object_class->byval_arg;
1763         sig->params [1] = &mono_defaults.int_class->byval_arg;
1764         sig->params [2] = &mono_defaults.int_class->byval_arg;
1765         sig->params [3] = &mono_defaults.int_class->byval_arg;
1766         sig->params [4] = &klass->byval_arg;
1767         sig->ret = &mono_defaults.void_class->byval_arg;
1768
1769 #ifndef DISABLE_JIT
1770         mono_mb_emit_ldarg (mb, 0);
1771         pos = mono_mb_emit_proxy_check (mb, CEE_BNE_UN);
1772
1773         mono_mb_emit_ldarg (mb, 0);
1774         mono_mb_emit_ldarg (mb, 1);
1775         mono_mb_emit_ldarg (mb, 2);
1776         mono_mb_emit_ldarg (mb, 4);
1777         if (klass->valuetype)
1778                 mono_mb_emit_op (mb, CEE_BOX, klass);
1779
1780         mono_mb_emit_managed_call (mb, mono_marshal_get_stfld_remote_wrapper (klass), NULL);
1781
1782         mono_mb_emit_byte (mb, CEE_RET);
1783
1784         mono_mb_patch_branch (mb, pos);
1785
1786         mono_mb_emit_ldarg (mb, 0);
1787         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1788         mono_mb_emit_byte (mb, CEE_MONO_OBJADDR);
1789         mono_mb_emit_ldarg (mb, 3);
1790         mono_mb_emit_byte (mb, CEE_ADD);
1791         mono_mb_emit_ldarg (mb, 4);
1792
1793         switch (t) {
1794         case MONO_TYPE_I1:
1795         case MONO_TYPE_U1:
1796         case MONO_TYPE_BOOLEAN:
1797         case MONO_TYPE_CHAR:
1798         case MONO_TYPE_I2:
1799         case MONO_TYPE_U2:
1800         case MONO_TYPE_I4:
1801         case MONO_TYPE_U4:
1802         case MONO_TYPE_I8:
1803         case MONO_TYPE_U8:
1804         case MONO_TYPE_R4:
1805         case MONO_TYPE_R8:
1806         case MONO_TYPE_ARRAY:
1807         case MONO_TYPE_SZARRAY:
1808         case MONO_TYPE_OBJECT:
1809         case MONO_TYPE_CLASS:
1810         case MONO_TYPE_STRING:
1811         case MONO_TYPE_I:
1812         case MONO_TYPE_U:
1813         case MONO_TYPE_PTR:
1814         case MONO_TYPE_FNPTR:
1815                 mono_mb_emit_byte (mb, mono_type_to_stind (type));
1816                 break;
1817         case MONO_TYPE_VALUETYPE:
1818                 g_assert (!klass->enumtype);
1819                 mono_mb_emit_op (mb, CEE_STOBJ, klass);
1820                 break;
1821         case MONO_TYPE_GENERICINST:
1822         case MONO_TYPE_VAR:
1823         case MONO_TYPE_MVAR:
1824                 mono_mb_emit_op (mb, CEE_STOBJ, klass);
1825                 break;
1826         default:
1827                 g_warning ("type %x not implemented", type->type);
1828                 g_assert_not_reached ();
1829         }
1830
1831         mono_mb_emit_byte (mb, CEE_RET);
1832 #endif
1833
1834         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
1835         info->d.proxy.klass = klass;
1836         res = mono_mb_create_and_cache_full (cache, klass,
1837                                                                                  mb, sig, sig->param_count + 16,
1838                                                                                  info, NULL);
1839         mono_mb_free (mb);
1840         
1841         return res;
1842 }
1843
1844 MonoMethod *
1845 mono_marshal_get_proxy_cancast (MonoClass *klass)
1846 {
1847         static MonoMethodSignature *isint_sig = NULL;
1848         GHashTable *cache;
1849         MonoMethod *res;
1850         WrapperInfo *info;
1851         int pos_failed, pos_end;
1852         char *name, *klass_name;
1853         MonoMethod *can_cast_to;
1854         MonoMethodDesc *desc;
1855         MonoMethodBuilder *mb;
1856
1857         cache = get_cache (&klass->image->proxy_isinst_cache, mono_aligned_addr_hash, NULL);
1858         if ((res = mono_marshal_find_in_cache (cache, klass)))
1859                 return res;
1860
1861         if (!isint_sig) {
1862                 isint_sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1863                 isint_sig->params [0] = &mono_defaults.object_class->byval_arg;
1864                 isint_sig->ret = &mono_defaults.object_class->byval_arg;
1865                 isint_sig->pinvoke = 0;
1866         }
1867
1868         klass_name = mono_type_full_name (&klass->byval_arg);
1869         name = g_strdup_printf ("__proxy_isinst_wrapper_%s", klass_name); 
1870         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_PROXY_ISINST);
1871         g_free (klass_name);
1872         g_free (name);
1873         
1874         mb->method->save_lmf = 1;
1875
1876 #ifndef DISABLE_JIT
1877         /* get the real proxy from the transparent proxy*/
1878         mono_mb_emit_ldarg (mb, 0);
1879         mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoTransparentProxy, rp));
1880         mono_mb_emit_byte (mb, CEE_LDIND_REF);
1881         
1882         /* get the reflection type from the type handle */
1883         mono_mb_emit_ptr (mb, &klass->byval_arg);
1884         mono_mb_emit_icall (mb, type_from_handle);
1885         
1886         mono_mb_emit_ldarg (mb, 0);
1887         
1888         /* make the call to CanCastTo (type, ob) */
1889         desc = mono_method_desc_new ("IRemotingTypeInfo:CanCastTo", FALSE);
1890         can_cast_to = mono_method_desc_search_in_class (desc, mono_defaults.iremotingtypeinfo_class);
1891         g_assert (can_cast_to);
1892         mono_method_desc_free (desc);
1893         mono_mb_emit_op (mb, CEE_CALLVIRT, can_cast_to);
1894         
1895         pos_failed = mono_mb_emit_branch (mb, CEE_BRFALSE);
1896
1897         /* Upgrade the proxy vtable by calling: mono_upgrade_remote_class_wrapper (type, ob)*/
1898         mono_mb_emit_ptr (mb, &klass->byval_arg);
1899         mono_mb_emit_icall (mb, type_from_handle);
1900         mono_mb_emit_ldarg (mb, 0);
1901         
1902         mono_mb_emit_icall (mb, mono_upgrade_remote_class_wrapper);
1903         mono_marshal_emit_thread_interrupt_checkpoint (mb);
1904         
1905         mono_mb_emit_ldarg (mb, 0);
1906         pos_end = mono_mb_emit_branch (mb, CEE_BR);
1907         
1908         /* fail */
1909         
1910         mono_mb_patch_branch (mb, pos_failed);
1911         mono_mb_emit_byte (mb, CEE_LDNULL);
1912         
1913         /* the end */
1914         
1915         mono_mb_patch_branch (mb, pos_end);
1916         mono_mb_emit_byte (mb, CEE_RET);
1917 #endif
1918
1919         info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
1920         info->d.proxy.klass = klass;
1921         res = mono_mb_create_and_cache_full (cache, klass, mb, isint_sig, isint_sig->param_count + 16, info, NULL);
1922         mono_mb_free (mb);
1923
1924         return res;
1925 }
1926
1927 void
1928 mono_upgrade_remote_class_wrapper (MonoReflectionType *rtype, MonoTransparentProxy *tproxy)
1929 {
1930         MonoClass *klass;
1931         MonoDomain *domain = ((MonoObject*)tproxy)->vtable->domain;
1932         klass = mono_class_from_mono_type (rtype->type);
1933         mono_upgrade_remote_class (domain, (MonoObject*)tproxy, klass);
1934 }
1935
1936 #else /* DISABLE_REMOTING */
1937
1938 void
1939 mono_remoting_init (void)
1940 {
1941 }
1942
1943 #endif /* DISABLE_REMOTING */
1944
1945 /* mono_get_xdomain_marshal_type()
1946  * Returns the kind of marshalling that a type needs for cross domain calls.
1947  */
1948 static MonoXDomainMarshalType
1949 mono_get_xdomain_marshal_type (MonoType *t)
1950 {
1951         switch (t->type) {
1952         case MONO_TYPE_VOID:
1953                 g_assert_not_reached ();
1954                 break;
1955         case MONO_TYPE_U1:
1956         case MONO_TYPE_I1:
1957         case MONO_TYPE_BOOLEAN:
1958         case MONO_TYPE_U2:
1959         case MONO_TYPE_I2:
1960         case MONO_TYPE_CHAR:
1961         case MONO_TYPE_U4:
1962         case MONO_TYPE_I4:
1963         case MONO_TYPE_I8:
1964         case MONO_TYPE_U8:
1965         case MONO_TYPE_R4:
1966         case MONO_TYPE_R8:
1967                 return MONO_MARSHAL_NONE;
1968         case MONO_TYPE_STRING:
1969                 return MONO_MARSHAL_COPY;
1970         case MONO_TYPE_ARRAY:
1971         case MONO_TYPE_SZARRAY: {
1972                 MonoClass *elem_class = mono_class_from_mono_type (t)->element_class;
1973                 if (mono_get_xdomain_marshal_type (&(elem_class->byval_arg)) != MONO_MARSHAL_SERIALIZE)
1974                         return MONO_MARSHAL_COPY;
1975                 break;
1976         }
1977         default:
1978                 break;
1979         }
1980         return MONO_MARSHAL_SERIALIZE;
1981 }
1982
1983 /* mono_marshal_xdomain_copy_value
1984  * Makes a copy of "val" suitable for the current domain.
1985  */
1986 MonoObject *
1987 mono_marshal_xdomain_copy_value (MonoObject *val)
1988 {
1989         MonoError error;
1990         MonoDomain *domain;
1991         if (val == NULL) return NULL;
1992
1993         domain = mono_domain_get ();
1994
1995         switch (mono_object_class (val)->byval_arg.type) {
1996         case MONO_TYPE_VOID:
1997                 g_assert_not_reached ();
1998                 break;
1999         case MONO_TYPE_U1:
2000         case MONO_TYPE_I1:
2001         case MONO_TYPE_BOOLEAN:
2002         case MONO_TYPE_U2:
2003         case MONO_TYPE_I2:
2004         case MONO_TYPE_CHAR:
2005         case MONO_TYPE_U4:
2006         case MONO_TYPE_I4:
2007         case MONO_TYPE_I8:
2008         case MONO_TYPE_U8:
2009         case MONO_TYPE_R4:
2010         case MONO_TYPE_R8: {
2011                 return mono_value_box (domain, mono_object_class (val), ((char*)val) + sizeof(MonoObject));
2012         }
2013         case MONO_TYPE_STRING: {
2014                 MonoString *str = (MonoString *) val;
2015                 MonoObject *res = NULL;
2016                 res = (MonoObject *) mono_string_new_utf16_checked (domain, mono_string_chars (str), mono_string_length (str), &error);
2017                 mono_error_raise_exception (&error); /* FIXME don't raise here */
2018                 return res;
2019         }
2020         case MONO_TYPE_ARRAY:
2021         case MONO_TYPE_SZARRAY: {
2022                 MonoArray *acopy;
2023                 MonoXDomainMarshalType mt = mono_get_xdomain_marshal_type (&(mono_object_class (val)->element_class->byval_arg));
2024                 if (mt == MONO_MARSHAL_SERIALIZE) return NULL;
2025                 acopy = mono_array_clone_in_domain (domain, (MonoArray *) val);
2026                 if (mt == MONO_MARSHAL_COPY) {
2027                         int i, len = mono_array_length (acopy);
2028                         for (i = 0; i < len; i++) {
2029                                 MonoObject *item = (MonoObject *)mono_array_get (acopy, gpointer, i);
2030                                 mono_array_setref (acopy, i, mono_marshal_xdomain_copy_value (item));
2031                         }
2032                 }
2033                 return (MonoObject *) acopy;
2034         }
2035         default:
2036                 break;
2037         }
2038
2039         return NULL;
2040 }