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