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 throw new NotImplementedException ("ProxyCheckCast");
119 internal static IMethodReturnMessage InternalExecuteMessage (
120 MarshalByRefObject target, IMethodCallMessage reqMsg)
122 ReturnMessage result;
124 Type tt = target.GetType ();
126 if (reqMsg.MethodBase.DeclaringType == tt ||
127 reqMsg.MethodBase == FieldSetterMethod ||
128 reqMsg.MethodBase == FieldGetterMethod) {
129 method = reqMsg.MethodBase;
131 method = GetVirtualMethod (tt, reqMsg.MethodBase);
134 throw new RemotingException (
135 String.Format ("Cannot resolve method {0}:{1}", tt, reqMsg.MethodName));
138 if (reqMsg.MethodBase.IsGenericMethod) {
139 Type[] genericArguments = reqMsg.MethodBase.GetGenericArguments ();
140 MethodInfo gmd = ((MethodInfo)method).GetGenericMethodDefinition ();
141 method = gmd.MakeGenericMethod (genericArguments);
144 object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
149 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
151 // Collect parameters with Out flag from the request message
152 // FIXME: This can be done in the unmanaged side and will be
155 ParameterInfo[] parameters = method.GetParameters();
156 object[] returnArgs = new object [parameters.Length];
160 foreach (ParameterInfo par in parameters)
162 if (par.IsOut && !par.ParameterType.IsByRef)
163 returnArgs [n++] = reqMsg.GetArg (par.Position);
164 else if (par.ParameterType.IsByRef)
165 returnArgs [n++] = out_args [noa++];
167 returnArgs [n++] = null;
170 result = new ReturnMessage (rval, returnArgs, n, ExecutionContext.CreateLogicalCallContext (true), reqMsg);
174 result = new ReturnMessage (e, reqMsg);
177 CallContext.RestoreCallContext (oldContext);
181 public static IMethodReturnMessage ExecuteMessage (
182 MarshalByRefObject target, IMethodCallMessage reqMsg)
184 if (IsTransparentProxy(target))
186 // Message must go through all chain of sinks
187 RealProxy rp = GetRealProxy (target);
188 return (IMethodReturnMessage) rp.Invoke (reqMsg);
191 return InternalExecuteMessage (target, reqMsg);
194 [System.Runtime.InteropServices.ComVisible (true)]
195 public static object Connect (Type classToProxy, string url)
197 ObjRef objRef = new ObjRef (classToProxy, url, null);
198 return GetRemoteObject (objRef, classToProxy);
201 [System.Runtime.InteropServices.ComVisible (true)]
202 public static object Connect (Type classToProxy, string url, object data)
204 ObjRef objRef = new ObjRef (classToProxy, url, data);
205 return GetRemoteObject (objRef, classToProxy);
208 public static bool Disconnect (MarshalByRefObject obj)
210 if (obj == null) throw new ArgumentNullException ("obj");
212 ServerIdentity identity;
214 if (IsTransparentProxy (obj))
216 // CBOs are always accessed through a proxy, even in the server, so
217 // for server CBOs it is ok to disconnect a proxy
219 RealProxy proxy = GetRealProxy(obj);
220 if (proxy.GetProxiedType().IsContextful && (proxy.ObjectIdentity is ServerIdentity))
221 identity = proxy.ObjectIdentity as ServerIdentity;
223 throw new ArgumentException ("The obj parameter is a proxy.");
226 identity = obj.ObjectIdentity;
227 obj.ObjectIdentity = null;
230 if (identity == null || !identity.IsConnected)
234 LifetimeServices.StopTrackingLifetime (identity);
235 DisposeIdentity (identity);
236 TrackingServices.NotifyDisconnectedObject (obj);
241 public static Type GetServerTypeForUri (string URI)
243 ServerIdentity ident = GetIdentityForUri (URI) as ServerIdentity;
244 if (ident == null) return null;
245 return ident.ObjectType;
248 public static string GetObjectUri (MarshalByRefObject obj)
250 Identity ident = GetObjectIdentity(obj);
251 if (ident is ClientIdentity) return ((ClientIdentity)ident).TargetUri;
252 else if (ident != null) return ident.ObjectUri;
256 public static object Unmarshal (ObjRef objectRef)
258 return Unmarshal (objectRef, true);
261 public static object Unmarshal (ObjRef objectRef, bool fRefine)
263 Type classToProxy = fRefine ? objectRef.ServerType : typeof (MarshalByRefObject);
264 if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
266 if (objectRef.IsReferenceToWellKnow) {
267 object obj = GetRemoteObject (objectRef, classToProxy);
268 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
275 if (classToProxy.IsContextful) {
276 // Look for a ProxyAttribute
277 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute), true);
279 obj = att.CreateProxy (objectRef, classToProxy, null, null).GetTransparentProxy();
280 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
284 obj = GetProxyForRemoteObject (objectRef, classToProxy);
285 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
290 public static ObjRef Marshal (MarshalByRefObject Obj)
292 return Marshal (Obj, null, null);
295 public static ObjRef Marshal (MarshalByRefObject Obj, string URI)
297 return Marshal (Obj, URI, null);
300 public static ObjRef Marshal (MarshalByRefObject Obj, string ObjURI, Type RequestedType)
302 if (IsTransparentProxy (Obj))
304 RealProxy proxy = RemotingServices.GetRealProxy (Obj);
305 Identity identity = proxy.ObjectIdentity;
307 if (identity != null)
309 if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
311 // Unregistered local contextbound object. Register now.
312 ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
313 if (ObjURI == null) ObjURI = NewUri();
314 cboundIdentity.ObjectUri = ObjURI;
315 RegisterServerIdentity (cboundIdentity);
316 cboundIdentity.StartTrackingLifetime ((ILease)Obj.InitializeLifetimeService());
317 return cboundIdentity.CreateObjRef (RequestedType);
319 else if (ObjURI != null)
320 throw new RemotingException ("It is not possible marshal a proxy of a remote object.");
322 ObjRef or = proxy.ObjectIdentity.CreateObjRef (RequestedType);
323 TrackingServices.NotifyMarshaledObject (Obj, or);
328 if (RequestedType == null) RequestedType = Obj.GetType ();
332 if (Obj.ObjectIdentity == null)
335 CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
340 ClientActivatedIdentity identity = GetIdentityForUri ("/" + ObjURI) as ClientActivatedIdentity;
341 if (identity == null || Obj != identity.GetServerObject())
342 CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
347 if (IsTransparentProxy (Obj))
348 oref = RemotingServices.GetRealProxy (Obj).ObjectIdentity.CreateObjRef (RequestedType);
350 oref = Obj.CreateObjRef (RequestedType);
352 TrackingServices.NotifyMarshaledObject (Obj, oref);
356 static string NewUri ()
358 if (app_id == null) {
361 app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
365 int n = Interlocked.Increment (ref next_id);
366 return app_id + Environment.TickCount.ToString("x") + "_" + n + ".rem";
369 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
370 public static RealProxy GetRealProxy (object proxy)
372 if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy.");
373 return (RealProxy)((TransparentProxy)proxy)._rp;
376 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
378 Type type = Type.GetType (msg.TypeName);
380 throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
382 return GetMethodBaseFromName (type, msg.MethodName, (Type[]) msg.MethodSignature);
385 internal static MethodBase GetMethodBaseFromName (Type type, string methodName, Type[] signature)
387 if (type.IsInterface) {
388 return FindInterfaceMethod (type, methodName, signature);
391 MethodBase method = null;
392 if (signature == null)
393 method = type.GetMethod (methodName, methodBindings);
395 method = type.GetMethod (methodName, methodBindings, null, (Type[]) signature, null);
400 if (methodName == "FieldSetter")
401 return FieldSetterMethod;
403 if (methodName == "FieldGetter")
404 return FieldGetterMethod;
406 if (signature == null)
407 return type.GetConstructor (methodBindings, null, Type.EmptyTypes, null);
409 return type.GetConstructor (methodBindings, null, signature, null);
413 static MethodBase FindInterfaceMethod (Type type, string methodName, Type[] signature)
415 MethodBase method = null;
417 if (signature == null)
418 method = type.GetMethod (methodName, methodBindings);
420 method = type.GetMethod (methodName, methodBindings, null, signature, null);
422 if (method != null) return method;
424 foreach (Type t in type.GetInterfaces ()) {
425 method = FindInterfaceMethod (t, methodName, signature);
426 if (method != null) return method;
432 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
434 if (obj == null) throw new ArgumentNullException ("obj");
436 ObjRef oref = Marshal ((MarshalByRefObject)obj);
437 oref.GetObjectData (info, context);
440 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
442 Identity ident = GetObjectIdentity(obj);
443 if (ident == null) return null;
444 else return ident.CreateObjRef(null);
447 public static object GetLifetimeService (MarshalByRefObject obj)
449 if (obj == null) return null;
450 return obj.GetLifetimeService ();
453 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
455 if (IsTransparentProxy(obj))
456 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
458 throw new ArgumentException ("obj must be a proxy.","obj");
462 [Conditional ("REMOTING_PERF")]
463 [Obsolete ("It existed for only internal use in .NET and unimplemented in mono")]
464 public static void LogRemotingStage (int stage)
466 throw new NotImplementedException ();
469 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
471 // It seems that this it what MS returns.
475 public static bool IsMethodOverloaded(IMethodMessage msg)
477 const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
478 MonoType type = (MonoType) msg.MethodBase.DeclaringType;
479 return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1;
482 public static bool IsObjectOutOfAppDomain(object tp)
484 MarshalByRefObject mbr = tp as MarshalByRefObject;
489 // TODO: use internal call for better performance
490 Identity ident = GetObjectIdentity (mbr);
491 return ident is ClientIdentity;
494 public static bool IsObjectOutOfContext(object tp)
496 MarshalByRefObject mbr = tp as MarshalByRefObject;
501 // TODO: use internal call for better performance
502 Identity ident = GetObjectIdentity (mbr);
503 if (ident == null) return false;
505 ServerIdentity sident = ident as ServerIdentity;
506 if (sident != null) return sident.Context != System.Threading.Thread.CurrentContext;
510 public static bool IsOneWay(MethodBase method)
512 return method.IsDefined (typeof (OneWayAttribute), false);
515 internal static bool IsAsyncMessage(IMessage msg)
517 if (! (msg is MonoMethodMessage)) return false;
518 else if (((MonoMethodMessage)msg).IsAsync) return true;
519 else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
523 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
525 if (IsTransparentProxy (obj)) {
526 RealProxy proxy = RemotingServices.GetRealProxy(obj);
527 Identity identity = proxy.ObjectIdentity;
529 if (identity != null && !(identity is ServerIdentity) && !proxy.GetProxiedType().IsContextful)
530 throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
536 #region Internal Methods
538 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
540 if (entry.ContextAttributes != null || activationAttributes != null)
542 ArrayList props = new ArrayList ();
543 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
544 if (activationAttributes != null) props.AddRange (activationAttributes);
545 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
548 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
551 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
553 string activationUrl = url;
554 if (!activationUrl.EndsWith ("/"))
555 activationUrl += "/";
556 activationUrl += "RemoteActivationService.rem";
559 GetClientChannelSinkChain (activationUrl, null, out objectUri);
561 RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
562 return proxy.GetTransparentProxy();
565 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
567 return Connect (entry.ObjectType, entry.ObjectUrl, null);
570 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
572 if (type.IsContextful)
574 // Look for a ProxyAttribute
575 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
577 return att.CreateInstance (type);
579 RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
580 return proxy.GetTransparentProxy();
583 internal static object CreateClientProxyForComInterop (Type type)
585 Mono.Interop.ComInteropProxy proxy = Mono.Interop.ComInteropProxy.CreateProxy (type);
586 return proxy.GetTransparentProxy ();
589 internal static Identity GetIdentityForUri (string uri)
591 string normUri = GetNormalizedUri (uri);
594 Identity i = (Identity) uri_hash [normUri];
597 normUri = RemoveAppNameFromUri (uri);
599 i = (Identity) uri_hash [normUri];
607 // If the specified uri starts with the application name,
608 // RemoveAppNameFromUri returns the uri w/out the leading
609 // application name, otherwise it returns null.
611 // Assumes that the uri is not normalized.
613 static string RemoveAppNameFromUri (string uri)
615 string name = RemotingConfiguration.ApplicationName;
616 if (name == null) return null;
617 name = "/" + name + "/";
618 if (uri.StartsWith (name))
619 return uri.Substring (name.Length);
624 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
626 if (IsTransparentProxy(obj))
627 return GetRealProxy (obj).ObjectIdentity;
629 return obj.ObjectIdentity;
632 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
634 // This method looks for an identity for the given url.
635 // If an identity is not found, it creates the identity and
636 // assigns it a proxy to the remote object.
638 // Creates the client sink chain for the given url or channelData.
639 // It will also get the object uri from the url.
641 object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
644 IMessageSink sink = GetClientChannelSinkChain (objRef.URI, channelData, out objectUri);
646 if (objectUri == null) objectUri = objRef.URI;
651 string uri = GetNormalizedUri (objRef.URI);
653 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
654 if (identity != null)
656 // Object already registered
657 clientProxy = identity.ClientProxy;
658 if (clientProxy != null) return identity;
660 // The proxy has just been GCed, so its identity cannot
661 // be reused. Just dispose it.
662 DisposeIdentity (identity);
665 // Creates an identity and a proxy for the remote object
667 identity = new ClientIdentity (objectUri, objRef);
668 identity.ChannelSink = sink;
670 // Registers the identity
671 uri_hash [uri] = identity;
672 if (proxyType != null)
674 RemotingProxy proxy = new RemotingProxy (proxyType, identity);
675 CrossAppDomainSink cds = sink as CrossAppDomainSink;
677 proxy.SetTargetDomain (cds.TargetDomainId);
679 clientProxy = proxy.GetTransparentProxy();
680 identity.ClientProxy = (MarshalByRefObject) clientProxy;
686 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
688 IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
693 string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url);
694 throw new RemotingException (msg);
698 string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url);
699 throw new RemotingException (msg);
705 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
707 ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
708 identity.ChannelSink = ChannelServices.CrossContextChannel;
712 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
714 ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
715 identity.AttachServerObject (realObject, Context.DefaultContext);
716 RegisterServerIdentity (identity);
717 identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
721 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
723 ServerIdentity identity;
725 if (mode == WellKnownObjectMode.SingleCall)
726 identity = new SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
728 identity = new SingletonIdentity(objectUri, Context.DefaultContext, objectType);
730 RegisterServerIdentity (identity);
734 private static void RegisterServerIdentity(ServerIdentity identity)
738 if (uri_hash.ContainsKey (identity.ObjectUri))
739 throw new RemotingException ("Uri already in use: " + identity.ObjectUri + ".");
741 uri_hash[identity.ObjectUri] = identity;
745 internal static object GetProxyForRemoteObject (ObjRef objref, Type classToProxy)
747 ClientActivatedIdentity identity = GetIdentityForUri (objref.URI) as ClientActivatedIdentity;
748 if (identity != null) return identity.GetServerObject ();
749 else return GetRemoteObject (objref, classToProxy);
752 internal static object GetRemoteObject(ObjRef objRef, Type proxyType)
755 GetOrCreateClientIdentity (objRef, proxyType, out proxy);
759 // This method is called by the runtime
760 internal static object GetServerObject (string uri)
762 ClientActivatedIdentity identity = GetIdentityForUri (uri) as ClientActivatedIdentity;
763 if (identity == null) throw new RemotingException ("Server for uri '" + uri + "' not found");
764 return identity.GetServerObject ();
767 // This method is called by the runtime
768 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
769 internal static byte[] SerializeCallData (object obj)
771 LogicalCallContext ctx = ExecutionContext.CreateLogicalCallContext (false);
773 CACD cad = new CACD ();
779 if (obj == null) return null;
780 MemoryStream ms = new MemoryStream ();
781 _serializationFormatter.Serialize (ms, obj);
782 return ms.ToArray ();
785 // This method is called by the runtime
786 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
787 internal static object DeserializeCallData (byte[] array)
789 if (array == null) return null;
791 MemoryStream ms = new MemoryStream (array);
792 object obj = _deserializationFormatter.Deserialize (ms);
795 CACD cad = (CACD) obj;
797 CallContext.UpdateCurrentLogicalCallContext ((LogicalCallContext) cad.c);
802 // This method is called by the runtime
803 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
804 internal static byte[] SerializeExceptionData (Exception ex)
811 MemoryStream ms = new MemoryStream ();
812 _serializationFormatter.Serialize (ms, ex);
813 return ms.ToArray ();
815 catch (Exception e) {
816 if (e is ThreadAbortException) {
817 Thread.ResetAbort ();
821 else if (retry == 2) {
822 ex = new Exception ();
823 ex.SetMessage (e.Message);
824 ex.SetStackTrace (e.StackTrace);
835 catch (Exception tex)
837 byte[] data = SerializeExceptionData (tex);
838 Thread.ResetAbort ();
843 internal static object GetDomainProxy(AppDomain domain)
847 Context currentContext = Thread.CurrentContext;
851 data = (byte[])AppDomain.InvokeInDomain (domain, typeof (AppDomain).GetMethod ("GetMarshalledDomainObjRef", BindingFlags.Instance|BindingFlags.NonPublic), domain, null);
855 AppDomain.InternalSetContext (currentContext);
858 byte[] data_copy = new byte [data.Length];
859 data.CopyTo (data_copy, 0);
860 MemoryStream stream = new MemoryStream (data_copy);
861 ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
862 return (AppDomain) RemotingServices.Unmarshal(appref);
865 private static void RegisterInternalChannels()
867 CrossAppDomainChannel.RegisterCrossAppDomainChannel();
870 internal static void DisposeIdentity (Identity ident)
874 if (!ident.Disposed) {
875 ClientIdentity clientId = ident as ClientIdentity;
876 if (clientId != null)
877 uri_hash.Remove (GetNormalizedUri (clientId.TargetUri));
879 uri_hash.Remove (ident.ObjectUri);
881 ident.Disposed = true;
886 internal static Identity GetMessageTargetIdentity (IMessage msg)
888 // Returns the identity where the message is sent
890 if (msg is IInternalMessage)
891 return ((IInternalMessage)msg).TargetIdentity;
895 string uri = GetNormalizedUri (((IMethodMessage)msg).Uri);
896 return uri_hash [uri] as ServerIdentity;
900 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
902 if (msg is IInternalMessage)
903 ((IInternalMessage)msg).TargetIdentity = ident;
906 internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
908 if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
910 Array alocal = (Array) local;
911 if (alocal.Rank == 1)
913 Array.Copy ((Array) remote, alocal, alocal.Length);
924 static string GetNormalizedUri (string uri)
926 if (uri.StartsWith ("/")) return uri.Substring (1);