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;
51 using System.Runtime.ConstrainedExecution;
52 using System.Runtime.Serialization.Formatters;
55 namespace System.Runtime.Remoting
58 [System.Runtime.InteropServices.ComVisible (true)]
60 public sealed class RemotingServices
62 // Holds the identities of the objects, using uri as index
63 static Hashtable uri_hash = new Hashtable ();
65 static BinaryFormatter _serializationFormatter;
66 static BinaryFormatter _deserializationFormatter;
68 internal static string app_id;
69 static int next_id = 1;
70 static readonly BindingFlags methodBindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
71 static readonly MethodInfo FieldSetterMethod;
72 static readonly MethodInfo FieldGetterMethod;
74 // Holds information in xdomain calls. Names are short to minimize serialized size.
77 public object d; /* call data */
78 public object c; /* call context */
81 static RemotingServices ()
83 RemotingSurrogateSelector surrogateSelector = new RemotingSurrogateSelector ();
84 StreamingContext context = new StreamingContext (StreamingContextStates.Remoting, null);
85 _serializationFormatter = new BinaryFormatter (surrogateSelector, context);
86 _deserializationFormatter = new BinaryFormatter (null, context);
88 _serializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
89 _deserializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
92 RegisterInternalChannels ();
93 app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
94 CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
96 FieldSetterMethod = typeof(object).GetMethod ("FieldSetter", BindingFlags.NonPublic|BindingFlags.Instance);
97 FieldGetterMethod = typeof(object).GetMethod ("FieldGetter", BindingFlags.NonPublic|BindingFlags.Instance);
100 private RemotingServices () {}
102 [MethodImplAttribute(MethodImplOptions.InternalCall)]
103 internal extern static object InternalExecute (MethodBase method, Object obj,
104 Object[] parameters, out object [] out_args);
106 // Returns the actual implementation of @method in @type.
107 [MethodImplAttribute(MethodImplOptions.InternalCall)]
108 internal extern static MethodBase GetVirtualMethod (Type type, MethodBase method);
111 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
113 [MethodImplAttribute(MethodImplOptions.InternalCall)]
114 public extern static bool IsTransparentProxy (object proxy);
116 internal static IMethodReturnMessage InternalExecuteMessage (
117 MarshalByRefObject target, IMethodCallMessage reqMsg)
119 ReturnMessage result;
121 Type tt = target.GetType ();
123 if (reqMsg.MethodBase.DeclaringType == tt ||
124 reqMsg.MethodBase == FieldSetterMethod ||
125 reqMsg.MethodBase == FieldGetterMethod) {
126 method = reqMsg.MethodBase;
128 method = GetVirtualMethod (tt, reqMsg.MethodBase);
131 throw new RemotingException (
132 String.Format ("Cannot resolve method {0}:{1}", tt, reqMsg.MethodName));
136 if (reqMsg.MethodBase.IsGenericMethod) {
137 Type[] genericArguments = reqMsg.MethodBase.GetGenericArguments ();
138 method = ((MethodInfo)method).MakeGenericMethod (genericArguments);
142 object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
147 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
149 // Collect parameters with Out flag from the request message
150 // FIXME: This can be done in the unmanaged side and will be
153 ParameterInfo[] parameters = method.GetParameters();
154 object[] returnArgs = new object [parameters.Length];
158 foreach (ParameterInfo par in parameters)
160 if (par.IsOut && !par.ParameterType.IsByRef)
161 returnArgs [n++] = reqMsg.GetArg (par.Position);
162 else if (par.ParameterType.IsByRef)
163 returnArgs [n++] = out_args [noa++];
165 returnArgs [n++] = null;
168 result = new ReturnMessage (rval, returnArgs, n, CallContext.CreateLogicalCallContext (true), reqMsg);
172 result = new ReturnMessage (e, reqMsg);
175 CallContext.RestoreCallContext (oldContext);
179 public static IMethodReturnMessage ExecuteMessage (
180 MarshalByRefObject target, IMethodCallMessage reqMsg)
182 if (IsTransparentProxy(target))
184 // Message must go through all chain of sinks
185 RealProxy rp = GetRealProxy (target);
186 return (IMethodReturnMessage) rp.Invoke (reqMsg);
189 return InternalExecuteMessage (target, reqMsg);
193 [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);
202 [System.Runtime.InteropServices.ComVisible (true)]
204 public static object Connect (Type classToProxy, string url, object data)
206 ObjRef objRef = new ObjRef (classToProxy, url, data);
207 return GetRemoteObject (objRef, classToProxy);
210 public static bool Disconnect (MarshalByRefObject obj)
212 if (obj == null) throw new ArgumentNullException ("obj");
214 ServerIdentity identity;
216 if (IsTransparentProxy (obj))
218 // CBOs are always accessed through a proxy, even in the server, so
219 // for server CBOs it is ok to disconnect a proxy
221 RealProxy proxy = GetRealProxy(obj);
222 if (proxy.GetProxiedType().IsContextful && (proxy.ObjectIdentity is ServerIdentity))
223 identity = proxy.ObjectIdentity as ServerIdentity;
225 throw new ArgumentException ("The obj parameter is a proxy.");
228 identity = obj.ObjectIdentity;
229 obj.ObjectIdentity = null;
232 if (identity == null || !identity.IsConnected)
236 LifetimeServices.StopTrackingLifetime (identity);
237 DisposeIdentity (identity);
238 TrackingServices.NotifyDisconnectedObject (obj);
243 public static Type GetServerTypeForUri (string URI)
245 ServerIdentity ident = GetIdentityForUri (URI) as ServerIdentity;
246 if (ident == null) return null;
247 return ident.ObjectType;
250 public static string GetObjectUri (MarshalByRefObject obj)
252 Identity ident = GetObjectIdentity(obj);
253 if (ident is ClientIdentity) return ((ClientIdentity)ident).TargetUri;
254 else if (ident != null) return ident.ObjectUri;
258 public static object Unmarshal (ObjRef objectRef)
260 return Unmarshal (objectRef, true);
263 public static object Unmarshal (ObjRef objectRef, bool fRefine)
265 Type classToProxy = fRefine ? objectRef.ServerType : typeof (MarshalByRefObject);
266 if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
268 if (objectRef.IsReferenceToWellKnow) {
269 object obj = GetRemoteObject (objectRef, classToProxy);
270 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
277 if (classToProxy.IsContextful) {
278 // Look for a ProxyAttribute
279 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute), true);
281 obj = att.CreateProxy (objectRef, classToProxy, null, null).GetTransparentProxy();
282 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
286 obj = GetProxyForRemoteObject (objectRef, classToProxy);
287 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
292 public static ObjRef Marshal (MarshalByRefObject Obj)
294 return Marshal (Obj, null, null);
297 public static ObjRef Marshal (MarshalByRefObject Obj, string URI)
299 return Marshal (Obj, URI, null);
302 public static ObjRef Marshal (MarshalByRefObject Obj, string ObjURI, Type RequestedType)
304 if (IsTransparentProxy (Obj))
306 RealProxy proxy = RemotingServices.GetRealProxy (Obj);
307 Identity identity = proxy.ObjectIdentity;
309 if (identity != null)
311 if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
313 // Unregistered local contextbound object. Register now.
314 ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
315 if (ObjURI == null) ObjURI = NewUri();
316 cboundIdentity.ObjectUri = ObjURI;
317 RegisterServerIdentity (cboundIdentity);
318 cboundIdentity.StartTrackingLifetime ((ILease)Obj.InitializeLifetimeService());
319 return cboundIdentity.CreateObjRef (RequestedType);
321 else if (ObjURI != null)
322 throw new RemotingException ("It is not possible marshal a proxy of a remote object.");
324 ObjRef or = proxy.ObjectIdentity.CreateObjRef (RequestedType);
325 TrackingServices.NotifyMarshaledObject (Obj, or);
330 if (RequestedType == null) RequestedType = Obj.GetType ();
334 if (Obj.ObjectIdentity == null)
337 CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
342 ClientActivatedIdentity identity = GetIdentityForUri ("/" + ObjURI) as ClientActivatedIdentity;
343 if (identity == null || Obj != identity.GetServerObject())
344 CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
349 if (IsTransparentProxy (Obj))
350 oref = RemotingServices.GetRealProxy (Obj).ObjectIdentity.CreateObjRef (RequestedType);
352 oref = Obj.CreateObjRef (RequestedType);
354 TrackingServices.NotifyMarshaledObject (Obj, oref);
358 static string NewUri ()
360 int n = Interlocked.Increment (ref next_id);
361 return app_id + Environment.TickCount.ToString("x") + "_" + n + ".rem";
365 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
367 public static RealProxy GetRealProxy (object proxy)
369 if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy.");
370 return (RealProxy)((TransparentProxy)proxy)._rp;
373 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
375 Type type = Type.GetType (msg.TypeName);
377 throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
379 return GetMethodBaseFromName (type, msg.MethodName, (Type[]) msg.MethodSignature);
382 internal static MethodBase GetMethodBaseFromName (Type type, string methodName, Type[] signature)
384 if (type.IsInterface) {
385 return FindInterfaceMethod (type, methodName, signature);
388 MethodBase method = null;
389 if (signature == null)
390 method = type.GetMethod (methodName, methodBindings);
392 method = type.GetMethod (methodName, methodBindings, null, (Type[]) signature, null);
397 if (methodName == "FieldSetter")
398 return FieldSetterMethod;
400 if (methodName == "FieldGetter")
401 return FieldGetterMethod;
403 if (signature == null)
404 return type.GetConstructor (methodBindings, null, Type.EmptyTypes, null);
406 return type.GetConstructor (methodBindings, null, signature, null);
410 static MethodBase FindInterfaceMethod (Type type, string methodName, Type[] signature)
412 MethodBase method = null;
414 if (signature == null)
415 method = type.GetMethod (methodName, methodBindings);
417 method = type.GetMethod (methodName, methodBindings, null, signature, null);
419 if (method != null) return method;
421 foreach (Type t in type.GetInterfaces ()) {
422 method = FindInterfaceMethod (t, methodName, signature);
423 if (method != null) return method;
429 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
431 if (obj == null) throw new ArgumentNullException ("obj");
433 ObjRef oref = Marshal ((MarshalByRefObject)obj);
434 oref.GetObjectData (info, context);
437 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
439 Identity ident = GetObjectIdentity(obj);
440 if (ident == null) return null;
441 else return ident.CreateObjRef(null);
444 public static object GetLifetimeService (MarshalByRefObject obj)
446 if (obj == null) return null;
447 return obj.GetLifetimeService ();
450 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
452 if (IsTransparentProxy(obj))
453 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
455 throw new ArgumentException ("obj must be a proxy.","obj");
459 [Conditional ("REMOTING_PERF")]
461 [Obsolete ("It existed for only internal use in .NET and unimplemented in mono")]
463 public static void LogRemotingStage (int stage)
465 throw new NotImplementedException ();
468 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
470 // It seems that this it what MS returns.
474 public static bool IsMethodOverloaded(IMethodMessage msg)
476 const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
477 MonoType type = (MonoType) msg.MethodBase.DeclaringType;
478 return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1;
481 public static bool IsObjectOutOfAppDomain(object tp)
483 MarshalByRefObject mbr = tp as MarshalByRefObject;
488 // TODO: use internal call for better performance
489 Identity ident = GetObjectIdentity (mbr);
490 return ident is ClientIdentity;
493 public static bool IsObjectOutOfContext(object tp)
495 MarshalByRefObject mbr = tp as MarshalByRefObject;
500 // TODO: use internal call for better performance
501 Identity ident = GetObjectIdentity (mbr);
502 if (ident == null) return false;
504 ServerIdentity sident = ident as ServerIdentity;
505 if (sident != null) return sident.Context != System.Threading.Thread.CurrentContext;
509 public static bool IsOneWay(MethodBase method)
511 return method.IsDefined (typeof (OneWayAttribute), false);
514 internal static bool IsAsyncMessage(IMessage msg)
516 if (! (msg is MonoMethodMessage)) return false;
517 else if (((MonoMethodMessage)msg).IsAsync) return true;
518 else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
522 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
524 if (IsTransparentProxy (obj)) {
525 RealProxy proxy = RemotingServices.GetRealProxy(obj);
526 Identity identity = proxy.ObjectIdentity;
528 if (identity != null && !(identity is ServerIdentity) && !proxy.GetProxiedType().IsContextful)
529 throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
535 #region Internal Methods
537 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
539 if (entry.ContextAttributes != null || activationAttributes != null)
541 ArrayList props = new ArrayList ();
542 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
543 if (activationAttributes != null) props.AddRange (activationAttributes);
544 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
547 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
550 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
552 string activationUrl = url;
553 if (!activationUrl.EndsWith ("/"))
554 activationUrl += "/";
555 activationUrl += "RemoteActivationService.rem";
558 GetClientChannelSinkChain (activationUrl, null, out objectUri);
560 RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
561 return proxy.GetTransparentProxy();
564 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
566 return Connect (entry.ObjectType, entry.ObjectUrl, null);
569 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
571 if (type.IsContextful)
573 // Look for a ProxyAttribute
574 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
576 return att.CreateInstance (type);
578 RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
579 return proxy.GetTransparentProxy();
582 internal static object CreateClientProxyForComInterop (Type type)
584 Mono.Interop.ComInteropProxy proxy = new Mono.Interop.ComInteropProxy (type);
585 return proxy.GetTransparentProxy ();
588 internal static Identity GetIdentityForUri (string uri)
590 string normUri = GetNormalizedUri (uri);
593 Identity i = (Identity) uri_hash [normUri];
596 normUri = RemoveAppNameFromUri (uri);
598 i = (Identity) uri_hash [normUri];
606 // If the specified uri starts with the application name,
607 // RemoveAppNameFromUri returns the uri w/out the leading
608 // application name, otherwise it returns null.
610 // Assumes that the uri is not normalized.
612 static string RemoveAppNameFromUri (string uri)
614 string name = RemotingConfiguration.ApplicationName;
615 if (name == null) return null;
616 name = "/" + name + "/";
617 if (uri.StartsWith (name))
618 return uri.Substring (name.Length);
623 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
625 if (IsTransparentProxy(obj))
626 return GetRealProxy (obj).ObjectIdentity;
628 return obj.ObjectIdentity;
631 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
633 // This method looks for an identity for the given url.
634 // If an identity is not found, it creates the identity and
635 // assigns it a proxy to the remote object.
637 // Creates the client sink chain for the given url or channelData.
638 // It will also get the object uri from the url.
640 object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
643 IMessageSink sink = GetClientChannelSinkChain (objRef.URI, channelData, out objectUri);
645 if (objectUri == null) objectUri = objRef.URI;
650 string uri = GetNormalizedUri (objRef.URI);
652 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
653 if (identity != null)
655 // Object already registered
656 clientProxy = identity.ClientProxy;
657 if (clientProxy != null) return identity;
659 // The proxy has just been GCed, so its identity cannot
660 // be reused. Just dispose it.
661 DisposeIdentity (identity);
664 // Creates an identity and a proxy for the remote object
666 identity = new ClientIdentity (objectUri, objRef);
667 identity.ChannelSink = sink;
669 // Registers the identity
670 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;
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 = CallContext.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.UpdateCurrentCallContext ((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);