Merge pull request #555 from jack-pappas/sigaltstack-patch
[mono.git] / mcs / class / corlib / System.Runtime.Remoting / RemotingServices.cs
index 9b35a91a8c7a210f4a7af42df7840236b77883a9..f4bab8d4ad1c5c19dea2259422a92a9129a87b08 100644 (file)
@@ -7,10 +7,7 @@
 //   Patrik Torstensson
 //
 // (C) 2001 Ximian, Inc.  http://www.ximian.com
-//
-
-//
-// Copyright (C) 2004 Novell, Inc (http://www.novell.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
@@ -32,7 +29,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-using System;
 using System.Diagnostics;
 using System.Text;
 using System.Reflection;
@@ -48,10 +44,20 @@ 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
 {
-       public sealed class RemotingServices 
+       [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 ();           
@@ -59,9 +65,13 @@ namespace System.Runtime.Remoting
                static BinaryFormatter _serializationFormatter;
                static BinaryFormatter _deserializationFormatter;
                
-               internal static string app_id;
+               static string app_id;
+               static readonly object app_id_lock = new object ();
+               
                static int next_id = 1;
-               static readonly BindingFlags methodBindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
+               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]
@@ -76,28 +86,63 @@ namespace System.Runtime.Remoting
                        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 ();
-                       app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
                        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 = reqMsg.MethodBase.DeclaringType == tt ? reqMsg.MethodBase : tt.GetMethod(reqMsg.MethodName, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance, null, (Type[]) reqMsg.MethodSignature, null);
+                       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 
@@ -148,12 +193,14 @@ namespace System.Runtime.Remoting
                                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);
@@ -188,13 +235,14 @@ namespace System.Runtime.Remoting
                        {
                                LifetimeServices.StopTrackingLifetime (identity);
                                DisposeIdentity (identity);
+                               TrackingServices.NotifyDisconnectedObject (obj);
                                return true;
                        }
                }
 
-               public static Type GetServerTypeForUri (string uri)
+               public static Type GetServerTypeForUri (string URI)
                {
-                       ServerIdentity ident = GetIdentityForUri (uri) as ServerIdentity;
+                       ServerIdentity ident = GetIdentityForUri (URI) as ServerIdentity;
                        if (ident == null) return null;
                        return ident.ObjectType;
                }
@@ -207,46 +255,55 @@ namespace System.Runtime.Remoting
                        else return null;
                }
 
-               public static object Unmarshal (ObjRef objref)
+               public static object Unmarshal (ObjRef objectRef)
                {
-                       return Unmarshal(objref, true);
+                       return Unmarshal (objectRef, true);
                }
 
-               public static object Unmarshal (ObjRef objref, bool fRefine)
+               public static object Unmarshal (ObjRef objectRef, bool fRefine)
                {
-                       Type classToProxy = fRefine ? objref.ServerType : typeof (MarshalByRefObject);
+                       Type classToProxy = fRefine ? objectRef.ServerType : typeof (MarshalByRefObject);
                        if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
 
-                       if (objref.IsReferenceToWellKnow)
-                               return GetRemoteObject(objref, classToProxy);
+                       if (objectRef.IsReferenceToWellKnow) {
+                               object obj = GetRemoteObject (objectRef, classToProxy);
+                               TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
+                               return obj;
+                       }
                        else
                        {
-                               if (classToProxy.IsContextful)
-                               {
+                               object obj;
+                               
+                               if (classToProxy.IsContextful) {
                                        // Look for a ProxyAttribute
-                                       ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute),true);
-                                       if (att != null)
-                                               return att.CreateProxy (objref, classToProxy, null, null).GetTransparentProxy();
+                                       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;
+                                       }
                                }
-                               return GetProxyForRemoteObject (objref, classToProxy);
+                               obj = GetProxyForRemoteObject (objectRef, classToProxy);
+                               TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
+                               return obj;
                        }
                }
 
-               public static ObjRef Marshal (MarshalByRefObject obj)
+               public static ObjRef Marshal (MarshalByRefObject Obj)
                {
-                       return Marshal (obj, null, null);
+                       return Marshal (Obj, null, null);
                }
                
-               public static ObjRef Marshal (MarshalByRefObject obj, string uri)
+               public static ObjRef Marshal (MarshalByRefObject Obj, string URI)
                {
-                       return Marshal (obj, uri, null);
+                       return Marshal (Obj, URI, null);
                }
                
