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