GetMarshalledDomainObjRef() is needed also in the 2.1-based profiles for appdomain...
[mono.git] / mcs / class / corlib / System / AppDomain.cs
1 //
2 // System.AppDomain.cs
3 //
4 // Authors:
5 //   Paolo Molaro (lupus@ximian.com)
6 //   Dietmar Maurer (dietmar@ximian.com)
7 //   Miguel de Icaza (miguel@ximian.com)
8 //   Gonzalo Paniagua (gonzalo@ximian.com)
9 //   Patrik Torstensson
10 //   Sebastien Pouliot (sebastien@ximian.com)
11 //
12 // (C) 2001, 2002 Ximian, Inc.  http://www.ximian.com
13 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
14 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
15 //
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
23 // 
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
26 // 
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 //
35
36 using System.Collections;
37 using System.Globalization;
38 using System.IO;
39 using System.Reflection;
40 using System.Reflection.Emit;
41 using System.Threading;
42 using System.Runtime.CompilerServices;
43 using System.Runtime.InteropServices;
44 using System.Runtime.Remoting;
45 using System.Runtime.Remoting.Contexts;
46 using System.Runtime.Remoting.Channels;
47 using System.Runtime.Remoting.Messaging;
48 using System.Security;
49 using System.Security.Permissions;
50 using System.Security.Policy;
51 using System.Security.Principal;
52 using System.Configuration.Assemblies;
53
54 using System.Collections.Generic;
55 using System.Runtime.ConstrainedExecution;
56 using System.Text;
57
58 namespace System {
59
60         [ComVisible (true)]
61 #if !NET_2_1 || MOONLIGHT
62         [ComDefaultInterface (typeof (_AppDomain))]
63 #endif
64         [ClassInterface(ClassInterfaceType.None)]
65 #if MOONLIGHT
66         public sealed class AppDomain : _AppDomain {
67 #elif NET_2_1
68         public sealed class AppDomain : MarshalByRefObject, _AppDomain {
69 #else
70         public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory {
71 #endif
72         #pragma warning disable 169
73         #region Sync with object-internals.h
74                 IntPtr _mono_app_domain;
75                 #endregion
76         #pragma warning restore 169
77                 static string _process_guid;
78
79                 [ThreadStatic]
80                 static Hashtable type_resolve_in_progress;
81
82                 [ThreadStatic]
83                 static Hashtable assembly_resolve_in_progress;
84
85                 [ThreadStatic]
86                 static Hashtable assembly_resolve_in_progress_refonly;
87 #if !MOONLIGHT
88                 // CAS
89                 private Evidence _evidence;
90                 private PermissionSet _granted;
91
92                 // non-CAS
93                 private PrincipalPolicy _principalPolicy;
94
95                 [ThreadStatic]
96                 private static IPrincipal _principal;
97 #endif
98                 static AppDomain default_domain;
99
100                 private AppDomain ()
101                 {
102                 }
103
104                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
105                 private extern AppDomainSetup getSetup ();
106
107 #if NET_2_1
108                 internal
109 #endif
110                 AppDomainSetup SetupInformationNoCopy {
111                         get { return getSetup (); }
112                 }
113
114                 public AppDomainSetup SetupInformation {
115                         get {
116                                 AppDomainSetup setup = getSetup ();
117                                 return new AppDomainSetup (setup);
118                         }
119                 }
120
121 #if !NET_2_1
122                 [MonoTODO]
123                 public ApplicationTrust ApplicationTrust {
124                         get { throw new NotImplementedException (); }
125                 }
126 #endif
127 #if !MOONLIGHT
128                 public string BaseDirectory {
129                         get {
130                                 string path = SetupInformationNoCopy.ApplicationBase;
131 #if !NET_2_1
132                                 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
133                                         // we cannot divulge local file informations
134                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
135                                 }
136 #endif
137                                 return path;
138                         }
139                 }
140
141                 public string RelativeSearchPath {
142                         get {
143                                 string path = SetupInformationNoCopy.PrivateBinPath;
144 #if !NET_2_1
145                                 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
146                                         // we cannot divulge local file informations
147                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
148                                 }
149 #endif
150                                 return path;
151                         }
152                 }
153
154                 public string DynamicDirectory {
155                         get {
156                                 AppDomainSetup setup = SetupInformationNoCopy;
157                                 if (setup.DynamicBase == null)
158                                         return null;
159
160                                 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
161 #if !NET_2_1
162                                 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
163                                         // we cannot divulge local file informations
164                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
165                                 }
166 #endif
167                                 return path;
168                         }
169                 }
170
171                 public bool ShadowCopyFiles {
172                         get {
173                                 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
174                         }
175                 }
176 #endif
177
178                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
179                 private extern string getFriendlyName ();
180
181                 public string FriendlyName {
182                         get {
183                                 return getFriendlyName ();
184                         }
185                 }
186 #if !MOONLIGHT
187                 public Evidence Evidence {
188                         get {
189                                 // if the host (runtime) hasn't provided it's own evidence...
190                                 if (_evidence == null) {
191                                         // ... we will provide our own
192                                         lock (this) {
193                                                 // the executed assembly from the "default" appdomain
194                                                 // or null if we're not in the default appdomain or
195                                                 // if there is no entry assembly (embedded mono)
196                                                 Assembly a = Assembly.GetEntryAssembly ();
197                                                 if (a == null) {
198                                                         if (this == DefaultDomain)
199                                                                 // mono is embedded
200                                                                 return new Evidence ();
201                                                         else
202                                                                 _evidence = AppDomain.DefaultDomain.Evidence;
203                                                 } else {
204                                                         _evidence = Evidence.GetDefaultHostEvidence (a);
205                                                 }
206                                         }
207                                 }
208                                 return new Evidence (_evidence);        // return a copy
209                         }
210                 }
211
212                 internal IPrincipal DefaultPrincipal {
213                         get {
214                                 if (_principal == null) {
215                                         switch (_principalPolicy) {
216                                                 case PrincipalPolicy.UnauthenticatedPrincipal:
217                                                         _principal = new GenericPrincipal (
218                                                                 new GenericIdentity (String.Empty, String.Empty), null);
219                                                         break;
220                                                 case PrincipalPolicy.WindowsPrincipal:
221                                                         _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
222                                                         break;
223                                         }
224                                 }
225                                 return _principal; 
226                         }
227                 }
228
229                 // for AppDomain there is only an allowed (i.e. granted) set
230                 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
231                 internal PermissionSet GrantedPermissionSet {
232                         get { return _granted; }
233                 }
234 #endif
235
236 #if NET_4_0
237                 public PermissionSet PermissionSet {
238                         get { return _granted ?? (_granted = new PermissionSet (PermissionState.Unrestricted)); }
239                 }
240 #endif
241
242                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
243                 private static extern AppDomain getCurDomain ();
244                 
245                 public static AppDomain CurrentDomain {
246                         get {
247                                 return getCurDomain ();
248                         }
249                 }
250
251                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
252                 private static extern AppDomain getRootDomain ();
253
254                 internal static AppDomain DefaultDomain {
255                         get {
256                                 if (default_domain == null) {
257                                         AppDomain rd = getRootDomain ();
258                                         if (rd == CurrentDomain)
259                                                 default_domain = rd;
260                                         else
261                                                 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
262                                 }
263                                 return default_domain;
264                         }
265                 }
266
267 #if !MOONLIGHT
268
269                 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
270                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
271                 public void AppendPrivatePath (string path)
272                 {
273                         if (path == null || path.Length == 0)
274                                 return;
275
276                         AppDomainSetup setup = SetupInformationNoCopy;
277
278                         string pp = setup.PrivateBinPath;
279                         if (pp == null || pp.Length == 0) {
280                                 setup.PrivateBinPath = path;
281                                 return;
282                         }
283
284                         pp = pp.Trim ();
285                         if (pp [pp.Length - 1] != Path.PathSeparator)
286                                 pp += Path.PathSeparator;
287
288                         setup.PrivateBinPath = pp + path;
289                 }
290
291                 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
292                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
293                 public void ClearPrivatePath ()
294                 {
295                         SetupInformationNoCopy.PrivateBinPath = String.Empty;
296                 }
297
298                 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
299                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
300                 public void ClearShadowCopyPath ()
301                 {
302                         SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
303                 }
304
305 #if !NET_2_1
306                 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
307                 {
308                         return Activator.CreateComInstanceFrom (assemblyName, typeName);
309                 }
310
311                 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
312                         byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
313                 {
314                         return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
315                 }
316 #endif
317
318                 public ObjectHandle CreateInstance (string assemblyName, string typeName)
319                 {
320                         if (assemblyName == null)
321                                 throw new ArgumentNullException ("assemblyName");
322
323                         return Activator.CreateInstance (assemblyName, typeName);
324                 }
325
326                 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
327                 {
328                         if (assemblyName == null)
329                                 throw new ArgumentNullException ("assemblyName");
330
331                         return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
332                 }
333
334 #if NET_4_0
335                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
336 #endif
337                 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
338                                                     Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
339                                                     Evidence securityAttributes)
340                 {
341                         if (assemblyName == null)
342                                 throw new ArgumentNullException ("assemblyName");
343
344                         return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
345                                 culture, activationAttributes, securityAttributes);
346                 }
347
348                 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
349                 {
350                         ObjectHandle oh = CreateInstance (assemblyName, typeName);
351                         return (oh != null) ? oh.Unwrap () : null;
352                 }
353
354                 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
355                 {
356                         ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
357                         return (oh != null) ? oh.Unwrap () : null;
358                 }
359
360 #if NET_4_0
361                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
362 #endif
363                 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
364                                                        BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
365                                                        object[] activationAttributes, Evidence securityAttributes)
366                 {
367                         ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
368                                 culture, activationAttributes, securityAttributes);
369                         return (oh != null) ? oh.Unwrap () : null;
370                 }
371
372 #if NET_4_0
373                 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
374                                                     Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
375                 {
376                         if (assemblyName == null)
377                                 throw new ArgumentNullException ("assemblyName");
378
379                         return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
380                                 culture, activationAttributes, null);
381                 }
382                 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
383                                                        BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
384                                                        object[] activationAttributes)
385                 {
386                         ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
387                                 culture, activationAttributes);
388                         return (oh != null) ? oh.Unwrap () : null;
389                 }
390
391                 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
392                                                         BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
393                                                         object[] activationAttributes)
394                 {
395                         if (assemblyFile == null)
396                                 throw new ArgumentNullException ("assemblyFile");
397
398                         return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
399                                                              culture, activationAttributes, null);
400                 }
401
402                 public object CreateInstanceFromAndUnwrap (string assemblyFile, string typeName, bool ignoreCase,
403                                                            BindingFlags bindingAttr, Binder binder, object[] args,
404                                                            CultureInfo culture, object[] activationAttributes)
405                 {
406                         ObjectHandle oh = CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
407                                 culture, activationAttributes);
408
409                         return (oh != null) ? oh.Unwrap () : null;
410                 }
411 #endif
412
413                 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
414                 {
415                         if (assemblyFile == null)
416                                 throw new ArgumentNullException ("assemblyFile");
417
418                         return Activator.CreateInstanceFrom (assemblyFile, typeName);
419                 }
420
421                 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
422                 {
423                         if (assemblyFile == null)
424                                 throw new ArgumentNullException ("assemblyFile");
425
426                         return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
427                 }
428
429 #if NET_4_0
430                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
431 #endif
432                 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
433                                                         BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
434                                                         object[] activationAttributes, Evidence securityAttributes)
435                 {
436                         if (assemblyFile == null)
437                                 throw new ArgumentNullException ("assemblyFile");
438
439                         return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
440                                                              culture, activationAttributes, securityAttributes);
441                 }
442
443                 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
444                 {
445                         ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
446                         return (oh != null) ? oh.Unwrap () : null;
447                 }
448
449                 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
450                 {
451                         ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
452                         return (oh != null) ? oh.Unwrap () : null;
453                 }
454
455 #if NET_4_0
456                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
457 #endif
458                 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
459                                                            BindingFlags bindingAttr, Binder binder, object[] args,
460                                                            CultureInfo culture, object[] activationAttributes,
461                                                            Evidence securityAttributes)
462                 {
463                         ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
464                                 culture, activationAttributes, securityAttributes);
465
466                         return (oh != null) ? oh.Unwrap () : null;
467                 }
468
469 #endif // !NET_2_1
470
471                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
472                 {
473                         return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
474                 }
475
476 #if NET_4_0
477                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
478 #endif
479                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
480                 {
481                         return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
482                 }
483
484                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
485                 {
486                         return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
487                 }
488
489 #if NET_4_0
490                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
491 #endif
492                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
493                                                               Evidence evidence)
494                 {
495                         return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
496                 }
497
498 #if NET_4_0
499                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
500 #endif
501                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
502                                                               PermissionSet requiredPermissions,
503                                                               PermissionSet optionalPermissions,
504                                                               PermissionSet refusedPermissions)
505                 {
506                         return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
507                                 refusedPermissions, false);
508                 }
509
510 #if NET_4_0
511                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
512 #endif
513                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
514                                                               PermissionSet requiredPermissions,
515                                                               PermissionSet optionalPermissions,
516                                                               PermissionSet refusedPermissions)
517                 {
518                         return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
519                                 refusedPermissions, false);
520                 }
521
522 #if NET_4_0
523                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
524 #endif
525                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
526                                                               PermissionSet requiredPermissions,
527                                                               PermissionSet optionalPermissions,
528                                                               PermissionSet refusedPermissions)
529                 {
530                         return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
531                                 refusedPermissions, false);
532                 }
533
534 #if NET_4_0
535                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
536 #endif
537                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
538                                                               Evidence evidence,
539                                                               PermissionSet requiredPermissions,
540                                                               PermissionSet optionalPermissions,
541                                                               PermissionSet refusedPermissions)
542                 {
543                         return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
544                                 refusedPermissions, false);
545                 }
546
547 #if NET_4_0
548                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
549 #endif
550                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
551                                                               Evidence evidence,
552                                                               PermissionSet requiredPermissions,
553                                                               PermissionSet optionalPermissions,
554                                                               PermissionSet refusedPermissions, bool isSynchronized)
555                 {
556                         if (name == null)
557                                 throw new ArgumentNullException ("name");
558                         ValidateAssemblyName (name.Name);
559
560                         // FIXME: examine all other parameters
561                         
562                         AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
563                         ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
564                         return ab;
565                 }
566
567                 // NET 3.5 method
568 #if NET_4_0
569                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
570 #endif
571                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
572                                                               Evidence evidence,
573                                                               PermissionSet requiredPermissions,
574                                                               PermissionSet optionalPermissions,
575                                                               PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
576                 {
577                         AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
578                         if (assemblyAttributes != null)
579                                 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
580                                         ab.SetCustomAttribute (cb);
581                                 }
582                         return ab;
583                 }
584
585                 // NET 3.5 method
586                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
587                 {
588                         return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
589                 }
590
591 #if NET_4_0
592                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
593                 {
594                         return DefineDynamicAssembly (name, access, dir, null, null, null, null, isSynchronized, assemblyAttributes);
595                 }
596
597                 [MonoLimitation ("The argument securityContextSource is ignored")]
598                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes, SecurityContextSource securityContextSource)
599                 {
600                         return DefineDynamicAssembly (name, access, assemblyAttributes);
601                 }
602 #endif
603
604                 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
605                 {
606                         return new AssemblyBuilder (name, null, access, true);
607                 }
608
609                 //
610                 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
611                 // so, when you call AppDomain.DoCallBack, that's a remote call
612                 //
613                 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
614                 {
615                         if (callBackDelegate != null)
616                                 callBackDelegate ();
617                 }
618
619                 public int ExecuteAssembly (string assemblyFile)
620                 {
621                         return ExecuteAssembly (assemblyFile, (Evidence)null, null);
622                 }
623
624 #if NET_4_0
625                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
626 #endif
627                 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
628                 {
629                         return ExecuteAssembly (assemblyFile, assemblySecurity, null);
630                 }
631
632 #if NET_4_0
633                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
634 #endif
635                 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
636                 {
637                         Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
638                         return ExecuteAssemblyInternal (a, args);
639                 }
640
641 #if NET_4_0
642                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
643 #endif
644                 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
645                 {
646                         Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
647                         return ExecuteAssemblyInternal (a, args);
648                 }
649
650
651 #if NET_4_0
652                 public int ExecuteAssembly (string assemblyFile, string[] args)
653                 {
654                         Assembly a = Assembly.LoadFrom (assemblyFile, null);
655                         return ExecuteAssemblyInternal (a, args);
656                 }
657
658                 public int ExecuteAssembly (string assemblyFile, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
659                 {
660                         Assembly a = Assembly.LoadFrom (assemblyFile, null, hashValue, hashAlgorithm);
661                         return ExecuteAssemblyInternal (a, args);
662                 }
663 #endif
664
665                 int ExecuteAssemblyInternal (Assembly a, string[] args)
666                 {
667                         if (a.EntryPoint == null)
668                                 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
669                         return ExecuteAssembly (a, args);
670                 }
671
672                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
673                 private extern int ExecuteAssembly (Assembly a, string[] args);
674                 
675                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
676                 private extern Assembly [] GetAssemblies (bool refOnly);
677
678                 public Assembly [] GetAssemblies ()
679                 {
680                         return GetAssemblies (false);
681                 }
682
683                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
684                 public extern object GetData (string name);
685
686                 public new Type GetType()
687                 {
688                         return base.GetType ();
689                 }
690
691 #if !MOONLIGHT
692                 public override object InitializeLifetimeService ()
693                 {
694                         return null;
695                 }
696 #endif
697
698                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
699                 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
700
701                 public Assembly Load (AssemblyName assemblyRef)
702                 {
703                         return Load (assemblyRef, null);
704                 }
705
706                 internal Assembly LoadSatellite (AssemblyName assemblyRef, bool throwOnError)
707                 {
708                         if (assemblyRef == null)
709                                 throw new ArgumentNullException ("assemblyRef");
710
711                         Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
712                         if (result == null && throwOnError)
713                                 throw new FileNotFoundException (null, assemblyRef.Name);
714                         return result;
715                 }
716
717 #if NET_4_0
718                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
719 #endif
720                 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
721                 {
722                         if (assemblyRef == null)
723                                 throw new ArgumentNullException ("assemblyRef");
724
725                         if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
726                                 if (assemblyRef.CodeBase != null)
727                                         return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
728                                 else
729                                         throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
730                         }
731
732                         Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
733                         if (assembly != null)
734                                 return assembly;
735
736                         if (assemblyRef.CodeBase == null)
737                                 throw new FileNotFoundException (null, assemblyRef.Name);
738
739                         string cb = assemblyRef.CodeBase;
740                         if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
741                                 cb = new Mono.Security.Uri (cb).LocalPath;
742
743                         try {
744                                 assembly = Assembly.LoadFrom (cb, assemblySecurity);
745                         } catch {
746                                 throw new FileNotFoundException (null, assemblyRef.Name);
747                         }
748                         AssemblyName aname = assembly.GetName ();
749                         // Name, version, culture, publickeytoken. Anything else?
750                         if (assemblyRef.Name != aname.Name)
751                                 throw new FileNotFoundException (null, assemblyRef.Name);
752
753                         if (assemblyRef.Version != null && assemblyRef.Version != new Version (0, 0, 0, 0) && assemblyRef.Version != aname.Version)
754                                 throw new FileNotFoundException (null, assemblyRef.Name);
755
756                         if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
757                                 throw new FileNotFoundException (null, assemblyRef.Name);
758
759                         byte [] pt = assemblyRef.GetPublicKeyToken ();
760                         if (pt != null && pt.Length != 0) {
761                                 byte [] loaded_pt = aname.GetPublicKeyToken ();
762                                 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
763                                         throw new FileNotFoundException (null, assemblyRef.Name);
764                                 for (int i = pt.Length - 1; i >= 0; i--)
765                                         if (loaded_pt [i] != pt [i])
766                                                 throw new FileNotFoundException (null, assemblyRef.Name);
767                         }
768                         return assembly;
769                 }
770
771                 public Assembly Load (string assemblyString)
772                 {
773                         return Load (assemblyString, null, false);
774                 }
775
776 #if NET_4_0
777                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
778 #endif
779                 public Assembly Load (string assemblyString, Evidence assemblySecurity)
780                 {
781                         return Load (assemblyString, assemblySecurity, false);
782                 }
783                 
784                 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
785                 {
786                         if (assemblyString == null)
787                                 throw new ArgumentNullException ("assemblyString");
788                                 
789                         if (assemblyString.Length == 0)
790                                 throw new ArgumentException ("assemblyString cannot have zero length");
791
792                         Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
793                         if (assembly == null)
794                                 throw new FileNotFoundException (null, assemblyString);
795                         return assembly;
796                 }
797
798                 public Assembly Load (byte[] rawAssembly)
799                 {
800                         return Load (rawAssembly, null, null);
801                 }
802
803                 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
804                 {
805                         return Load (rawAssembly, rawSymbolStore, null);
806                 }
807
808                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
809                 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
810
811 #if NET_4_0
812                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
813 #endif
814                 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
815                 {
816                         return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
817                 }
818
819                 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
820                 {
821                         if (rawAssembly == null)
822                                 throw new ArgumentNullException ("rawAssembly");
823
824                         Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
825                         assembly.FromByteArray = true;
826                         return assembly;
827                 }
828 #if !MOONLIGHT
829 #if NET_4_0
830                 [Obsolete ("AppDomain policy levels are obsolete")]
831 #endif
832                 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
833                 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
834                 {
835                         if (domainPolicy == null)
836                                 throw new ArgumentNullException ("domainPolicy");
837                         if (_granted != null) {
838                                 throw new PolicyException (Locale.GetText (
839                                         "An AppDomain policy is already specified."));
840                         }
841                         if (IsFinalizingForUnload ())
842                                 throw new AppDomainUnloadedException ();
843
844                         PolicyStatement ps = domainPolicy.Resolve (_evidence);
845                         _granted = ps.PermissionSet;
846                 }
847
848                 [Obsolete ("Use AppDomainSetup.SetCachePath")]
849                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
850                 public void SetCachePath (string path)
851                 {
852                         SetupInformationNoCopy.CachePath = path;
853                 }
854
855                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
856                 public void SetPrincipalPolicy (PrincipalPolicy policy)
857                 {
858                         if (IsFinalizingForUnload ())
859                                 throw new AppDomainUnloadedException ();
860
861                         _principalPolicy = policy;
862                         _principal = null;
863                 }
864
865                 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
866                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
867                 public void SetShadowCopyFiles()
868                 {
869                         SetupInformationNoCopy.ShadowCopyFiles = "true";
870                 }
871
872                 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
873                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
874                 public void SetShadowCopyPath (string path)
875                 {
876                         SetupInformationNoCopy.ShadowCopyDirectories = path;
877                 }
878
879                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
880                 public void SetThreadPrincipal (IPrincipal principal)
881                 {
882                         if (principal == null)
883                                 throw new ArgumentNullException ("principal");
884                         if (_principal != null)
885                                 throw new PolicyException (Locale.GetText ("principal already present."));
886                         if (IsFinalizingForUnload ())
887                                 throw new AppDomainUnloadedException ();
888
889                         _principal = principal;
890                 }
891 #endif
892                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
893                 private static extern AppDomain InternalSetDomainByID (int domain_id);
894  
895                 // Changes the active domain and returns the old domain
896                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
897                 private static extern AppDomain InternalSetDomain (AppDomain context);
898
899                 // Notifies the runtime that this thread references 'domain'.
900                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
901                 internal static extern void InternalPushDomainRef (AppDomain domain);
902
903                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
904                 internal static extern void InternalPushDomainRefByID (int domain_id);
905
906                 // Undoes the effect of the last PushDomainRef call
907                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
908                 internal static extern void InternalPopDomainRef ();
909
910                 // Changes the active context and returns the old context
911                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
912                 internal static extern Context InternalSetContext (Context context);
913
914                 // Returns the current context
915                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
916                 internal static extern Context InternalGetContext ();
917
918                 // Returns the current context
919                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
920                 internal static extern Context InternalGetDefaultContext ();
921
922                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
923                 internal static extern string InternalGetProcessGuid (string newguid);
924
925                 // This method is handled specially by the runtime
926                 // It is the only managed method which is allowed to set the current
927                 // appdomain
928                 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
929                 {
930                         AppDomain current = CurrentDomain;
931                         bool pushed = false;
932
933                         try {
934                                 Exception exc;
935                                 InternalPushDomainRef (domain);
936                                 pushed = true;
937                                 InternalSetDomain (domain);
938                                 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
939                                 if (exc != null)
940                                         throw exc;
941                                 return o;
942                         }
943                         finally {
944                                 InternalSetDomain (current);
945                                 if (pushed)
946                                         InternalPopDomainRef ();
947                         }
948                 }
949
950                 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
951                 {
952                         AppDomain current = CurrentDomain;
953                         bool pushed = false;
954
955                         try {
956                                 Exception exc;
957                                 InternalPushDomainRefByID (domain_id);
958                                 pushed = true;
959                                 InternalSetDomainByID (domain_id);
960                                 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
961                                 if (exc != null)
962                                         throw exc;
963                                 return o;
964                         }
965                         finally {
966                                 InternalSetDomain (current);
967                                 if (pushed)
968                                         InternalPopDomainRef ();
969                         }
970                 }
971
972                 internal static String GetProcessGuid ()
973                 {
974                         if (_process_guid == null) {
975                                 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
976                         }
977                         return _process_guid;
978                 }
979
980 #if !MOONLIGHT
981
982                 public static AppDomain CreateDomain (string friendlyName)
983                 {
984                         return CreateDomain (friendlyName, null, null);
985                 }
986                 
987                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
988                 {
989                         return CreateDomain (friendlyName, securityInfo, null);
990                 }
991
992                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
993                 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
994
995                 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
996                 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
997                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
998                 {
999                         if (friendlyName == null)
1000                                 throw new System.ArgumentNullException ("friendlyName");
1001
1002                         AppDomain def = AppDomain.DefaultDomain;
1003                         if (info == null) {
1004                                 // if null, get default domain's SetupInformation       
1005                                 if (def == null)
1006                                         info = new AppDomainSetup ();   // we're default!
1007                                 else
1008                                         info = def.SetupInformation;
1009                         }
1010                         else
1011                                 info = new AppDomainSetup (info);       // copy
1012
1013                         // todo: allow setup in the other domain
1014                         if (def != null) {
1015                                 if (!info.Equals (def.SetupInformation)) {
1016                                         // If not specified use default domain's app base.
1017                                         if (info.ApplicationBase == null)
1018                                                 info.ApplicationBase = def.SetupInformation.ApplicationBase;
1019                                         if (info.ConfigurationFile == null)
1020                                                 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
1021                                 }
1022                         } else if (info.ConfigurationFile == null)
1023                                 info.ConfigurationFile = "[I don't have a config file]";
1024
1025 #if !NET_2_1
1026                         if (info.AppDomainInitializer != null) {
1027                                 if (!info.AppDomainInitializer.Method.IsStatic)
1028                                         throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
1029                         }
1030 #endif
1031
1032                         info.SerializeNonPrimitives ();
1033
1034                         AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
1035                         if (securityInfo == null) {
1036                                 // get default domain's Evidence (unless we're are the default!)
1037                                 if (def == null)
1038                                         ad._evidence = null;            // we'll get them later (GetEntryAssembly)
1039                                 else
1040                                         ad._evidence = def.Evidence;    // new (shallow) copy
1041                         }
1042                         else
1043                                 ad._evidence = new Evidence (securityInfo);     // copy
1044
1045 #if !NET_2_1
1046                         if (info.AppDomainInitializer != null) {
1047                                 Loader loader = new Loader (
1048                                         info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
1049                                 ad.DoCallBack (loader.Load);
1050
1051                                 Initializer initializer = new Initializer (
1052                                         info.AppDomainInitializer,
1053                                         info.AppDomainInitializerArguments);
1054                                 ad.DoCallBack (initializer.Initialize);
1055                         }
1056 #endif
1057
1058                         return ad;
1059                 }
1060
1061 #if !NET_2_1
1062                 [Serializable]
1063                 class Loader {
1064
1065                         string assembly;
1066
1067                         public Loader (string assembly)
1068                         {
1069                                 this.assembly = assembly;
1070                         }
1071
1072                         public void Load ()
1073                         {
1074                                 Assembly.LoadFrom (assembly);
1075                         }
1076                 }
1077
1078                 [Serializable]
1079                 class Initializer {
1080
1081                         AppDomainInitializer initializer;
1082                         string [] arguments;
1083
1084                         public Initializer (AppDomainInitializer initializer, string [] arguments)
1085                         {
1086                                 this.initializer = initializer;
1087                                 this.arguments = arguments;
1088                         }
1089
1090                         public void Initialize ()
1091                         {
1092                                 initializer (arguments);
1093                         }
1094                 }
1095 #endif
1096
1097                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
1098                                                       string appRelativeSearchPath, bool shadowCopyFiles)
1099                 {
1100                         return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
1101                 }
1102                 
1103 #if !NET_2_1
1104                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
1105                                                       PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
1106                 {
1107                         if (info == null)
1108                                 throw new ArgumentNullException ("info");
1109
1110                         info.ApplicationTrust = new ApplicationTrust (grantSet, fullTrustAssemblies ?? new StrongName [0]);
1111                         return CreateDomain (friendlyName, securityInfo, info);         
1112                 }
1113 #endif
1114
1115                 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
1116                 {
1117                         AppDomainSetup info = new AppDomainSetup ();
1118
1119                         info.ApplicationBase = appBasePath;
1120                         info.PrivateBinPath = appRelativeSearchPath;
1121
1122                         if (shadowCopyFiles)
1123                                 info.ShadowCopyFiles = "true";
1124                         else
1125                                 info.ShadowCopyFiles = "false";
1126
1127                         return info;
1128                 }
1129 #endif // !NET_2_1
1130
1131                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1132                 private static extern bool InternalIsFinalizingForUnload (int domain_id);
1133
1134                 public bool IsFinalizingForUnload()
1135                 {
1136                         return InternalIsFinalizingForUnload (getDomainID ());
1137                 }
1138
1139                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1140                 static extern void InternalUnload (int domain_id);
1141
1142                 // We do this because if the domain is a transparant proxy this
1143                 // will still return the correct domain id.
1144                 private int getDomainID ()
1145                 {
1146                         return Thread.GetDomainID ();
1147                 }
1148
1149                 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1150                 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1151                 public static void Unload (AppDomain domain)
1152                 {
1153                         if (domain == null)
1154                                 throw new ArgumentNullException ("domain");
1155
1156                         InternalUnload (domain.getDomainID());
1157                 }
1158
1159                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1160                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1161                 public extern void SetData (string name, object data);
1162
1163                 [MonoLimitation ("The permission field is ignored")]
1164                 public void SetData (string name, object data, IPermission permission)
1165                 {
1166                         SetData (name, data);
1167                 }
1168
1169 #if !NET_2_1
1170                 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1171                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1172                 public void SetDynamicBase (string path)
1173                 {
1174                         SetupInformationNoCopy.DynamicBase = path;
1175                 }
1176 #endif // !NET_2_1
1177
1178                 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1179                         + " because it does not provide a stable Id when managed"
1180                         + " threads are running on fibers (aka lightweight"
1181                         + " threads). To get a stable identifier for a managed"
1182                         + " thread, use the ManagedThreadId property on Thread.'")]
1183                 public static int GetCurrentThreadId ()
1184                 {
1185                         return Thread.CurrentThreadId;
1186                 }
1187
1188                 public override string ToString ()
1189                 {
1190 #if !MOONLIGHT
1191                         return getFriendlyName ();
1192 #else
1193                         StringBuilder sb = new StringBuilder ("Name:");
1194                         sb.AppendLine (FriendlyName);
1195                         sb.AppendLine ("There are no context policies.");
1196                         return sb.ToString ();
1197 #endif
1198                 }
1199
1200                 private static void ValidateAssemblyName (string name)
1201                 {
1202                         if (name == null || name.Length == 0)
1203                                 throw new ArgumentException ("The Name of " +
1204                                         "AssemblyName cannot be null or a " +
1205                                         "zero-length string.");
1206
1207                         bool isValid = true;
1208
1209                         for (int i = 0; i < name.Length; i++) {
1210                                 char c = name [i];
1211
1212                                 // do not allow leading whitespace
1213                                 if (i == 0 && char.IsWhiteSpace (c)) {
1214                                         isValid = false;
1215                                         break;
1216                                 }
1217
1218                                 // do not allow /,\ or : in name
1219                                 if (c == '/' || c == '\\' || c == ':') {
1220                                         isValid = false;
1221                                         break;
1222                                 }
1223                         }
1224
1225                         if (!isValid)
1226                                 throw new ArgumentException ("The Name of " +
1227                                         "AssemblyName cannot start with " +
1228                                         "whitespace, or contain '/', '\\' " +
1229                                         " or ':'.");
1230                 }
1231
1232                 // The following methods are called from the runtime. Don't change signatures.
1233 #pragma warning disable 169             
1234                 private void DoAssemblyLoad (Assembly assembly)
1235                 {
1236                         if (AssemblyLoad == null)
1237                                 return;
1238
1239                         AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1240                 }
1241
1242                 private Assembly DoAssemblyResolve (string name, bool refonly)
1243                 {
1244                         ResolveEventHandler del;
1245 #if !NET_2_1
1246                         if (refonly)
1247                                 del = ReflectionOnlyAssemblyResolve;
1248                         else
1249                                 del = AssemblyResolve;
1250 #else
1251                         del = AssemblyResolve;
1252 #endif
1253                         if (del == null)
1254                                 return null;
1255                         
1256                         /* Prevent infinite recursion */
1257                         Hashtable ht;
1258                         if (refonly) {
1259                                 ht = assembly_resolve_in_progress_refonly;
1260                                 if (ht == null) {
1261                                         ht = new Hashtable ();
1262                                         assembly_resolve_in_progress_refonly = ht;
1263                                 }
1264                         } else {
1265                                 ht = assembly_resolve_in_progress;
1266                                 if (ht == null) {
1267                                         ht = new Hashtable ();
1268                                         assembly_resolve_in_progress = ht;
1269                                 }
1270                         }
1271
1272                         string s = (string) ht [name];
1273                         if (s != null)
1274                                 return null;
1275                         ht [name] = name;
1276                         try {
1277                                 Delegate[] invocation_list = del.GetInvocationList ();
1278
1279                                 foreach (Delegate eh in invocation_list) {
1280                                         ResolveEventHandler handler = (ResolveEventHandler) eh;
1281                                         Assembly assembly = handler (this, new ResolveEventArgs (name));
1282                                         if (assembly != null)
1283                                                 return assembly;
1284                                 }
1285                                 return null;
1286                         }
1287                         finally {
1288                                 ht.Remove (name);
1289                         }
1290                 }
1291
1292                 internal Assembly DoTypeResolve (Object name_or_tb)
1293                 {
1294                         if (TypeResolve == null)
1295                                 return null;
1296
1297                         string name;
1298
1299                         if (name_or_tb is TypeBuilder)
1300                                 name = ((TypeBuilder) name_or_tb).FullName;
1301                         else
1302                                 name = (string) name_or_tb;
1303
1304                         /* Prevent infinite recursion */
1305                         Hashtable ht = type_resolve_in_progress;
1306                         if (ht == null) {
1307                                 ht = new Hashtable ();
1308                                 type_resolve_in_progress = ht;
1309                         }
1310
1311                         if (ht.Contains (name))
1312                                 return null;
1313                         else
1314                                 ht [name] = name;
1315
1316                         try {
1317                                 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1318                                         ResolveEventHandler eh = (ResolveEventHandler) d;
1319                                         Assembly assembly = eh (this, new ResolveEventArgs (name));
1320                                         if (assembly != null)
1321                                                 return assembly;
1322                                 }
1323                                 return null;
1324                         }
1325                         finally {
1326                                 ht.Remove (name);
1327                         }
1328                 }
1329
1330                 internal Assembly DoResourceResolve (string name, Assembly requesting) {
1331                         if (ResourceResolve == null)
1332                                 return null;
1333
1334                         Delegate[] invocation_list = ResourceResolve.GetInvocationList ();
1335
1336                         foreach (Delegate eh in invocation_list) {
1337                                 ResolveEventHandler handler = (ResolveEventHandler) eh;
1338 #if NET_4_0
1339                                 Assembly assembly = handler (this, new ResolveEventArgs (name, requesting));
1340 #else
1341                                 Assembly assembly = handler (this, new ResolveEventArgs (name));
1342 #endif
1343                                 if (assembly != null)
1344                                         return assembly;
1345                         }
1346                         return null;
1347                 }
1348
1349                 private void DoDomainUnload ()
1350                 {
1351                         if (DomainUnload != null)
1352                                 DomainUnload(this, null);
1353                 }
1354
1355                 internal byte[] GetMarshalledDomainObjRef ()
1356                 {
1357                         ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1358                         return CADSerializer.SerializeObject (oref).GetBuffer();
1359                 }
1360
1361                 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1362                                                       out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1363                 {
1364                         IMessage reqDomMsg;
1365
1366                         if (null != arrRequest)
1367                                 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1368                         else
1369                                 reqDomMsg = new MethodCall (cadMsg);
1370
1371                         IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1372
1373                         cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1374                         if (null == cadMrm) {
1375                                 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1376                         } 
1377                         else
1378                                 arrResponse = null;
1379                 }
1380
1381 #pragma warning restore 169
1382
1383                 // End of methods called from the runtime
1384                 
1385                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1386                 public event AssemblyLoadEventHandler AssemblyLoad;
1387
1388                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1389                 public event ResolveEventHandler AssemblyResolve;
1390
1391                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1392                 public event EventHandler DomainUnload;
1393
1394                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1395                 public event EventHandler ProcessExit;
1396
1397                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1398                 public event ResolveEventHandler ResourceResolve;
1399
1400                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1401                 public event ResolveEventHandler TypeResolve;
1402
1403                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1404                 public event UnhandledExceptionEventHandler UnhandledException;
1405
1406 #if NET_4_0
1407                 [MonoTODO]
1408                 public bool IsHomogenous {
1409                         get { return true; }
1410                 }
1411
1412                 [MonoTODO]
1413                 public bool IsFullyTrusted {
1414                         get { return true; }
1415                 }
1416 #endif
1417
1418         #pragma warning disable 649
1419                 private AppDomainManager _domain_manager;
1420         #pragma warning restore 649
1421
1422                 // default is null
1423                 public AppDomainManager DomainManager {
1424                         get { return _domain_manager; }
1425                 }
1426
1427 #if (!MOONLIGHT)
1428
1429                 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1430
1431         #pragma warning disable 649
1432                 private ActivationContext _activation;
1433                 private ApplicationIdentity _applicationIdentity;
1434         #pragma warning restore 649
1435
1436                 // properties
1437
1438                 public ActivationContext ActivationContext {
1439                         get { return _activation; }
1440                 }
1441
1442                 public ApplicationIdentity ApplicationIdentity {
1443                         get { return _applicationIdentity; }
1444                 }
1445
1446                 public int Id {
1447                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1448                         get { return getDomainID (); }
1449                 }
1450
1451                 // methods
1452
1453                 [MonoTODO ("This routine only returns the parameter currently")]
1454                 [ComVisible (false)]
1455                 public string ApplyPolicy (string assemblyName)
1456                 {
1457                         if (assemblyName == null)
1458                                 throw new ArgumentNullException ("assemblyName");
1459                         if (assemblyName.Length == 0) // String.Empty
1460                                 throw new ArgumentException ("assemblyName");
1461                         return assemblyName;
1462                 }
1463
1464                 // static methods
1465
1466                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1467                         string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1468                 {
1469                         AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1470
1471                         info.AppDomainInitializerArguments = adInitArgs;
1472                         info.AppDomainInitializer = adInit;
1473
1474                         return CreateDomain (friendlyName, securityInfo, info);
1475                 }
1476
1477                 public int ExecuteAssemblyByName (string assemblyName)
1478                 {
1479                         return ExecuteAssemblyByName (assemblyName, (Evidence)null, null);
1480                 }
1481
1482 #if NET_4_0
1483                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1484 #endif
1485                 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1486                 {
1487                         return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1488                 }
1489
1490 #if NET_4_0
1491                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1492 #endif
1493                 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1494                 {
1495                         Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1496
1497                         return ExecuteAssemblyInternal (a, args);
1498                 }
1499
1500 #if NET_4_0
1501                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1502 #endif
1503                 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1504                 {
1505                         Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1506
1507                         return ExecuteAssemblyInternal (a, args);
1508                 }
1509
1510 #if NET_4_0
1511                 public int ExecuteAssemblyByName (string assemblyName, params string[] args)
1512                 {
1513                         Assembly a = Assembly.Load (assemblyName, null);
1514
1515                         return ExecuteAssemblyInternal (a, args);
1516                 }
1517
1518                 public int ExecuteAssemblyByName (AssemblyName assemblyName, params string[] args)
1519                 {
1520                         Assembly a = Assembly.Load (assemblyName, null);
1521
1522                         return ExecuteAssemblyInternal (a, args);
1523                 }
1524 #endif
1525
1526                 public bool IsDefaultAppDomain ()
1527                 {
1528                         return Object.ReferenceEquals (this, DefaultDomain);
1529                 }
1530
1531                 public Assembly[] ReflectionOnlyGetAssemblies ()
1532                 {
1533                         return GetAssemblies (true);
1534                 }
1535
1536 #else // MOONLIGHT
1537
1538                 public int ExecuteAssemblyByName (string assemblyName)
1539                 {
1540                         // critical code in SL that we're not calling in ML
1541                         throw new NotImplementedException ();
1542                 }
1543 #endif
1544
1545 #if !NET_2_1
1546                 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1547                 {
1548                         throw new NotImplementedException ();
1549                 }
1550
1551                 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1552                 {
1553                         throw new NotImplementedException ();
1554                 }
1555
1556                 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1557                 {
1558                         throw new NotImplementedException ();
1559                 }
1560
1561                 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1562                         IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1563                 {
1564                         throw new NotImplementedException ();
1565                 }
1566 #endif
1567
1568 #if NET_4_0 || MOONLIGHT || MOBILE
1569                 List<string> compatibility_switch;
1570
1571                 public bool? IsCompatibilitySwitchSet (string value)
1572                 {
1573                         if (value == null)
1574                                 throw new ArgumentNullException ("value");
1575
1576                         // default (at least for SL4) is to return false for unknown values (can't get a null out of it)
1577                         return ((compatibility_switch != null) && compatibility_switch.Contains (value));
1578                 }
1579
1580                 internal void SetCompatibilitySwitch (string value)
1581                 {
1582                         if (compatibility_switch == null)
1583                                 compatibility_switch = new List<string> ();
1584                         compatibility_switch.Add (value);
1585                 }
1586
1587                 [MonoTODO ("Currently always returns false")]
1588                 public static bool MonitoringIsEnabled { 
1589                         get { return false; }
1590                         set { throw new NotImplementedException (); }
1591                 }
1592
1593                 [MonoTODO]
1594                 public long MonitoringSurvivedMemorySize {
1595                         get { throw new NotImplementedException (); }
1596                 }
1597
1598                 [MonoTODO]
1599                 public static long MonitoringSurvivedProcessMemorySize {
1600                         get { throw new NotImplementedException (); }
1601                 }
1602
1603                 [MonoTODO]
1604                 public long MonitoringTotalAllocatedMemorySize {
1605                         get { throw new NotImplementedException (); }
1606                 }
1607
1608                 [MonoTODO]
1609                 public TimeSpan MonitoringTotalProcessorTime {
1610                         get { throw new NotImplementedException (); }
1611                 }
1612 #endif
1613         }
1614 }