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