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