2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mcs / class / corlib / System.Runtime.Remoting / RemotingServices.cs
index 09f649274a0636be6c138edf3a968b792c24fd31..9b35a91a8c7a210f4a7af42df7840236b77883a9 100644 (file)
@@ -9,7 +9,31 @@
 // (C) 2001 Ximian, Inc.  http://www.ximian.com
 //
 
+//
+// Copyright (C) 2004 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;
+using System.Diagnostics;
 using System.Text;
 using System.Reflection;
 using System.Threading;
@@ -22,6 +46,7 @@ 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;
 
 namespace System.Runtime.Remoting
@@ -31,11 +56,27 @@ namespace System.Runtime.Remoting
                // Holds the identities of the objects, using uri as index
                static Hashtable uri_hash = new Hashtable ();           
 
+               static BinaryFormatter _serializationFormatter;
+               static BinaryFormatter _deserializationFormatter;
+               
                internal static string app_id;
                static int next_id = 1;
+               static readonly BindingFlags methodBindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
+               
+               // 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);
+                       
                        RegisterInternalChannels ();
                        app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
                        CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
@@ -44,7 +85,7 @@ namespace System.Runtime.Remoting
                private RemotingServices () {}
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
-               internal extern static object InternalExecute (MonoMethod method, Object obj,
+               internal extern static object InternalExecute (MethodBase method, Object obj,
                                                               Object[] parameters, out object [] out_args);
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -55,7 +96,8 @@ namespace System.Runtime.Remoting
                {
                        ReturnMessage result;
                        
-                       MonoMethod method = (MonoMethod) target.GetType().GetMethod(reqMsg.MethodName, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance, null, (Type[]) reqMsg.MethodSignature, null);
+                       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);
                        object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
                        
                        try 
@@ -64,7 +106,9 @@ namespace System.Runtime.Remoting
                                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];
                                
@@ -76,9 +120,11 @@ namespace System.Runtime.Remoting
                                                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(), reqMsg);
+                               result = new ReturnMessage (rval, returnArgs, n, CallContext.CreateLogicalCallContext (true), reqMsg);
                        } 
                        catch (Exception e) 
                        {
@@ -131,8 +177,10 @@ namespace System.Runtime.Remoting
                                else
                                        throw new ArgumentException ("The obj parameter is a proxy.");
                        }
-                       else
+                       else {
                                identity = obj.ObjectIdentity;
+                               obj.ObjectIdentity = null;
+                       }
 
                        if (identity == null || !identity.IsConnected)
                                return false;
@@ -260,12 +308,49 @@ namespace System.Runtime.Remoting
                        Type type = Type.GetType (msg.TypeName);
                        if (type == null)
                                throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
-
-                       BindingFlags bflags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
-                       if (msg.MethodSignature == null)
-                               return type.GetMethod (msg.MethodName, bflags);
+                               
+                       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 (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
-                               return type.GetMethod (msg.MethodName, bflags, null, (Type[]) msg.MethodSignature, null);
+                               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)
@@ -297,6 +382,8 @@ namespace System.Runtime.Remoting
                                throw new ArgumentException ("obj must be a proxy.","obj");                     
                }
 
