Merge pull request #1659 from alexanderkyte/stringbuilder-referencesource
[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 using System.Runtime.ConstrainedExecution;
50 using System.Runtime.Serialization.Formatters;
51
52 namespace System.Runtime.Remoting
53 {
54         [System.Runtime.InteropServices.ComVisible (true)]
55         static
56         public class RemotingServices 
57         {
58                 // Holds the identities of the objects, using uri as index
59                 static Hashtable uri_hash = new Hashtable ();           
60
61                 static BinaryFormatter _serializationFormatter;
62                 static BinaryFormatter _deserializationFormatter;
63                 
64                 static string app_id;
65                 static readonly object app_id_lock = new object ();
66                 
67                 static int next_id = 1;
68                 const BindingFlags methodBindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
69                 static readonly MethodInfo FieldSetterMethod;
70                 static readonly MethodInfo FieldGetterMethod;
71                 
72                 // Holds information in xdomain calls. Names are short to minimize serialized size.
73                 [Serializable]
74                 class CACD {
75                         public object d;        /* call data */
76                         public object c;        /* call context */
77                 }
78                 
79                 static RemotingServices ()
80                 {
81                         RemotingSurrogateSelector surrogateSelector = new RemotingSurrogateSelector ();
82                         StreamingContext context = new StreamingContext (StreamingContextStates.Remoting, null);
83                         _serializationFormatter = new BinaryFormatter (surrogateSelector, context);
84                         _deserializationFormatter = new BinaryFormatter (null, context);
85                         _serializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
86                         _deserializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
87                         
88                         RegisterInternalChannels ();
89                         CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
90                         
91                         FieldSetterMethod = typeof(object).GetMethod ("FieldSetter", BindingFlags.NonPublic|BindingFlags.Instance);
92                         FieldGetterMethod = typeof(object).GetMethod ("FieldGetter", BindingFlags.NonPublic|BindingFlags.Instance);
93                 }
94
95                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
96                 internal extern static object InternalExecute (MethodBase method, Object obj,
97                                                                Object[] parameters, out object [] out_args);
98
99                 // Returns the actual implementation of @method in @type.
100                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
101                 internal extern static MethodBase GetVirtualMethod (Type type, MethodBase method);
102
103 #if DISABLE_REMOTING
104                 public static bool IsTransparentProxy (object proxy)
105                 {
106                         throw new NotSupportedException ();
107                 }
108 #else
109                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
110                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
111                 public extern static bool IsTransparentProxy (object proxy);
112
113                 internal static bool ProxyCheckCast (RealProxy rp, RuntimeType castType)
114                 {
115                         // TODO: What should it do?
116                         return true;
117                 }
118 #endif
119
120                 internal static IMethodReturnMessage InternalExecuteMessage (
121                         MarshalByRefObject target, IMethodCallMessage reqMsg)
122                 {
123                         ReturnMessage result;
124                         
125                         Type tt = target.GetType ();
126                         MethodBase method;
127                         if (reqMsg.MethodBase.DeclaringType == tt ||
128                             reqMsg.MethodBase == FieldSetterMethod || 
129                             reqMsg.MethodBase == FieldGetterMethod) {
130                                 method = reqMsg.MethodBase;
131                         } else {
132                                 method = GetVirtualMethod (tt, reqMsg.MethodBase);
133
134                                 if (method == null)
135                                         throw new RemotingException (
136                                                 String.Format ("Cannot resolve method {0}:{1}", tt, reqMsg.MethodName));
137                         }
138
139                         if (reqMsg.MethodBase.IsGenericMethod) {
140                                 Type[] genericArguments = reqMsg.MethodBase.GetGenericArguments ();
141                                 MethodInfo gmd = ((MethodInfo)method).GetGenericMethodDefinition ();
142                                 method = gmd.MakeGenericMethod (genericArguments);
143                         }
144
145                         object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
146                         
147                         try 
148                         {
149                                 object [] out_args;
150                                 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
151                         
152                                 // Collect parameters with Out flag from the request message
153                                 // FIXME: This can be done in the unmanaged side and will be
154                                 // more efficient
155                                 
156                                 ParameterInfo[] parameters = method.GetParameters();
157                                 object[] returnArgs = new object [parameters.Length];
158                                 
159                                 int n = 0;
160                                 int noa = 0;
161                                 foreach (ParameterInfo par in parameters)
162                                 {
163                                         if (par.IsOut && !par.ParameterType.IsByRef) 
164                                                 returnArgs [n++] = reqMsg.GetArg (par.Position);
165                                         else if (par.ParameterType.IsByRef)
166                                                 returnArgs [n++] = out_args [noa++]; 
167                                         else
168                                                 returnArgs [n++] = null; 
169                                 }
170                                 
171                                 result = new ReturnMessage (rval, returnArgs, n, ExecutionContext.CreateLogicalCallContext (true), reqMsg);
172                         } 
173                         catch (Exception e) 
174                         {
175                                 result = new ReturnMessage (e, reqMsg);
176                         }
177                         
178                         CallContext.RestoreCallContext (oldContext);
179                         return result;
180                 }
181
182                 public static IMethodReturnMessage ExecuteMessage (
183                         MarshalByRefObject target, IMethodCallMessage reqMsg)
184                 {
185                         if (IsTransparentProxy(target))
186                         {
187                                 // Message must go through all chain of sinks
188                                 RealProxy rp = GetRealProxy (target);
189                                 return (IMethodReturnMessage) rp.Invoke (reqMsg);
190                         }
191                         else    // Direct call
192                                 return InternalExecuteMessage (target, reqMsg);
193                 }
194
195                 [System.Runtime.InteropServices.ComVisible (true)]
196                 public static object Connect (Type classToProxy, string url)
197                 {
198                         ObjRef objRef = new ObjRef (classToProxy, url, null);
199                         return GetRemoteObject (objRef, classToProxy);
200                 }
201
202                 [System.Runtime.InteropServices.ComVisible (true)]
203                 public static object Connect (Type classToProxy, string url, object data)
204                 {
205                         ObjRef objRef = new ObjRef (classToProxy, url, data);
206                         return GetRemoteObject (objRef, classToProxy);
207                 }
208
209                 public static bool Disconnect (MarshalByRefObject obj)
210                 {
211                         if (obj == null) throw new ArgumentNullException ("obj");
212
213                         ServerIdentity identity;
214
215                         if (IsTransparentProxy (obj))
216                         {
217                                 // CBOs are always accessed through a proxy, even in the server, so
218                                 // for server CBOs it is ok to disconnect a proxy
219
220                                 RealProxy proxy = GetRealProxy(obj);
221                                 if (proxy.GetProxiedType().IsContextful && (proxy.ObjectIdentity is ServerIdentity))
222                                         identity = proxy.ObjectIdentity as ServerIdentity;
223                                 else
224                                         throw new ArgumentException ("The obj parameter is a proxy.");
225                         }
226                         else {
227                                 identity = obj.ObjectIdentity;
228                                 obj.ObjectIdentity = null;
229                         }
230
231                         if (identity == null || !identity.IsConnected)
232                                 return false;
233                         else
234                         {
235                                 LifetimeServices.StopTrackingLifetime (identity);
236                                 DisposeIdentity (identity);
237                                 TrackingServices.NotifyDisconnectedObject (obj);
238                                 return true;
239                         }
240                 }
241
242                 public static Type GetServerTypeForUri (string URI)
243                 {
244                         ServerIdentity ident = GetIdentityForUri (URI) as ServerIdentity;
245                         if (ident == null) return null;
246                         return ident.ObjectType;
247                 }
248
249                 public static string GetObjectUri (MarshalByRefObject obj)
250                 {
251                         Identity ident = GetObjectIdentity(obj);
252                         if (ident is ClientIdentity) return ((ClientIdentity)ident).TargetUri;
253                         else if (ident != null) return ident.ObjectUri;
254                         else return null;
255                 }
256
257                 public static object Unmarshal (ObjRef objectRef)
258                 {
259                         return Unmarshal (objectRef, true);
260                 }
261
262                 public static object Unmarshal (ObjRef objectRef, bool fRefine)
263                 {
264                         Type classToProxy = fRefine ? objectRef.ServerType : typeof (MarshalByRefObject);
265                         if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
266
267                         if (objectRef.IsReferenceToWellKnow) {
268                                 object obj = GetRemoteObject (objectRef, classToProxy);
269                                 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
270                                 return obj;
271                         }
272                         else
273                         {
274                                 object obj;
275                                 
276                                 if (classToProxy.IsContextful) {
277                                         // Look for a ProxyAttribute
278                                         ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute), true);
279                                         if (att != null) {
280                                                 obj = att.CreateProxy (objectRef, classToProxy, null, null).GetTransparentProxy();
281                                                 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
282                                                 return obj;
283                                         }
284                                 }
285                                 obj = GetProxyForRemoteObject (objectRef, classToProxy);
286                                 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
287                                 return obj;
288                         }
289                 }
290
291                 public static ObjRef Marshal (MarshalByRefObject Obj)
292                 {
293                         return Marshal (Obj, null, null);
294                 }
295                 
296                 public static ObjRef Marshal (MarshalByRefObject Obj, string URI)
297                 {
298                         return Marshal (Obj, URI, null);
299                 }
300                 
301                 public static ObjRef Marshal (MarshalByRefObject Obj, string ObjURI, Type RequestedType)
302                 {
303                         if (IsTransparentProxy (Obj))
304                         {
305                                 RealProxy proxy = RemotingServices.GetRealProxy (Obj);
306                                 Identity identity = proxy.ObjectIdentity;
307
308                                 if (identity != null)
309                                 {
310                                         if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
311                                         {
312                                                 // Unregistered local contextbound object. Register now.
313                                                 ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
314                                                 if (ObjURI == null) ObjURI = NewUri();
315                                                 cboundIdentity.ObjectUri = ObjURI;
316                                                 RegisterServerIdentity (cboundIdentity);
317                                                 cboundIdentity.StartTrackingLifetime ((ILease)Obj.InitializeLifetimeService());
318                                                 return cboundIdentity.CreateObjRef (RequestedType);
319                                         }
320                                         else if (ObjURI != null)
321                                                 throw new RemotingException ("It is not possible marshal a proxy of a remote object.");
322
323                                         ObjRef or = proxy.ObjectIdentity.CreateObjRef (RequestedType);
324                                         TrackingServices.NotifyMarshaledObject (Obj, or);
325                                         return or;
326                                 }
327                         }
328
329                         if (RequestedType == null) RequestedType = Obj.GetType ();
330
331                         if (ObjURI == null) 
332                         {
333                                 if (Obj.ObjectIdentity == null)
334                                 {
335                                         ObjURI = NewUri();
336                                         CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
337                                 }
338                         }
339                         else
340                         {
341                                 ClientActivatedIdentity identity = GetIdentityForUri ("/" + ObjURI) as ClientActivatedIdentity;
342                                 if (identity == null || Obj != identity.GetServerObject()) 
343                                         CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
344                         }
345
346                         ObjRef oref;
347                         
348                         if (IsTransparentProxy (Obj))
349                                 oref = RemotingServices.GetRealProxy (Obj).ObjectIdentity.CreateObjRef (RequestedType);
350                         else
351                                 oref = Obj.CreateObjRef (RequestedType);
352                         
353                         TrackingServices.NotifyMarshaledObject (Obj, oref);
354                         return oref;
355                 }
356
357                 static string NewUri ()
358                 {
359                         if (app_id == null) {
360                                 lock (app_id_lock) {
361                                         if (app_id == null)
362                                                 app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
363                                 }
364                         }
365
366                         int n = Interlocked.Increment (ref next_id);
367                         return app_id + Environment.TickCount.ToString("x") + "_" + n + ".rem";
368                 }
369
370                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
371                 public static RealProxy GetRealProxy (object proxy)
372                 {
373                         if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy.");
374                         return (RealProxy)((TransparentProxy)proxy)._rp;
375                 }
376
377                 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
378                 {
379                         Type type = Type.GetType (msg.TypeName);
380                         if (type == null)
381                                 throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
382
383                         return GetMethodBaseFromName (type, msg.MethodName, (Type[]) msg.MethodSignature);
384                 }
385
386                 internal static MethodBase GetMethodBaseFromName (Type type, string methodName, Type[] signature)
387                 {
388                         if (type.IsInterface) {
389                                 return FindInterfaceMethod (type, methodName, signature);
390                         }
391                         else {
392                                 MethodBase method = null;
393                                 if (signature == null)
394                                         method = type.GetMethod (methodName, methodBindings);
395                                 else
396                                         method = type.GetMethod (methodName, methodBindings, null, (Type[]) signature, null);
397                                 
398                                 if (method != null)
399                                         return method;
400                                         
401                                 if (methodName == "FieldSetter")
402                                         return FieldSetterMethod;
403
404                                 if (methodName == "FieldGetter")
405                                         return FieldGetterMethod;
406                                 
407                                 if (signature == null)
408                                         return type.GetConstructor (methodBindings, null, Type.EmptyTypes, null);
409                                 else
410                                         return type.GetConstructor (methodBindings, null, signature, null);
411                         }
412                 }
413                 
414                 static MethodBase FindInterfaceMethod (Type type, string methodName, Type[] signature)
415                 {
416                         MethodBase method = null;
417                         
418                         if (signature == null)
419                                 method = type.GetMethod (methodName, methodBindings);
420                         else
421                                 method = type.GetMethod (methodName, methodBindings, null, signature, null);
422                                 
423                         if (method != null) return method;
424                         
425                         foreach (Type t in type.GetInterfaces ()) {
426                                 method = FindInterfaceMethod (t, methodName, signature);
427                                 if (method != null) return method;
428                         }
429                         
430                         return null;
431                 }
432
433                 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
434                 {
435                         if (obj == null) throw new ArgumentNullException ("obj");
436
437                         ObjRef oref = Marshal ((MarshalByRefObject)obj);
438                         oref.GetObjectData (info, context);
439                 }
440
441                 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
442                 {
443                         Identity ident = GetObjectIdentity(obj);
444                         if (ident == null) return null;
445                         else return ident.CreateObjRef(null);
446                 }
447
448                 public static object GetLifetimeService (MarshalByRefObject obj)
449                 {
450                         if (obj == null) return null;
451                         return obj.GetLifetimeService ();
452                 }
453
454                 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
455                 {
456                         if (IsTransparentProxy(obj))
457                                 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
458                         else
459                                 throw new ArgumentException ("obj must be a proxy.","obj");                     
460                 }
461
462                 [MonoTODO]
463                 [Conditional ("REMOTING_PERF")]
464                 [Obsolete ("It existed for only internal use in .NET and unimplemented in mono")]
465                 public static void LogRemotingStage (int stage)
466                 {
467                         throw new NotImplementedException ();
468                 }
469
470                 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
471                 {
472                         // It seems that this it what MS returns.
473                         return msg.Uri;
474                 }
475
476                 public static bool IsMethodOverloaded(IMethodMessage msg)
477                 {
478                         const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
479                         MonoType type = (MonoType) msg.MethodBase.DeclaringType;
480                         return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1;
481                 }
482
483                 public static bool IsObjectOutOfAppDomain(object tp)
484                 {
485                         MarshalByRefObject mbr = tp as MarshalByRefObject;
486
487                         if (mbr == null)
488                                 return false;
489
490                         // TODO: use internal call for better performance
491                         Identity ident = GetObjectIdentity (mbr);
492                         return ident is ClientIdentity;
493                 }
494
495                 public static bool IsObjectOutOfContext(object tp)
496                 {
497                         MarshalByRefObject mbr = tp as MarshalByRefObject;
498
499                         if (mbr == null)
500                                 return false;
501
502                         // TODO: use internal call for better performance
503                         Identity ident = GetObjectIdentity (mbr);
504                         if (ident == null) return false;
505                         
506                         ServerIdentity sident = ident as ServerIdentity;
507                         if (sident != null) return sident.Context != System.Threading.Thread.CurrentContext;
508                         else return true;
509                 }
510
511                 public static bool IsOneWay(MethodBase method)
512                 {
513                         return method.IsDefined (typeof (OneWayAttribute), false);
514                 }
515
516                 internal static bool IsAsyncMessage(IMessage msg)
517                 {
518                         if (! (msg is MonoMethodMessage)) return false;
519                         else if (((MonoMethodMessage)msg).IsAsync) return true;
520                         else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
521                         else return false;
522                 }
523
524                 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
525                 {
526                         if (IsTransparentProxy (obj)) {
527                                 RealProxy proxy = RemotingServices.GetRealProxy(obj);
528                                 Identity identity = proxy.ObjectIdentity;
529
530                                 if (identity != null && !(identity is ServerIdentity) && !proxy.GetProxiedType().IsContextful)
531                                         throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
532                         }
533                         
534                         Marshal (obj, uri);
535                 }
536
537                 #region Internal Methods
538                 
539                 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
540                 {
541                         if (entry.ContextAttributes != null || activationAttributes != null)
542                         {
543                                 ArrayList props = new ArrayList ();
544                                 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
545                                 if (activationAttributes != null) props.AddRange (activationAttributes);
546                                 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
547                         }
548                         else
549                                 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
550                 }
551         
552                 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
553                 {
554                         string activationUrl = url;
555                         if (!activationUrl.EndsWith ("/"))
556                                 activationUrl += "/";
557                         activationUrl += "RemoteActivationService.rem";
558
559                         string objectUri;
560                         GetClientChannelSinkChain (activationUrl, null, out objectUri);
561
562                         RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
563                         return proxy.GetTransparentProxy();
564                 }
565         
566                 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
567                 {
568                         return Connect (entry.ObjectType, entry.ObjectUrl, null);
569                 }
570         
571                 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
572                 {
573                         if (type.IsContextful)
574                         {
575                                 // Look for a ProxyAttribute
576                                 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
577                                 if (att != null)
578                                         return att.CreateInstance (type);
579                         }
580                         RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
581                         return proxy.GetTransparentProxy();
582                 }
583 #if !NET_2_1
584                 internal static object CreateClientProxyForComInterop (Type type)
585                 {
586                         Mono.Interop.ComInteropProxy proxy = Mono.Interop.ComInteropProxy.CreateProxy (type);
587                         return proxy.GetTransparentProxy ();
588                 }
589 #endif
590                 internal static Identity GetIdentityForUri (string uri)
591                 {
592                         string normUri = GetNormalizedUri (uri);
593                         lock (uri_hash)
594                         {
595                                 Identity i = (Identity) uri_hash [normUri];
596
597                                 if (i == null) {
598                                         normUri = RemoveAppNameFromUri (uri);
599                                         if (normUri != null)
600                                                 i = (Identity) uri_hash [normUri];
601                                 }
602
603                                 return i;
604                         }
605                 }
606
607                 //
608                 // If the specified uri starts with the application name,
609                 // RemoveAppNameFromUri returns the uri w/out the leading
610                 // application name, otherwise it returns null.
611                 //
612                 // Assumes that the uri is not normalized.
613                 //
614                 static string RemoveAppNameFromUri (string uri)
615                 {
616                         string name = RemotingConfiguration.ApplicationName;
617                         if (name == null) return null;
618                         name = "/" + name + "/";
619                         if (uri.StartsWith (name))
620                                 return uri.Substring (name.Length);
621                         else
622                                 return null;
623                 }
624
625                 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
626                 {
627                         if (IsTransparentProxy(obj))
628                                 return GetRealProxy (obj).ObjectIdentity;
629                         else
630                                 return obj.ObjectIdentity;
631                 }
632
633                 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
634                 {
635                         // This method looks for an identity for the given url. 
636                         // If an identity is not found, it creates the identity and 
637                         // assigns it a proxy to the remote object.
638
639                         // Creates the client sink chain for the given url or channelData.
640                         // It will also get the object uri from the url.
641
642                         object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
643
644                         string objectUri;
645                         IMessageSink sink = GetClientChannelSinkChain (objRef.URI, channelData, out objectUri);
646
647                         if (objectUri == null) objectUri = objRef.URI;
648
649                         lock (uri_hash)
650                         {
651                                 clientProxy = null;
652                                 string uri = GetNormalizedUri (objRef.URI);
653                                 
654                                 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
655                                 if (identity != null)
656                                 {
657                                         // Object already registered
658                                         clientProxy = identity.ClientProxy;
659                                         if (clientProxy != null) return identity;
660                                         
661                                         // The proxy has just been GCed, so its identity cannot
662                                         // be reused. Just dispose it.
663                                         DisposeIdentity (identity);
664                                 }
665
666                                 // Creates an identity and a proxy for the remote object
667
668                                 identity = new ClientIdentity (objectUri, objRef);
669                                 identity.ChannelSink = sink;
670
671                                 // Registers the identity
672                                 uri_hash [uri] = identity;
673                                 if (proxyType != null)
674                                 {
675                                         RemotingProxy proxy = new RemotingProxy (proxyType, identity);
676                                         CrossAppDomainSink cds = sink as CrossAppDomainSink;
677                                         if (cds != null)
678                                                 proxy.SetTargetDomain (cds.TargetDomainId);
679
680                                         clientProxy = proxy.GetTransparentProxy();
681                                         identity.ClientProxy = (MarshalByRefObject) clientProxy;
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 = ExecutionContext.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.UpdateCurrentLogicalCallContext ((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 }