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