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