merge r98600
[mono.git] / mcs / class / corlib / System.Runtime.Remoting.Proxies / RealProxy.cs
1 //
2 // System.Runtime.Remoting.Proxies.RealProxy.cs
3 //
4 // Authors:
5 //   Dietmar Maurer (dietmar@ximian.com)
6 //   Lluis Sanchez (lsg@ctv.es)
7 //   Patrik Torstensson
8 //
9 // (C) 2001 Ximian, Inc.  http://www.ximian.com
10 //
11
12 //
13 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
14 //
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:
22 // 
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
25 // 
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.
33 //
34
35 using System;
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
44 #if NET_2_0
45 using System.Runtime.InteropServices;
46 #endif
47
48 namespace System.Runtime.Remoting.Proxies
49 {
50         internal class TransparentProxy {
51                 public RealProxy _rp;
52                 IntPtr _class;
53                 bool _custom_type_info;
54         }
55         
56 #if NET_2_0
57         [ComVisible (true)]
58 #endif
59         public abstract class RealProxy {
60                 // other classes visible to the runtime 
61                 // derive from this class so keep these locals
62                 // in sync with the definition RealProxy 
63                 // in object-internals.h
64                 #region Sync with object-internals.h
65                 Type class_to_proxy;
66                 internal Context _targetContext;
67                 MarshalByRefObject _server;
68                 int _targetDomainId = -1;
69                 internal string _targetUri;
70                 internal Identity _objectIdentity;
71                 Object _objTP;\r
72                 object _stubData;\r
73         #endregion
74
75                 protected RealProxy ()
76                 {
77                 }
78
79                 protected RealProxy (Type classToProxy) : this(classToProxy, IntPtr.Zero, null)
80                 {
81                 }
82
83                 internal RealProxy (Type classToProxy, ClientIdentity identity) : this(classToProxy, IntPtr.Zero, null)
84                 {
85                         _objectIdentity = identity;
86                 }
87
88                 protected RealProxy (Type classToProxy, IntPtr stub, object stubData)
89                 {
90                         if (!classToProxy.IsMarshalByRef && !classToProxy.IsInterface)
91                                 throw new ArgumentException("object must be MarshalByRef");
92
93                         this.class_to_proxy = classToProxy;
94
95                         if (stub != IntPtr.Zero)
96                                 throw new NotSupportedException ("stub is not used in Mono");
97                 }
98
99                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
100                 extern static Type InternalGetProxyType (object transparentProxy);
101                 
102                 public Type GetProxiedType() 
103                 {
104                         if (_objTP == null) {
105                                 if (class_to_proxy.IsInterface) return typeof(MarshalByRefObject);
106                                 else return class_to_proxy;
107                         }
108                         return InternalGetProxyType (_objTP);
109                 }
110
111                 public virtual ObjRef CreateObjRef (Type requestedType)
112                 {
113                         return RemotingServices.Marshal ((MarshalByRefObject) GetTransparentProxy(), null, requestedType);
114                 }
115
116                 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
117                 {
118                         Object obj = GetTransparentProxy();\r
119                         RemotingServices.GetObjectData (obj, info, context);            \r
120                 }
121                 
122                 internal Identity ObjectIdentity
123                 {
124                         get { return _objectIdentity; }
125                         set { _objectIdentity = value; }
126                 }
127                 
128                 [MonoTODO]
129                 public virtual IntPtr GetCOMIUnknown (bool fIsMarshalled)
130                 {
131                         throw new NotImplementedException ();
132                 }
133                 
134                 [MonoTODO]
135                 public virtual void SetCOMIUnknown (IntPtr i)
136                 {
137                         throw new NotImplementedException ();
138                 }
139                 
140                 [MonoTODO]
141                 public virtual IntPtr SupportsInterface (ref Guid iid)
142                 {
143                         throw new NotImplementedException ();
144                 }
145                 
146                 public static object GetStubData (RealProxy rp)
147                 {
148                         return rp._stubData;
149                 }
150                 
151                 public static void SetStubData (RealProxy rp, object stubData)
152                 {
153                         rp._stubData = stubData;
154                 }
155
156                 public abstract IMessage Invoke (IMessage msg);
157
158                 /* this is called from unmanaged code */
159                 internal static object PrivateInvoke (RealProxy rp, IMessage msg, out Exception exc,
160                                                       out object [] out_args)
161                 {
162                         MonoMethodMessage mMsg = (MonoMethodMessage) msg;
163                         mMsg.LogicalCallContext = CallContext.CreateLogicalCallContext (true);
164                         CallType call_type = mMsg.CallType;
165                         bool is_remproxy = (rp is RemotingProxy);
166
167                         IMethodReturnMessage res_msg = null;
168                         
169                         if (call_type == CallType.BeginInvoke) \r
170                                 // todo: set CallMessage in runtime instead
171                                 mMsg.AsyncResult.CallMessage = mMsg;
172
173                         if (call_type == CallType.EndInvoke)
174                                 res_msg = (IMethodReturnMessage)mMsg.AsyncResult.EndInvoke ();
175
176                         // Check for constructor msg
177                         if (mMsg.MethodBase.IsConstructor) \r
178                         {
179                                 if (is_remproxy) \r
180                                         res_msg = (IMethodReturnMessage) (rp as RemotingProxy).ActivateRemoteObject ((IMethodMessage) msg);
181                                 else \r
182                                         msg = new ConstructionCall (rp.GetProxiedType ());
183                         }
184                                 
185                         if (null == res_msg) 
186                         {
187                                 res_msg = (IMethodReturnMessage)rp.Invoke (msg);
188 \r
189                                 // Note, from begining this code used AsyncResult.IsCompleted for\r
190                                 // checking if it was a remoting or custom proxy, but in some\r
191                                 // cases the remoting proxy finish before the call returns\r
192                                 // causing this method to be called, therefore causing all kind of bugs.\r
193                                 if ((!is_remproxy) && call_type == CallType.BeginInvoke)\r
194                                 {\r
195                                         IMessage asyncMsg = null;
196
197                                         // allow calltype EndInvoke to finish
198                                         asyncMsg = mMsg.AsyncResult.SyncProcessMessage (res_msg as IMessage);
199                                         res_msg = new ReturnMessage (asyncMsg, null, 0, null, res_msg as IMethodCallMessage);
200                                 }\r
201                         }
202                         
203                         if (res_msg.LogicalCallContext != null && res_msg.LogicalCallContext.HasInfo)
204                                 CallContext.UpdateCurrentCallContext (res_msg.LogicalCallContext);
205
206                         exc = res_msg.Exception;
207
208                         // todo: remove throw exception from the runtime invoke
209                         if (null != exc) {
210                                 out_args = null;
211                                 throw exc.FixRemotingException();
212                         }
213                         else if (res_msg is IConstructionReturnMessage || mMsg.CallType == CallType.BeginInvoke) {
214                                 out_args = res_msg.OutArgs;
215                         }
216                         else if (mMsg.CallType == CallType.Sync) {
217                                 out_args = ProcessResponse (res_msg, mMsg);
218                         }
219                         else if (mMsg.CallType == CallType.EndInvoke) {
220                                 out_args = ProcessResponse (res_msg, mMsg.AsyncResult.CallMessage);
221                         }
222                         else {
223                                 out_args = res_msg.OutArgs;
224                         }
225
226                         return res_msg.ReturnValue;
227                 }
228
229                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
230                 internal extern virtual object InternalGetTransparentProxy (string className);
231
232                 public virtual object GetTransparentProxy () 
233                 {
234                         if (_objTP == null) 
235                         {
236                                 string name;
237                                 IRemotingTypeInfo rti = this as IRemotingTypeInfo;
238                                 
239                                 if (rti != null) {
240                                         name = rti.TypeName;
241                                         if (name == null || name == typeof(MarshalByRefObject).AssemblyQualifiedName)
242                                                 name = class_to_proxy.AssemblyQualifiedName;
243                                 }
244                                 else
245                                         name = class_to_proxy.AssemblyQualifiedName;
246                                         
247                                 _objTP = InternalGetTransparentProxy (name);
248                         }
249                         return _objTP;
250                 }
251
252                 [MonoTODO]
253 #if NET_2_0
254                 [ComVisible (true)]
255 #endif
256                 public IConstructionReturnMessage InitializeServerObject(IConstructionCallMessage ctorMsg)
257                 {
258                         throw new NotImplementedException();
259                 }
260
261                 protected void AttachServer(MarshalByRefObject s)
262                 {
263                         _server = s;
264                 }
265
266                 protected MarshalByRefObject DetachServer()
267                 {
268                         MarshalByRefObject ob = _server;
269                         _server = null;
270                         return ob;
271                 }
272
273                 protected MarshalByRefObject GetUnwrappedServer()
274                 {
275                         return _server;
276                 }
277                 
278                 internal void SetTargetDomain (int domainId)
279                 {
280                         _targetDomainId = domainId;
281                 }
282                 
283                 // Called by the runtime
284                 internal object GetAppDomainTarget ()
285                 {
286                         if (_server == null) {
287                                 ClientActivatedIdentity identity = RemotingServices.GetIdentityForUri (_targetUri) as ClientActivatedIdentity;
288                                 if (identity == null) throw new RemotingException ("Server for uri '" + _targetUri + "' not found");
289                                 _server = identity.GetServerObject ();
290                         }
291                         return _server;
292                 }
293
294                 static object[] ProcessResponse (IMethodReturnMessage mrm, MonoMethodMessage call)
295                 {
296                         // Check return type
297
298                         MethodInfo mi = (MethodInfo) call.MethodBase;
299                         if (mrm.ReturnValue != null && !mi.ReturnType.IsInstanceOfType (mrm.ReturnValue))
300                                 throw new InvalidCastException ("Return value has an invalid type");
301
302                         // Check out parameters
303
304                         
305                         int no;
306                         
307                         if (call.NeedsOutProcessing (out no))
308                         {
309                                 ParameterInfo[] parameters = mi.GetParameters();
310                                 object[] outArgs = new object [no];
311                                 int narg = 0;
312         
313                                 foreach (ParameterInfo par in parameters)
314                                 {
315                                         if (par.IsOut && !par.ParameterType.IsByRef)
316                                         {
317                                                 // Special marshalling required
318                                                 object outArg = par.Position < mrm.ArgCount ? mrm.GetArg (par.Position) : null;
319                                                 if (outArg != null) {
320                                                         object local = call.GetArg (par.Position);
321                                                         if (local == null) throw new RemotingException ("Unexpected null value in local out parameter '" + par.Name + "'");
322                                                         RemotingServices.UpdateOutArgObject (par, local, outArg);
323                                                 }
324                                         }
325                                         else if (par.ParameterType.IsByRef)
326                                         {
327                                                 object outArg = par.Position < mrm.ArgCount ? mrm.GetArg (par.Position) : null;
328                                                 if (outArg != null && !par.ParameterType.GetElementType ().IsInstanceOfType (outArg))
329                                                 {
330                                                         throw new InvalidCastException ("Return argument '" + par.Name + "' has an invalid type");
331                                                 }
332                                                 outArgs [narg++] = outArg;
333                                         }
334                                 }
335                                 return outArgs;
336                         }
337                         else
338                                 return new object [0];
339                 }
340         }
341 }