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