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