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