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