context: //
  // System.Runtime.Remoting.RemotingServices.cs
  //
  // Authors:
  //   Dietmar Maurer (dietmar@ximian.com)
  //   Lluis Sanchez Gual (lluis@ideary.com)
  //   Patrik Torstensson
  //
  // (C) 2001 Ximian, Inc.  http://www.ximian.com
  // Copyright (C) 2004, 2006 Novell, Inc (http://www.novell.com)
  //
  // Permission is hereby granted, free of charge, to any person obtaining
  // a copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to
  // permit persons to whom the Software is furnished to do so, subject to
  // the following conditions:
  // 
  // The above copyright notice and this permission notice shall be
  // included in all copies or substantial portions of the Software.
  // 
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  //
  
  using System.Diagnostics;
  using System.Text;
  using System.Reflection;
  using System.Threading;
  using System.Collections;
  using System.Runtime.Remoting.Messaging;
  using System.Runtime.Remoting.Proxies;
  using System.Runtime.Remoting.Channels;
  using System.Runtime.Remoting.Contexts;
  using System.Runtime.Remoting.Activation;
  using System.Runtime.Remoting.Lifetime;
  using System.Runtime.CompilerServices;
  using System.Runtime.Serialization;
  using System.Runtime.Serialization.Formatters.Binary;
  using System.IO;
  using System.Runtime.Remoting.Services;
  using System.Security.Permissions;
  using System.Runtime.ConstrainedExecution;
  using System.Runtime.Serialization.Formatters;
  
  namespace System.Runtime.Remoting
  {
  	[System.Runtime.InteropServices.ComVisible (true)]
  #if NET_4_0
  	static
  #else
  	sealed
  #endif
  	public class RemotingServices 
  	{
  		// Holds the identities of the objects, using uri as index
  		static Hashtable uri_hash = new Hashtable ();		
  
  		static BinaryFormatter _serializationFormatter;
  		static BinaryFormatter _deserializationFormatter;
  		
  		static string app_id;
  		static readonly object app_id_lock = new object ();
  		
  		static int next_id = 1;
  		const BindingFlags methodBindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
  		static readonly MethodInfo FieldSetterMethod;
  		static readonly MethodInfo FieldGetterMethod;
  		
  		// Holds information in xdomain calls. Names are short to minimize serialized size.
  		[Serializable]
  		class CACD {
  			public object d;	/* call data */
  			public object c;	/* call context */
  		}
  		
  		static RemotingServices ()
  		{
  			RemotingSurrogateSelector surrogateSelector = new RemotingSurrogateSelector ();
  			StreamingContext context = new StreamingContext (StreamingContextStates.Remoting, null);
  			_serializationFormatter = new BinaryFormatter (surrogateSelector, context);
  			_deserializationFormatter = new BinaryFormatter (null, context);
  			_serializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
  			_deserializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
  			
  			RegisterInternalChannels ();
  			CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
  			
  			FieldSetterMethod = typeof(object).GetMethod ("FieldSetter", BindingFlags.NonPublic|BindingFlags.Instance);
  			FieldGetterMethod = typeof(object).GetMethod ("FieldGetter", BindingFlags.NonPublic|BindingFlags.Instance);
  		}
  #if !NET_4_0
  		private RemotingServices () {}
  #endif
  
  		[MethodImplAttribute(MethodImplOptions.InternalCall)]
  		internal extern static object InternalExecute (MethodBase method, Object obj,
  							       Object[] parameters, out object [] out_args);
  
  		// Returns the actual implementation of @method in @type.
  		[MethodImplAttribute(MethodImplOptions.InternalCall)]
  		internal extern static MethodBase GetVirtualMethod (Type type, MethodBase method);
  
  #if DISABLE_REMOTING
  		public static bool IsTransparentProxy (object proxy)
  		{
  			throw new NotSupportedException ();
  		}
  #else
  		[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  		[MethodImplAttribute(MethodImplOptions.InternalCall)]
  		public extern static bool IsTransparentProxy (object proxy);
  #endif
  
  		internal static IMethodReturnMessage InternalExecuteMessage (
  		        MarshalByRefObject target, IMethodCallMessage reqMsg)
  		{
  			ReturnMessage result;
  			
  			Type tt = target.GetType ();
  			MethodBase method;
  			if (reqMsg.MethodBase.DeclaringType == tt ||
  			    reqMsg.MethodBase == FieldSetterMethod || 
  			    reqMsg.MethodBase == FieldGetterMethod) {
  				method = reqMsg.MethodBase;
  			} else {
  				method = GetVirtualMethod (tt, reqMsg.MethodBase);
  
  				if (method == null)
  					throw new RemotingException (
  						String.Format ("Cannot resolve method {0}:{1}", tt, reqMsg.MethodName));
  			}
  
  			if (reqMsg.MethodBase.IsGenericMethod) {
  				Type[] genericArguments = reqMsg.MethodBase.GetGenericArguments ();
  				MethodInfo gmd = ((MethodInfo)method).GetGenericMethodDefinition ();
  				method = gmd.MakeGenericMethod (genericArguments);
  			}
  
  			object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
  			
  			try 
  			{
  				object [] out_args;
  				object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
  			
  				// Collect parameters with Out flag from the request message
  				// FIXME: This can be done in the unmanaged side and will be
  				// more efficient
  				
  				ParameterInfo[] parameters = method.GetParameters();
  				object[] returnArgs = new object [parameters.Length];
  				
  				int n = 0;
  				int noa = 0;
  				foreach (ParameterInfo par in parameters)
  				{
  					if (par.IsOut && !par.ParameterType.IsByRef) 
  						returnArgs [n++] = reqMsg.GetArg (par.Position);
  					else if (par.ParameterType.IsByRef)
  						returnArgs [n++] = out_args [noa++]; 
  					else
  						returnArgs [n++] = null; 
  				}
  				
  				result = new ReturnMessage (rval, returnArgs, n, CallContext.CreateLogicalCallContext (true), reqMsg);
  			} 
  			catch (Exception e) 
  			{
  				result = new ReturnMessage (e, reqMsg);
  			}
  			
  			CallContext.RestoreCallContext (oldContext);
  			return result;
  		}
  
  		public static IMethodReturnMessage ExecuteMessage (
  			MarshalByRefObject target, IMethodCallMessage reqMsg)
  		{
  			if (IsTransparentProxy(target))
  			{
  				// Message must go through all chain of sinks
  				RealProxy rp = GetRealProxy (target);
  				return (IMethodReturnMessage) rp.Invoke (reqMsg);
  			}
  			else	// Direct call
  				return InternalExecuteMessage (target, reqMsg);
  		}
  
  		[System.Runtime.InteropServices.ComVisible (true)]
  		public static object Connect (Type classToProxy, string url)
  		{
  			ObjRef objRef = new ObjRef (classToProxy, url, null);
  			return GetRemoteObject (objRef, classToProxy);
  		}
  
  		[System.Runtime.InteropServices.ComVisible (true)]
  		public static object Connect (Type classToProxy, string url, object data)
  		{
  			ObjRef objRef = new ObjRef (classToProxy, url, data);
  			return GetRemoteObject (objRef, classToProxy);
  		}
  
  		public static bool Disconnect (MarshalByRefObject obj)
  		{
  			if (obj == null) throw new ArgumentNullException ("obj");
  
  			ServerIdentity identity;
  
  			if (IsTransparentProxy (obj))
  			{
  				// CBOs are always accessed through a proxy, even in the server, so
  				// for server CBOs it is ok to disconnect a proxy
  
  				RealProxy proxy = GetRealProxy(obj);
  				if (proxy.GetProxiedType().IsContextful && (proxy.ObjectIdentity is ServerIdentity))
  					identity = proxy.ObjectIdentity as ServerIdentity;
  				else
  					throw new ArgumentException ("The obj parameter is a proxy.");
  			}
  			else {
  				identity = obj.ObjectIdentity;
  				obj.ObjectIdentity = null;
  			}
  
  			if (identity == null || !identity.IsConnected)
  				return false;
  			else
  			{
  				LifetimeServices.StopTrackingLifetime (identity);
  				DisposeIdentity (identity);
  				TrackingServices.NotifyDisconnectedObject (obj);
  				return true;
  			}
  		}
  
  		public static Type GetServerTypeForUri (string URI)
  		{
  			ServerIdentity ident = GetIdentityForUri (URI) as ServerIdentity;
  			if (ident == null) return null;
  			return ident.ObjectType;
  		}
  
  		public static string GetObjectUri (MarshalByRefObject obj)
  		{
  			Identity ident = GetObjectIdentity(obj);
  			if (ident is ClientIdentity) return ((ClientIdentity)ident).TargetUri;
  			else if (ident != null) return ident.ObjectUri;
  			else return null;
  		}
  
  		public static object Unmarshal (ObjRef objectRef)
  		{
  			return Unmarshal (objectRef, true);
  		}
  
  		public static object Unmarshal (ObjRef objectRef, bool fRefine)
  		{
  			Type classToProxy = fRefine ? objectRef.ServerType : typeof (MarshalByRefObject);
  			if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
  
  			if (objectRef.IsReferenceToWellKnow) {
  				object obj = GetRemoteObject (objectRef, classToProxy);
  				TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
  				return obj;
  			}
  			else
  			{
  				object obj;
  				
  				if (classToProxy.IsContextful) {
  					// Look for a ProxyAttribute
  					ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute), true);
  					if (att != null) {
  						obj = att.CreateProxy (objectRef, classToProxy, null, null).GetTransparentProxy();
  						TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
  						return obj;
  					}
  				}
  				obj = GetProxyForRemoteObject (objectRef, classToProxy);
  				TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
  				return obj;
  			}
  		}
  
  		public static ObjRef Marshal (MarshalByRefObject Obj)
  		{
  			return Marshal (Obj, null, null);
  		}
  		
  		public static ObjRef Marshal (MarshalByRefObject Obj, string URI)
  		{
  			return Marshal (Obj, URI, null);
  		}
  		
  		public static ObjRef Marshal (MarshalByRefObject Obj, string ObjURI, Type RequestedType)
  		{
  			if (IsTransparentProxy (Obj))
  			{
  				RealProxy proxy = RemotingServices.GetRealProxy (Obj);
  				Identity identity = proxy.ObjectIdentity;
  
  				if (identity != null)
  				{
  					if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
  					{
  						// Unregistered local contextbound object. Register now.
  						ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
  						if (ObjURI == null) ObjURI = NewUri();
  						cboundIdentity.ObjectUri = ObjURI;
  						RegisterServerIdentity (cboundIdentity);
  						cboundIdentity.StartTrackingLifetime ((ILease)Obj.InitializeLifetimeService());
  						return cboundIdentity.CreateObjRef (RequestedType);
  					}
  					else if (ObjURI != null)
  						throw new RemotingException ("It is not possible marshal a proxy of a remote object.");
  
  					ObjRef or = proxy.ObjectIdentity.CreateObjRef (RequestedType);
  					TrackingServices.NotifyMarshaledObject (Obj, or);
  					return or;
  				}
  			}
  
  			if (RequestedType == null) RequestedType = Obj.GetType ();
  
  			if (ObjURI == null) 
  			{
  				if (Obj.ObjectIdentity == null)
  				{
  					ObjURI = NewUri();
  					CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
  				}
  			}
  			else
  			{
  				ClientActivatedIdentity identity = GetIdentityForUri ("/" + ObjURI) as ClientActivatedIdentity;
  				if (identity == null || Obj != identity.GetServerObject()) 
  					CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
  			}
  
  			ObjRef oref;
  			
  			if (IsTransparentProxy (Obj))
  				oref = RemotingServices.GetRealProxy (Obj).ObjectIdentity.CreateObjRef (RequestedType);
  			else
  				oref = Obj.CreateObjRef (RequestedType);
  			
  			TrackingServices.NotifyMarshaledObject (Obj, oref);
  			return oref;
  		}
  
  		static string NewUri ()
  		{
  			if (app_id == null) {
  				lock (app_id_lock) {
  					if (app_id == null)
  						app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
  				}
  			}
  
  			int n = Interlocked.Increment (ref next_id);
  			return app_id + Environment.TickCount.ToString("x") + "_" + n + ".rem";
  		}
  
  		[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  		public static RealProxy GetRealProxy (object proxy)
  		{
  			if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy.");
  			return (RealProxy)((TransparentProxy)proxy)._rp;
  		}
  
  		public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
  		{
  			Type type = Type.GetType (msg.TypeName);
  			if (type == null)
  				throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
  
  			return GetMethodBaseFromName (type, msg.MethodName, (Type[]) msg.MethodSignature);
  		}
  
  		internal static MethodBase GetMethodBaseFromName (Type type, string methodName, Type[] signature)
  		{
  			if (type.IsInterface) {
  				return FindInterfaceMethod (type, methodName, signature);
  			}
  			else {
  				MethodBase method = null;
  				if (signature == null)
  					method = type.GetMethod (methodName, methodBindings);
  				else
  					method = type.GetMethod (methodName, methodBindings, null, (Type[]) signature, null);
  				
  				if (method != null)
  					return method;
  					
  				if (methodName == "FieldSetter")
  					return FieldSetterMethod;
  
  				if (methodName == "FieldGetter")
  					return FieldGetterMethod;
  				
  				if (signature == null)
  					return type.GetConstructor (methodBindings, null, Type.EmptyTypes, null);
  				else
  					return type.GetConstructor (methodBindings, null, signature, null);
  			}
  		}
  		
  		static MethodBase FindInterfaceMethod (Type type, string methodName, Type[] signature)
  		{
  			MethodBase method = null;
  			
  			if (signature == null)
  				method = type.GetMethod (methodName, methodBindings);
  			else
  				method = type.GetMethod (methodName, methodBindings, null, signature, null);
  				
  			if (method != null) return method;
  			
  			foreach (Type t in type.GetInterfaces ()) {
  				method = FindInterfaceMethod (t, methodName, signature);
  				if (method != null) return method;
  			}
  			
  			return null;
  		}
  
  		public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
  		{
  			if (obj == null) throw new ArgumentNullException ("obj");
  
  			ObjRef oref = Marshal ((MarshalByRefObject)obj);
  			oref.GetObjectData (info, context);
  		}
  
  		public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
  		{
  			Identity ident = GetObjectIdentity(obj);
  			if (ident == null) return null;
  			else return ident.CreateObjRef(null);
  		}
  
  		public static object GetLifetimeService (MarshalByRefObject obj)
  		{
  			if (obj == null) return null;
  			return obj.GetLifetimeService ();
  		}
  
  		public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
  		{
  			if (IsTransparentProxy(obj))
  				return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
  			else
  				throw new ArgumentException ("obj must be a proxy.","obj");			
  		}
  
  		[MonoTODO]
  		[Conditional ("REMOTING_PERF")]
  		[Obsolete ("It existed for only internal use in .NET and unimplemented in mono")]
  		public static void LogRemotingStage (int stage)
  		{
  			throw new NotImplementedException ();
  		}
  
  		public static string GetSessionIdForMethodMessage(IMethodMessage msg)
  		{
  			// It seems that this it what MS returns.
  			return msg.Uri;
  		}
  
  		public static bool IsMethodOverloaded(IMethodMessage msg)
  		{
  			const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
  			MonoType type = (MonoType) msg.MethodBase.DeclaringType;
  			return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1;
  		}
  
  		public static bool IsObjectOutOfAppDomain(object tp)
  		{
  			MarshalByRefObject mbr = tp as MarshalByRefObject;
  
  			if (mbr == null)
  				return false;
  
  			// TODO: use internal call for better performance
  			Identity ident = GetObjectIdentity (mbr);
  			return ident is ClientIdentity;
  		}
  
  		public static bool IsObjectOutOfContext(object tp)
  		{
  			MarshalByRefObject mbr = tp as MarshalByRefObject;
  
  			if (mbr == null)
  				return false;
  
  			// TODO: use internal call for better performance
  			Identity ident = GetObjectIdentity (mbr);
  			if (ident == null) return false;
  			
  			ServerIdentity sident = ident as ServerIdentity;
  			if (sident != null) return sident.Context != System.Threading.Thread.CurrentContext;
  			else return true;
  		}
  
  		public static bool IsOneWay(MethodBase method)
  		{
  			return method.IsDefined (typeof (OneWayAttribute), false);
  		}
  
  		internal static bool IsAsyncMessage(IMessage msg)
  		{
  			if (! (msg is MonoMethodMessage)) return false;
  			else if (((MonoMethodMessage)msg).IsAsync) return true;
  			else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
  			else return false;
  		}
  
  		public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
  		{
  			if (IsTransparentProxy (obj)) {
  				RealProxy proxy = RemotingServices.GetRealProxy(obj);
  				Identity identity = proxy.ObjectIdentity;
  
  				if (identity != null && !(identity is ServerIdentity) && !proxy.GetProxiedType().IsContextful)
  					throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
  			}
  			
  			Marshal (obj, uri);
  		}
  
  		#region Internal Methods
  		
  		internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
  		{
  			if (entry.ContextAttributes != null || activationAttributes != null)
  			{
  				ArrayList props = new ArrayList ();
  				if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
  				if (activationAttributes != null) props.AddRange (activationAttributes);
  				return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
  			}
  			else
  				return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
  		}
  	
  		internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
  		{
  			string activationUrl = url;
  
gt: 			if (!activationUrl.EndsWith ("/"))