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