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