Skip to content

XP event5x XPListening, games, ratings, comments and chat earn five times the XP

leftLeaderboard

pe.rs

246 lines10.1 KBRust
//! What a Windows module is, read from its file: the machine it was built for and the names it exports. Reading a//! file's bytes runs none of its code, so it opens no licence window: this is how the scan tells, without loading//! anything, that a `.dll` is an old-format plugin (it exports `VSTPluginMain` or `main`) or that a module is 32-bit//! and can't run in this 64-bit app. Only the headers and the export table are read, never the whole file.use std::fs::File;use std::io::{Read, Seek, SeekFrom};use std::path::Path;/// IMAGE_FILE_MACHINE_AMD64: the only kind of module this app's 64-bit host can load.pub const X64: u16 = 0x8664;/// IMAGE_FILE_MACHINE_I386: 32-bit.pub const X86: u16 = 0x014C;pub const ARM64: u16 = 0xAA64;pub const ARM: u16 = 0x01C4;/// No export table bigger than this is read (real ones are a few kilobytes; the cap keeps a broken file cheap).const MAX_EXPORT_BYTES: u32 = 4 << 20;/// Nor more names than this.const MAX_NAMES: u32 = 65536;#[derive(Debug, Clone, PartialEq, Default)]pub struct Info {    pub machine: u16,    /// The exported function names (by name; exports by number alone have none).    pub exports: Vec<String>,}impl Info {    pub fn exports_any(&self, names: &[&str]) -> bool {        self.exports.iter().any(|e| names.contains(&e.as_str()))    }}/// The entry points an old-format (VST 2) plugin exports: `VSTPluginMain`, or `main` in plugins from before it.pub const VST2_ENTRIES: &[&str] = &["VSTPluginMain", "main"];/// A VST 3 module's one entry point (the tests check the compiler put it there).#[allow(dead_code)]pub const VST3_ENTRY: &str = "GetPluginFactory";/// Little-endian reads from a slice, None past its end.fn u16_at(b: &[u8], at: usize) -> Option<u16> {    b.get(at..at + 2).map(|s| u16::from_le_bytes([s[0], s[1]]))}fn u32_at(b: &[u8], at: usize) -> Option<u32> {    b.get(at..at + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]))}fn bad(what: &str) -> std::io::Error {    std::io::Error::new(std::io::ErrorKind::InvalidData, format!("not a Windows module ({what})"))}fn read_at(f: &mut File, offset: u64, len: usize) -> std::io::Result<Vec<u8>> {    f.seek(SeekFrom::Start(offset))?;    let mut buf = vec![0u8; len];    let mut got = 0;    while got < len {        match f.read(&mut buf[got..])? {            0 => break,            n => got += n,        }    }    buf.truncate(got);    Ok(buf)}struct Section {    va: u32,    size: u32,    raw: u32,    raw_size: u32,}/// The file offset of a relative virtual address, through the section that holds it.fn offset_of(sections: &[Section], rva: u32) -> Option<u64> {    sections.iter().find_map(|s| {        let span = s.size.max(s.raw_size);        (rva >= s.va && rva - s.va < span && rva - s.va < s.raw_size).then(|| s.raw as u64 + (rva - s.va) as u64)    })}/// Reads the module at `path`: its machine and its exported names.pub fn read(path: &Path) -> std::io::Result<Info> {    let mut f = File::open(path)?;    let dos = read_at(&mut f, 0, 64)?;    if dos.get(0..2) != Some(b"MZ") {        return Err(bad("no MZ header"));    }    let pe = u32_at(&dos, 0x3C).ok_or_else(|| bad("short header"))? as u64;    if pe > 1 << 20 {        return Err(bad("header out of place"));    }    // The signature, the COFF header (20 bytes) and room for the largest optional header and many sections.    let head = read_at(&mut f, pe, 24 + 240 + 40 * 96)?;    if head.get(0..4) != Some(b"PE\0\0") {        return Err(bad("no PE signature"));    }    let machine = u16_at(&head, 4).ok_or_else(|| bad("short COFF header"))?;    let sections_n = u16_at(&head, 6).ok_or_else(|| bad("short COFF header"))? as usize;    let opt_size = u16_at(&head, 20).ok_or_else(|| bad("short COFF header"))? as usize;    let opt = 24;    let magic = u16_at(&head, opt).ok_or_else(|| bad("no optional header"))?;    // The data directories start 96 bytes in for PE32 (32-bit), 112 for PE32+ (64-bit); the export table is the first.    let (count_at, dirs_at) = match magic {        0x10B => (opt + 92, opt + 96),        0x20B => (opt + 108, opt + 112),        _ => return Err(bad("unknown optional header")),    };    let mut info = Info { machine, exports: Vec::new() };    let dirs = u32_at(&head, count_at).unwrap_or(0);    if dirs == 0 || opt_size < dirs_at - opt + 8 {        return Ok(info);    }    let (export_rva, export_size) = match (u32_at(&head, dirs_at), u32_at(&head, dirs_at + 4)) {        (Some(r), Some(s)) if r != 0 && s >= 40 => (r, s.min(MAX_EXPORT_BYTES)),        _ => return Ok(info),    };    let table = opt + opt_size;    let mut sections = Vec::new();    for i in 0..sections_n.min(96) {        let s = table + i * 40;        let (Some(size), Some(va), Some(raw_size), Some(raw)) = (u32_at(&head, s + 8), u32_at(&head, s + 12), u32_at(&head, s + 16), u32_at(&head, s + 20)) else {            break;        };        sections.push(Section { va, size, raw, raw_size });    }    let Some(at) = offset_of(&sections, export_rva) else { return Ok(info) };    // The directory, its name table and (usually) the names themselves are all inside the export data directory.    let region = read_at(&mut f, at, export_size as usize)?;    let in_region = |rva: u32| -> Option<usize> { rva.checked_sub(export_rva).map(|d| d as usize).filter(|&d| d < region.len()) };    let names = u32_at(&region, 24).unwrap_or(0).min(MAX_NAMES);    let names_rva = u32_at(&region, 32).unwrap_or(0);    for i in 0..names {        let entry = names_rva.wrapping_add(i * 4);        let name_rva = match in_region(entry).and_then(|d| u32_at(&region, d)) {            Some(r) => r,            None => match offset_of(&sections, entry) {                Some(o) => match read_at(&mut f, o, 4)? {                    b if b.len() == 4 => u32::from_le_bytes([b[0], b[1], b[2], b[3]]),                    _ => break,                },                None => break,            },        };        let bytes = match in_region(name_rva) {            Some(d) => region[d..].iter().take(256).copied().take_while(|&c| c != 0).collect::<Vec<u8>>(),            None => match offset_of(&sections, name_rva) {                Some(o) => read_at(&mut f, o, 256)?.into_iter().take_while(|&c| c != 0).collect(),                None => continue,            },        };        if let Ok(name) = String::from_utf8(bytes) {            info.exports.push(name);        }    }    Ok(info)}/// Just the machine, for a module whose exports don't matter.pub fn machine(path: &Path) -> std::io::Result<u16> {    read(path).map(|i| i.machine)}#[cfg(test)]pub mod tests {    use super::*;    fn tmp(name: &str) -> std::path::PathBuf {        let base = std::env::var_os("JW_TEST_DIR").map(std::path::PathBuf::from).unwrap_or_else(std::env::temp_dir);        let d = base.join(format!("jw-pe-{name}-{}", std::process::id()));        let _ = std::fs::remove_dir_all(&d);        std::fs::create_dir_all(&d).unwrap();        d    }    /// A minimal 64-bit image with one section holding an export table that names `names`, laid out as a linker does.    pub fn image(machine: u16, names: &[&str]) -> Vec<u8> {        let mut b = vec![0u8; 0x400];        b[0..2].copy_from_slice(b"MZ");        b[0x3C..0x40].copy_from_slice(&0x80u32.to_le_bytes());        let pe = 0x80;        b[pe..pe + 4].copy_from_slice(b"PE\0\0");        b[pe + 4..pe + 6].copy_from_slice(&machine.to_le_bytes());        b[pe + 6..pe + 8].copy_from_slice(&1u16.to_le_bytes());        b[pe + 20..pe + 22].copy_from_slice(&240u16.to_le_bytes());        let opt = pe + 24;        b[opt..opt + 2].copy_from_slice(&0x20Bu16.to_le_bytes());        b[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes());        // The section: virtual 0x1000, raw at 0x400.        let sec = opt + 240;        b[sec..sec + 8].copy_from_slice(b".rdata\0\0");        let mut data = vec![0u8; 40];        let names_at = 40u32;        let strings_at = names_at + 4 * names.len() as u32;        let mut strings = Vec::new();        let mut rvas = Vec::new();        for n in names {            rvas.push(0x1000 + strings_at + strings.len() as u32);            strings.extend_from_slice(n.as_bytes());            strings.push(0);        }        data[24..28].copy_from_slice(&(names.len() as u32).to_le_bytes());        data[32..36].copy_from_slice(&(0x1000 + names_at).to_le_bytes());        for r in rvas {            data.extend_from_slice(&r.to_le_bytes());        }        data.extend_from_slice(&strings);        let size = data.len() as u32;        b[opt + 112..opt + 116].copy_from_slice(&0x1000u32.to_le_bytes());        b[opt + 116..opt + 120].copy_from_slice(&size.to_le_bytes());        b[sec + 8..sec + 12].copy_from_slice(&size.to_le_bytes());        b[sec + 12..sec + 16].copy_from_slice(&0x1000u32.to_le_bytes());        b[sec + 16..sec + 20].copy_from_slice(&size.to_le_bytes());        b[sec + 20..sec + 24].copy_from_slice(&0x400u32.to_le_bytes());        b.extend_from_slice(&data);        b    }    #[test]    fn exports_and_machines_are_read_from_the_file() {        let d = tmp("read");        let p = d.join("a.dll");        std::fs::write(&p, image(X64, &["GetPluginFactory", "InitDll"])).unwrap();        let i = read(&p).unwrap();        assert_eq!(i.machine, X64);        assert_eq!(i.exports, ["GetPluginFactory", "InitDll"]);        assert!(i.exports_any(&[VST3_ENTRY]) && !i.exports_any(VST2_ENTRIES));        std::fs::write(&p, image(X86, &["main"])).unwrap();        let i = read(&p).unwrap();        assert_eq!(i.machine, X86);        assert!(i.exports_any(VST2_ENTRIES));        // Not a module, a cut one, nonsense offsets: an error or no exports, never a panic.        std::fs::write(&p, b"not a module").unwrap();        assert!(read(&p).is_err());        let mut cut = image(X64, &["VSTPluginMain"]);        cut.truncate(0x90);        std::fs::write(&p, &cut).unwrap();        assert!(read(&p).is_err());        let mut odd = image(X64, &["VSTPluginMain"]);        odd[0x400 + 32..0x400 + 36].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes());        std::fs::write(&p, &odd).unwrap();        assert!(read(&p).unwrap().exports.is_empty());        let _ = std::fs::remove_dir_all(&d);    }}