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