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