hao 0.0.19

Read, edit, create and write .net assemblies
Documentation
use super::{CustomAttribute, DeclSecurity, Entry, EntryName};
use crate::{
    dotnet::md::streams::tables_stream::{
        AssemblyFlags, FileFlags, ManifestResourceFlags, TypeAttributes,
    },
    sync::Shared,
    Module,
};

/// The module's own identity (the single `Module` table row, II.22.30).
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct ModuleDef {
    /// Reserved; always 0.
    pub generation: u16,
    /// File name of the module, e.g. `Example.dll`.
    pub name: String,
    /// Module version ID: a GUID the compiler makes fresh for each build.
    pub mvid: uuid::Uuid,
    /// Edit-and-Continue generation ID; usually nil.
    pub enc_id: uuid::Uuid,
    /// Edit-and-Continue base generation ID; usually nil.
    pub enc_base_id: uuid::Uuid,
    /// Attributes applied to the module (`[module: ...]`).
    pub custom_attributes: Vec<CustomAttribute>,
}

impl EntryName for ModuleDef {
    fn entry_name(&self) -> String {
        self.name.clone()
    }
}

/// A four part assembly version, `major.minor.build.revision`. Displays as `1.2.3.4`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct Version {
    /// First component.
    pub major: u16,
    /// Second component.
    pub minor: u16,
    /// Third component.
    pub build: u16,
    /// Fourth component.
    pub revision: u16,
}

impl std::fmt::Display for Version {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}.{}.{}.{}",
            self.major, self.minor, self.build, self.revision
        )
    }
}

/// The assembly manifest of the current module.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct Assembly {
    /// Hash algorithm used for the assembly's files, e.g. `0x8004` for SHA-1.
    pub hash_alg_id: u32,
    /// The assembly version.
    pub version: Version,
    /// Whether `public_key` is set, retargetability, processor architecture, ...
    pub flags: AssemblyFlags,
    /// Full public key for a strong-named assembly; empty if unsigned.
    pub public_key: Vec<u8>,
    /// Simple name, without the extension, e.g. `System.Runtime`.
    pub name: String,
    /// Culture for a satellite assembly, e.g. `en-US`; empty for neutral.
    pub culture: String,
    /// Assembly-level declarative security (permission requests).
    pub security: Vec<DeclSecurity>,
    /// Attributes applied to the assembly (`[assembly: ...]`).
    pub custom_attributes: Vec<CustomAttribute>,
}

impl EntryName for Assembly {
    fn entry_name(&self) -> String {
        self.name.clone()
    }
}

/// A reference to another assembly this module uses (II.22.5).
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct AssemblyRef {
    /// The version referenced.
    pub version: Version,
    /// Notably `PublicKey`: set when `public_key_or_token` is a full key rather than a token.
    pub flags: AssemblyFlags,
    /// The referenced assembly's public key, or (usually) its 8 byte token; empty if unsigned.
    pub public_key_or_token: Vec<u8>,
    /// Simple name, e.g. `System.Runtime`.
    pub name: String,
    /// Culture, empty for neutral.
    pub culture: String,
    /// Hash of the referenced assembly; usually empty.
    pub hash_value: Vec<u8>,
    /// Attributes applied to this reference.
    pub custom_attributes: Vec<CustomAttribute>,
    /// Set by [`Module::load_dependencies`].
    pub resolved: Option<Shared<Module>>,
}

impl AssemblyRef {
    const KNOWN_CORLIB_NAMES: &'static [&'static str] = &[
        "System.Private.CoreLib",
        "netstandard",
        "mscorlib",
        "corefx",
        "System.Runtime",
    ];

    /// Whether this references the core library (`System.Private.CoreLib`,
    /// `mscorlib`, `netstandard`, `System.Runtime`, ...), where `System.Object` lives.
    pub fn is_corlib(&self) -> bool {
        Self::KNOWN_CORLIB_NAMES
            .iter()
            .any(|s| self.name.eq_ignore_ascii_case(s))
    }
}

impl EntryName for AssemblyRef {
    fn entry_name(&self) -> String {
        self.name.clone()
    }
}

/// Another file of a multi-file assembly (II.22.19): a netmodule or a resource file.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct File {
    /// Whether the file contains metadata (a module) or not (e.g. a resource).
    pub flags: FileFlags,
    /// File name, relative to the assembly.
    pub name: String,
    /// Hash of the file's contents.
    pub hash_value: Vec<u8>,
    /// Attributes applied to this file entry.
    pub custom_attributes: Vec<CustomAttribute>,
}

impl EntryName for File {
    fn entry_name(&self) -> String {
        self.name.clone()
    }
}

/// Where an exported type or linked resource actually lives.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum Implementation {
    /// In another file of this assembly.
    File(Entry<File>),
    /// In another assembly (a type forwarder).
    AssemblyRef(Entry<AssemblyRef>),
    /// Nested in another exported type.
    ExportedType(Entry<ExportedType>),
}

/// A type exported (or forwarded) by this assembly.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct ExportedType {
    /// The exported type's visibility and other type flags.
    pub flags: TypeAttributes,
    /// Hint: the type's `TypeDef` row in the module that defines it; 0 for forwarders.
    pub type_def_id: u32,
    /// Type name.
    pub name: String,
    /// Namespace; empty for nested types.
    pub namespace: String,
    /// Where the type is defined.
    pub implementation: Option<Implementation>,
    /// Attributes applied to the exported type.
    pub custom_attributes: Vec<CustomAttribute>,
}

impl EntryName for ExportedType {
    fn entry_name(&self) -> String {
        format!("{}.{}", self.namespace, self.name)
    }
}

/// Where a [`ManifestResource`]'s bytes are.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum ResourceData {
    /// Stored in this module's image.
    Embedded(Vec<u8>),
    /// Stored in another file or assembly.
    Linked {
        /// The file or assembly holding the data.
        implementation: Implementation,
        /// Byte offset of the data within that file.
        offset: u32,
    },
}

impl Default for ResourceData {
    fn default() -> Self {
        Self::Embedded(Vec::new())
    }
}

/// A resource of the assembly (II.22.24), e.g. a `.resources` file.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct ManifestResource {
    /// Visibility: public or private to the assembly.
    pub flags: ManifestResourceFlags,
    /// Resource name, e.g. `Example.Properties.Resources.resources`.
    pub name: String,
    /// The bytes, or where to find them.
    pub data: ResourceData,
    /// Attributes applied to the resource.
    pub custom_attributes: Vec<CustomAttribute>,
}

impl EntryName for ManifestResource {
    fn entry_name(&self) -> String {
        self.name.clone()
    }
}