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