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