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