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)]
60 public 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;
69 static readonly object app_id_lock = new object ();
71 static int next_id = 1;
72 const BindingFlags methodBindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
73 static readonly MethodInfo FieldSetterMethod;
74 static readonly MethodInfo FieldGetterMethod;
76 // Holds information in xdomain calls. Names are short to minimize serialized size.
79 public object d; /* call data */
80 public object c; /* call context */
83 static RemotingServices ()
85 RemotingSurrogateSelector surrogateSelector = new RemotingSurrogateSelector ();
86 StreamingContext context = new StreamingContext (StreamingContextStates.Remoting, null);
87 _serializationFormatter = new BinaryFormatter (surrogateSelector, context);
88 _deserializationFormatter = new BinaryFormatter (null, context);
89 _serializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
90 _deserializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
92 RegisterInternalChannels ();
93 CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
95 FieldSetterMethod = typeof(object).GetMethod ("FieldSetter", BindingFlags.NonPublic|BindingFlags.Instance);
96 FieldGetterMethod = typeof(object).GetMethod ("FieldGetter", BindingFlags.NonPublic|BindingFlags.Instance);
99 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 public static bool IsTransparentProxy (object proxy)
113 throw new NotSupportedException ();
116 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
117 [MethodImplAttribute(MethodImplOptions.InternalCall)]
118 public extern static bool IsTransparentProxy (object proxy);
121 internal static IMethodReturnMessage InternalExecuteMessage (
122 MarshalByRefObject target, IMethodCallMessage reqMsg)
124 ReturnMessage result;
126 Type tt = target.GetType ();
128 if (reqMsg.MethodBase.DeclaringType == tt ||
129 reqMsg.MethodBase == FieldSetterMethod ||
130 reqMsg.MethodBase == FieldGetterMethod) {
131 method = reqMsg.MethodBase;
133 method = GetVirtualMethod (tt, reqMsg.MethodBase);
136 throw new RemotingException (
137 String.Format ("Cannot resolve method {0}:{1}", tt, reqMsg.MethodName));
140 if (reqMsg.MethodBase.IsGenericMethod) {
141 Type[] genericArguments = reqMsg.MethodBase.GetGenericArguments ();
142 MethodInfo gmd = ((MethodInfo)method).GetGenericMethodDefinition ();
143 method = gmd.MakeGenericMethod (genericArguments);
146 object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
151 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
153 // Collect parameters with Out flag from the request message
154 // FIXME: This can be done in the unmanaged side and will be
157 ParameterInfo[] parameters = method.GetParameters();
158 object[] returnArgs = new object [parameters.Length];
162 foreach (ParameterInfo par in parameters)
164 if (par.IsOut && !par.ParameterType.IsByRef)
165 returnArgs [n++] = reqMsg.GetArg (par.Position);
166 else if (par.ParameterType.IsByRef)
167 returnArgs [n++] = out_args [noa++];
169 returnArgs [n++] = null;
172 result = new ReturnMessage (rval, returnArgs, n, CallContext.CreateLogicalCallContext (true), reqMsg);
176 result = new ReturnMessage (e, reqMsg);
179 CallContext.RestoreCallContext (oldContext);
183 public static IMethodReturnMessage ExecuteMessage (
184 MarshalByRefObject target, IMethodCallMessage reqMsg)
186 if (IsTransparentProxy(target))
188 // Message must go through all chain of sinks
189 RealProxy rp = GetRealProxy (target);
190 return (IMethodReturnMessage) rp.Invoke (reqMsg);
193 return InternalExecuteMessage (target, reqMsg);
196 [System.Runtime.InteropServices.ComVisible (true)]
197 public static object Connect (Type classToProxy, string url)
199 ObjRef objRef = new ObjRef (classToProxy, url, null);
200 return GetRemoteObject (objRef, classToProxy);
203 [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 if (app_id == null) {
363 app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
367 int n = Interlocked.Increment (ref next_id);
368 return app_id + Environment.TickCount.ToString("x") + "_" + n + ".rem";
371 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
372 public static RealProxy GetRealProxy (object proxy)
374 if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy.");
375 return (RealProxy)((TransparentProxy)proxy)._rp;
378 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
380 Type type = Type.GetType (msg.TypeName);
382 throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
384 return GetMethodBaseFromName (type, msg.MethodName, (Type[]) msg.MethodSignature);
387 internal static MethodBase GetMethodBaseFromName (Type type, string methodName, Type[] signature)
389 if (type.IsInterface) {
390 return FindInterfaceMethod (type, methodName, signature);
393 MethodBase method = null;
394 if (signature == null)
395 method = type.GetMethod (methodName, methodBindings);
397 method = type.GetMethod (methodName, methodBindings, null, (Type[]) signature, null);
402 if (methodName == "FieldSetter")
403 return FieldSetterMethod;
405 if (methodName == "FieldGetter")
406 return FieldGetterMethod;
408 if (signature == null)
409 return type.GetConstructor (methodBindings, null, Type.EmptyTypes, null);
411 return type.GetConstructor (methodBindings, null, signature, null);
415 static MethodBase FindInterfaceMethod (Type type, string methodName, Type[] signature)
417 MethodBase method = null;
419 if (signature == null)
420 method = type.GetMethod (methodName, methodBindings);
422 method = type.GetMethod (methodName, methodBindings, null, signature, null);
424 if (method != null) return method;
426 foreach (Type t in type.GetInterfaces ()) {
427 method = FindInterfaceMethod (t, methodName, signature);
428 if (method != null) return method;
434 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
436 if (obj == null) throw new ArgumentNullException ("obj");
438 ObjRef oref = Marshal ((MarshalByRefObject)obj);
439 oref.GetObjectData (info, context);
442 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
444 Identity ident = GetObjectIdentity(obj);
445 if (ident == null) return null;
446 else return ident.CreateObjRef(null);
449 public static object GetLifetimeService (MarshalByRefObject obj)
451 if (obj == null) return null;
452 return obj.GetLifetimeService ();
455 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
457 if (IsTransparentProxy(obj))
458 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
460 throw new ArgumentException ("obj must be a proxy.","obj");
464 [Conditional ("REMOTING_PERF")]
465 [Obsolete ("It existed for only internal use in .NET and unimplemented in mono")]
466 public static void LogRemotingStage (int stage)
468 throw new NotImplementedException ();
471 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
473 // It seems that this it what MS returns.
477 public static bool IsMethodOverloaded(IMethodMessage msg)
479 const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
480 MonoType type = (MonoType) msg.MethodBase.DeclaringType;
481 return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1;
484 public static bool IsObjectOutOfAppDomain(object tp)
486 MarshalByRefObject mbr = tp as MarshalByRefObject;
491 // TODO: use internal call for better performance
492 Identity ident = GetObjectIdentity (mbr);
493 return ident is ClientIdentity;
496 public static bool IsObjectOutOfContext(object tp)
498 MarshalByRefObject mbr = tp as MarshalByRefObject;
503 // TODO: use internal call for better performance
504 Identity ident = GetObjectIdentity (mbr);
505 if (ident == null) return false;
507 ServerIdentity sident = ident as ServerIdentity;
508 if (sident != null) return sident.Context != System.Threading.Thread.CurrentContext;
512 public static bool IsOneWay(MethodBase method)
514 return method.IsDefined (typeof (OneWayAttribute), false);
517 internal static bool IsAsyncMessage(IMessage msg)
519 if (! (msg is MonoMethodMessage)) return false;
520 else if (((MonoMethodMessage)msg).IsAsync) return true;
521 else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
525 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
527 if (IsTransparentProxy (obj)) {
528 RealProxy proxy = RemotingServices.GetRealProxy(obj);
529 Identity identity = proxy.ObjectIdentity;
531 if (identity != null && !(identity is ServerIdentity) && !proxy.GetProxiedType().IsContextful)
532 throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
538 #region Internal Methods
540 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
542 if (entry.ContextAttributes != null || activationAttributes != null)
544 ArrayList props = new ArrayList ();
545 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
546 if (activationAttributes != null) props.AddRange (activationAttributes);
547 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
550 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
553 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
555 string activationUrl = url;
556 if (!activationUrl.EndsWith ("/"))
557 activationUrl += "/";
558 activationUrl += "RemoteActivationService.rem";
561 GetClientChannelSinkChain (activationUrl, null, out objectUri);
563 RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
564 return proxy.GetTransparentProxy();
567 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
569 return Connect (entry.ObjectType, entry.ObjectUrl, null);
572 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
574 if (type.IsContextful)
576 // Look for a ProxyAttribute
577 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
579 return att.CreateInstance (type);
581 RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
582 return proxy.GetTransparentProxy();
585 internal static object CreateClientProxyForComInterop (Type type)
587 Mono.Interop.ComInteropProxy proxy = Mono.Interop.ComInteropProxy.CreateProxy (type);
588 return proxy.GetTransparentProxy ();
591 internal static Identity GetIdentityForUri (string uri)
593 string normUri = GetNormalizedUri (uri);
596 Identity i = (Identity) uri_hash [normUri];
599 normUri = RemoveAppNameFromUri (uri);
601 i = (Identity) uri_hash [normUri];
609 // If the specified uri starts with the application name,
610 // RemoveAppNameFromUri returns the uri w/out the leading
611 // application name, otherwise it returns null.
613 // Assumes that the uri is not normalized.
615 static string RemoveAppNameFromUri (string uri)
617 string name = RemotingConfiguration.ApplicationName;
618 if (name == null) return null;
619 name = "/" + name + "/";
620 if (uri.StartsWith (name))
621 return uri.Substring (name.Length);
626 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
628 if (IsTransparentProxy(obj))
629 return GetRealProxy (obj).ObjectIdentity;
631 return obj.ObjectIdentity;
634 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
636 // This method looks for an identity for the given url.
637 // If an identity is not found, it creates the identity and
638 // assigns it a proxy to the remote object.
640 // Creates the client sink chain for the given url or channelData.
641 // It will also get the object uri from the url.
643 object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
646 IMessageSink sink = GetClientChannelSinkChain (objRef.URI, channelData, out objectUri);
648 if (objectUri == null) objectUri = objRef.URI;
653 string uri = GetNormalizedUri (objRef.URI);
655 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
656 if (identity != null)
658 // Object already registered
659 clientProxy = identity.ClientProxy;
660 if (clientProxy != null) return identity;
662 // The proxy has just been GCed, so its identity cannot
663 // be reused. Just dispose it.
664 DisposeIdentity (identity);
667 // Creates an identity and a proxy for the remote object
669 identity = new ClientIdentity (objectUri, objRef);
670 identity.ChannelSink = sink;
672 // Registers the identity
673 uri_hash [uri] = identity;
674 if (proxyType != null)
676 RemotingProxy proxy = new RemotingProxy (proxyType, identity);
677 CrossAppDomainSink cds = sink as CrossAppDomainSink;
679 proxy.SetTargetDomain (cds.TargetDomainId);
681 clientProxy = proxy.GetTransparentProxy();
682 identity.ClientProxy = (MarshalByRefObject) clientProxy;
688 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
690 IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
695 string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url);
696 throw new RemotingException (msg);
700 string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url);
701 throw new RemotingException (msg);
707 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
709 ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
710 identity.ChannelSink = ChannelServices.CrossContextChannel;
714 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
716 ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
717 identity.AttachServerObject (realObject, Context.DefaultContext);
718 RegisterServerIdentity (identity);
719 identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
723 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
725 ServerIdentity identity;
727 if (mode == WellKnownObjectMode.SingleCall)
728 identity = new SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
730 identity = new SingletonIdentity(objectUri, Context.DefaultContext, objectType);
732 RegisterServerIdentity (identity);
736 private static void RegisterServerIdentity(ServerIdentity identity)
740 if (uri_hash.ContainsKey (identity.ObjectUri))
741 throw new RemotingException ("Uri already in use: " + identity.ObjectUri + ".");
743 uri_hash[identity.ObjectUri] = identity;
747 internal static object GetProxyForRemoteObject (ObjRef objref, Type classToProxy)
749 ClientActivatedIdentity identity = GetIdentityForUri (objref.URI) as ClientActivatedIdentity;
750 if (identity != null) return identity.GetServerObject ();
751 else return GetRemoteObject (objref, classToProxy);
754 internal static object GetRemoteObject(ObjRef objRef, Type proxyType)
757 GetOrCreateClientIdentity (objRef, proxyType, out proxy);
761 // This method is called by the runtime
762 internal static object GetServerObject (string uri)
764 ClientActivatedIdentity identity = GetIdentityForUri (uri) as ClientActivatedIdentity;
765 if (identity == null) throw new RemotingException ("Server for uri '" + uri + "' not found");
766 return identity.GetServerObject ();
769 // This method is called by the runtime
770 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
771 internal static byte[] SerializeCallData (object obj)
773 LogicalCallContext ctx = CallContext.CreateLogicalCallContext (false);
775 CACD cad = new CACD ();
781 if (obj == null) return null;
782 MemoryStream ms = new MemoryStream ();
783 _serializationFormatter.Serialize (ms, obj);
784 return ms.ToArray ();
787 // This method is called by the runtime
788 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
789 internal static object DeserializeCallData (byte[] array)
791 if (array == null) return null;
793 MemoryStream ms = new MemoryStream (array);
794 object obj = _deserializationFormatter.Deserialize (ms);
797 CACD cad = (CACD) obj;
799 CallContext.UpdateCurrentCallContext ((LogicalCallContext) cad.c);
804 // This method is called by the runtime
805 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
806 internal static byte[] SerializeExceptionData (Exception ex)
813 MemoryStream ms = new MemoryStream ();
814 _serializationFormatter.Serialize (ms, ex);
815 return ms.ToArray ();
817 catch (Exception e) {
818 if (e is ThreadAbortException) {
819 Thread.ResetAbort ();
823 else if (retry == 2) {
824 ex = new Exception ();
825 ex.SetMessage (e.Message);
826 ex.SetStackTrace (e.StackTrace);
837 catch (Exception tex)
839 byte[] data = SerializeExceptionData (tex);
840 Thread.ResetAbort ();
845 internal static object GetDomainProxy(AppDomain domain)
849 Context currentContext = Thread.CurrentContext;
853 data = (byte[])AppDomain.InvokeInDomain (domain, typeof (AppDomain).GetMethod ("GetMarshalledDomainObjRef", BindingFlags.Instance|BindingFlags.NonPublic), domain, null);
857 AppDomain.InternalSetContext (currentContext);
860 byte[] data_copy = new byte [data.Length];
861 data.CopyTo (data_copy, 0);
862 MemoryStream stream = new MemoryStream (data_copy);
863 ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
864 return (AppDomain) RemotingServices.Unmarshal(appref);
867 private static void RegisterInternalChannels()
869 CrossAppDomainChannel.RegisterCrossAppDomainChannel();
872 internal static void DisposeIdentity (Identity ident)
876 if (!ident.Disposed) {
877 ClientIdentity clientId = ident as ClientIdentity;
878 if (clientId != null)
879 uri_hash.Remove (GetNormalizedUri (clientId.TargetUri));
881 uri_hash.Remove (ident.ObjectUri);
883 ident.Disposed = true;
888 internal static Identity GetMessageTargetIdentity (IMessage msg)
890 // Returns the identity where the message is sent
892 if (msg is IInternalMessage)
893 return ((IInternalMessage)msg).TargetIdentity;
897 string uri = GetNormalizedUri (((IMethodMessage)msg).Uri);
898 return uri_hash [uri] as ServerIdentity;
902 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
904 if (msg is IInternalMessage)
905 ((IInternalMessage)msg).TargetIdentity = ident;
908 internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
910 if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
912 Array alocal = (Array) local;
913 if (alocal.Rank == 1)
915 Array.Copy ((Array) remote, alocal, alocal.Length);
926 static string GetNormalizedUri (string uri)
928 if (uri.StartsWith ("/")) return uri.Substring (1);