Skip to content

Commit

Permalink
Read short import files
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisDenton committed Jun 24, 2023
1 parent 60c9721 commit 5ef8f36
Show file tree
Hide file tree
Showing 4 changed files with 182 additions and 2 deletions.
31 changes: 29 additions & 2 deletions crates/examples/src/objdump.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use object::read::archive::ArchiveFile;
use object::read::coff;
use object::read::macho::{DyldCache, FatArch, FatHeader};
use object::{Endianness, Object, ObjectComdat, ObjectSection, ObjectSymbol};
use object::{Endianness, FileKind, Object, ObjectComdat, ObjectSection, ObjectSymbol};
use std::io::{Result, Write};

pub fn print<W: Write, E: Write>(
Expand All @@ -21,7 +22,11 @@ pub fn print<W: Write, E: Write>(
writeln!(w)?;
writeln!(w, "{}:", String::from_utf8_lossy(member.name()))?;
if let Ok(data) = member.data(file) {
dump_object(w, e, data)?;
if FileKind::parse(data) == Ok(FileKind::CoffImportFile) {
dump_import(w, e, data)?;
} else {
dump_object(w, e, data)?;
}
}
}
}
Expand Down Expand Up @@ -245,3 +250,25 @@ fn dump_parsed_object<W: Write, E: Write>(w: &mut W, e: &mut E, file: &object::F

Ok(())
}

fn dump_import<W: Write, E: Write>(w: &mut W, e: &mut E, data: &[u8]) -> Result<()> {
let file = match coff::CoffImportFile::parse(data) {
Ok(import) => import,
Err(err) => {
writeln!(e, "Failed to parse short import: {}", err)?;
return Ok(());
}
};

writeln!(w, "Format: Short Import File")?;
writeln!(w, "Architecture: {:?}", file.architecture())?;
writeln!(w, "DLL: {:?}", String::from_utf8_lossy(file.dll()))?;
writeln!(w, "Symbol: {:?}", String::from_utf8_lossy(file.symbol()))?;
write!(w, "Import: ")?;
match file.import() {
coff::ImportName::Ordinal(n) => writeln!(w, "Ordinal({})", n)?,
coff::ImportName::Name(name) => writeln!(w, "Name({:?})", String::from_utf8_lossy(name))?,
}
writeln!(w, "Type: {:?}", file.import_type())?;
Ok(())
}
145 changes: 145 additions & 0 deletions src/read/coff/import.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
//! Support for reading short import files.
//!
//! These are used by some Windows linkers as a more compact way to describe
//! dynamically imported symbols.
use crate::read::{Architecture, Error, ReadError, ReadRef, Result};
use crate::{pe, ByteString, Bytes, LittleEndian as LE};

/// A Windows short form description of a symbol to import.
/// Used in Windows import libraries. This is not an object file.
#[derive(Debug, Clone)]
pub struct CoffImportFile<'data> {
header: &'data pe::ImportObjectHeader,
dll: ByteString<'data>,
symbol: ByteString<'data>,
kind: ImportType,
import: Option<ByteString<'data>>,
}
impl<'data> CoffImportFile<'data> {
/// Parse it.
pub fn parse<R: ReadRef<'data>>(data: R) -> Result<Self> {
let mut offset = 0;
let header = pe::ImportObjectHeader::parse(data, &mut offset)?;
let data_size = header.size_of_data.get(LE);
let mut strings = Bytes(
data.read_bytes(&mut offset, data_size as u64)
.read_error("Invalid COFF import library data size")?,
);
let symbol = strings
.read_string()
.read_error("Could not read COFF import library symbol name")?;
let dll = strings
.read_string()
.read_error("Could not read COFF import library DLL name")?;

// Unmangles a name by removing a `?`, `@` or `_` prefix.
fn strip_prefix(s: &[u8]) -> &[u8] {
match s.split_first() {
Some((b, rest)) if [b'?', b'@', b'_'].contains(b) => rest,
_ => s,
}
}
Ok(Self {
header,
dll: ByteString(dll),
symbol: ByteString(symbol),
kind: match header.name_type.get(LE) & 0b11 {
pe::IMPORT_OBJECT_CODE => ImportType::Code,
pe::IMPORT_OBJECT_DATA => ImportType::Data,
pe::IMPORT_OBJECT_CONST => ImportType::Const,
0b11 => return Err(Error("Invalid COFF import library import type")),
_ => unreachable!("COFF import library ImportType must be a two bit number"),
},
import: match (header.name_type.get(LE) >> 2) & 0b111 {
pe::IMPORT_OBJECT_ORDINAL => None,
pe::IMPORT_OBJECT_NAME => Some(symbol),
pe::IMPORT_OBJECT_NAME_NO_PREFIX => Some(strip_prefix(symbol)),
pe::IMPORT_OBJECT_NAME_UNDECORATE => {
Some(strip_prefix(symbol).split(|&b| b == b'@').next().unwrap())
}
pe::IMPORT_OBJECT_NAME_EXPORTAS => Some(
strings
.read_string()
.read_error("Could not read COFF import library export name")?,
),
5..=7 => return Err(Error("Unknown COFF import library name type")),
_ => unreachable!("COFF import library name type must be a three bit number"),
}
.map(ByteString),
})
}

