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