2 // System.Runtime.Remoting.RemotingServices.cs
5 // Dietmar Maurer (dietmar@ximian.com)
6 // Lluis Sanchez Gual (lluis@ideary.com)
9 // (C) 2001 Ximian, Inc. http://www.ximian.com
10 // Copyright (C) 2004, 2006 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Diagnostics;
34 using System.Reflection;
35 using System.Threading;
36 using System.Collections;
37 using System.Runtime.Remoting.Messaging;
38 using System.Runtime.Remoting.Proxies;
39 using System.Runtime.Remoting.Channels;
40 using System.Runtime.Remoting.Contexts;
41 using System.Runtime.Remoting.Activation;
42 using System.Runtime.Remoting.Lifetime;
43 using System.Runtime.CompilerServices;
44 using System.Runtime.Serialization;
45 using System.Runtime.Serialization.Formatters.Binary;
47 using System.Runtime.Remoting.Services;
48 using System.Security.Permissions;
49 using System.Runtime.ConstrainedExecution;
50 using System.Runtime.Serialization.Formatters;
52 namespace System.Runtime.Remoting
54 [System.Runtime.InteropServices.ComVisible (true)]
56 public class RemotingServices
58 // Holds the identities of the objects, using uri as index
59 static Hashtable uri_hash = new Hashtable ();
61 static BinaryFormatter _serializationFormatter;
62 static BinaryFormatter _deserializationFormatter;
65 static readonly object app_id_lock = new object ();
67 static int next_id = 1;
68 const BindingFlags methodBindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
69 static readonly MethodInfo FieldSetterMethod;
70 static readonly MethodInfo FieldGetterMethod;
72 // Holds information in xdomain calls. Names are short to minimize serialized size.
75 public object d; /* call data */
76 public object c; /* call context */
79 static RemotingServices ()
81 RemotingSurrogateSelector surrogateSelector = new RemotingSurrogateSelector ();
82 StreamingContext context = new StreamingContext (StreamingContextStates.Remoting, null);
83 _serializationFormatter = new BinaryFormatter (surrogateSelector, context);
84 _deserializationFormatter = new BinaryFormatter (null, context);
85 _serializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
86 _deserializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
88 RegisterInternalChannels ();
89 CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
91 FieldSetterMethod = typeof(object).GetMethod ("FieldSetter", BindingFlags.NonPublic|BindingFlags.Instance);
92 FieldGetterMethod = typeof(object).GetMethod ("FieldGetter", BindingFlags.NonPublic|BindingFlags.Instance);
95 [MethodImplAttribute(MethodImplOptions.InternalCall)]
96 internal extern static object InternalExecute (MethodBase method, Object obj,
97 Object[] parameters, out object [] out_args);
99 // Returns the actual implementation of @method in @type.
100 [MethodImplAttribute(MethodImplOptions.InternalCall)]
101 internal extern static MethodBase GetVirtualMethod (Type type, MethodBase method);
104 public static bool IsTransparentProxy (object proxy)
106 throw new NotSupportedException ();
109 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
110 [MethodImplAttribute(MethodImplOptions.InternalCall)]
111 public extern static bool IsTransparentProxy (object proxy);
113 internal static bool ProxyCheckCast (RealProxy rp, RuntimeType castType)
115 // TODO: What should it do?
120 internal static IMethodReturnMessage InternalExecuteMessage (
121 MarshalByRefObject target, IMethodCallMessage reqMsg)
123 ReturnMessage result;
125 Type tt = target.GetType ();
127 if (reqMsg.MethodBase.DeclaringType == tt ||
128 reqMsg.MethodBase == FieldSetterMethod ||
129 reqMsg.MethodBase == FieldGetterMethod) {
130 method = reqMsg.MethodBase;
132 method = GetVirtualMethod (tt, reqMsg.MethodBase);
135 throw new RemotingException (
136 String.Format ("Cannot resolve method {0}:{1}", tt, reqMsg.MethodName));
139 if (reqMsg.MethodBase.IsGenericMethod) {
140 Type[] genericArguments = reqMsg.MethodBase.GetGenericArguments ();
141 MethodInfo gmd = ((MethodInfo)method).GetGenericMethodDefinition ();
142 method = gmd.MakeGenericMethod (genericArguments);
145 object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
150 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
152 // Collect parameters with Out flag from the request message
153 // FIXME: This can be done in the unmanaged side and will be
156 ParameterInfo[] parameters = method.GetParameters();
157 object[] returnArgs = new object [parameters.Length];
161 foreach (ParameterInfo par in parameters)
163 if (par.IsOut && !par.ParameterType.IsByRef)
164 returnArgs [n++] = reqMsg.GetArg (par.Position);
165 else if (par.ParameterType.IsByRef)
166 returnArgs [n++] = out_args [noa++];
168 returnArgs [n++] = null;
171 result = new ReturnMessage (rval, returnArgs, n, ExecutionContext.CreateLogicalCallContext (true), reqMsg);
175 result = new ReturnMessage (e, reqMsg);
178 CallContext.RestoreCallContext (oldContext);
182 public static IMethodReturnMessage ExecuteMessage (
183 MarshalByRefObject target, IMethodCallMessage reqMsg)
185 if (IsTransparentProxy(target))
187 // Message must go through all chain of sinks
188 RealProxy rp = GetRealProxy (target);
189 return (IMethodReturnMessage) rp.Invoke (reqMsg);
192 return InternalExecuteMessage (target, reqMsg);
195 [System.Runtime.InteropServices.ComVisible (true)]
196 public static object Connect (Type classToProxy, string url)
198 ObjRef objRef = new ObjRef (classToProxy, url, null);
199 return GetRemoteObject (objRef, classToProxy);
202 [System.Runtime.InteropServices.ComVisible (true)]
203 public static object Connect (Type classToProxy, string url, object data)
205 ObjRef objRef = new ObjRef (classToProxy, url, data);
206 return GetRemoteObject (objRef, classToProxy);
209 public static bool Disconnect (MarshalByRefObject obj)
211 if (obj == null) throw new ArgumentNullException ("obj");
213 ServerIdentity identity;
215 if (IsTransparentProxy (obj))
217 // CBOs are always accessed through a proxy, even in the server, so
218 // for server CBOs it is ok to disconnect a proxy
220 RealProxy proxy = GetRealProxy(obj);
221 if (proxy.GetProxiedType().IsContextful && (proxy.ObjectIdentity is ServerIdentity))
222 identity = proxy.ObjectIdentity as ServerIdentity;
224 throw new ArgumentException ("The obj parameter is a proxy.");
227 identity = obj.ObjectIdentity;
228 obj.ObjectIdentity = null;
231 if (identity == null || !identity.IsConnected)
235 LifetimeServices.StopTrackingLifetime (identity);
236 DisposeIdentity (identity);
237 TrackingServices.NotifyDisconnectedObject (obj);
242 public static Type GetServerTypeForUri (string URI)
244 ServerIdentity ident = GetIdentityForUri (URI) as ServerIdentity;
245 if (ident == null) return null;
246 return ident.ObjectType;
249 public static string GetObjectUri (MarshalByRefObject obj)
251 Identity ident = GetObjectIdentity(obj);
252 if (ident is ClientIdentity) return ((ClientIdentity)ident).TargetUri;
253 else if (ident != null) return ident.ObjectUri;
257 public static object Unmarshal (ObjRef objectRef)
259 return Unmarshal (objectRef, true);
262 public static object Unmarshal (ObjRef objectRef, bool fRefine)
264 Type classToProxy = fRefine ? objectRef.ServerType : typeof (MarshalByRefObject);
265 if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
267 if (objectRef.IsReferenceToWellKnow) {
268 object obj = GetRemoteObject (objectRef, classToProxy);
269 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
276 if (classToProxy.IsContextful) {
277 // Look for a ProxyAttribute
278 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute), true);
280 obj = att.CreateProxy (objectRef, classToProxy, null, null).GetTransparentProxy();
281 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
285 obj = GetProxyForRemoteObject (objectRef, classToProxy);
286 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
291 public static ObjRef Marshal (MarshalByRefObject Obj)
293 return Marshal (Obj, null, null);
296 public static ObjRef Marshal (MarshalByRefObject Obj, string URI)
298 return Marshal (Obj, URI, null);
301 public static ObjRef Marshal (MarshalByRefObject Obj, string ObjURI, Type RequestedType)
303 if (IsTransparentProxy (Obj))
305 RealProxy proxy = RemotingServices.GetRealProxy (Obj);
306 Identity identity = proxy.ObjectIdentity;
308 if (identity != null)
310 if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
312 // Unregistered local contextbound object. Register now.
313 ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
314 if (ObjURI == null) ObjURI = NewUri();
315 cboundIdentity.ObjectUri = ObjURI;
316 RegisterServerIdentity (cboundIdentity);
317 cboundIdentity.StartTrackingLifetime ((ILease)Obj.InitializeLifetimeService());
318 return cboundIdentity.CreateObjRef (RequestedType);
320 else if (ObjURI != null)
321 throw new RemotingException ("It is not possible marshal a proxy of a remote object.");
323 ObjRef or = proxy.ObjectIdentity.CreateObjRef (RequestedType);
324 TrackingServices.NotifyMarshaledObject (Obj, or);
329 if (RequestedType == null) RequestedType = Obj.GetType ();
333 if (Obj.ObjectIdentity == null)
336 CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
341 ClientActivatedIdentity identity = GetIdentityForUri ("/" + ObjURI) as ClientActivatedIdentity;
342 if (identity == null || Obj != identity.GetServerObject())
343 CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
348 if (IsTransparentProxy (Obj))
349 oref = RemotingServices.GetRealProxy (Obj).ObjectIdentity.CreateObjRef (RequestedType);
351 oref = Obj.CreateObjRef (RequestedType);
353 TrackingServices.NotifyMarshaledObject (Obj, oref);
357 static string NewUri ()
359 if (app_id == null) {
362 app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
366 int n = Interlocked.Increment (ref next_id);
367 return app_id + Environment.TickCount.ToString("x") + "_" + n + ".rem";
370 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
371 public static RealProxy GetRealProxy (object proxy)
373 if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy.");
374 return (RealProxy)((TransparentProxy)proxy)._rp;
377 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
379 Type type = Type.GetType (msg.TypeName);
381 throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
383 return GetMethodBaseFromName (type, msg.MethodName, (Type[]) msg.MethodSignature);
386 internal static MethodBase GetMethodBaseFromName (Type type, string methodName, Type[] signature)
388 if (type.IsInterface) {
389 return FindInterfaceMethod (type, methodName, signature);
392 MethodBase method = null;
393 if (signature == null)
394 method = type.GetMethod (methodName, methodBindings);
396 method = type.GetMethod (methodName, methodBindings, null, (Type[]) signature, null);
401 if (methodName == "FieldSetter")
402 return FieldSetterMethod;
404 if (methodName == "FieldGetter")
405 return FieldGetterMethod;
407 if (signature == null)
408 return type.GetConstructor (methodBindings, null, Type.EmptyTypes, null);
410 return type.GetConstructor (methodBindings, null, signature, null);
414 static MethodBase FindInterfaceMethod (Type type, string methodName, Type[] signature)
416 MethodBase method = null;
418 if (signature == null)
419 method = type.GetMethod (methodName, methodBindings);
421 method = type.GetMethod (methodName, methodBindings, null, signature, null);
423 if (method != null) return method;
425 foreach (Type t in type.GetInterfaces ()) {
426 method = FindInterfaceMethod (t, methodName, signature);
427 if (method != null) return method;
433 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
435 if (obj == null) throw new ArgumentNullException ("obj");
437 ObjRef oref = Marshal ((MarshalByRefObject)obj);
438 oref.GetObjectData (info, context);
441 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
443 Identity ident = GetObjectIdentity(obj);
444 if (ident == null) return null;
445 else return ident.CreateObjRef(null);
448 public static object GetLifetimeService (MarshalByRefObject obj)
450 if (obj == null) return null;
451 return obj.GetLifetimeService ();
454 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
456 if (IsTransparentProxy(obj))
457 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
459 throw new ArgumentException ("obj must be a proxy.","obj");
463 [Conditional ("REMOTING_PERF")]
464 [Obsolete ("It existed for only internal use in .NET and unimplemented in mono")]
465 public static void LogRemotingStage (int stage)
467 throw new NotImplementedException ();
470 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
472 // It seems that this it what MS returns.
476 public static bool IsMethodOverloaded(IMethodMessage msg)
478 const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
479 MonoType type = (MonoType) msg.MethodBase.DeclaringType;
480 return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1;
483 public static bool IsObjectOutOfAppDomain(object tp)
485 MarshalByRefObject mbr = tp as MarshalByRefObject;
490 // TODO: use internal call for better performance
491 Identity ident = GetObjectIdentity (mbr);
492 return ident is ClientIdentity;
495 public static bool IsObjectOutOfContext(object tp)
497 MarshalByRefObject mbr = tp as MarshalByRefObject;
502 // TODO: use internal call for better performance
503 Identity ident = GetObjectIdentity (mbr);
504 if (ident == null) return false;
506 ServerIdentity sident = ident as ServerIdentity;
507 if (sident != null) return sident.Context != System.Threading.Thread.CurrentContext;
511 public static bool IsOneWay(MethodBase method)
513 return method.IsDefined (typeof (OneWayAttribute), false);
516 internal static bool IsAsyncMessage(IMessage msg)
518 if (! (msg is MonoMethodMessage)) return false;
519 else if (((MonoMethodMessage)msg).IsAsync) return true;
520 else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
524 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
526 if (IsTransparentProxy (obj)) {
527 RealProxy proxy = RemotingServices.GetRealProxy(obj);
528 Identity identity = proxy.ObjectIdentity;
530 if (identity != null && !(identity is ServerIdentity) && !proxy.GetProxiedType().IsContextful)
531 throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
537 #region Internal Methods
539 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
541 if (entry.ContextAttributes != null || activationAttributes != null)
543 ArrayList props = new ArrayList ();
544 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
545 if (activationAttributes != null) props.AddRange (activationAttributes);
546 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
549 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
552 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
554 string activationUrl = url;
555 if (!activationUrl.EndsWith ("/"))
556 activationUrl += "/";
557 activationUrl += "RemoteActivationService.rem";
560 GetClientChannelSinkChain (activationUrl, null, out objectUri);
562 RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
563 return proxy.GetTransparentProxy();
566 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
568 return Connect (entry.ObjectType, entry.ObjectUrl, null);
571 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
573 if (type.IsContextful)
575 // Look for a ProxyAttribute
576 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
578 return att.CreateInstance (type);
580 RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
581 return proxy.GetTransparentProxy();
584 internal static object CreateClientProxyForComInterop (Type type)
586 Mono.Interop.ComInteropProxy proxy = Mono.Interop.ComInteropProxy.CreateProxy (type);
587 return proxy.GetTransparentProxy ();
590 internal static Identity GetIdentityForUri (string uri)
592 string normUri = GetNormalizedUri (uri);
595 Identity i = (Identity) uri_hash [normUri];
598 normUri = RemoveAppNameFromUri (uri);
600 i = (Identity) uri_hash [normUri];
608 // If the specified uri starts with the application name,
609 // RemoveAppNameFromUri returns the uri w/out the leading
610 // application name, otherwise it returns null.
612 // Assumes that the uri is not normalized.
614 static string RemoveAppNameFromUri (string uri)
616 string name = RemotingConfiguration.ApplicationName;
617 if (name == null) return null;
618 name = "/" + name + "/";
619 if (uri.StartsWith (name))
620 return uri.Substring (name.Length);
625 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
627 if (IsTransparentProxy(obj))
628 return GetRealProxy (obj).ObjectIdentity;
630 return obj.ObjectIdentity;
633 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
635 // This method looks for an identity for the given url.
636 // If an identity is not found, it creates the identity and
637 // assigns it a proxy to the remote object.
639 // Creates the client sink chain for the given url or channelData.
640 // It will also get the object uri from the url.
642 object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
645 IMessageSink sink = GetClientChannelSinkChain (objRef.URI, channelData, out objectUri);
647 if (objectUri == null) objectUri = objRef.URI;
652 string uri = GetNormalizedUri (objRef.URI);
654 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
655 if (identity != null)
657 // Object already registered
658 clientProxy = identity.ClientProxy;
659 if (clientProxy != null) return identity;
661 // The proxy has just been GCed, so its identity cannot
662 // be reused. Just dispose it.
663 DisposeIdentity (identity);
666 // Creates an identity and a proxy for the remote object
668 identity = new ClientIdentity (objectUri, objRef);
669 identity.ChannelSink = sink;
671 // Registers the identity
672 uri_hash [uri] = identity;
673 if (proxyType != null)
675 RemotingProxy proxy = new RemotingProxy (proxyType, identity);
676 CrossAppDomainSink cds = sink as CrossAppDomainSink;
678 proxy.SetTargetDomain (cds.TargetDomainId);
680 clientProxy = proxy.GetTransparentProxy();
681 identity.ClientProxy = (MarshalByRefObject) clientProxy;
687 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
689 IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
694 string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url);
695 throw new RemotingException (msg);
699 string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url);
700 throw new RemotingException (msg);
706 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
708 ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
709 identity.ChannelSink = ChannelServices.CrossContextChannel;
713 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
715 ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
716 identity.AttachServerObject (realObject, Context.DefaultContext);
717 RegisterServerIdentity (identity);
718 identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
722 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
724 ServerIdentity identity;
726 if (mode == WellKnownObjectMode.SingleCall)
727 identity = new SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
729 identity = new SingletonIdentity(objectUri, Context.DefaultContext, objectType);
731 RegisterServerIdentity (identity);
735 private static void RegisterServerIdentity(ServerIdentity identity)
739 if (uri_hash.ContainsKey (identity.ObjectUri))
740 throw new RemotingException ("Uri already in use: " + identity.ObjectUri + ".");
742 uri_hash[identity.ObjectUri] = identity;
746 internal static object GetProxyForRemoteObject (ObjRef objref, Type classToProxy)
748 ClientActivatedIdentity identity = GetIdentityForUri (objref.URI) as ClientActivatedIdentity;
749 if (identity != null) return identity.GetServerObject ();
750 else return GetRemoteObject (objref, classToProxy);
753 internal static object GetRemoteObject(ObjRef objRef, Type proxyType)
756 GetOrCreateClientIdentity (objRef, proxyType, out proxy);
760 // This method is called by the runtime
761 internal static object GetServerObject (string uri)
763 ClientActivatedIdentity identity = GetIdentityForUri (uri) as ClientActivatedIdentity;
764 if (identity == null) throw new RemotingException ("Server for uri '" + uri + "' not found");
765 return identity.GetServerObject ();
768 // This method is called by the runtime
769 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
770 internal static byte[] SerializeCallData (object obj)
772 LogicalCallContext ctx = ExecutionContext.CreateLogicalCallContext (false);
774 CACD cad = new CACD ();
780 if (obj == null) return null;
781 MemoryStream ms = new MemoryStream ();
782 _serializationFormatter.Serialize (ms, obj);
783 return ms.ToArray ();
786 // This method is called by the runtime
787 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
788 internal static object DeserializeCallData (byte[] array)
790 if (array == null) return null;
792 MemoryStream ms = new MemoryStream (array);
793 object obj = _deserializationFormatter.Deserialize (ms);
796 CACD cad = (CACD) obj;
798 CallContext.UpdateCurrentLogicalCallContext ((LogicalCallContext) cad.c);
803 // This method is called by the runtime
804 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
805 internal static byte[] SerializeExceptionData (Exception ex)
812 MemoryStream ms = new MemoryStream ();
813 _serializationFormatter.Serialize (ms, ex);
814 return ms.ToArray ();
816 catch (Exception e) {
817 if (e is ThreadAbortException) {
818 Thread.ResetAbort ();
822 else if (retry == 2) {
823 ex = new Exception ();
824 ex.SetMessage (e.Message);
825 ex.SetStackTrace (e.StackTrace);
836 catch (Exception tex)
838 byte[] data = SerializeExceptionData (tex);
839 Thread.ResetAbort ();
844 internal static object GetDomainProxy(AppDomain domain)
848 Context currentContext = Thread.CurrentContext;
852 data = (byte[])AppDomain.InvokeInDomain (domain, typeof (AppDomain).GetMethod ("GetMarshalledDomainObjRef", BindingFlags.Instance|BindingFlags.NonPublic), domain, null);
856 AppDomain.InternalSetContext (currentContext);
859 byte[] data_copy = new byte [data.Length];
860 data.CopyTo (data_copy, 0);
861 MemoryStream stream = new MemoryStream (data_copy);
862 ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
863 return (AppDomain) RemotingServices.Unmarshal(appref);
866 private static void RegisterInternalChannels()
868 CrossAppDomainChannel.RegisterCrossAppDomainChannel();
871 internal static void DisposeIdentity (Identity ident)
875 if (!ident.Disposed) {
876 ClientIdentity clientId = ident as ClientIdentity;
877 if (clientId != null)
878 uri_hash.Remove (GetNormalizedUri (clientId.TargetUri));
880 uri_hash.Remove (ident.ObjectUri);
882 ident.Disposed = true;
887 internal static Identity GetMessageTargetIdentity (IMessage msg)
889 // Returns the identity where the message is sent
891 if (msg is IInternalMessage)
892 return ((IInternalMessage)msg).TargetIdentity;
896 string uri = GetNormalizedUri (((IMethodMessage)msg).Uri);
897 return uri_hash [uri] as ServerIdentity;
901 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
903 if (msg is IInternalMessage)
904 ((IInternalMessage)msg).TargetIdentity = ident;
907 internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
909 if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
911 Array alocal = (Array) local;
912 if (alocal.Rank == 1)
914 Array.Copy ((Array) remote, alocal, alocal.Length);
925 static string GetNormalizedUri (string uri)
927 if (uri.StartsWith ("/")) return uri.Substring (1);