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