New tests, updates
[mono.git] / mcs / class / corlib / System.Runtime.Remoting / RemotingServices.cs
1 //
2 // System.Runtime.Remoting.RemotingServices.cs
3 //
4 // Authors:
5 //   Dietmar Maurer (dietmar@ximian.com)
6 //   Lluis Sanchez Gual (lluis@ideary.com)
7 //   Patrik Torstensson
8 //
9 // (C) 2001 Ximian, Inc.  http://www.ximian.com
10 // Copyright (C) 2004, 2006 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.Diagnostics;
33 using System.Text;
34 using System.Reflection;
35 using System.Threading;
36 using System.Collections;
37 using System.Runtime.Remoting.Messaging;
38 using System.Runtime.Remoting.Proxies;
39 using System.Runtime.Remoting.Channels;
40 using System.Runtime.Remoting.Contexts;
41 using System.Runtime.Remoting.Activation;
42 using System.Runtime.Remoting.Lifetime;
43 using System.Runtime.CompilerServices;
44 using System.Runtime.Serialization;
45 using System.Runtime.Serialization.Formatters.Binary;
46 using System.IO;
47 using System.Runtime.Remoting.Services;
48 using System.Security.Permissions;
49
50 #if NET_2_0
51 using System.Runtime.ConstrainedExecution;
52 using System.Runtime.Serialization.Formatters;
53 #endif
54
55 namespace System.Runtime.Remoting
56 {
57 #if NET_2_0
58         [System.Runtime.InteropServices.ComVisible (true)]
59 #endif
60         public sealed class RemotingServices 
61         {
62                 // Holds the identities of the objects, using uri as index
63                 static Hashtable uri_hash = new Hashtable ();           
64
65                 static BinaryFormatter _serializationFormatter;
66                 static BinaryFormatter _deserializationFormatter;
67                 
68                 internal static string app_id;
69                 static int next_id = 1;
70                 static readonly BindingFlags methodBindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
71                 static readonly MethodInfo FieldSetterMethod;
72                 static readonly MethodInfo FieldGetterMethod;
73                 
74                 // Holds information in xdomain calls. Names are short to minimize serialized size.
75                 [Serializable]
76                 class CACD {
77                         public object d;        /* call data */
78                         public object c;        /* call context */
79                 }
80                 
81                 static RemotingServices ()
82                 {
83                         RemotingSurrogateSelector surrogateSelector = new RemotingSurrogateSelector ();
84                         StreamingContext context = new StreamingContext (StreamingContextStates.Remoting, null);
85                         _serializationFormatter = new BinaryFormatter (surrogateSelector, context);
86                         _deserializationFormatter = new BinaryFormatter (null, context);
87 #if NET_2_0
88                         _serializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
89                         _deserializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
90 #endif
91                         
92                         RegisterInternalChannels ();
93                         app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
94                         CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
95                         
96                         FieldSetterMethod = typeof(object).GetMethod ("FieldSetter", BindingFlags.NonPublic|BindingFlags.Instance);
97                         FieldGetterMethod = typeof(object).GetMethod ("FieldGetter", BindingFlags.NonPublic|BindingFlags.Instance);
98                 }
99         
100                 private RemotingServices () {}
101
102                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
103                 internal extern static object InternalExecute (MethodBase method, Object obj,
104                                                                Object[] parameters, out object [] out_args);
105
106                 // Returns the actual implementation of @method in @type.
107                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
108                 internal extern static MethodBase GetVirtualMethod (Type type, MethodBase method);
109
110 #if NET_2_0
111                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
112 #endif
113                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
114                 public extern static bool IsTransparentProxy (object proxy);
115                 
116                 internal static IMethodReturnMessage InternalExecuteMessage (
117                         MarshalByRefObject target, IMethodCallMessage reqMsg)
118                 {
119                         ReturnMessage result;
120                         
121                         Type tt = target.GetType ();
122                         MethodBase method;
123                         if (reqMsg.MethodBase.DeclaringType == tt ||
124                             reqMsg.MethodBase == FieldSetterMethod || 
125                             reqMsg.MethodBase == FieldGetterMethod) {
126                                 method = reqMsg.MethodBase;
127                         } else {
128                                 method = GetVirtualMethod (tt, reqMsg.MethodBase);
129
130                                 if (method == null)
131                                         throw new RemotingException (
132                                                 String.Format ("Cannot resolve method {0}:{1}", tt, reqMsg.MethodName));
133                         }
134
135 #if NET_2_0
136                         if (reqMsg.MethodBase.IsGenericMethod) {
137                                 Type[] genericArguments = reqMsg.MethodBase.GetGenericArguments ();
138                                 method = ((MethodInfo)method).MakeGenericMethod (genericArguments);
139                         }
140 #endif
141
142                         object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
143                         
144                         try 
145                         {
146                                 object [] out_args;
147                                 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
148                         
149                                 // Collect parameters with Out flag from the request message
150                                 // FIXME: This can be done in the unmanaged side and will be
151                                 // more efficient
152                                 
153                                 ParameterInfo[] parameters = method.GetParameters();
154                                 object[] returnArgs = new object [parameters.Length];
155                                 
156                                 int n = 0;
157                                 int noa = 0;
158                                 foreach (ParameterInfo par in parameters)
159                                 {
160                                         if (par.IsOut && !par.ParameterType.IsByRef) 
161                                                 returnArgs [n++] = reqMsg.GetArg (par.Position);
162                                         else if (par.ParameterType.IsByRef)
163                                                 returnArgs [n++] = out_args [noa++]; 
164                                         else
165                                                 returnArgs [n++] = null; 
166                                 }
167                                 
168                                 result = new ReturnMessage (rval, returnArgs, n, CallContext.CreateLogicalCallContext (true), reqMsg);
169                         } 
170                         catch (Exception e) 
171                         {
172                                 result = new ReturnMessage (e, reqMsg);
173                         }
174                         
175                         CallContext.RestoreCallContext (oldContext);
176                         return result;
177                 }
178
179                 public static IMethodReturnMessage ExecuteMessage (
180                         MarshalByRefObject target, IMethodCallMessage reqMsg)
181                 {
182                         if (IsTransparentProxy(target))
183                         {
184                                 // Message must go through all chain of sinks
185                                 RealProxy rp = GetRealProxy (target);
186                                 return (IMethodReturnMessage) rp.Invoke (reqMsg);
187                         }
188                         else    // Direct call
189                                 return InternalExecuteMessage (target, reqMsg);
190                 }
191
192 #if NET_2_0
193                 [System.Runtime.InteropServices.ComVisible (true)]
194 #endif
195                 public static object Connect (Type classToProxy, string url)
196                 {
197                         ObjRef objRef = new ObjRef (classToProxy, url, null);
198                         return GetRemoteObject (objRef, classToProxy);
199                 }
200
201 #if NET_2_0
202                 [System.Runtime.InteropServices.ComVisible (true)]
203 #endif
204                 public static object Connect (Type classToProxy, string url, object data)
205                 {
206                         ObjRef objRef = new ObjRef (classToProxy, url, data);
207                         return GetRemoteObject (objRef, classToProxy);
208                 }
209
210                 public static bool Disconnect (MarshalByRefObject obj)
211                 {
212                         if (obj == null) throw new ArgumentNullException ("obj");
213
214                         ServerIdentity identity;
215
216                         if (IsTransparentProxy (obj))
217                         {
218                                 // CBOs are always accessed through a proxy, even in the server, so
219                                 // for server CBOs it is ok to disconnect a proxy
220
221                                 RealProxy proxy = GetRealProxy(obj);
222                                 if (proxy.GetProxiedType().IsContextful && (proxy.ObjectIdentity is ServerIdentity))
223                                         identity = proxy.ObjectIdentity as ServerIdentity;
224                                 else
225                                         throw new ArgumentException ("The obj parameter is a proxy.");
226                         }
227                         else {
228                                 identity = obj.ObjectIdentity;
229                                 obj.ObjectIdentity = null;
230                         }
231
232                         if (identity == null || !identity.IsConnected)
233                                 return false;
234                         else
235                         {
236                                 LifetimeServices.StopTrackingLifetime (identity);
237                                 DisposeIdentity (identity);
238                                 TrackingServices.NotifyDisconnectedObject (obj);
239                                 return true;
240                         }
241                 }
242
243                 public static Type GetServerTypeForUri (string URI)
244                 {
245                         ServerIdentity ident = GetIdentityForUri (URI) as ServerIdentity;
246                         if (ident == null) return null;
247                         return ident.ObjectType;
248                 }
249
250                 public static string GetObjectUri (MarshalByRefObject obj)
251                 {
252                         Identity ident = GetObjectIdentity(obj);
253                         if (ident is ClientIdentity) return ((ClientIdentity)ident).TargetUri;
254                         else if (ident != null) return ident.ObjectUri;
255                         else return null;
256                 }
257
258                 public static object Unmarshal (ObjRef objectRef)
259                 {
260                         return Unmarshal (objectRef, true);
261                 }
262
263                 public static object Unmarshal (ObjRef objectRef, bool fRefine)
264                 {
265                         Type classToProxy = fRefine ? objectRef.ServerType : typeof (MarshalByRefObject);
266                         if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
267
268                         if (objectRef.IsReferenceToWellKnow) {
269                                 object obj = GetRemoteObject (objectRef, classToProxy);
270                                 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
271                                 return obj;
272                         }
273                         else
274                         {
275                                 object obj;
276                                 
277                                 if (classToProxy.IsContextful) {
278                                         // Look for a ProxyAttribute
279                                         ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute), true);
280                                         if (att != null) {
281                                                 obj = att.CreateProxy (objectRef, classToProxy, null, null).GetTransparentProxy();
282                                                 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
283                                                 return obj;
284                                         }
285                                 }
286                                 obj = GetProxyForRemoteObject (objectRef, classToProxy);
287                                 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
288                                 return obj;
289                         }
290                 }
291
292                 public static ObjRef Marshal (MarshalByRefObject Obj)
293                 {
294                         return Marshal (Obj, null, null);
295                 }
296                 
297                 public static ObjRef Marshal (MarshalByRefObject Obj, string URI)
298                 {
299                         return Marshal (Obj, URI, null);
300                 }
301                 
302                 public static ObjRef Marshal (MarshalByRefObject Obj, string ObjURI, Type RequestedType)
303                 {
304                         if (IsTransparentProxy (Obj))
305                         {
306                                 RealProxy proxy = RemotingServices.GetRealProxy (Obj);
307                                 Identity identity = proxy.ObjectIdentity;
308
309                                 if (identity != null)
310                                 {
311                                         if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
312                                         {
313                                                 // Unregistered local contextbound object. Register now.
314                                                 ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
315                                                 if (ObjURI == null) ObjURI = NewUri();
316                                                 cboundIdentity.ObjectUri = ObjURI;
317                                                 RegisterServerIdentity (cboundIdentity);
318                                                 cboundIdentity.StartTrackingLifetime ((ILease)Obj.InitializeLifetimeService());
319                                                 return cboundIdentity.CreateObjRef (RequestedType);
320                                         }
321                                         else if (ObjURI != null)
322                                                 throw new RemotingException ("It is not possible marshal a proxy of a remote object.");
323
324                                         ObjRef or = proxy.ObjectIdentity.CreateObjRef (RequestedType);
325                                         TrackingServices.NotifyMarshaledObject (Obj, or);
326                                         return or;
327                                 }
328                         }
329
330                         if (RequestedType == null) RequestedType = Obj.GetType ();
331
332                         if (ObjURI == null) 
333                         {
334                                 if (Obj.ObjectIdentity == null)
335                                 {
336                                         ObjURI = NewUri();
337                                         CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
338                                 }
339                         }
340                         else
341                         {
342                                 ClientActivatedIdentity identity = GetIdentityForUri ("/" + ObjURI) as ClientActivatedIdentity;
343                                 if (identity == null || Obj != identity.GetServerObject()) 
344                                         CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
345                         }
346
347                         ObjRef oref;
348                         
349                         if (IsTransparentProxy (Obj))
350                                 oref = RemotingServices.GetRealProxy (Obj).ObjectIdentity.CreateObjRef (RequestedType);
351                         else
352                                 oref = Obj.CreateObjRef (RequestedType);
353                         
354                         TrackingServices.NotifyMarshaledObject (Obj, oref);
355                         return oref;
356                 }
357
358                 static string NewUri ()
359                 {
360                         int n = Interlocked.Increment (ref next_id);
361                         return app_id + Environment.TickCount.ToString("x") + "_" + n + ".rem";
362                 }
363
364 #if NET_2_0
365                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
366 #endif
367                 public static RealProxy GetRealProxy (object proxy)
368                 {
369                         if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy.");
370                         return (RealProxy)((TransparentProxy)proxy)._rp;
371                 }
372
373                 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
374                 {
375                         Type type = Type.GetType (msg.TypeName);
376                         if (type == null)
377                                 throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
378
379                         return GetMethodBaseFromName (type, msg.MethodName, (Type[]) msg.MethodSignature);
380                 }
381
382                 internal static MethodBase GetMethodBaseFromName (Type type, string methodName, Type[] signature)
383                 {
384                         if (type.IsInterface) {
385                                 return FindInterfaceMethod (type, methodName, signature);
386                         }
387                         else {
388                                 MethodBase method = null;
389                                 if (signature == null)
390                                         method = type.GetMethod (methodName, methodBindings);
391                                 else
392                                         method = type.GetMethod (methodName, methodBindings, null, (Type[]) signature, null);
393                                 
394                                 if (method != null)
395                                         return method;
396                                         
397                                 if (methodName == "FieldSetter")
398                                         return FieldSetterMethod;
399
400                                 if (methodName == "FieldGetter")
401                                         return FieldGetterMethod;
402                                 
403                                 if (signature == null)
404                                         return type.GetConstructor (methodBindings, null, Type.EmptyTypes, null);
405                                 else
406                                         return type.GetConstructor (methodBindings, null, signature, null);
407                         }
408                 }
409                 
410                 static MethodBase FindInterfaceMethod (Type type, string methodName, Type[] signature)
411                 {
412                         MethodBase method = null;
413                         
414                         if (signature == null)
415                                 method = type.GetMethod (methodName, methodBindings);
416                         else
417                                 method = type.GetMethod (methodName, methodBindings, null, signature, null);
418                                 
419                         if (method != null) return method;
420                         
421                         foreach (Type t in type.GetInterfaces ()) {
422                                 method = FindInterfaceMethod (t, methodName, signature);
423                                 if (method != null) return method;
424                         }
425                         
426                         return null;
427                 }
428
429                 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
430                 {
431                         if (obj == null) throw new ArgumentNullException ("obj");
432
433                         ObjRef oref = Marshal ((MarshalByRefObject)obj);
434                         oref.GetObjectData (info, context);
435                 }
436
437                 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
438                 {
439                         Identity ident = GetObjectIdentity(obj);
440                         if (ident == null) return null;
441                         else return ident.CreateObjRef(null);
442                 }
443
444                 public static object GetLifetimeService (MarshalByRefObject obj)
445                 {
446                         if (obj == null) return null;
447                         return obj.GetLifetimeService ();
448                 }
449
450                 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
451                 {
452                         if (IsTransparentProxy(obj))
453                                 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
454                         else
455                                 throw new ArgumentException ("obj must be a proxy.","obj");                     
456                 }
457
458                 [MonoTODO]
459                 [Conditional ("REMOTING_PERF")]
460 #if NET_2_0
461                 [Obsolete ("It existed for only internal use in .NET and unimplemented in mono")]
462 #endif
463                 public static void LogRemotingStage (int stage)
464                 {
465                         throw new NotImplementedException ();
466                 }
467
468                 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
469                 {
470                         // It seems that this it what MS returns.
471                         return msg.Uri;
472                 }
473
474                 public static bool IsMethodOverloaded(IMethodMessage msg)
475                 {
476                         const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
477                         MonoType type = (MonoType) msg.MethodBase.DeclaringType;
478                         return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1;
479                 }
480
481                 public static bool IsObjectOutOfAppDomain(object tp)
482                 {
483                         MarshalByRefObject mbr = tp as MarshalByRefObject;
484
485                         if (mbr == null)
486                                 return false;
487
488                         // TODO: use internal call for better performance
489                         Identity ident = GetObjectIdentity (mbr);
490                         return ident is ClientIdentity;
491                 }
492
493                 public static bool IsObjectOutOfContext(object tp)
494                 {
495                         MarshalByRefObject mbr = tp as MarshalByRefObject;
496
497                         if (mbr == null)
498                                 return false;
499
500                         // TODO: use internal call for better performance
501                         Identity ident = GetObjectIdentity (mbr);
502                         if (ident == null) return false;
503                         
504                         ServerIdentity sident = ident as ServerIdentity;
505                         if (sident != null) return sident.Context != System.Threading.Thread.CurrentContext;
506                         else return true;
507                 }
508
509                 public static bool IsOneWay(MethodBase method)
510                 {
511                         return method.IsDefined (typeof (OneWayAttribute), false);
512                 }
513
514                 internal static bool IsAsyncMessage(IMessage msg)
515                 {
516                         if (! (msg is MonoMethodMessage)) return false;
517                         else if (((MonoMethodMessage)msg).IsAsync) return true;
518                         else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
519                         else return false;
520                 }
521
522                 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
523                 {
524                         if (IsTransparentProxy (obj)) {
525                                 RealProxy proxy = RemotingServices.GetRealProxy(obj);
526                                 Identity identity = proxy.ObjectIdentity;
527
528                                 if (identity != null && !(identity is ServerIdentity) && !proxy.GetProxiedType().IsContextful)
529                                         throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
530                         }
531                         
532                         Marshal (obj, uri);
533                 }
534
535                 #region Internal Methods
536                 
537                 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
538                 {
539                         if (entry.ContextAttributes != null || activationAttributes != null)
540                         {
541                                 ArrayList props = new ArrayList ();
542                                 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
543                                 if (activationAttributes != null) props.AddRange (activationAttributes);
544                                 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
545                         }
546                         else
547                                 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
548                 }
549         
550                 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
551                 {
552                         string activationUrl = url;
553                         if (!activationUrl.EndsWith ("/"))
554                                 activationUrl += "/";
555                         activationUrl += "RemoteActivationService.rem";
556
557                         string objectUri;
558                         GetClientChannelSinkChain (activationUrl, null, out objectUri);
559
560                         RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
561                         return proxy.GetTransparentProxy();
562                 }
563         
564                 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
565                 {
566                         return Connect (entry.ObjectType, entry.ObjectUrl, null);
567                 }
568         
569                 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
570                 {
571                         if (type.IsContextful)
572                         {
573                                 // Look for a ProxyAttribute
574                                 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
575                                 if (att != null)
576                                         return att.CreateInstance (type);
577                         }
578                         RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
579                         return proxy.GetTransparentProxy();
580                 }
581
582                 internal static object CreateClientProxyForComInterop (Type type)
583                 {
584                         Mono.Interop.ComInteropProxy proxy = new Mono.Interop.ComInteropProxy (type);
585                         return proxy.GetTransparentProxy ();
586                 }
587         
588                 internal static Identity GetIdentityForUri (string uri)
589                 {
590                         string normUri = GetNormalizedUri (uri);
591                         lock (uri_hash)
592                         {
593                                 Identity i = (Identity) uri_hash [normUri];
594
595                                 if (i == null) {
596                                         normUri = RemoveAppNameFromUri (uri);
597                                         if (normUri != null)
598                                                 i = (Identity) uri_hash [normUri];
599                                 }
600
601                                 return i;
602                         }
603                 }
604
605                 //
606                 // If the specified uri starts with the application name,
607                 // RemoveAppNameFromUri returns the uri w/out the leading
608                 // application name, otherwise it returns null.
609                 //
610                 // Assumes that the uri is not normalized.
611                 //
612                 static string RemoveAppNameFromUri (string uri)
613                 {
614                         string name = RemotingConfiguration.ApplicationName;
615                         if (name == null) return null;
616                         name = "/" + name + "/";
617                         if (uri.StartsWith (name))
618                                 return uri.Substring (name.Length);
619                         else
620                                 return null;
621                 }
622
623                 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
624                 {
625                         if (IsTransparentProxy(obj))
626                                 return GetRealProxy (obj).ObjectIdentity;
627                         else
628                                 return obj.ObjectIdentity;
629                 }
630
631                 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
632                 {
633                         // This method looks for an identity for the given url. 
634                         // If an identity is not found, it creates the identity and 
635                         // assigns it a proxy to the remote object.
636
637                         // Creates the client sink chain for the given url or channelData.
638                         // It will also get the object uri from the url.
639
640                         object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
641
642                         string objectUri;
643                         IMessageSink sink = GetClientChannelSinkChain (objRef.URI, channelData, out objectUri);
644
645                         if (objectUri == null) objectUri = objRef.URI;
646
647                         lock (uri_hash)
648                         {
649                                 clientProxy = null;
650                                 string uri = GetNormalizedUri (objRef.URI);
651                                 
652                                 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
653                                 if (identity != null)
654                                 {
655                                         // Object already registered
656                                         clientProxy = identity.ClientProxy;
657                                         if (clientProxy != null) return identity;
658                                         
659                                         // The proxy has just been GCed, so its identity cannot
660                                         // be reused. Just dispose it.
661                                         DisposeIdentity (identity);
662                                 }
663
664                                 // Creates an identity and a proxy for the remote object
665
666                                 identity = new ClientIdentity (objectUri, objRef);
667                                 identity.ChannelSink = sink;
668
669                                 // Registers the identity
670                                 uri_hash [uri] = identity;
671                                 
672                                 if (proxyType != null)
673                                 {
674                                         RemotingProxy proxy = new RemotingProxy (proxyType, identity);
675                                         CrossAppDomainSink cds = sink as CrossAppDomainSink;
676                                         if (cds != null)
677                                                 proxy.SetTargetDomain (cds.TargetDomainId);
678
679                                         clientProxy = proxy.GetTransparentProxy();
680                                         identity.ClientProxy = (MarshalByRefObject) clientProxy;
681                                 }
682
683                                 return identity;
684                         }
685                 }
686
687                 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
688                 {
689                         IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
690                         if (sink == null) 
691                         {
692                                 if (url != null) 
693                                 {
694                                         string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url); 
695                                         throw new RemotingException (msg);
696                                 }
697                                 else 
698                                 {
699                                         string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url); 
700                                         throw new RemotingException (msg);
701                                 }
702                         }
703                         return sink;
704                 }
705
706                 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
707                 {
708                         ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
709                         identity.ChannelSink = ChannelServices.CrossContextChannel;
710                         return identity;
711                 }
712
713                 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
714                 {
715                         ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
716                         identity.AttachServerObject (realObject, Context.DefaultContext);
717                         RegisterServerIdentity (identity);
718                         identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
719                         return identity;
720                 }
721
722                 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
723                 {
724                         ServerIdentity identity;
725
726                         if (mode == WellKnownObjectMode.SingleCall)
727                                 identity = new  SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
728                         else
729                                 identity = new  SingletonIdentity(objectUri, Context.DefaultContext, objectType);
730
731                         RegisterServerIdentity (identity);
732                         return identity;
733                 }
734
735                 private static void RegisterServerIdentity(ServerIdentity identity)
736                 {
737                         lock (uri_hash)
738                         {
739                                 if (uri_hash.ContainsKey (identity.ObjectUri)) 
740                                         throw new RemotingException ("Uri already in use: " + identity.ObjectUri + ".");
741
742                                 uri_hash[identity.ObjectUri] = identity;
743                         }
744                 }
745
746                 internal static object GetProxyForRemoteObject (ObjRef objref, Type classToProxy)
747                 {
748                         ClientActivatedIdentity identity = GetIdentityForUri (objref.URI) as ClientActivatedIdentity;
749                         if (identity != null) return identity.GetServerObject ();
750                         else return GetRemoteObject (objref, classToProxy);
751                 }
752
753                 internal static object GetRemoteObject(ObjRef objRef, Type proxyType)
754                 {
755                         object proxy;
756                         GetOrCreateClientIdentity (objRef, proxyType, out proxy);
757                         return proxy;
758                 }
759                 
760                 // This method is called by the runtime
761                 internal static object GetServerObject (string uri)
762                 {
763                         ClientActivatedIdentity identity = GetIdentityForUri (uri) as ClientActivatedIdentity;
764                         if (identity == null) throw new RemotingException ("Server for uri '" + uri + "' not found");
765                         return identity.GetServerObject ();
766                 }
767
768                 // This method is called by the runtime
769                 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
770                 internal static byte[] SerializeCallData (object obj)
771                 {
772                         LogicalCallContext ctx = CallContext.CreateLogicalCallContext (false);
773                         if (ctx != null) {
774                                 CACD cad = new CACD ();
775                                 cad.d = obj;
776                                 cad.c = ctx;
777                                 obj = cad;
778                         }
779                         
780                         if (obj == null) return null;
781                         MemoryStream ms = new MemoryStream ();
782                         _serializationFormatter.Serialize (ms, obj);
783                         return ms.ToArray ();
784                 }
785
786                 // This method is called by the runtime
787                 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
788                 internal static object DeserializeCallData (byte[] array)
789                 {
790                         if (array == null) return null;
791                         
792                         MemoryStream ms = new MemoryStream (array);
793                         object obj = _deserializationFormatter.Deserialize (ms);
794                         
795                         if (obj is CACD) {
796                                 CACD cad = (CACD) obj;
797                                 obj = cad.d;
798                                 CallContext.UpdateCurrentCallContext ((LogicalCallContext) cad.c);
799                         }
800                         return obj;
801                 }
802                 
803                 // This method is called by the runtime
804                 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
805                 internal static byte[] SerializeExceptionData (Exception ex)
806                 {
807                         try {
808                                 int retry = 4;
809                                 
810                                 do {
811                                         try {
812                                                 MemoryStream ms = new MemoryStream ();
813                                                 _serializationFormatter.Serialize (ms, ex);
814                                                 return ms.ToArray ();
815                                         }
816                                         catch (Exception e) {
817                                                 if (e is ThreadAbortException) {
818                                                         Thread.ResetAbort ();
819                                                         retry = 5;
820                                                         ex = e;
821                                                 }
822                                                 else if (retry == 2) {
823                                                         ex = new Exception ();
824                                                         ex.SetMessage (e.Message);
825                                                         ex.SetStackTrace (e.StackTrace);
826                                                 }
827                                                 else
828                                                         ex = e;
829                                         }
830                                         retry--;
831                                 }
832                                 while (retry > 0);
833                                 
834                                 return null;
835                         }
836                         catch (Exception tex)
837                         {
838                                 byte[] data = SerializeExceptionData (tex);
839                                 Thread.ResetAbort ();
840                                 return data;
841                         }
842                 }
843                 
844                 internal static object GetDomainProxy(AppDomain domain) 
845                 {
846                         byte[] data = null;
847
848                         Context currentContext = Thread.CurrentContext;
849
850                         try
851                         {
852                                 data = (byte[])AppDomain.InvokeInDomain (domain, typeof (AppDomain).GetMethod ("GetMarshalledDomainObjRef", BindingFlags.Instance|BindingFlags.NonPublic), domain, null);
853                         }
854                         finally
855                         {
856                                 AppDomain.InternalSetContext (currentContext);
857                         }                               
858
859                         byte[] data_copy = new byte [data.Length];
860                         data.CopyTo (data_copy, 0);
861                         MemoryStream stream = new MemoryStream (data_copy);
862                         ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
863                         return (AppDomain) RemotingServices.Unmarshal(appref);
864                 }
865
866                 private static void RegisterInternalChannels() 
867                 {
868                         CrossAppDomainChannel.RegisterCrossAppDomainChannel();
869                 }
870                 
871                 internal static void DisposeIdentity (Identity ident)
872                 {
873                         lock (uri_hash)
874                         {
875                                 if (!ident.Disposed) {
876                                         ClientIdentity clientId = ident as ClientIdentity;
877                                         if (clientId != null)
878                                                 uri_hash.Remove (GetNormalizedUri (clientId.TargetUri));
879                                         else
880                                                 uri_hash.Remove (ident.ObjectUri);
881                                                 
882                                         ident.Disposed = true;
883                                 }
884                         }
885                 }
886
887                 internal static Identity GetMessageTargetIdentity (IMessage msg)
888                 {
889                         // Returns the identity where the message is sent
890
891                         if (msg is IInternalMessage) 
892                                 return ((IInternalMessage)msg).TargetIdentity;
893
894                         lock (uri_hash)
895                         {
896                                 string uri = GetNormalizedUri (((IMethodMessage)msg).Uri);
897                                 return uri_hash [uri] as ServerIdentity;
898                         }
899                 }
900
901                 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
902                 {
903                         if (msg is IInternalMessage) 
904                                 ((IInternalMessage)msg).TargetIdentity = ident;
905                 }
906                 
907                 internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
908                 {
909                         if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
910                         {
911                                 Array alocal = (Array) local;
912                                 if (alocal.Rank == 1)
913                                 {
914                                         Array.Copy ((Array) remote, alocal, alocal.Length);
915                                         return true;
916                                 }
917                                 else
918                                 {
919                                         // TODO
920                                 }
921                         }
922                         return false;
923                 }
924                 
925                 static string GetNormalizedUri (string uri)
926                 {
927                         if (uri.StartsWith ("/")) return uri.Substring (1);
928                         else return uri;
929                 }
930
931                 #endregion
932         }
933 }