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