2009-12-02 Jb Evain <jbevain@novell.com>
[mcs.git] / class / corlib / System.Reflection / Assembly.cs
blobdcfa6ae6f433977a26ddb84ff515501412bf0c59
1 //
2 // System.Reflection/Assembly.cs
3 //
4 // Author:
5 // Paolo Molaro (lupus@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc. http://www.ximian.com
8 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 //
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 //
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.Security;
31 using System.Security.Policy;
32 using System.Security.Permissions;
33 using System.Runtime.Serialization;
34 using System.Reflection;
35 using System.Reflection.Emit;
36 using System.IO;
37 using System.Globalization;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40 using System.Collections;
41 using System.Configuration.Assemblies;
43 using Mono.Security;
45 namespace System.Reflection {
47 #pragma warning disable 659 // overrides Equals but not GetHashCode
49 [ComVisible (true)]
50 [ComDefaultInterfaceAttribute (typeof (_Assembly))]
51 [Serializable]
52 [ClassInterface(ClassInterfaceType.None)]
53 #if NET_2_1
54 public class Assembly : ICustomAttributeProvider, _Assembly {
55 #else
56 public class Assembly : ICustomAttributeProvider, _Assembly, IEvidenceFactory, ISerializable {
57 #endif
59 internal class ResolveEventHolder {
60 public event ModuleResolveEventHandler ModuleResolve;
63 // Note: changes to fields must be reflected in _MonoReflectionAssembly struct (object-internals.h)
64 #pragma warning disable 169
65 private IntPtr _mono_assembly;
66 #pragma warning restore 169
68 private ResolveEventHolder resolve_event_holder;
69 private Evidence _evidence;
70 internal PermissionSet _minimum; // for SecurityAction.RequestMinimum
71 internal PermissionSet _optional; // for SecurityAction.RequestOptional
72 internal PermissionSet _refuse; // for SecurityAction.RequestRefuse
73 private PermissionSet _granted; // for the resolved assembly granted permissions
74 private PermissionSet _denied; // for the resolved assembly denied permissions
75 private bool fromByteArray;
76 private string assemblyName;
78 internal Assembly ()
80 resolve_event_holder = new ResolveEventHolder ();
84 // We can't store the event directly in this class, since the
85 // compiler would silently insert the fields before _mono_assembly
87 public event ModuleResolveEventHandler ModuleResolve {
88 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
89 add {
90 resolve_event_holder.ModuleResolve += value;
92 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
93 remove {
94 resolve_event_holder.ModuleResolve -= value;
98 [MethodImplAttribute (MethodImplOptions.InternalCall)]
99 private extern string get_code_base (bool escaped);
101 [MethodImplAttribute (MethodImplOptions.InternalCall)]
102 private extern string get_fullname ();
104 [MethodImplAttribute (MethodImplOptions.InternalCall)]
105 private extern string get_location ();
107 [MethodImplAttribute (MethodImplOptions.InternalCall)]
108 private extern string InternalImageRuntimeVersion ();
110 // SECURITY: this should be the only caller to icall get_code_base
111 private string GetCodeBase (bool escaped)
113 string cb = get_code_base (escaped);
114 #if !NET_2_1
115 if (SecurityManager.SecurityEnabled) {
116 // we cannot divulge local file informations
117 if (String.Compare ("FILE://", 0, cb, 0, 7, true, CultureInfo.InvariantCulture) == 0) {
118 string file = cb.Substring (7);
119 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, file).Demand ();
122 #endif
123 return cb;
126 public virtual string CodeBase {
127 get { return GetCodeBase (false); }
130 public virtual string EscapedCodeBase {
131 get { return GetCodeBase (true); }
134 public virtual string FullName {
135 get {
137 // FIXME: This is wrong, but it gets us going
138 // in the compiler for now
140 return ToString ();
144 public virtual extern MethodInfo EntryPoint {
145 [MethodImplAttribute (MethodImplOptions.InternalCall)]
146 get;
148 #if !NET_2_1 || MONOTOUCH
149 public virtual Evidence Evidence {
150 [SecurityPermission (SecurityAction.Demand, ControlEvidence = true)]
151 get { return UnprotectedGetEvidence (); }
154 // note: the security runtime requires evidences but may be unable to do so...
155 internal Evidence UnprotectedGetEvidence ()
157 // if the host (runtime) hasn't provided it's own evidence...
158 if (_evidence == null) {
159 // ... we will provide our own
160 lock (this) {
161 _evidence = Evidence.GetDefaultHostEvidence (this);
164 return _evidence;
167 [MethodImplAttribute (MethodImplOptions.InternalCall)]
168 private extern bool get_global_assembly_cache ();
170 public bool GlobalAssemblyCache {
171 get {
172 return get_global_assembly_cache ();
175 #endif
176 internal bool FromByteArray {
177 set { fromByteArray = value; }
180 public virtual String Location {
181 get {
182 if (fromByteArray)
183 return String.Empty;
185 string loc = get_location ();
186 #if !NET_2_1
187 if ((loc != String.Empty) && SecurityManager.SecurityEnabled) {
188 // we cannot divulge local file informations
189 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, loc).Demand ();
191 #endif
192 return loc;
196 [ComVisible (false)]
197 public virtual string ImageRuntimeVersion {
198 get {
199 return InternalImageRuntimeVersion ();
203 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
204 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
206 if (info == null)
207 throw new ArgumentNullException ("info");
209 UnitySerializationHolder.GetAssemblyData (this, info, context);
212 public virtual bool IsDefined (Type attributeType, bool inherit)
214 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
217 public virtual object [] GetCustomAttributes (bool inherit)
219 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
222 public virtual object [] GetCustomAttributes (Type attributeType, bool inherit)
224 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
227 [MethodImplAttribute (MethodImplOptions.InternalCall)]
228 private extern object GetFilesInternal (String name, bool getResourceModules);
230 public virtual FileStream[] GetFiles ()
232 return GetFiles (false);
235 public virtual FileStream [] GetFiles (bool getResourceModules)
237 string[] names = (string[]) GetFilesInternal (null, getResourceModules);
238 if (names == null)
239 return new FileStream [0];
241 string location = Location;
243 FileStream[] res;
244 if (location != String.Empty) {
245 res = new FileStream [names.Length + 1];
246 res [0] = new FileStream (location, FileMode.Open, FileAccess.Read);
247 for (int i = 0; i < names.Length; ++i)
248 res [i + 1] = new FileStream (names [i], FileMode.Open, FileAccess.Read);
249 } else {
250 res = new FileStream [names.Length];
251 for (int i = 0; i < names.Length; ++i)
252 res [i] = new FileStream (names [i], FileMode.Open, FileAccess.Read);
254 return res;
257 public virtual FileStream GetFile (String name)
259 if (name == null)
260 throw new ArgumentNullException (null, "Name cannot be null.");
261 if (name.Length == 0)
262 throw new ArgumentException ("Empty name is not valid");
264 string filename = (string)GetFilesInternal (name, true);
265 if (filename != null)
266 return new FileStream (filename, FileMode.Open, FileAccess.Read);
267 else
268 return null;
271 [MethodImplAttribute (MethodImplOptions.InternalCall)]
272 internal extern IntPtr GetManifestResourceInternal (String name, out int size, out Module module);
274 public virtual Stream GetManifestResourceStream (String name)
276 if (name == null)
277 throw new ArgumentNullException ("name");
278 if (name.Length == 0)
279 throw new ArgumentException ("String cannot have zero length.",
280 "name");
282 ManifestResourceInfo info = GetManifestResourceInfo (name);
283 if (info == null)
284 return null;
286 if (info.ReferencedAssembly != null)
287 return info.ReferencedAssembly.GetManifestResourceStream (name);
288 if ((info.FileName != null) && (info.ResourceLocation == 0)) {
289 if (fromByteArray)
290 throw new FileNotFoundException (info.FileName);
292 string location = Path.GetDirectoryName (Location);
293 string filename = Path.Combine (location, info.FileName);
294 #if NET_2_1 && !MONOTOUCH
295 // we don't control the content of 'info.FileName' so we want to make sure we keep to ourselves
296 filename = Path.GetFullPath (filename);
297 if (!filename.StartsWith (location))
298 throw new SecurityException ("non-rooted access to manifest resource");
299 #endif
300 return new FileStream (filename, FileMode.Open, FileAccess.Read);
303 int size;
304 Module module;
305 IntPtr data = GetManifestResourceInternal (name, out size, out module);
306 if (data == (IntPtr) 0)
307 return null;
308 else {
309 UnmanagedMemoryStream stream;
310 unsafe {
311 stream = new UnmanagedMemoryStream ((byte*) data, size);
314 * The returned pointer points inside metadata, so
315 * we have to increase the refcount of the module, and decrease
316 * it when the stream is finalized.
318 stream.Closed += new EventHandler (new ResourceCloseHandler (module).OnClose);
319 return stream;
323 public virtual Stream GetManifestResourceStream (Type type, String name)
325 string ns;
326 if (type != null) {
327 ns = type.Namespace;
328 } else {
329 if (name == null)
330 throw new ArgumentNullException ("type");
331 ns = null;
334 if (ns == null || ns.Length == 0)
335 return GetManifestResourceStream (name);
336 else
337 return GetManifestResourceStream (ns + "." + name);
340 [MethodImplAttribute (MethodImplOptions.InternalCall)]
341 internal virtual extern Type[] GetTypes (bool exportedOnly);
343 public virtual Type[] GetTypes ()
345 return GetTypes (false);
348 public virtual Type[] GetExportedTypes ()
350 return GetTypes (true);
353 public virtual Type GetType (String name, Boolean throwOnError)
355 return GetType (name, throwOnError, false);
358 public virtual Type GetType (String name) {
359 return GetType (name, false, false);
362 [MethodImplAttribute (MethodImplOptions.InternalCall)]
363 internal extern Type InternalGetType (Module module, String name, Boolean throwOnError, Boolean ignoreCase);
365 public Type GetType (string name, bool throwOnError, bool ignoreCase)
367 if (name == null)
368 throw new ArgumentNullException (name);
369 if (name.Length == 0)
370 throw new ArgumentException ("name", "Name cannot be empty");
372 return InternalGetType (null, name, throwOnError, ignoreCase);
375 [MethodImplAttribute (MethodImplOptions.InternalCall)]
376 internal extern static void InternalGetAssemblyName (string assemblyFile, AssemblyName aname);
378 [MethodImplAttribute (MethodImplOptions.InternalCall)]
379 static extern void FillName (Assembly ass, AssemblyName aname);
381 [MonoTODO ("copiedName == true is not supported")]
382 public virtual AssemblyName GetName (Boolean copiedName)
384 // CodeBase, which is restricted, will be copied into the AssemblyName object so...
385 if (SecurityManager.SecurityEnabled) {
386 GetCodeBase (true); // this will ensure the Demand is made
388 return UnprotectedGetName ();
391 public virtual AssemblyName GetName ()
393 return GetName (false);
396 // the security runtime requires access to the assemblyname (e.g. to get the strongname)
397 internal virtual AssemblyName UnprotectedGetName ()
399 AssemblyName aname = new AssemblyName ();
400 FillName (this, aname);
401 return aname;
404 public override string ToString ()
406 // note: ToString work without requiring CodeBase (so no checks are needed)
408 if (assemblyName != null)
409 return assemblyName;
411 assemblyName = get_fullname ();
412 return assemblyName;
415 public static String CreateQualifiedName (String assemblyName, String typeName)
417 return typeName + ", " + assemblyName;
420 public static Assembly GetAssembly (Type type)
422 if (type != null)
423 return type.Assembly;
424 throw new ArgumentNullException ("type");
428 [MethodImplAttribute (MethodImplOptions.InternalCall)]
429 public static extern Assembly GetEntryAssembly();
431 public Assembly GetSatelliteAssembly (CultureInfo culture)
433 return GetSatelliteAssembly (culture, null, true);
436 public Assembly GetSatelliteAssembly (CultureInfo culture, Version version)
438 return GetSatelliteAssembly (culture, version, true);
441 internal Assembly GetSatelliteAssemblyNoThrow (CultureInfo culture, Version version)
443 return GetSatelliteAssembly (culture, version, false);
446 private Assembly GetSatelliteAssembly (CultureInfo culture, Version version, bool throwOnError)
448 if (culture == null)
449 throw new ArgumentException ("culture");
451 AssemblyName aname = GetName (true);
452 if (version != null)
453 aname.Version = version;
455 aname.CultureInfo = culture;
456 aname.Name = aname.Name + ".resources";
457 Assembly assembly;
459 try {
460 assembly = AppDomain.CurrentDomain.LoadSatellite (aname);
461 if (assembly != null)
462 return assembly;
463 } catch (FileNotFoundException) {
464 assembly = null;
465 // ignore
468 // Try the assembly directory
469 string location = Path.GetDirectoryName (Location);
470 string fullName = Path.Combine (location, Path.Combine (culture.Name, aname.Name + ".dll"));
471 #if NET_2_1 && !MONOTOUCH
472 // it's unlikely that culture.Name or aname.Name could contain stuff like ".." but...
473 fullName = Path.GetFullPath (fullName);
474 if (!fullName.StartsWith (location)) {
475 if (throwOnError)
476 throw new SecurityException ("non-rooted access to satellite assembly");
477 return null;
479 #endif
480 if (!throwOnError && !File.Exists (fullName))
481 return null;
483 return LoadFrom (fullName);
486 [MethodImplAttribute (MethodImplOptions.InternalCall)]
487 private extern static Assembly LoadFrom (String assemblyFile, bool refonly);
489 public static Assembly LoadFrom (String assemblyFile)
491 return LoadFrom (assemblyFile, false);
494 public static Assembly LoadFrom (String assemblyFile, Evidence securityEvidence)
496 Assembly a = LoadFrom (assemblyFile, false);
497 #if !NET_2_1
498 if ((a != null) && (securityEvidence != null)) {
499 // merge evidence (i.e. replace defaults with provided evidences)
500 a.Evidence.Merge (securityEvidence);
502 #endif
503 return a;
506 [MonoTODO("This overload is not currently implemented")]
507 // FIXME: What are we missing?
508 public static Assembly LoadFrom (String assemblyFile, Evidence securityEvidence, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
510 if (assemblyFile == null)
511 throw new ArgumentNullException ("assemblyFile");
512 if (assemblyFile == String.Empty)
513 throw new ArgumentException ("Name can't be the empty string", "assemblyFile");
514 throw new NotImplementedException ();
517 public static Assembly LoadFile (String path, Evidence securityEvidence)
519 if (path == null)
520 throw new ArgumentNullException ("path");
521 if (path == String.Empty)
522 throw new ArgumentException ("Path can't be empty", "path");
523 // FIXME: Make this do the right thing
524 return LoadFrom (path, securityEvidence);
527 public static Assembly LoadFile (String path)
529 return LoadFile (path, null);
532 public static Assembly Load (String assemblyString)
534 return AppDomain.CurrentDomain.Load (assemblyString);
537 public static Assembly Load (String assemblyString, Evidence assemblySecurity)
539 return AppDomain.CurrentDomain.Load (assemblyString, assemblySecurity);
542 public static Assembly Load (AssemblyName assemblyRef)
544 return AppDomain.CurrentDomain.Load (assemblyRef);
547 public static Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
549 return AppDomain.CurrentDomain.Load (assemblyRef, assemblySecurity);
552 public static Assembly Load (Byte[] rawAssembly)
554 return AppDomain.CurrentDomain.Load (rawAssembly);
557 public static Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore)
559 return AppDomain.CurrentDomain.Load (rawAssembly, rawSymbolStore);
562 public static Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore,
563 Evidence securityEvidence)
565 return AppDomain.CurrentDomain.Load (rawAssembly, rawSymbolStore, securityEvidence);
568 public static Assembly ReflectionOnlyLoad (byte[] rawAssembly)
570 return AppDomain.CurrentDomain.Load (rawAssembly, null, null, true);
573 public static Assembly ReflectionOnlyLoad (string assemblyString)
575 return AppDomain.CurrentDomain.Load (assemblyString, null, true);
578 public static Assembly ReflectionOnlyLoadFrom (string assemblyFile)
580 if (assemblyFile == null)
581 throw new ArgumentNullException ("assemblyFile");
583 return LoadFrom (assemblyFile, true);
586 public static Assembly LoadWithPartialName (string partialName)
588 return LoadWithPartialName (partialName, null);
591 [MonoTODO ("Not implemented")]
592 public Module LoadModule (string moduleName, byte [] rawModule)
594 throw new NotImplementedException ();
597 [MonoTODO ("Not implemented")]
598 public Module LoadModule (string moduleName, byte [] rawModule, byte [] rawSymbolStore)
600 throw new NotImplementedException ();
603 [MethodImplAttribute (MethodImplOptions.InternalCall)]
604 private static extern Assembly load_with_partial_name (string name, Evidence e);
606 public static Assembly LoadWithPartialName (string partialName, Evidence securityEvidence)
608 return LoadWithPartialName (partialName, securityEvidence, true);
612 * LAMESPEC: It is possible for this method to throw exceptions IF the name supplied
613 * is a valid gac name and contains filesystem entry charachters at the end of the name
614 * ie System/// will throw an exception. However ////System will not as that is canocolized
615 * out of the name.
618 // FIXME: LoadWithPartialName must look cache (no CAS) or read from disk (CAS)
619 internal static Assembly LoadWithPartialName (string partialName, Evidence securityEvidence, bool oldBehavior)
621 if (!oldBehavior)
622 throw new NotImplementedException ();
624 if (partialName == null)
625 throw new NullReferenceException ();
627 return load_with_partial_name (partialName, securityEvidence);
630 public Object CreateInstance (String typeName)
632 return CreateInstance (typeName, false);
635 public Object CreateInstance (String typeName, Boolean ignoreCase)
637 Type t = GetType (typeName, false, ignoreCase);
638 if (t == null)
639 return null;
641 try {
642 return Activator.CreateInstance (t);
643 } catch (InvalidOperationException) {
644 throw new ArgumentException ("It is illegal to invoke a method on a Type loaded via ReflectionOnly methods.");
648 public Object CreateInstance (String typeName, Boolean ignoreCase,
649 BindingFlags bindingAttr, Binder binder,
650 Object[] args, CultureInfo culture,
651 Object[] activationAttributes)
653 Type t = GetType (typeName, false, ignoreCase);
654 if (t == null)
655 return null;
657 try {
658 return Activator.CreateInstance (t, bindingAttr, binder, args, culture, activationAttributes);
659 } catch (InvalidOperationException) {
660 throw new ArgumentException ("It is illegal to invoke a method on a Type loaded via ReflectionOnly methods.");
664 public Module[] GetLoadedModules ()
666 return GetLoadedModules (false);
669 // FIXME: Currently, the two sets of modules are equal
670 public Module[] GetLoadedModules (bool getResourceModules)
672 return GetModules (getResourceModules);
675 public Module[] GetModules ()
677 return GetModules (false);
680 public Module GetModule (String name)
682 if (name == null)
683 throw new ArgumentNullException ("name");
684 if (name.Length == 0)
685 throw new ArgumentException ("Name can't be empty");
687 Module[] modules = GetModules (true);
688 foreach (Module module in modules) {
689 if (module.ScopeName == name)
690 return module;
693 return null;
696 [MethodImplAttribute (MethodImplOptions.InternalCall)]
697 internal virtual extern Module[] GetModulesInternal ();
699 public Module[] GetModules (bool getResourceModules) {
700 Module[] modules = GetModulesInternal ();
702 if (!getResourceModules) {
703 ArrayList result = new ArrayList (modules.Length);
704 foreach (Module m in modules)
705 if (!m.IsResource ())
706 result.Add (m);
707 return (Module[])result.ToArray (typeof (Module));
709 else
710 return modules;
713 [MethodImplAttribute (MethodImplOptions.InternalCall)]
714 internal extern string[] GetNamespaces ();
716 [MethodImplAttribute (MethodImplOptions.InternalCall)]
717 public extern virtual String[] GetManifestResourceNames ();
719 [MethodImplAttribute (MethodImplOptions.InternalCall)]
720 public extern static Assembly GetExecutingAssembly ();
722 [MethodImplAttribute (MethodImplOptions.InternalCall)]
723 public extern static Assembly GetCallingAssembly ();
725 [MethodImplAttribute (MethodImplOptions.InternalCall)]
726 public extern AssemblyName[] GetReferencedAssemblies ();
728 [MethodImplAttribute (MethodImplOptions.InternalCall)]
729 private extern bool GetManifestResourceInfoInternal (String name, ManifestResourceInfo info);
731 public virtual ManifestResourceInfo GetManifestResourceInfo (String resourceName)
733 if (resourceName == null)
734 throw new ArgumentNullException ("resourceName");
735 if (resourceName.Length == 0)
736 throw new ArgumentException ("String cannot have zero length.");
737 ManifestResourceInfo result = new ManifestResourceInfo ();
738 bool found = GetManifestResourceInfoInternal (resourceName, result);
739 if (found)
740 return result;
741 else
742 return null;
745 private class ResourceCloseHandler {
746 #pragma warning disable 169, 414
747 Module module;
748 #pragma warning restore 169, 414
750 public ResourceCloseHandler (Module module) {
751 this.module = module;
754 public void OnClose (object sender, EventArgs e) {
755 // The module dtor will take care of things
756 module = null;
761 // The following functions are only for the Mono Debugger.
764 [MethodImplAttribute (MethodImplOptions.InternalCall)]
765 internal static extern int MonoDebugger_GetMethodToken (MethodBase method);
767 [MonoTODO ("Currently it always returns zero")]
768 [ComVisible (false)]
769 public long HostContext {
770 get { return 0; }
773 [ComVisible (false)]
774 public Module ManifestModule {
775 get {
776 return GetManifestModule ();
780 internal virtual Module GetManifestModule () {
781 return GetManifestModuleInternal ();
784 [MethodImplAttribute (MethodImplOptions.InternalCall)]
785 internal extern Module GetManifestModuleInternal ();
787 [ComVisible (false)]
788 public virtual extern bool ReflectionOnly {
789 [MethodImplAttribute (MethodImplOptions.InternalCall)]
790 get;
793 public override bool Equals (object o)
795 if (((object) this) == o)
796 return true;
798 if (o == null)
799 return false;
801 Assembly other = (Assembly) o;
802 return other._mono_assembly == _mono_assembly;
805 #if !NET_2_1 || MONOTOUCH
806 // Code Access Security
808 internal void Resolve ()
810 lock (this) {
811 // FIXME: As we (currently) delay the resolution until the first CAS
812 // Demand it's too late to evaluate the Minimum permission set as a
813 // condition to load the assembly into the AppDomain
814 LoadAssemblyPermissions ();
815 Evidence e = new Evidence (UnprotectedGetEvidence ()); // we need a copy to add PRE
816 e.AddHost (new PermissionRequestEvidence (_minimum, _optional, _refuse));
817 _granted = SecurityManager.ResolvePolicy (e,
818 _minimum, _optional, _refuse, out _denied);
822 internal PermissionSet GrantedPermissionSet {
823 get {
824 if (_granted == null) {
825 if (SecurityManager.ResolvingPolicyLevel != null) {
826 if (SecurityManager.ResolvingPolicyLevel.IsFullTrustAssembly (this))
827 return DefaultPolicies.FullTrust;
828 else
829 return null; // we can't resolve during resolution
831 Resolve ();
833 return _granted;
837 internal PermissionSet DeniedPermissionSet {
838 get {
839 // yes we look for granted, as denied may be null
840 if (_granted == null) {
841 if (SecurityManager.ResolvingPolicyLevel != null) {
842 if (SecurityManager.ResolvingPolicyLevel.IsFullTrustAssembly (this))
843 return null;
844 else
845 return DefaultPolicies.FullTrust; // deny unrestricted
847 Resolve ();
849 return _denied;
853 [MethodImplAttribute (MethodImplOptions.InternalCall)]
854 extern internal static bool LoadPermissions (Assembly a,
855 ref IntPtr minimum, ref int minLength,
856 ref IntPtr optional, ref int optLength,
857 ref IntPtr refused, ref int refLength);
859 // Support for SecurityAction.RequestMinimum, RequestOptional and RequestRefuse
860 private void LoadAssemblyPermissions ()
862 IntPtr minimum = IntPtr.Zero, optional = IntPtr.Zero, refused = IntPtr.Zero;
863 int minLength = 0, optLength = 0, refLength = 0;
864 if (LoadPermissions (this, ref minimum, ref minLength, ref optional,
865 ref optLength, ref refused, ref refLength)) {
867 // Note: no need to cache these permission sets as they will only be created once
868 // at assembly resolution time.
869 if (minLength > 0) {
870 byte[] data = new byte [minLength];
871 Marshal.Copy (minimum, data, 0, minLength);
872 _minimum = SecurityManager.Decode (data);
874 if (optLength > 0) {
875 byte[] data = new byte [optLength];
876 Marshal.Copy (optional, data, 0, optLength);
877 _optional = SecurityManager.Decode (data);
879 if (refLength > 0) {
880 byte[] data = new byte [refLength];
881 Marshal.Copy (refused, data, 0, refLength);
882 _refuse = SecurityManager.Decode (data);
886 #endif
890 #pragma warning restore 659