-               public static ObjRef Marshal (MarshalByRefObject obj, string uri, Type requested_type)
+               public static ObjRef Marshal (MarshalByRefObject Obj, string ObjURI, Type RequestedType)
                {
-                       if (IsTransparentProxy (obj))
+                       if (IsTransparentProxy (Obj))
                        {
-                               RealProxy proxy = RemotingServices.GetRealProxy(obj);
+                               RealProxy proxy = RemotingServices.GetRealProxy (Obj);
                                Identity identity = proxy.ObjectIdentity;
 
                                if (identity != null)
@@ -255,48 +312,63 @@ namespace System.Runtime.Remoting
                                        {
                                                // Unregistered local contextbound object. Register now.
                                                ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
-                                               if (uri == null) uri = NewUri();
-                                               cboundIdentity.ObjectUri = uri;
+                                               if (ObjURI == null) ObjURI = NewUri();
+                                               cboundIdentity.ObjectUri = ObjURI;
                                                RegisterServerIdentity (cboundIdentity);
-                                               cboundIdentity.StartTrackingLifetime ((ILease)obj.InitializeLifetimeService());
-                                               return cboundIdentity.CreateObjRef(requested_type);
+                                               cboundIdentity.StartTrackingLifetime ((ILease)Obj.InitializeLifetimeService());
+                                               return cboundIdentity.CreateObjRef (RequestedType);
                                        }
-                                       else if (uri != null)
+                                       else if (ObjURI != null)
                                                throw new RemotingException ("It is not possible marshal a proxy of a remote object.");
 
-                                       return proxy.ObjectIdentity.CreateObjRef(requested_type);
+                                       ObjRef or = proxy.ObjectIdentity.CreateObjRef (RequestedType);
+                                       TrackingServices.NotifyMarshaledObject (Obj, or);
+                                       return or;
                                }
                        }
 
-                       if (requested_type == null) requested_type = obj.GetType();
+                       if (RequestedType == null) RequestedType = Obj.GetType ();
 
-                       if (uri == null) 
+                       if (ObjURI == null) 
                        {
-                               if (obj.ObjectIdentity == null)
+                               if (Obj.ObjectIdentity == null)
                                {
-                                       uri = NewUri();
-                                       CreateClientActivatedServerIdentity (obj, requested_type, uri);
+                                       ObjURI = NewUri();
+                                       CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
                                }
                        }
                        else
                        {
-                               ClientActivatedIdentity identity = GetIdentityForUri ("/" + uri) as ClientActivatedIdentity;
-                               if (identity == null || obj != identity.GetServerObject()) 
-                                       CreateClientActivatedServerIdentity (obj, requested_type, uri);
+                               ClientActivatedIdentity identity = GetIdentityForUri ("/" + ObjURI) as ClientActivatedIdentity;
+                               if (identity == null || Obj != identity.GetServerObject()) 
+                                       CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
                        }
 
-                       if (IsTransparentProxy (obj))
-                               return RemotingServices.GetRealProxy(obj).ObjectIdentity.CreateObjRef (requested_type);
+                       ObjRef oref;
+                       
+                       if (IsTransparentProxy (Obj))
+                               oref = RemotingServices.GetRealProxy (Obj).ObjectIdentity.CreateObjRef (RequestedType);
                        else
