2 // System.Runtime.Remoting.Proxies.RealProxy.cs
5 // Dietmar Maurer (dietmar@ximian.com)
6 // Lluis Sanchez (lsg@ctv.es)
9 // (C) 2001 Ximian, Inc. http://www.ximian.com
13 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Reflection;
37 using System.Runtime.Remoting;
38 using System.Runtime.Remoting.Messaging;
39 using System.Runtime.Remoting.Activation;
40 using System.Runtime.Remoting.Contexts;
41 using System.Runtime.CompilerServices;
42 using System.Runtime.Serialization;
43 using System.Runtime.InteropServices;
44 using System.Threading;
46 namespace System.Runtime.Remoting.Proxies
48 #pragma warning disable 169, 649
49 [StructLayout (LayoutKind.Sequential)]
50 internal class TransparentProxy {
52 Mono.RuntimeRemoteClassHandle _class;
53 bool _custom_type_info;
55 unsafe internal RuntimeType GetProxyType () {
56 RuntimeTypeHandle h = _class.ProxyClass.GetTypeHandle ();
57 return (RuntimeType)Type.GetTypeFromHandle (h);
60 bool IsContextBoundObject {
61 get { return GetProxyType ().IsContextful; }
64 Context TargetContext {
65 get { return _rp._targetContext; }
68 bool InCurrentContext () {
69 return IsContextBoundObject && Object.ReferenceEquals (TargetContext, Thread.CurrentContext);
72 internal object LoadRemoteFieldNew (IntPtr classPtr, IntPtr fieldPtr) {
73 Mono.RuntimeClassHandle classHandle = new Mono.RuntimeClassHandle (classPtr);
74 RuntimeFieldHandle fieldHandle = new RuntimeFieldHandle (fieldPtr);
75 RuntimeTypeHandle typeHandle = classHandle.GetTypeHandle ();
77 FieldInfo field = FieldInfo.GetFieldFromHandle (fieldHandle);
79 if (InCurrentContext ()) {
80 object o = _rp._server;
81 return field.GetValue(o);
84 object[] inArgs = new object[] { Type.GetTypeFromHandle(typeHandle).FullName,
86 object[] outArgsMsg = new object[1];
87 MethodInfo minfo = typeof(object).GetMethod("FieldGetter", BindingFlags.NonPublic | BindingFlags.Instance);
89 throw new MissingMethodException ("System.Object", "FieldGetter");
90 MonoMethodMessage msg = new MonoMethodMessage (minfo, inArgs, outArgsMsg);
93 RealProxy.PrivateInvoke (_rp, msg, out exc, out outArgs);
99 #pragma warning restore 169, 649
102 [StructLayout (LayoutKind.Sequential)]
103 public abstract class RealProxy {
104 // other classes visible to the runtime
105 // derive from this class so keep these locals
106 // in sync with the definition RealProxy
107 // in object-internals.h
109 #pragma warning disable 169, 414
110 #region Sync with object-internals.h
112 internal Context _targetContext;
113 internal MarshalByRefObject _server;
114 int _targetDomainId = -1;
115 internal string _targetUri;
116 internal Identity _objectIdentity;
120 #pragma warning restore 169, 414
122 protected RealProxy ()
126 protected RealProxy (Type classToProxy) : this(classToProxy, IntPtr.Zero, null)
130 internal RealProxy (Type classToProxy, ClientIdentity identity) : this(classToProxy, IntPtr.Zero, null)
132 _objectIdentity = identity;
135 protected RealProxy (Type classToProxy, IntPtr stub, object stubData)
137 if (!classToProxy.IsMarshalByRef && !classToProxy.IsInterface)
138 throw new ArgumentException("object must be MarshalByRef");
140 this.class_to_proxy = classToProxy;
142 if (stub != IntPtr.Zero)
143 throw new NotSupportedException ("stub is not used in Mono");
146 [MethodImplAttribute(MethodImplOptions.InternalCall)]
147 extern static Type InternalGetProxyType (object transparentProxy);
149 public Type GetProxiedType()
151 if (_objTP == null) {
152 if (class_to_proxy.IsInterface) return typeof(MarshalByRefObject);
153 else return class_to_proxy;
155 return InternalGetProxyType (_objTP);
158 public virtual ObjRef CreateObjRef (Type requestedType)
160 return RemotingServices.Marshal ((MarshalByRefObject) GetTransparentProxy(), null, requestedType);
163 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
165 Object obj = GetTransparentProxy();
166 RemotingServices.GetObjectData (obj, info, context);
169 internal Identity ObjectIdentity
171 get { return _objectIdentity; }
172 set { _objectIdentity = value; }
176 public virtual IntPtr GetCOMIUnknown (bool fIsMarshalled)
178 throw new NotImplementedException ();
182 public virtual void SetCOMIUnknown (IntPtr i)
184 throw new NotImplementedException ();
188 public virtual IntPtr SupportsInterface (ref Guid iid)
190 throw new NotImplementedException ();
193 public static object GetStubData (RealProxy rp)
198 public static void SetStubData (RealProxy rp, object stubData)
200 rp._stubData = stubData;
203 public abstract IMessage Invoke (IMessage msg);
205 /* this is called from unmanaged code */
206 internal static object PrivateInvoke (RealProxy rp, IMessage msg, out Exception exc,
207 out object [] out_args)
209 MonoMethodMessage mMsg = (MonoMethodMessage) msg;
210 mMsg.LogicalCallContext = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
211 CallType call_type = mMsg.CallType;
212 bool is_remproxy = (rp is RemotingProxy);
215 IMethodReturnMessage res_msg = null;
217 if (call_type == CallType.BeginInvoke)
218 // todo: set CallMessage in runtime instead
219 mMsg.AsyncResult.CallMessage = mMsg;
221 if (call_type == CallType.EndInvoke)
222 res_msg = (IMethodReturnMessage)mMsg.AsyncResult.EndInvoke ();
224 // Check for constructor msg
225 if (mMsg.MethodBase.IsConstructor)
228 res_msg = (IMethodReturnMessage) (rp as RemotingProxy).ActivateRemoteObject ((IMethodMessage) msg);
230 msg = new ConstructionCall (rp.GetProxiedType ());
238 res_msg = (IMethodReturnMessage)rp.Invoke (msg);
239 } catch (Exception ex) {
241 if (call_type == CallType.BeginInvoke) {
242 // If async dispatch crashes, don't propagate the exception.
243 // The exception will be raised when calling EndInvoke.
244 mMsg.AsyncResult.SyncProcessMessage (new ReturnMessage (ex, msg as IMethodCallMessage));
245 res_msg = new ReturnMessage (null, null, 0, null, msg as IMethodCallMessage);
250 // Note, from begining this code used AsyncResult.IsCompleted for
251 // checking if it was a remoting or custom proxy, but in some
252 // cases the remoting proxy finish before the call returns
253 // causing this method to be called, therefore causing all kind of bugs.
254 if ((!is_remproxy) && call_type == CallType.BeginInvoke && !failed)
256 IMessage asyncMsg = null;
258 // allow calltype EndInvoke to finish
259 asyncMsg = mMsg.AsyncResult.SyncProcessMessage (res_msg as IMessage);
260 out_args = res_msg.OutArgs;
261 res_msg = new ReturnMessage (asyncMsg, null, 0, null, res_msg as IMethodCallMessage);
265 if (res_msg.LogicalCallContext != null && res_msg.LogicalCallContext.HasInfo) {
266 Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext.Merge (res_msg.LogicalCallContext);
269 exc = res_msg.Exception;
271 // todo: remove throw exception from the runtime invoke
274 throw exc.FixRemotingException();
276 else if (res_msg is IConstructionReturnMessage) {
277 if (out_args == null)
278 out_args = res_msg.OutArgs;
280 else if (mMsg.CallType == CallType.BeginInvoke) {
281 // We don't have OutArgs in this case.
283 else if (mMsg.CallType == CallType.Sync) {
284 out_args = ProcessResponse (res_msg, mMsg);
286 else if (mMsg.CallType == CallType.EndInvoke) {
287 out_args = ProcessResponse (res_msg, mMsg.AsyncResult.CallMessage);
290 if (out_args == null)
291 out_args = res_msg.OutArgs;
294 return res_msg.ReturnValue;
297 [MethodImplAttribute(MethodImplOptions.InternalCall)]
298 internal extern virtual object InternalGetTransparentProxy (string className);
300 public virtual object GetTransparentProxy ()
305 IRemotingTypeInfo rti = this as IRemotingTypeInfo;
309 if (name == null || name == typeof(MarshalByRefObject).AssemblyQualifiedName)
310 name = class_to_proxy.AssemblyQualifiedName;
313 name = class_to_proxy.AssemblyQualifiedName;
315 _objTP = InternalGetTransparentProxy (name);
322 public IConstructionReturnMessage InitializeServerObject(IConstructionCallMessage ctorMsg)
324 throw new NotImplementedException();
327 protected void AttachServer(MarshalByRefObject s)
332 protected MarshalByRefObject DetachServer()
334 MarshalByRefObject ob = _server;
339 protected MarshalByRefObject GetUnwrappedServer()
344 internal void SetTargetDomain (int domainId)
346 _targetDomainId = domainId;
349 // Called by the runtime
350 internal object GetAppDomainTarget ()
352 if (_server == null) {
353 ClientActivatedIdentity identity = RemotingServices.GetIdentityForUri (_targetUri) as ClientActivatedIdentity;
354 if (identity == null) throw new RemotingException ("Server for uri '" + _targetUri + "' not found");
355 _server = identity.GetServerObject ();
360 static object[] ProcessResponse (IMethodReturnMessage mrm, MonoMethodMessage call)
364 MethodInfo mi = (MethodInfo) call.MethodBase;
365 if (mrm.ReturnValue != null && !mi.ReturnType.IsInstanceOfType (mrm.ReturnValue))
366 throw new InvalidCastException ("Return value has an invalid type");
368 // Check out parameters
373 if (call.NeedsOutProcessing (out no))
375 ParameterInfo[] parameters = mi.GetParameters();
376 object[] outArgs = new object [no];
379 foreach (ParameterInfo par in parameters)
381 if (par.IsOut && !par.ParameterType.IsByRef)
383 // Special marshalling required
384 object outArg = par.Position < mrm.ArgCount ? mrm.GetArg (par.Position) : null;
385 if (outArg != null) {
386 object local = call.GetArg (par.Position);
387 if (local == null) throw new RemotingException ("Unexpected null value in local out parameter '" + par.Name + "'");
388 RemotingServices.UpdateOutArgObject (par, local, outArg);
391 else if (par.ParameterType.IsByRef)
393 object outArg = par.Position < mrm.ArgCount ? mrm.GetArg (par.Position) : null;
394 if (outArg != null && !par.ParameterType.GetElementType ().IsInstanceOfType (outArg))
396 throw new InvalidCastException ("Return argument '" + par.Name + "' has an invalid type");
398 outArgs [narg++] = outArg;
404 return new object [0];