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