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