/// Get the machine type.
pub fn architecture(&self) -> Architecture {
match self.header.machine.get(LE) {
pe::IMAGE_FILE_MACHINE_ARMNT => Architecture::Arm,
pe::IMAGE_FILE_MACHINE_ARM64 => Architecture::Aarch64,
pe::IMAGE_FILE_MACHINE_I386 => Architecture::I386,
pe::IMAGE_FILE_MACHINE_AMD64 => Architecture::X86_64,
_ => Architecture::Unknown,
}
}

/// The name of the DLL to import the symbol from.
pub fn dll(&self) -> &'data [u8] {
self.dll.0
}

/// The name exported from the DLL.
pub fn import(&self) -> ImportName<'data> {
match self.import {
Some(name) => ImportName::Name(name.0),
None => ImportName::Ordinal(self.header.ordinal_or_hint.get(LE)),
}
}

/// The type of import. Usually either a function or data.
pub fn import_type(&self) -> ImportType {
self.kind
}

/// The public symbol name
pub fn symbol(&self) -> &'data [u8] {
self.symbol.0
}
}

/// The name or ordinal to import.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImportName<'data> {
/// Import by ordinal. Ordinarily this is a 1-based index.
Ordinal(u16),
/// Import by name.
Name(&'data [u8]),
}

/// The kind of import.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ImportType {
/// Executable code
Code,
/// Some data
Data,
/// A constant value.
Const,
}

impl pe::ImportObjectHeader {
/// Read the short import header.
///
/// Also checks that the signature and version are valid.
/// Directly following this header will be the string data.
pub fn parse<'data, R: ReadRef<'data>>(data: R, offset: &mut u64) -> Result<&'data Self> {
let header = data
.read::<crate::pe::ImportObjectHeader>(offset)
.read_error("Invalid COFF import library header size")?;
if header.sig1.get(LE) != 0 || header.sig2.get(LE) != pe::IMPORT_OBJECT_HDR_SIG2 {
Err(Error("Invalid COFF import library header"))
} else if header.version.get(LE) != 0 {
Err(Error("Unknown COFF import library header version"))
} else {
Ok(header)
}
}
}
3 changes: 3 additions & 0 deletions src/read/coff/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@ pub use relocation::*;

mod comdat;
pub use comdat::*;

mod import;
pub use import::*;
5 changes: 5 additions & 0 deletions src/read/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,9 @@ pub enum FileKind {
/// This supports a larger number of sections.
#[cfg(feature = "coff")]
CoffBig,
/// A Windows short import file.
#[cfg(feature = "coff")]
CoffImportFile,
/// A dyld cache file containing Mach-O images.
#[cfg(feature = "macho")]
DyldCache,
Expand Down Expand Up @@ -263,6 +266,8 @@ impl FileKind {
[0x01, 0xDF, ..] => FileKind::Xcoff32,
#[cfg(feature = "xcoff")]
[0x01, 0xF7, ..] => FileKind::Xcoff64,
#[cfg(feature = "coff")]
[0, 0, 0xFF, 0xFF, ..] => FileKind::CoffImportFile,
_ => return Err(Error("Unknown file magic")),
};
Ok(kind)
Expand Down

0 comments on commit 5ef8f36

Please sign in to comment.