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