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