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