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