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