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