hao 0.0.19

Read, edit, create and write .net assemblies
Documentation
use crate::error::{HaoError, Result};
use crate::io::DataReader;

use pewter::pe::optional_header::OptionalHeader;
use pewter::pe::sections::cor20::ImageCor20Header;
use pewter::pe::sections::SectionRow;
use pewter::PEFile;

/// A parsed PE file, with helpers for finding the .NET (CLI) header and reading
/// data at relative virtual addresses. [`Module`](crate::Module) loads through it.
pub struct PEImage<'a> {
    /// The underlying pewter PE file.
    pub pe: PEFile<'a>,
}

impl<'a> PEImage<'a> {
    /// Parses `data` as a PE image; fails with [`BadPeFormat`](HaoError::BadPeFormat).
    pub fn load_bytes(data: &'a [u8]) -> Result<Self> {
        let pe = PEFile::parse(data).map_err(|_| HaoError::BadPeFormat)?;

        Ok(Self { pe })
    }

    /// Wraps an already-parsed [`PEFile`], avoiding a re-parse.
    pub fn from_pe(pe: PEFile<'a>) -> Self {
        Self { pe }
    }

    /// The optional header (entry point, image base, data directories); every
    /// executable image has one.
    pub fn optional_header(&self) -> Result<&OptionalHeader> {
        self.pe
            .optional_header
            .as_ref()
            .ok_or(HaoError::BadPeFormat)
    }

    /// The section containing `rva`, if any.
    pub fn rva_to_section(&self, rva: u32) -> Option<&SectionRow<'_>> {
        self.pe.sections.find_rva(rva as usize)
    }

    /// Not implemented: always panics.
    pub fn rva_to_file_offset_(&self, _rva: u32) -> Result<usize> {
        todo!()
    }

    /// A reader over the section data starting at `rva`, cut to `size` bytes if
    /// given (otherwise up to the end of the section).
    ///
    /// Fails with [`BadRva`](HaoError::BadRva) if no section contains `rva`.
    pub fn create_reader(&self, rva: u32, size: Option<usize>) -> Result<DataReader<'a>> {
        let data = self
            .pe
            .sections
            .find_rva_data(rva as usize)
            .ok_or(HaoError::BadRva(rva))?;

        let data = if let Some(size) = size {
            &data[..size]
        } else {
            data
        };

        Ok(DataReader::new(data))
    }

    /// Reads the CLI (COR20) header, which locates the metadata, resources and
    /// strong-name signature. Fails with [`NotDotNetBinary`](HaoError::NotDotNetBinary)
    /// for a native image.
    pub fn read_clr_rt_header(&self) -> Result<ImageCor20Header> {
        let clr = self
            .pe
            .read_clr_runtime_header()
            .map_err(|_| HaoError::BadImageFormat("Failed to read image cor20 header"))?;

        let header = clr.ok_or(HaoError::NotDotNetBinary)?;

        Ok(header)
    }
}