+               [MonoTODO]
+               [Conditional ("REMOTING_PERF")]
                public static void LogRemotingStage (int stage)
                {
                        throw new NotImplementedException ();
@@ -310,33 +397,32 @@ namespace System.Runtime.Remoting
 
                public static bool IsMethodOverloaded(IMethodMessage msg)
                {
-                       // TODO: use internal call for better performance
-                       Type type = msg.MethodBase.DeclaringType;
-                       MemberInfo[] members = type.GetMember (msg.MethodName, MemberTypes.Method, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
-                       return members.Length > 1;
+                       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)
                {
                        // TODO: use internal call for better performance
                        Identity ident = GetObjectIdentity((MarshalByRefObject)tp);
-                       if (ident != null) return !ident.IsFromThisAppDomain;
-                       else return false;
+                       return ident is ClientIdentity;
                }
 
                public static bool IsObjectOutOfContext(object tp)
                {
                        // TODO: use internal call for better performance
-                       ServerIdentity ident = GetObjectIdentity((MarshalByRefObject)tp) as ServerIdentity;
-                       if (ident != null) return ident.Context != System.Threading.Thread.CurrentContext;
-                       else return false;
+                       Identity ident = GetObjectIdentity((MarshalByRefObject)tp);
+                       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)
                {
-                       // TODO: use internal call for better performance
-                       object[] atts = method.GetCustomAttributes (typeof (OneWayAttribute), false);
-                       return atts.Length > 0;
+                       return method.IsDefined (typeof (OneWayAttribute), false);
                }
 
                internal static bool IsAsyncMessage(IMessage msg)
@@ -349,7 +435,14 @@ namespace System.Runtime.Remoting
 
                public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
                {
-                       if (IsTransparentProxy (obj)) throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
+                       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);
                }
 
@@ -423,10 +516,9 @@ namespace System.Runtime.Remoting
                        // It will also get the object uri from the url.
 
                        object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
-                       string url = (channelData == null) ? objRef.URI : null;
 
                        string objectUri;
-                       IMessageSink sink = GetClientChannelSinkChain (url, channelData, out objectUri);
+                       IMessageSink sink = GetClientChannelSinkChain (objRef.URI, channelData, out objectUri);
 
                        if (objectUri == null) objectUri = objRef.URI;
 
@@ -458,6 +550,10 @@ namespace System.Runtime.Remoting
                                if (proxyType != null)
                                {
                                        RemotingProxy proxy = new RemotingProxy (proxyType, identity);
+                                       CrossAppDomainSink cds = sink as CrossAppDomainSink;
+                                       if (cds != null)
+                                               proxy.SetTargetDomain (cds.TargetDomainId);
+
                                        clientProxy = proxy.GetTransparentProxy();
                                        identity.ClientProxy = (MarshalByRefObject) clientProxy;
                                }
@@ -538,7 +634,88 @@ namespace System.Runtime.Remoting
                        GetOrCreateClientIdentity (objRef, proxyType, out proxy);
                        return proxy;
                }
+               
+               // This method is called by the runtime
+               internal static object GetServerObject (string uri)
+               {
+                       ClientActivatedIdentity identity = GetIdentityForUri (uri) as ClientActivatedIdentity;
+                       if (identity == null) throw new RemotingException ("Server for uri '" + uri + "' not found");
+                       return identity.GetServerObject ();
+               }
+
+               // This method is called by the runtime
+               internal static byte[] SerializeCallData (object obj)
+               {
+                       LogicalCallContext ctx = CallContext.CreateLogicalCallContext (false);
+                       if (ctx != null) {
+                               CACD cad = new CACD ();
+                               cad.d = obj;
+                               cad.c = ctx;
+                               obj = cad;
+                       }
+                       
+                       if (obj == null) return null;
+                       MemoryStream ms = new MemoryStream ();
+                       _serializationFormatter.Serialize (ms, obj);
+                       return ms.ToArray ();
+               }
 
+               // This method is called by the runtime
+               internal static object DeserializeCallData (byte[] array)
+               {
+                       if (array == null) return null;
+                       
+                       MemoryStream ms = new MemoryStream (array);
+                       object obj = _deserializationFormatter.Deserialize (ms);
+                       
+                       if (obj is CACD) {
+                               CACD cad = (CACD) obj;
+                               obj = cad.d;
+                               CallContext.UpdateCurrentCallContext ((LogicalCallContext) cad.c);
+                       }
+                       return obj;
+               }
+               
+               // This method is called by the runtime
+               internal static byte[] SerializeExceptionData (Exception ex)
+               {
+                       try {
+                               int retry = 4;
+                               
+                               do {
+                                       try {
+                                               MemoryStream ms = new MemoryStream ();
+                                               _serializationFormatter.Serialize (ms, ex);
+                                               return ms.ToArray ();
+                                       }
+                                       catch (Exception e) {
+                                               if (e is ThreadAbortException) {
+                                                       Thread.ResetAbort ();
+                                                       retry = 5;
+                                                       ex = e;
+                                               }
+                                               else if (retry == 2) {
+                                                       ex = new Exception ();
+                                                       ex.SetMessage (e.Message);
+                                                       ex.SetStackTrace (e.StackTrace);
+                                               }
+                                               else
+                                                       ex = e;
+                                       }
+                                       retry--;
+                               }
+                               while (retry > 0);
+                               
+                               return null;
+                       }
+                       catch (Exception tex)
+                       {
+                               byte[] data = SerializeExceptionData (tex);
+                               Thread.ResetAbort ();
+                               return data;
+                       }
+               }
+               
                internal static object GetDomainProxy(AppDomain domain) 
                {
                        byte[] data = null;