463aded43a0c48e9d5f738d81ef8aff68b063179
[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
45 namespace System.Runtime.Remoting.Proxies
46 {
47         internal class TransparentProxy {
48                 public RealProxy _rp;
49                 IntPtr _class;
50                 bool _custom_type_info;
51         }
52         
53         public abstract class RealProxy {
54
55                 Type class_to_proxy;
56                 internal Context _targetContext;
57                 MarshalByRefObject _server;
58                 internal Identity _objectIdentity;
59                 Object _objTP;
60                 object _stubData;
61
62                 protected RealProxy ()
63                 {
64                 }
65
66                 protected RealProxy (Type classToProxy) : this(classToProxy, IntPtr.Zero, null)
67                 {
68                 }
69
70                 internal RealProxy (Type classToProxy, ClientIdentity identity) : this(classToProxy, IntPtr.Zero, null)
71                 {
72                         _objectIdentity = identity;
73                 }
74
75                 protected RealProxy (Type classToProxy, IntPtr stub, object stubData)
76                 {
77                         if (!classToProxy.IsMarshalByRef && !classToProxy.IsInterface)
78                                 throw new ArgumentException("object must be MarshalByRef");
79
80                         this.class_to_proxy = classToProxy;
81
82                         if (stub != IntPtr.Zero)
83                                 throw new NotSupportedException ("stub is not used in Mono");
84                 }
85
86                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
87                 extern static Type InternalGetProxyType (object transparentProxy);
88                 
89                 public Type GetProxiedType() 
90                 {
91                         if (_objTP == null) {
92                                 if (class_to_proxy.IsInterface) return typeof(MarshalByRefObject);
93                                 else return class_to_proxy;
94                         }
95                         return InternalGetProxyType (_objTP);
96                 }
97
98                 public virtual ObjRef CreateObjRef (Type requestedType)
99                 {
100                         return RemotingServices.Marshal ((MarshalByRefObject) GetTransparentProxy(), null, requestedType);
101                 }
102
103                 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
104                 {
105                         Object obj = GetTransparentProxy();\r
106                         RemotingServices.GetObjectData (obj, info, context);            \r
107                 }
108                 
109                 internal Identity ObjectIdentity
110                 {
111                         get { return _objectIdentity; }
112                         set { _objectIdentity = value; }
113                 }
114                 
115                 [MonoTODO]
116                 public virtual IntPtr GetCOMIUnknown (bool fIsMarshalled)
117                 {
118                         throw new NotImplementedException ();
119                 }
120                 
121                 [MonoTODO]
122                 public virtual void SetCOMIUnknown (IntPtr i)
123                 {
124                         throw new NotImplementedException ();
125                 }
126                 
127                 [MonoTODO]
128                 public virtual IntPtr SupportsInterface (ref Guid iid)
129                 {
130                         throw new NotImplementedException ();
131                 }
132                 
133                 public static object GetStubData (RealProxy rp)
134                 {
135                         return rp._stubData;
136                 }
137                 
138                 public static void SetStubData (RealProxy rp, object stubData)
139                 {
140                         rp._stubData = stubData;
141                 }
142
143                 public abstract IMessage Invoke (IMessage msg);
144
145                 /* this is called from unmanaged code */
146                 internal static object PrivateInvoke (RealProxy rp, IMessage msg, out Exception exc,
147                                                       out object [] out_args)
148                 {
149                         MonoMethodMessage mMsg = (MonoMethodMessage) msg;
150                         mMsg.LogicalCallContext = CallContext.CreateLogicalCallContext();
151                         CallType call_type = mMsg.CallType;
152                         bool is_remproxy = (rp as RemotingProxy) != null;
153
154                         IMethodReturnMessage res_msg = null;
155                         
156                         if (call_type == CallType.BeginInvoke) \r
157                                 // todo: set CallMessage in runtime instead
158                                 mMsg.AsyncResult.CallMessage = mMsg;
159
160                         if (call_type == CallType.EndInvoke)
161                                 res_msg = (IMethodReturnMessage)mMsg.AsyncResult.EndInvoke ();
162
163                         // Check for constructor msg
164                         if (mMsg.MethodBase.IsConstructor) \r
165                         {
166                                 if (is_remproxy) \r
167                                         res_msg = (IMethodReturnMessage) (rp as RemotingProxy).ActivateRemoteObject ((IMethodMessage) msg);
168                                 else \r
169                                         msg = new ConstructionCall (rp.GetProxiedType ());
170                         }
171                                 
172                         if (null == res_msg) 
173                         {
174                                 res_msg = (IMethodReturnMessage)rp.Invoke (msg);
175 \r
176                                 // Note, from begining this code used AsyncResult.IsCompleted for\r
177                                 // checking if it was a remoting or custom proxy, but in some\r
178                                 // cases the remoting proxy finish before the call returns\r
179                                 // causing this method to be called, therefore causing all kind of bugs.\r
180                                 if ((!is_remproxy) && call_type == CallType.BeginInvoke)\r
181                                 {\r
182                                         IMessage asyncMsg = null;
183
184                                         // allow calltype EndInvoke to finish
185                                         asyncMsg = mMsg.AsyncResult.SyncProcessMessage (res_msg as IMessage);
186                                         res_msg = new ReturnMessage (asyncMsg, null, 0, null, res_msg as IMethodCallMessage);
187                                 }\r
188                         }
189                         
190                         if (res_msg.LogicalCallContext != null && res_msg.LogicalCallContext.HasInfo)
191                                 CallContext.UpdateCurrentCallContext (res_msg.LogicalCallContext);
192
193                         exc = res_msg.Exception;
194
195                         // todo: remove throw exception from the runtime invoke
196                         if (null != exc) {
197                                 out_args = null;
198                                 throw exc.FixRemotingException();
199                         }
200                         else if (res_msg is IConstructionReturnMessage || mMsg.CallType == CallType.BeginInvoke) {
201                                 out_args = res_msg.OutArgs;
202                         }
203                         else if (mMsg.CallType == CallType.Sync) {
204                                 out_args = ProcessResponse (res_msg, mMsg);
205                         }
206                         else if (mMsg.CallType == CallType.EndInvoke) {
207                                 out_args = ProcessResponse (res_msg, mMsg.AsyncResult.CallMessage);
208                         }
209                         else {
210                                 out_args = res_msg.OutArgs;
211                         }
212
213                         return res_msg.ReturnValue;
214                 }
215
216                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
217                 internal extern virtual object InternalGetTransparentProxy (string className);
218
219                 public virtual object GetTransparentProxy () 
220                 {
221                         if (_objTP == null) 
222                         {
223                                 string name;
224                                 IRemotingTypeInfo rti = this as IRemotingTypeInfo;
225                                 
226                                 if (rti != null) {
227                                         name = rti.TypeName;
228                                         if (name == null || name == typeof(MarshalByRefObject).AssemblyQualifiedName)
229                                                 name = class_to_proxy.AssemblyQualifiedName;
230                                 }
231                                 else
232                                         name = class_to_proxy.AssemblyQualifiedName;
233                                         
234                                 _objTP = InternalGetTransparentProxy (name);
235                         }
236                         return _objTP;
237                 }
238
239                 [MonoTODO]
240                 public IConstructionReturnMessage InitializeServerObject(IConstructionCallMessage ctorMsg)
241                 {
242                         throw new NotImplementedException();
243                 }
244
245                 protected void AttachServer(MarshalByRefObject s)
246                 {
247                         _server = s;
248                 }
249
250                 protected MarshalByRefObject DetachServer()
251                 {
252                         MarshalByRefObject ob = _server;
253                         _server = null;
254                         return ob;
255                 }
256
257                 protected MarshalByRefObject GetUnwrappedServer()
258                 {
259                         return _server;
260                 }
261
262                 static object[] ProcessResponse (IMethodReturnMessage mrm, IMethodCallMessage call)
263                 {
264                         // Check return type
265
266                         MethodInfo mi = (MethodInfo) call.MethodBase;
267                         if (mrm.ReturnValue != null && !mi.ReturnType.IsInstanceOfType (mrm.ReturnValue))
268                                 throw new RemotingException ("Return value has an invalid type");
269
270                         // Check out parameters
271
272                         if (mrm.OutArgCount > 0)
273                         {
274                                 ParameterInfo[] parameters = mi.GetParameters();
275                                 int no = 0;
276                                 foreach (ParameterInfo par in parameters)
277                                         if (par.ParameterType.IsByRef) no++;
278                                 
279                                 object[] outArgs = new object [no];
280                                 int narg = 0;
281                                 int nout = 0;
282         
283                                 foreach (ParameterInfo par in parameters)
284                                 {
285                                         if (par.IsOut && !par.ParameterType.IsByRef)
286                                         {
287                                                 // Special marshalling required
288                                                 
289                                                 object outArg = mrm.GetOutArg (nout++);
290                                                 if (outArg != null) {
291                                                         object local = call.GetArg (par.Position);
292                                                         if (local == null) throw new RemotingException ("Unexpected null value in local out parameter '" + par.Position + " " + par.Name + "'");
293                                                         RemotingServices.UpdateOutArgObject (par, local, outArg);
294                                                 }
295                                         }
296                                         else if (par.ParameterType.IsByRef)
297                                         {
298                                                 object outArg = mrm.GetOutArg (nout++);
299                                                 if (outArg != null && !par.ParameterType.IsInstanceOfType (outArg))
300                                                 {
301                                                         throw new RemotingException ("Return argument '" + par.Name + "' has an invalid type");
302                                                 }
303                                                 outArgs [narg++] = outArg;
304                                         }
305                                 }
306                                 return outArgs;
307                         }
308                         else
309                                 return new object [0];
310                 }
311         }
312 }