2 // System.Reflection/Assembly.cs
5 // Paolo Molaro (lupus@ximian.com)
7 // (C) 2001 Ximian, Inc. http://www.ximian.com
8 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
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:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
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;
37 using System.Globalization;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40 using System.Collections;
41 using System.Configuration.Assemblies;
45 namespace System.Reflection {
48 [ComDefaultInterfaceAttribute (typeof (_Assembly))]
50 [ClassInterface(ClassInterfaceType.None)]
52 public class Assembly : ICustomAttributeProvider, _Assembly {
54 public class Assembly : ICustomAttributeProvider, _Assembly, IEvidenceFactory, ISerializable {
57 internal class ResolveEventHolder {
58 public event ModuleResolveEventHandler ModuleResolve;
61 // Note: changes to fields must be reflected in _MonoReflectionAssembly struct (object-internals.h)
62 #pragma warning disable 169
63 private IntPtr _mono_assembly;
64 #pragma warning restore 169
66 private ResolveEventHolder resolve_event_holder;
67 private Evidence _evidence;
68 internal PermissionSet _minimum; // for SecurityAction.RequestMinimum
69 internal PermissionSet _optional; // for SecurityAction.RequestOptional
70 internal PermissionSet _refuse; // for SecurityAction.RequestRefuse
71 private PermissionSet _granted; // for the resolved assembly granted permissions
72 private PermissionSet _denied; // for the resolved assembly denied permissions
73 private bool fromByteArray;
74 private string assemblyName;
78 resolve_event_holder = new ResolveEventHolder ();
82 // We can't store the event directly in this class, since the
83 // compiler would silently insert the fields before _mono_assembly
85 public event ModuleResolveEventHandler ModuleResolve {
86 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
88 resolve_event_holder.ModuleResolve += value;
90 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
92 resolve_event_holder.ModuleResolve -= value;
96 [MethodImplAttribute (MethodImplOptions.InternalCall)]
97 private extern string get_code_base (bool escaped);
99 [MethodImplAttribute (MethodImplOptions.InternalCall)]
100 private extern string get_fullname ();
102 [MethodImplAttribute (MethodImplOptions.InternalCall)]
103 private extern string get_location ();
105 [MethodImplAttribute (MethodImplOptions.InternalCall)]
106 private extern string InternalImageRuntimeVersion ();
108 // SECURITY: this should be the only caller to icall get_code_base
109 private string GetCodeBase (bool escaped)
111 string cb = get_code_base (escaped);
113 if (SecurityManager.SecurityEnabled) {
114 // we cannot divulge local file informations
115 if (String.Compare ("FILE://", 0, cb, 0, 7, true, CultureInfo.InvariantCulture) == 0) {
116 string file = cb.Substring (7);
117 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, file).Demand ();
124 public virtual string CodeBase {
125 get { return GetCodeBase (false); }
128 public virtual string EscapedCodeBase {
129 get { return GetCodeBase (true); }
132 public virtual string FullName {
135 // FIXME: This is wrong, but it gets us going
136 // in the compiler for now
142 public virtual extern MethodInfo EntryPoint {
143 [MethodImplAttribute (MethodImplOptions.InternalCall)]
146 #if !NET_2_1 || MONOTOUCH
147 public virtual Evidence Evidence {
148 [SecurityPermission (SecurityAction.Demand, ControlEvidence = true)]
149 get { return UnprotectedGetEvidence (); }
152 // note: the security runtime requires evidences but may be unable to do so...
153 internal Evidence UnprotectedGetEvidence ()
155 // if the host (runtime) hasn't provided it's own evidence...
156 if (_evidence == null) {
157 // ... we will provide our own
159 _evidence = Evidence.GetDefaultHostEvidence (this);
165 [MethodImplAttribute (MethodImplOptions.InternalCall)]
166 private extern bool get_global_assembly_cache ();
168 public bool GlobalAssemblyCache {
170 return get_global_assembly_cache ();
174 internal bool FromByteArray {
175 set { fromByteArray = value; }
178 public virtual String Location {
183 string loc = get_location ();
185 if ((loc != String.Empty) && SecurityManager.SecurityEnabled) {
186 // we cannot divulge local file informations
187 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, loc).Demand ();
195 public virtual string ImageRuntimeVersion {
197 return InternalImageRuntimeVersion ();
201 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
202 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
205 throw new ArgumentNullException ("info");
207 UnitySerializationHolder.GetAssemblyData (this, info, context);
210 public virtual bool IsDefined (Type attributeType, bool inherit)
212 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
215 public virtual object [] GetCustomAttributes (bool inherit)
217 return MonoCustomAttrs.GetCustomAttributes (this, inherit);
220 public virtual object [] GetCustomAttributes (Type attributeType, bool inherit)
222 return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
225 [MethodImplAttribute (MethodImplOptions.InternalCall)]
226 private extern object GetFilesInternal (String name, bool getResourceModules);
228 public virtual FileStream[] GetFiles ()
230 return GetFiles (false);
233 public virtual FileStream [] GetFiles (bool getResourceModules)
235 string[] names = (string[]) GetFilesInternal (null, getResourceModules);
237 return new FileStream [0];
239 string location = Location;
242 if (location != String.Empty) {
243 res = new FileStream [names.Length + 1];
244 res [0] = new FileStream (location, FileMode.Open, FileAccess.Read);
245 for (int i = 0; i < names.Length; ++i)
246 res [i + 1] = new FileStream (names [i], FileMode.Open, FileAccess.Read);
248 res = new FileStream [names.Length];
249 for (int i = 0; i < names.Length; ++i)
250 res [i] = new FileStream (names [i], FileMode.Open, FileAccess.Read);
255 public virtual FileStream GetFile (String name)
258 throw new ArgumentNullException (null, "Name cannot be null.");
259 if (name.Length == 0)
260 throw new ArgumentException ("Empty name is not valid");
262 string filename = (string)GetFilesInternal (name, true);
263 if (filename != null)
264 return new FileStream (filename, FileMode.Open, FileAccess.Read);
269 [MethodImplAttribute (MethodImplOptions.InternalCall)]
270 internal extern IntPtr GetManifestResourceInternal (String name, out int size, out Module module);
272 public virtual Stream GetManifestResourceStream (String name)
275 throw new ArgumentNullException ("name");
276 if (name.Length == 0)
277 throw new ArgumentException ("String cannot have zero length.",
280 ManifestResourceInfo info = GetManifestResourceInfo (name);
284 if (info.ReferencedAssembly != null)
285 return info.ReferencedAssembly.GetManifestResourceStream (name);
286 if ((info.FileName != null) && (info.ResourceLocation == 0)) {
288 throw new FileNotFoundException (info.FileName);
290 string location = Path.GetDirectoryName (Location);
291 string filename = Path.Combine (location, info.FileName);
292 #if NET_2_1 && !MONOTOUCH
293 // we don't control the content of 'info.FileName' so we want to make sure we keep to ourselves
294 filename = Path.GetFullPath (filename);
295 if (!filename.StartsWith (location))
296 throw new SecurityException ("non-rooted access to manifest resource");
298 return new FileStream (filename, FileMode.Open, FileAccess.Read);
303 IntPtr data = GetManifestResourceInternal (name, out size, out module);
304 if (data == (IntPtr) 0)
307 UnmanagedMemoryStream stream;
309 stream = new UnmanagedMemoryStream ((byte*) data, size);
312 * The returned pointer points inside metadata, so
313 * we have to increase the refcount of the module, and decrease
314 * it when the stream is finalized.
316 stream.Closed += new EventHandler (new ResourceCloseHandler (module).OnClose);
321 public virtual Stream GetManifestResourceStream (Type type, String name)
328 throw new ArgumentNullException ("type");
332 if (ns == null || ns.Length == 0)
333 return GetManifestResourceStream (name);
335 return GetManifestResourceStream (ns + "." + name);
338 [MethodImplAttribute (MethodImplOptions.InternalCall)]
339 internal virtual extern Type[] GetTypes (bool exportedOnly);
341 public virtual Type[] GetTypes ()
343 return GetTypes (false);
346 public virtual Type[] GetExportedTypes ()
348 return GetTypes (true);
351 public virtual Type GetType (String name, Boolean throwOnError)
353 return GetType (name, throwOnError, false);
356 public virtual Type GetType (String name) {
357 return GetType (name, false, false);
360 [MethodImplAttribute (MethodImplOptions.InternalCall)]
361 internal extern Type InternalGetType (Module module, String name, Boolean throwOnError, Boolean ignoreCase);
363 public Type GetType (string name, bool throwOnError, bool ignoreCase)
366 throw new ArgumentNullException (name);
367 if (name.Length == 0)
368 throw new ArgumentException ("name", "Name cannot be empty");
370 return InternalGetType (null, name, throwOnError, ignoreCase);
373 [MethodImplAttribute (MethodImplOptions.InternalCall)]
374 internal extern static void InternalGetAssemblyName (string assemblyFile, AssemblyName aname);
376 [MethodImplAttribute (MethodImplOptions.InternalCall)]
377 static extern void FillName (Assembly ass, AssemblyName aname);
379 [MonoTODO ("copiedName == true is not supported")]
380 public virtual AssemblyName GetName (Boolean copiedName)
382 // CodeBase, which is restricted, will be copied into the AssemblyName object so...
383 if (SecurityManager.SecurityEnabled) {
384 GetCodeBase (true); // this will ensure the Demand is made
386 return UnprotectedGetName ();
389 public virtual AssemblyName GetName ()
391 return GetName (false);
394 // the security runtime requires access to the assemblyname (e.g. to get the strongname)
395 internal virtual AssemblyName UnprotectedGetName ()
397 AssemblyName aname = new AssemblyName ();
398 FillName (this, aname);
402 public override string ToString ()
404 // note: ToString work without requiring CodeBase (so no checks are needed)
406 if (assemblyName != null)
409 assemblyName = get_fullname ();
413 public static String CreateQualifiedName (String assemblyName, String typeName)
415 return typeName + ", " + assemblyName;
418 public static Assembly GetAssembly (Type type)
421 return type.Assembly;
422 throw new ArgumentNullException ("type");
426 [MethodImplAttribute (MethodImplOptions.InternalCall)]
427 public static extern Assembly GetEntryAssembly();
429 public Assembly GetSatelliteAssembly (CultureInfo culture)
431 return GetSatelliteAssembly (culture, null, true);
434 public Assembly GetSatelliteAssembly (CultureInfo culture, Version version)
436 return GetSatelliteAssembly (culture, version, true);
439 internal Assembly GetSatelliteAssemblyNoThrow (CultureInfo culture, Version version)
441 return GetSatelliteAssembly (culture, version, false);
444 private Assembly GetSatelliteAssembly (CultureInfo culture, Version version, bool throwOnError)
447 throw new ArgumentException ("culture");
449 AssemblyName aname = GetName (true);
451 aname.Version = version;
453 aname.CultureInfo = culture;
454 aname.Name = aname.Name + ".resources";
455 Assembly assembly = AppDomain.CurrentDomain.LoadSatellite (aname);
456 if (assembly != null)
459 // Try the assembly directory
460 string location = Path.GetDirectoryName (Location);
461 string fullName = Path.Combine (location, Path.Combine (culture.Name, aname.Name + ".dll"));
462 #if NET_2_1 && !MONOTOUCH
463 // it's unlikely that culture.Name or aname.Name could contain stuff like ".." but...
464 fullName = Path.GetFullPath (fullName);
465 if (!fullName.StartsWith (location)) {
467 throw new SecurityException ("non-rooted access to satellite assembly");
471 if (!throwOnError && !File.Exists (fullName))
474 return LoadFrom (fullName);
477 [MethodImplAttribute (MethodImplOptions.InternalCall)]
478 private extern static Assembly LoadFrom (String assemblyFile, bool refonly);
480 public static Assembly LoadFrom (String assemblyFile)
482 return LoadFrom (assemblyFile, false);
485 public static Assembly LoadFrom (String assemblyFile, Evidence securityEvidence)
487 Assembly a = LoadFrom (assemblyFile, false);
489 if ((a != null) && (securityEvidence != null)) {
490 // merge evidence (i.e. replace defaults with provided evidences)
491 a.Evidence.Merge (securityEvidence);
497 [MonoTODO("This overload is not currently implemented")]
498 // FIXME: What are we missing?
499 public static Assembly LoadFrom (String assemblyFile, Evidence securityEvidence, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
501 if (assemblyFile == null)
502 throw new ArgumentNullException ("assemblyFile");
503 if (assemblyFile == String.Empty)
504 throw new ArgumentException ("Name can't be the empty string", "assemblyFile");
505 throw new NotImplementedException ();
508 public static Assembly LoadFile (String path, Evidence securityEvidence)
511 throw new ArgumentNullException ("path");
512 if (path == String.Empty)
513 throw new ArgumentException ("Path can't be empty", "path");
514 // FIXME: Make this do the right thing
515 return LoadFrom (path, securityEvidence);
518 public static Assembly LoadFile (String path)
520 return LoadFile (path, null);
523 public static Assembly Load (String assemblyString)
525 return AppDomain.CurrentDomain.Load (assemblyString);
528 public static Assembly Load (String assemblyString, Evidence assemblySecurity)
530 return AppDomain.CurrentDomain.Load (assemblyString, assemblySecurity);
533 public static Assembly Load (AssemblyName assemblyRef)
535 return AppDomain.CurrentDomain.Load (assemblyRef);
538 public static Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
540 return AppDomain.CurrentDomain.Load (assemblyRef, assemblySecurity);
543 public static Assembly Load (Byte[] rawAssembly)
545 return AppDomain.CurrentDomain.Load (rawAssembly);
548 public static Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore)
550 return AppDomain.CurrentDomain.Load (rawAssembly, rawSymbolStore);
553 public static Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore,
554 Evidence securityEvidence)
556 return AppDomain.CurrentDomain.Load (rawAssembly, rawSymbolStore, securityEvidence);
559 public static Assembly ReflectionOnlyLoad (byte[] rawAssembly)
561 return AppDomain.CurrentDomain.Load (rawAssembly, null, null, true);
564 public static Assembly ReflectionOnlyLoad (string assemblyString)
566 return AppDomain.CurrentDomain.Load (assemblyString, null, true);
569 public static Assembly ReflectionOnlyLoadFrom (string assemblyFile)
571 if (assemblyFile == null)
572 throw new ArgumentNullException ("assemblyFile");
574 return LoadFrom (assemblyFile, true);
577 public static Assembly LoadWithPartialName (string partialName)
579 return LoadWithPartialName (partialName, null);
582 [MonoTODO ("Not implemented")]
583 public Module LoadModule (string moduleName, byte [] rawModule)
585 throw new NotImplementedException ();
588 [MonoTODO ("Not implemented")]
589 public Module LoadModule (string moduleName, byte [] rawModule, byte [] rawSymbolStore)
591 throw new NotImplementedException ();
594 [MethodImplAttribute (MethodImplOptions.InternalCall)]
595 private static extern Assembly load_with_partial_name (string name, Evidence e);
597 public static Assembly LoadWithPartialName (string partialName, Evidence securityEvidence)
599 return LoadWithPartialName (partialName, securityEvidence, true);
603 * LAMESPEC: It is possible for this method to throw exceptions IF the name supplied
604 * is a valid gac name and contains filesystem entry charachters at the end of the name
605 * ie System/// will throw an exception. However ////System will not as that is canocolized
609 // FIXME: LoadWithPartialName must look cache (no CAS) or read from disk (CAS)
610 internal static Assembly LoadWithPartialName (string partialName, Evidence securityEvidence, bool oldBehavior)
613 throw new NotImplementedException ();
615 if (partialName == null)
616 throw new NullReferenceException ();
618 return load_with_partial_name (partialName, securityEvidence);
621 public Object CreateInstance (String typeName)
623 return CreateInstance (typeName, false);
626 public Object CreateInstance (String typeName, Boolean ignoreCase)
628 Type t = GetType (typeName, false, ignoreCase);
633 return Activator.CreateInstance (t);
634 } catch (InvalidOperationException) {
635 throw new ArgumentException ("It is illegal to invoke a method on a Type loaded via ReflectionOnly methods.");
639 public Object CreateInstance (String typeName, Boolean ignoreCase,
640 BindingFlags bindingAttr, Binder binder,
641 Object[] args, CultureInfo culture,
642 Object[] activationAttributes)
644 Type t = GetType (typeName, false, ignoreCase);
649 return Activator.CreateInstance (t, bindingAttr, binder, args, culture, activationAttributes);
650 } catch (InvalidOperationException) {
651 throw new ArgumentException ("It is illegal to invoke a method on a Type loaded via ReflectionOnly methods.");
655 public Module[] GetLoadedModules ()
657 return GetLoadedModules (false);
660 // FIXME: Currently, the two sets of modules are equal
661 public Module[] GetLoadedModules (bool getResourceModules)
663 return GetModules (getResourceModules);
666 public Module[] GetModules ()
668 return GetModules (false);
671 public Module GetModule (String name)
674 throw new ArgumentNullException ("name");
675 if (name.Length == 0)
676 throw new ArgumentException ("Name can't be empty");
678 Module[] modules = GetModules (true);
679 foreach (Module module in modules) {
680 if (module.ScopeName == name)
687 [MethodImplAttribute (MethodImplOptions.InternalCall)]
688 internal virtual extern Module[] GetModulesInternal ();
690 public Module[] GetModules (bool getResourceModules) {
691 Module[] modules = GetModulesInternal ();
693 if (!getResourceModules) {
694 ArrayList result = new ArrayList (modules.Length);
695 foreach (Module m in modules)
696 if (!m.IsResource ())
698 return (Module[])result.ToArray (typeof (Module));
704 [MethodImplAttribute (MethodImplOptions.InternalCall)]
705 internal extern string[] GetNamespaces ();
707 [MethodImplAttribute (MethodImplOptions.InternalCall)]
708 public extern virtual String[] GetManifestResourceNames ();
710 [MethodImplAttribute (MethodImplOptions.InternalCall)]
711 public extern static Assembly GetExecutingAssembly ();
713 [MethodImplAttribute (MethodImplOptions.InternalCall)]
714 public extern static Assembly GetCallingAssembly ();
716 [MethodImplAttribute (MethodImplOptions.InternalCall)]
717 public extern AssemblyName[] GetReferencedAssemblies ();
719 [MethodImplAttribute (MethodImplOptions.InternalCall)]
720 private extern bool GetManifestResourceInfoInternal (String name, ManifestResourceInfo info);
722 public virtual ManifestResourceInfo GetManifestResourceInfo (String resourceName)
724 if (resourceName == null)
725 throw new ArgumentNullException ("resourceName");
726 if (resourceName.Length == 0)
727 throw new ArgumentException ("String cannot have zero length.");
728 ManifestResourceInfo result = new ManifestResourceInfo ();
729 bool found = GetManifestResourceInfoInternal (resourceName, result);
736 private class ResourceCloseHandler {
737 #pragma warning disable 169, 414
739 #pragma warning restore 169, 414
741 public ResourceCloseHandler (Module module) {
742 this.module = module;
745 public void OnClose (object sender, EventArgs e) {
746 // The module dtor will take care of things
752 // The following functions are only for the Mono Debugger.
755 [MethodImplAttribute (MethodImplOptions.InternalCall)]
756 internal static extern int MonoDebugger_GetMethodToken (MethodBase method);
758 [MonoTODO ("Currently it always returns zero")]
760 public long HostContext {
765 public Module ManifestModule {
767 return GetManifestModule ();
771 internal virtual Module GetManifestModule () {
772 return GetManifestModuleInternal ();
775 [MethodImplAttribute (MethodImplOptions.InternalCall)]
776 internal extern Module GetManifestModuleInternal ();
779 public virtual extern bool ReflectionOnly {
780 [MethodImplAttribute (MethodImplOptions.InternalCall)]
784 #if !NET_2_1 || MONOTOUCH
785 // Code Access Security
787 internal void Resolve ()
790 // FIXME: As we (currently) delay the resolution until the first CAS
791 // Demand it's too late to evaluate the Minimum permission set as a
792 // condition to load the assembly into the AppDomain
793 LoadAssemblyPermissions ();
794 Evidence e = new Evidence (UnprotectedGetEvidence ()); // we need a copy to add PRE
795 e.AddHost (new PermissionRequestEvidence (_minimum, _optional, _refuse));
796 _granted = SecurityManager.ResolvePolicy (e,
797 _minimum, _optional, _refuse, out _denied);
801 internal PermissionSet GrantedPermissionSet {
803 if (_granted == null) {
804 if (SecurityManager.ResolvingPolicyLevel != null) {
805 if (SecurityManager.ResolvingPolicyLevel.IsFullTrustAssembly (this))
806 return DefaultPolicies.FullTrust;
808 return null; // we can't resolve during resolution
816 internal PermissionSet DeniedPermissionSet {
818 // yes we look for granted, as denied may be null
819 if (_granted == null) {
820 if (SecurityManager.ResolvingPolicyLevel != null) {
821 if (SecurityManager.ResolvingPolicyLevel.IsFullTrustAssembly (this))
824 return DefaultPolicies.FullTrust; // deny unrestricted
832 [MethodImplAttribute (MethodImplOptions.InternalCall)]
833 extern internal static bool LoadPermissions (Assembly a,
834 ref IntPtr minimum, ref int minLength,
835 ref IntPtr optional, ref int optLength,
836 ref IntPtr refused, ref int refLength);
838 // Support for SecurityAction.RequestMinimum, RequestOptional and RequestRefuse
839 private void LoadAssemblyPermissions ()
841 IntPtr minimum = IntPtr.Zero, optional = IntPtr.Zero, refused = IntPtr.Zero;
842 int minLength = 0, optLength = 0, refLength = 0;
843 if (LoadPermissions (this, ref minimum, ref minLength, ref optional,
844 ref optLength, ref refused, ref refLength)) {
846 // Note: no need to cache these permission sets as they will only be created once
847 // at assembly resolution time.
849 byte[] data = new byte [minLength];
850 Marshal.Copy (minimum, data, 0, minLength);
851 _minimum = SecurityManager.Decode (data);
854 byte[] data = new byte [optLength];
855 Marshal.Copy (optional, data, 0, optLength);
856 _optional = SecurityManager.Decode (data);
859 byte[] data = new byte [refLength];
860 Marshal.Copy (refused, data, 0, refLength);
861 _refuse = SecurityManager.Decode (data);