-                               return obj.CreateObjRef(requested_type);
+                               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 + "_" + n + ".rem";
+                       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.");
@@ -308,10 +380,10 @@ namespace System.Runtime.Remoting
                        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) {
@@ -324,8 +396,14 @@ namespace System.Runtime.Remoting
                                else
                                        method = type.GetMethod (methodName, methodBindings, null, (Type[]) signature, null);
                                
-                               if (method != 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);
@@ -384,6 +462,7 @@ namespace System.Runtime.Remoting
 
                [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 ();
@@ -404,15 +483,25 @@ namespace System.Runtime.Remoting
 
                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((MarshalByRefObject)tp);
+                       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((MarshalByRefObject)tp);
+                       Identity ident = GetObjectIdentity (mbr);
                        if (ident == null) return false;
                        
                        ServerIdentity sident = ident as ServerIdentity;
@@ -463,10 +552,13 @@ namespace System.Runtime.Remoting
        
                internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
                {
-                       string activationUrl = url + "/RemoteActivationService.rem";
+                       string activationUrl = url;
+                       if (!activationUrl.EndsWith ("/"))
+                               activationUrl += "/";
+                       activationUrl += "RemoteActivationService.rem";
 
                        string objectUri;
-                       IMessageSink sink = GetClientChannelSinkChain (activationUrl, null, out objectUri);
+                       GetClientChannelSinkChain (activationUrl, null, out objectUri);
 
                        RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
                        return proxy.GetTransparentProxy();
@@ -489,15 +581,48 @@ namespace System.Runtime.Remoting
                        RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
                        return proxy.GetTransparentProxy();
                }
-       
+#if !NET_2_1
+               internal static object CreateClientProxyForComInterop (Type type)
+               {
+                       Mono.Interop.ComInteropProxy proxy = Mono.Interop.ComInteropProxy.CreateProxy (type);
+                       return proxy.GetTransparentProxy ();
+               }
+#endif
                internal static Identity GetIdentityForUri (string uri)
                {
+                       string normUri = GetNormalizedUri (uri);
                        lock (uri_hash)
                        {
-                               return (Identity)uri_hash [GetNormalizedUri(uri)];
+                               Identity i = (Identity) uri_hash [normUri];
+
+                               if (i == null) {
+                                       normUri = RemoveAppNameFromUri (uri);
+                                       if (normUri != null)
+                                               i = (Identity) uri_hash [normUri];
+                               }
+
+                               return i;
                        }
                }
 
+               //
+               // If the specified uri starts with the application name,
+               // RemoveAppNameFromUri returns the uri w/out the leading
+               // application name, otherwise it returns null.
+               //
+               // Assumes that the uri is not normalized.
+               //
+               static string RemoveAppNameFromUri (string uri)
+               {
+                       string name = RemotingConfiguration.ApplicationName;
+                       if (name == null) return null;
+                       name = "/" + name + "/";
+                       if (uri.StartsWith (name))
+                               return uri.Substring (name.Length);
+                       else
+                               return null;
+               }
+
                internal static Identity GetObjectIdentity (MarshalByRefObject obj)
                {
                        if (IsTransparentProxy(obj))
@@ -546,7 +671,6 @@ namespace System.Runtime.Remoting
 
                                // Registers the identity
                                uri_hash [uri] = identity;
-                               
                                if (proxyType != null)
                                {
                                        RemotingProxy proxy = new RemotingProxy (proxyType, identity);
@@ -557,7 +681,6 @@ namespace System.Runtime.Remoting
                                        clientProxy = proxy.GetTransparentProxy();
                                        identity.ClientProxy = (MarshalByRefObject) clientProxy;
                                }
-
                                return identity;
                        }
                }
@@ -644,6 +767,7 @@ namespace System.Runtime.Remoting
                }
 
                // This method is called by the runtime
+               [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
                internal static byte[] SerializeCallData (object obj)
                {
                        LogicalCallContext ctx = CallContext.CreateLogicalCallContext (false);
@@ -661,6 +785,7 @@ namespace System.Runtime.Remoting
                }
 
                // This method is called by the runtime
+               [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
                internal static object DeserializeCallData (byte[] array)
                {
                        if (array == null) return null;
@@ -677,6 +802,7 @@ namespace System.Runtime.Remoting
                }
                
                // This method is called by the runtime
+               [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
                internal static byte[] SerializeExceptionData (Exception ex)
                {
                        try {
@@ -731,7 +857,9 @@ namespace System.Runtime.Remoting
                                AppDomain.InternalSetContext (currentContext);
                        }                               
 
-                       MemoryStream stream = new MemoryStream (data);
+                       byte[] data_copy = new byte [data.Length];
+                       data.CopyTo (data_copy, 0);
+                       MemoryStream stream = new MemoryStream (data_copy);
                        ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
                        return (AppDomain) RemotingServices.Unmarshal(appref);
                }
@@ -779,14 +907,7 @@ namespace System.Runtime.Remoting
                
                internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
                {
-                       if (local is StringBuilder) 
-                       {
-                               StringBuilder sb = local as StringBuilder;
-                               sb.Remove (0, sb.Length);
-                               sb.Append (remote.ToString());
-                               return true;
-                       }
-                       else if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
+                       if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
                        {
                                Array alocal = (Array) local;
                                if (alocal.Rank == 1)