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