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)]
55 public sealed class RemotingServices
57 // Holds the identities of the objects, using uri as index
58 static Hashtable uri_hash = new Hashtable ();
60 static BinaryFormatter _serializationFormatter;
61 static BinaryFormatter _deserializationFormatter;
64 static readonly object app_id_lock = new object ();
66 static int next_id = 1;
67 const BindingFlags methodBindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
68 static readonly MethodInfo FieldSetterMethod;
69 static readonly MethodInfo FieldGetterMethod;
71 // Holds information in xdomain calls. Names are short to minimize serialized size.
74 public object d; /* call data */
75 public object c; /* call context */
78 static RemotingServices ()
80 RemotingSurrogateSelector surrogateSelector = new RemotingSurrogateSelector ();
81 StreamingContext context = new StreamingContext (StreamingContextStates.Remoting, null);
82 _serializationFormatter = new BinaryFormatter (surrogateSelector, context);
83 _deserializationFormatter = new BinaryFormatter (null, context);
84 _serializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
85 _deserializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
87 RegisterInternalChannels ();
88 CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
90 FieldSetterMethod = typeof(object).GetMethod ("FieldSetter", BindingFlags.NonPublic|BindingFlags.Instance);
91 FieldGetterMethod = typeof(object).GetMethod ("FieldGetter", BindingFlags.NonPublic|BindingFlags.Instance);
94 private RemotingServices () {}
96 [MethodImplAttribute(MethodImplOptions.InternalCall)]
97 internal extern static object InternalExecute (MethodBase method, Object obj,
98 Object[] parameters, out object [] out_args);
100 // Returns the actual implementation of @method in @type.
101 [MethodImplAttribute(MethodImplOptions.InternalCall)]
102 internal extern static MethodBase GetVirtualMethod (Type type, MethodBase method);
104 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
105 [MethodImplAttribute(MethodImplOptions.InternalCall)]
106 public extern static bool IsTransparentProxy (object proxy);
108 internal static IMethodReturnMessage InternalExecuteMessage (
109 MarshalByRefObject target, IMethodCallMessage reqMsg)
111 ReturnMessage result;
113 Type tt = target.GetType ();
115 if (reqMsg.MethodBase.DeclaringType == tt ||
116 reqMsg.MethodBase == FieldSetterMethod ||
117 reqMsg.MethodBase == FieldGetterMethod) {
118 method = reqMsg.MethodBase;
120 method = GetVirtualMethod (tt, reqMsg.MethodBase);
123 throw new RemotingException (
124 String.Format ("Cannot resolve method {0}:{1}", tt, reqMsg.MethodName));
127 if (reqMsg.MethodBase.IsGenericMethod) {
128 Type[] genericArguments = reqMsg.MethodBase.GetGenericArguments ();
129 method = ((MethodInfo)method).MakeGenericMethod (genericArguments);
132 object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
137 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
139 // Collect parameters with Out flag from the request message
140 // FIXME: This can be done in the unmanaged side and will be
143 ParameterInfo[] parameters = method.GetParameters();
144 object[] returnArgs = new object [parameters.Length];
148 foreach (ParameterInfo par in parameters)
150 if (par.IsOut && !par.ParameterType.IsByRef)
151 returnArgs [n++] = reqMsg.GetArg (par.Position);
152 else if (par.ParameterType.IsByRef)
153 returnArgs [n++] = out_args [noa++];
155 returnArgs [n++] = null;
158 result = new ReturnMessage (rval, returnArgs, n, CallContext.CreateLogicalCallContext (true), reqMsg);
162 result = new ReturnMessage (e, reqMsg);
165 CallContext.RestoreCallContext (oldContext);
169 public static IMethodReturnMessage ExecuteMessage (
170 MarshalByRefObject target, IMethodCallMessage reqMsg)
172 if (IsTransparentProxy(target))
174 // Message must go through all chain of sinks
175 RealProxy rp = GetRealProxy (target);
176 return (IMethodReturnMessage) rp.Invoke (reqMsg);
179 return InternalExecuteMessage (target, reqMsg);
182 [System.Runtime.InteropServices.ComVisible (true)]
183 public static object Connect (Type classToProxy, string url)
185 ObjRef objRef = new ObjRef (classToProxy, url, null);
186 return GetRemoteObject (objRef, classToProxy);
189 [System.Runtime.InteropServices.ComVisible (true)]
190 public static object Connect (Type classToProxy, string url, object data)
192 ObjRef objRef = new ObjRef (classToProxy, url, data);
193 return GetRemoteObject (objRef, classToProxy);
196 public static bool Disconnect (MarshalByRefObject obj)
198 if (obj == null) throw new ArgumentNullException ("obj");
200 ServerIdentity identity;
202 if (IsTransparentProxy (obj))
204 // CBOs are always accessed through a proxy, even in the server, so
205 // for server CBOs it is ok to disconnect a proxy
207 RealProxy proxy = GetRealProxy(obj);
208 if (proxy.GetProxiedType().IsContextful && (proxy.ObjectIdentity is ServerIdentity))
209 identity = proxy.ObjectIdentity as ServerIdentity;
211 throw new ArgumentException ("The obj parameter is a proxy.");
214 identity = obj.ObjectIdentity;
215 obj.ObjectIdentity = null;
218 if (identity == null || !identity.IsConnected)
222 LifetimeServices.StopTrackingLifetime (identity);
223 DisposeIdentity (identity);
224 TrackingServices.NotifyDisconnectedObject (obj);
229 public static Type GetServerTypeForUri (string URI)
231 ServerIdentity ident = GetIdentityForUri (URI) as ServerIdentity;
232 if (ident == null) return null;
233 return ident.ObjectType;
236 public static string GetObjectUri (MarshalByRefObject obj)
238 Identity ident = GetObjectIdentity(obj);
239 if (ident is ClientIdentity) return ((ClientIdentity)ident).TargetUri;
240 else if (ident != null) return ident.ObjectUri;
244 public static object Unmarshal (ObjRef objectRef)
246 return Unmarshal (objectRef, true);
249 public static object Unmarshal (ObjRef objectRef, bool fRefine)
251 Type classToProxy = fRefine ? objectRef.ServerType : typeof (MarshalByRefObject);
252 if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
254 if (objectRef.IsReferenceToWellKnow) {
255 object obj = GetRemoteObject (objectRef, classToProxy);
256 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
263 if (classToProxy.IsContextful) {
264 // Look for a ProxyAttribute
265 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute), true);
267 obj = att.CreateProxy (objectRef, classToProxy, null, null).GetTransparentProxy();
268 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
272 obj = GetProxyForRemoteObject (objectRef, classToProxy);
273 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
278 public static ObjRef Marshal (MarshalByRefObject Obj)
280 return Marshal (Obj, null, null);
283 public static ObjRef Marshal (MarshalByRefObject Obj, string URI)
285 return Marshal (Obj, URI, null);
288 public static ObjRef Marshal (MarshalByRefObject Obj, string ObjURI, Type RequestedType)
290 if (IsTransparentProxy (Obj))
292 RealProxy proxy = RemotingServices.GetRealProxy (Obj);
293 Identity identity = proxy.ObjectIdentity;
295 if (identity != null)
297 if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
299 // Unregistered local contextbound object. Register now.
300 ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
301 if (ObjURI == null) ObjURI = NewUri();
302 cboundIdentity.ObjectUri = ObjURI;
303 RegisterServerIdentity (cboundIdentity);
304 cboundIdentity.StartTrackingLifetime ((ILease)Obj.InitializeLifetimeService());
305 return cboundIdentity.CreateObjRef (RequestedType);
307 else if (ObjURI != null)
308 throw new RemotingException ("It is not possible marshal a proxy of a remote object.");
310 ObjRef or = proxy.ObjectIdentity.CreateObjRef (RequestedType);
311 TrackingServices.NotifyMarshaledObject (Obj, or);
316 if (RequestedType == null) RequestedType = Obj.GetType ();
320 if (Obj.ObjectIdentity == null)
323 CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
328 ClientActivatedIdentity identity = GetIdentityForUri ("/" + ObjURI) as ClientActivatedIdentity;
329 if (identity == null || Obj != identity.GetServerObject())
330 CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
335 if (IsTransparentProxy (Obj))
336 oref = RemotingServices.GetRealProxy (Obj).ObjectIdentity.CreateObjRef (RequestedType);
338 oref = Obj.CreateObjRef (RequestedType);
340 TrackingServices.NotifyMarshaledObject (Obj, oref);
344 static string NewUri ()
346 if (app_id == null) {
349 app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
353 int n = Interlocked.Increment (ref next_id);
354 return app_id + Environment.TickCount.ToString("x") + "_" + n + ".rem";
357 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
358 public static RealProxy GetRealProxy (object proxy)
360 if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy.");
361 return (RealProxy)((TransparentProxy)proxy)._rp;
364 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
366 Type type = Type.GetType (msg.TypeName);
368 throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
370 return GetMethodBaseFromName (type, msg.MethodName, (Type[]) msg.MethodSignature);
373 internal static MethodBase GetMethodBaseFromName (Type type, string methodName, Type[] signature)
375 if (type.IsInterface) {
376 return FindInterfaceMethod (type, methodName, signature);
379 MethodBase method = null;
380 if (signature == null)
381 method = type.GetMethod (methodName, methodBindings);
383 method = type.GetMethod (methodName, methodBindings, null, (Type[]) signature, null);
388 if (methodName == "FieldSetter")
389 return FieldSetterMethod;
391 if (methodName == "FieldGetter")
392 return FieldGetterMethod;
394 if (signature == null)
395 return type.GetConstructor (methodBindings, null, Type.EmptyTypes, null);
397 return type.GetConstructor (methodBindings, null, signature, null);
401 static MethodBase FindInterfaceMethod (Type type, string methodName, Type[] signature)
403 MethodBase method = null;
405 if (signature == null)
406 method = type.GetMethod (methodName, methodBindings);
408 method = type.GetMethod (methodName, methodBindings, null, signature, null);
410 if (method != null) return method;
412 foreach (Type t in type.GetInterfaces ()) {
413 method = FindInterfaceMethod (t, methodName, signature);
414 if (method != null) return method;
420 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
422 if (obj == null) throw new ArgumentNullException ("obj");
424 ObjRef oref = Marshal ((MarshalByRefObject)obj);
425 oref.GetObjectData (info, context);
428 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
430 Identity ident = GetObjectIdentity(obj);
431 if (ident == null) return null;
432 else return ident.CreateObjRef(null);
435 public static object GetLifetimeService (MarshalByRefObject obj)
437 if (obj == null) return null;
438 return obj.GetLifetimeService ();
441 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
443 if (IsTransparentProxy(obj))
444 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
446 throw new ArgumentException ("obj must be a proxy.","obj");
450 [Conditional ("REMOTING_PERF")]
451 [Obsolete ("It existed for only internal use in .NET and unimplemented in mono")]
452 public static void LogRemotingStage (int stage)
454 throw new NotImplementedException ();
457 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
459 // It seems that this it what MS returns.
463 public static bool IsMethodOverloaded(IMethodMessage msg)
465 const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
466 MonoType type = (MonoType) msg.MethodBase.DeclaringType;
467 return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1;
470 public static bool IsObjectOutOfAppDomain(object tp)
472 MarshalByRefObject mbr = tp as MarshalByRefObject;
477 // TODO: use internal call for better performance
478 Identity ident = GetObjectIdentity (mbr);
479 return ident is ClientIdentity;
482 public static bool IsObjectOutOfContext(object tp)
484 MarshalByRefObject mbr = tp as MarshalByRefObject;
489 // TODO: use internal call for better performance
490 Identity ident = GetObjectIdentity (mbr);
491 if (ident == null) return false;
493 ServerIdentity sident = ident as ServerIdentity;
494 if (sident != null) return sident.Context != System.Threading.Thread.CurrentContext;
498 public static bool IsOneWay(MethodBase method)
500 return method.IsDefined (typeof (OneWayAttribute), false);
503 internal static bool IsAsyncMessage(IMessage msg)
505 if (! (msg is MonoMethodMessage)) return false;
506 else if (((MonoMethodMessage)msg).IsAsync) return true;
507 else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
511 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
513 if (IsTransparentProxy (obj)) {
514 RealProxy proxy = RemotingServices.GetRealProxy(obj);
515 Identity identity = proxy.ObjectIdentity;
517 if (identity != null && !(identity is ServerIdentity) && !proxy.GetProxiedType().IsContextful)
518 throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
524 #region Internal Methods
526 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
528 if (entry.ContextAttributes != null || activationAttributes != null)
530 ArrayList props = new ArrayList ();
531 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
532 if (activationAttributes != null) props.AddRange (activationAttributes);
533 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
536 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
539 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
541 string activationUrl = url;
542 if (!activationUrl.EndsWith ("/"))
543 activationUrl += "/";
544 activationUrl += "RemoteActivationService.rem";
547 GetClientChannelSinkChain (activationUrl, null, out objectUri);
549 RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
550 return proxy.GetTransparentProxy();
553 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
555 return Connect (entry.ObjectType, entry.ObjectUrl, null);
558 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
560 if (type.IsContextful)
562 // Look for a ProxyAttribute
563 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
565 return att.CreateInstance (type);
567 RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
568 return proxy.GetTransparentProxy();
571 internal static object CreateClientProxyForComInterop (Type type)
573 Mono.Interop.ComInteropProxy proxy = Mono.Interop.ComInteropProxy.CreateProxy (type);
574 return proxy.GetTransparentProxy ();
577 internal static Identity GetIdentityForUri (string uri)
579 string normUri = GetNormalizedUri (uri);
582 Identity i = (Identity) uri_hash [normUri];
585 normUri = RemoveAppNameFromUri (uri);
587 i = (Identity) uri_hash [normUri];
595 // If the specified uri starts with the application name,
596 // RemoveAppNameFromUri returns the uri w/out the leading
597 // application name, otherwise it returns null.
599 // Assumes that the uri is not normalized.
601 static string RemoveAppNameFromUri (string uri)
603 string name = RemotingConfiguration.ApplicationName;
604 if (name == null) return null;
605 name = "/" + name + "/";
606 if (uri.StartsWith (name))
607 return uri.Substring (name.Length);
612 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
614 if (IsTransparentProxy(obj))
615 return GetRealProxy (obj).ObjectIdentity;
617 return obj.ObjectIdentity;
620 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
622 // This method looks for an identity for the given url.
623 // If an identity is not found, it creates the identity and
624 // assigns it a proxy to the remote object.
626 // Creates the client sink chain for the given url or channelData.
627 // It will also get the object uri from the url.
629 object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
632 IMessageSink sink = GetClientChannelSinkChain (objRef.URI, channelData, out objectUri);
634 if (objectUri == null) objectUri = objRef.URI;
639 string uri = GetNormalizedUri (objRef.URI);
641 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
642 if (identity != null)
644 // Object already registered
645 clientProxy = identity.ClientProxy;
646 if (clientProxy != null) return identity;
648 // The proxy has just been GCed, so its identity cannot
649 // be reused. Just dispose it.
650 DisposeIdentity (identity);
653 // Creates an identity and a proxy for the remote object
655 identity = new ClientIdentity (objectUri, objRef);
656 identity.ChannelSink = sink;
658 // Registers the identity
659 uri_hash [uri] = identity;
661 if (proxyType != null)
663 RemotingProxy proxy = new RemotingProxy (proxyType, identity);
664 CrossAppDomainSink cds = sink as CrossAppDomainSink;
666 proxy.SetTargetDomain (cds.TargetDomainId);
668 clientProxy = proxy.GetTransparentProxy();
669 identity.ClientProxy = (MarshalByRefObject) clientProxy;
676 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
678 IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
683 string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url);
684 throw new RemotingException (msg);
688 string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url);
689 throw new RemotingException (msg);
695 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
697 ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
698 identity.ChannelSink = ChannelServices.CrossContextChannel;
702 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
704 ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
705 identity.AttachServerObject (realObject, Context.DefaultContext);
706 RegisterServerIdentity (identity);
707 identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
711 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
713 ServerIdentity identity;
715 if (mode == WellKnownObjectMode.SingleCall)
716 identity = new SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
718 identity = new SingletonIdentity(objectUri, Context.DefaultContext, objectType);
720 RegisterServerIdentity (identity);
724 private static void RegisterServerIdentity(ServerIdentity identity)
728 if (uri_hash.ContainsKey (identity.ObjectUri))
729 throw new RemotingException ("Uri already in use: " + identity.ObjectUri + ".");
731 uri_hash[identity.ObjectUri] = identity;
735 internal static object GetProxyForRemoteObject (ObjRef objref, Type classToProxy)
737 ClientActivatedIdentity identity = GetIdentityForUri (objref.URI) as ClientActivatedIdentity;
738 if (identity != null) return identity.GetServerObject ();
739 else return GetRemoteObject (objref, classToProxy);
742 internal static object GetRemoteObject(ObjRef objRef, Type proxyType)
745 GetOrCreateClientIdentity (objRef, proxyType, out proxy);
749 // This method is called by the runtime
750 internal static object GetServerObject (string uri)
752 ClientActivatedIdentity identity = GetIdentityForUri (uri) as ClientActivatedIdentity;
753 if (identity == null) throw new RemotingException ("Server for uri '" + uri + "' not found");
754 return identity.GetServerObject ();
757 // This method is called by the runtime
758 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
759 internal static byte[] SerializeCallData (object obj)
761 LogicalCallContext ctx = CallContext.CreateLogicalCallContext (false);
763 CACD cad = new CACD ();
769 if (obj == null) return null;
770 MemoryStream ms = new MemoryStream ();
771 _serializationFormatter.Serialize (ms, obj);
772 return ms.ToArray ();
775 // This method is called by the runtime
776 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
777 internal static object DeserializeCallData (byte[] array)
779 if (array == null) return null;
781 MemoryStream ms = new MemoryStream (array);
782 object obj = _deserializationFormatter.Deserialize (ms);
785 CACD cad = (CACD) obj;
787 CallContext.UpdateCurrentCallContext ((LogicalCallContext) cad.c);
792 // This method is called by the runtime
793 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
794 internal static byte[] SerializeExceptionData (Exception ex)
801 MemoryStream ms = new MemoryStream ();
802 _serializationFormatter.Serialize (ms, ex);
803 return ms.ToArray ();
805 catch (Exception e) {
806 if (e is ThreadAbortException) {
807 Thread.ResetAbort ();
811 else if (retry == 2) {
812 ex = new Exception ();
813 ex.SetMessage (e.Message);
814 ex.SetStackTrace (e.StackTrace);
825 catch (Exception tex)
827 byte[] data = SerializeExceptionData (tex);
828 Thread.ResetAbort ();
833 internal static object GetDomainProxy(AppDomain domain)
837 Context currentContext = Thread.CurrentContext;
841 data = (byte[])AppDomain.InvokeInDomain (domain, typeof (AppDomain).GetMethod ("GetMarshalledDomainObjRef", BindingFlags.Instance|BindingFlags.NonPublic), domain, null);
845 AppDomain.InternalSetContext (currentContext);
848 byte[] data_copy = new byte [data.Length];
849 data.CopyTo (data_copy, 0);
850 MemoryStream stream = new MemoryStream (data_copy);
851 ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
852 return (AppDomain) RemotingServices.Unmarshal(appref);
855 private static void RegisterInternalChannels()
857 CrossAppDomainChannel.RegisterCrossAppDomainChannel();
860 internal static void DisposeIdentity (Identity ident)
864 if (!ident.Disposed) {
865 ClientIdentity clientId = ident as ClientIdentity;
866 if (clientId != null)
867 uri_hash.Remove (GetNormalizedUri (clientId.TargetUri));
869 uri_hash.Remove (ident.ObjectUri);
871 ident.Disposed = true;
876 internal static Identity GetMessageTargetIdentity (IMessage msg)
878 // Returns the identity where the message is sent
880 if (msg is IInternalMessage)
881 return ((IInternalMessage)msg).TargetIdentity;
885 string uri = GetNormalizedUri (((IMethodMessage)msg).Uri);
886 return uri_hash [uri] as ServerIdentity;
890 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
892 if (msg is IInternalMessage)
893 ((IInternalMessage)msg).TargetIdentity = ident;
896 internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
898 if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
900 Array alocal = (Array) local;
901 if (alocal.Rank == 1)
903 Array.Copy ((Array) remote, alocal, alocal.Length);
914 static string GetNormalizedUri (string uri)
916 if (uri.StartsWith ("/")) return uri.Substring (1);