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