blob: a4c11c3c5c1d5b9566a635382a0b4de63609ffda [file]
// Copyright 2026 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
//! Disassembler drivers and parsers for `llvm-objdump` and GNU `objdump`, plus
//! minimal ELF64 synthesis and section extraction.
use std::{
fs::{self, OpenOptions},
io::{ErrorKind, Write},
path::{Path, PathBuf},
process::Command,
sync::atomic::{AtomicU64, Ordering},
time::{SystemTime, UNIX_EPOCH},
};
use crate::{Arch, DisasmInsn, DisasmLeg};
const EM_X86_64: u16 = 62;
const EM_AARCH64: u16 = 183;
const ET_REL: u16 = 1;
const SHT_PROGBITS: u32 = 1;
const SHT_STRTAB: u32 = 3;
const SHF_ALLOC_EXEC: u64 = 0x6;
const MAX_TEMP_CREATE_ATTEMPTS: u32 = 64;
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
/// Build a minimal valid ELF64 relocatable object (`ET_REL`) containing a
/// single executable `.text` section with `text_bytes`.
pub fn build_minimal_elf64(arch: Arch, text_bytes: &[u8]) -> Vec<u8> {
let e_machine = match arch {
Arch::X86_64 => EM_X86_64,
Arch::AArch64 => EM_AARCH64,
};
let shstrtab: &[u8] = b"\0.text\0.shstrtab\0";
let ehdr_size: usize = 64;
let text_off = ehdr_size;
let shstr_off = text_off + text_bytes.len();
let unaligned_shoff = shstr_off + shstrtab.len();
let shoff = (unaligned_shoff + 7) & !7;
let pad_len = shoff - unaligned_shoff;
let mut out = Vec::with_capacity(shoff + 3 * 64);
// ELF64 header (64 bytes).
out.extend_from_slice(b"\x7fELF");
out.push(2); // ELFCLASS64
out.push(1); // ELFDATA2LSB
out.push(1); // EV_CURRENT
out.extend_from_slice(&[0u8; 9]);
out.extend_from_slice(&ET_REL.to_le_bytes());
out.extend_from_slice(&e_machine.to_le_bytes());
out.extend_from_slice(&1u32.to_le_bytes()); // e_version
out.extend_from_slice(&0u64.to_le_bytes()); // e_entry
out.extend_from_slice(&0u64.to_le_bytes()); // e_phoff
out.extend_from_slice(&(shoff as u64).to_le_bytes()); // e_shoff
out.extend_from_slice(&0u32.to_le_bytes()); // e_flags
out.extend_from_slice(&64u16.to_le_bytes()); // e_ehsize
out.extend_from_slice(&0u16.to_le_bytes()); // e_phentsize
out.extend_from_slice(&0u16.to_le_bytes()); // e_phnum
out.extend_from_slice(&64u16.to_le_bytes()); // e_shentsize
out.extend_from_slice(&3u16.to_le_bytes()); // e_shnum
out.extend_from_slice(&2u16.to_le_bytes()); // e_shstrndx
// Section payloads.
out.extend_from_slice(text_bytes);
out.extend_from_slice(shstrtab);
out.resize(out.len() + pad_len, 0);
// Section header 0: SHT_NULL.
out.resize(out.len() + 64, 0);
// Section header 1: `.text` (sh_name = 1).
push_shdr(
&mut out,
1,
SHT_PROGBITS,
SHF_ALLOC_EXEC,
text_off as u64,
text_bytes.len() as u64,
4,
);
// Section header 2: `.shstrtab` (sh_name = 7).
push_shdr(&mut out, 7, SHT_STRTAB, 0, shstr_off as u64, shstrtab.len() as u64, 1);
out
}
fn push_shdr(
out: &mut Vec<u8>,
sh_name: u32,
sh_type: u32,
sh_flags: u64,
sh_offset: u64,
sh_size: u64,
sh_addralign: u64,
) {
out.extend_from_slice(&sh_name.to_le_bytes());
out.extend_from_slice(&sh_type.to_le_bytes());
out.extend_from_slice(&sh_flags.to_le_bytes());
out.extend_from_slice(&0u64.to_le_bytes()); // sh_addr
out.extend_from_slice(&sh_offset.to_le_bytes());
out.extend_from_slice(&sh_size.to_le_bytes());
out.extend_from_slice(&0u32.to_le_bytes()); // sh_link
out.extend_from_slice(&0u32.to_le_bytes()); // sh_info
out.extend_from_slice(&sh_addralign.to_le_bytes());
out.extend_from_slice(&0u64.to_le_bytes()); // sh_entsize
}
fn checked_slice(buf: &[u8], off: usize, len: usize) -> Result<&[u8], String> {
let end =
off.checked_add(len).ok_or_else(|| format!("ELF offset overflow at {off} + {len}"))?;
buf.get(off..end).ok_or_else(|| format!("ELF truncated at offset {off}..{end}"))
}
fn read_u16_le(buf: &[u8], off: usize) -> Result<u16, String> {
let slice = checked_slice(buf, off, 2)?;
Ok(u16::from_le_bytes([slice[0], slice[1]]))
}
fn read_u32_le(buf: &[u8], off: usize) -> Result<u32, String> {
let slice = checked_slice(buf, off, 4)?;
Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
}
fn read_u64_le(buf: &[u8], off: usize) -> Result<u64, String> {
let slice = checked_slice(buf, off, 8)?;
Ok(u64::from_le_bytes([
slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
]))
}
fn u64_to_usize(val: u64, label: &str) -> Result<usize, String> {
usize::try_from(val).map_err(|_| format!("ELF {label} overflows usize: {val}"))
}
fn shdr_offset(e_shoff: usize, idx: usize, e_shentsize: usize) -> Result<usize, String> {
let delta = idx
.checked_mul(e_shentsize)
.ok_or_else(|| "ELF section header index multiplication overflow".to_string())?;
e_shoff.checked_add(delta).ok_or_else(|| "ELF section header offset overflow".to_string())
}
fn read_shdr_field_u64(elf: &[u8], hdr: usize, field_off: usize) -> Result<usize, String> {
let pos = hdr
.checked_add(field_off)
.ok_or_else(|| "ELF section header field offset overflow".to_string())?;
u64_to_usize(read_u64_le(elf, pos)?, "section header field")
}
/// Extract the target architecture and raw bytes of `section_name` (e.g.
/// `".text"`) from an ELF64 little-endian object or executable.
pub fn extract_elf64_section(elf: &[u8], section_name: &str) -> Result<(Arch, Vec<u8>), String> {
if elf.len() < 64 {
return Err("ELF file smaller than 64-byte header".to_string());
}
if &elf[0..4] != b"\x7fELF" {
return Err("invalid ELF magic".to_string());
}
if elf[4] != 2 || elf[5] != 1 {
return Err("only 64-bit little-endian ELF files are supported".to_string());
}
let e_machine = read_u16_le(elf, 18)?;
let arch = match e_machine {
EM_X86_64 => Arch::X86_64,
EM_AARCH64 => Arch::AArch64,
other => return Err(format!("unsupported ELF e_machine: {other}")),
};
let e_shoff = u64_to_usize(read_u64_le(elf, 40)?, "e_shoff")?;
let e_shentsize = usize::from(read_u16_le(elf, 58)?);
let e_shnum = usize::from(read_u16_le(elf, 60)?);
let e_shstrndx = usize::from(read_u16_le(elf, 62)?);
if e_shoff == 0 || e_shentsize < 64 || e_shnum == 0 || e_shstrndx >= e_shnum {
return Err("ELF missing valid section header table".to_string());
}
let shstr_hdr = shdr_offset(e_shoff, e_shstrndx, e_shentsize)?;
let shstr_type_off = shstr_hdr
.checked_add(4)
.ok_or_else(|| "ELF .shstrtab sh_type offset overflow".to_string())?;
if read_u32_le(elf, shstr_type_off)? == 8 {
return Err("ELF .shstrtab is SHT_NOBITS (no file bytes)".to_string());
}
let shstr_off = read_shdr_field_u64(elf, shstr_hdr, 24)?;
let shstr_size = read_shdr_field_u64(elf, shstr_hdr, 32)?;
let shstr = checked_slice(elf, shstr_off, shstr_size)
.map_err(|_| "ELF .shstrtab out of bounds".to_string())?;
for idx in 0..e_shnum {
let hdr = shdr_offset(e_shoff, idx, e_shentsize)?;
let name_off = usize::try_from(read_u32_le(elf, hdr)?)
.map_err(|_| "ELF section name offset overflow".to_string())?;
let Some(tail) = shstr.get(name_off..) else {
continue;
};
let end = tail.iter().position(|&b| b == 0).unwrap_or(tail.len());
let name = std::str::from_utf8(&tail[..end]).unwrap_or("");
if name == section_name {
let sh_type_off = hdr
.checked_add(4)
.ok_or_else(|| "ELF section header sh_type offset overflow".to_string())?;
let sh_type = read_u32_le(elf, sh_type_off)?;
if sh_type == 8 {
return Err(format!("section `{section_name}` is SHT_NOBITS (no file bytes)"));
}
let sec_off = read_shdr_field_u64(elf, hdr, 24)?;
let sec_size = read_shdr_field_u64(elf, hdr, 32)?;
let bytes = checked_slice(elf, sec_off, sec_size)
.map_err(|_| format!("section `{section_name}` out of bounds"))?;
return Ok((arch, bytes.to_vec()));
}
}
Err(format!("section `{section_name}` not found in ELF"))
}
/// Normalize raw hex tokens from `llvm-objdump` or GNU `objdump` into
/// little-endian instruction bytes matching Anneal's decoders.
///
/// On AArch64, both `llvm-objdump` and GNU `objdump` display each 32-bit
/// instruction word as an 8-hex-digit big-endian integer (e.g. `d65f03c0` for
/// `ret`), whereas `Anneal.ElfAArch64.decodeStream` consumes little-endian
/// bytes (`[0xc0, 0x03, 0x5f, 0xd6]`). Space-separated 2-hex-digit bytes are
/// preserved in order on both architectures.
pub fn parse_raw_insn_bytes(arch: Arch, raw_col: &str) -> Result<Vec<u8>, String> {
let mut out = Vec::new();
for tok in raw_col.split_whitespace() {
if !tok.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(format!("non-hex byte token `{tok}`"));
}
match (arch, tok.len()) {
(_, 2) => {
let b = u8::from_str_radix(tok, 16)
.map_err(|e| format!("invalid hex byte `{tok}`: {e}"))?;
out.push(b);
}
(Arch::AArch64, 8) => {
let word = u32::from_str_radix(tok, 16)
.map_err(|e| format!("invalid AArch64 word `{tok}`: {e}"))?;
out.extend_from_slice(&word.to_le_bytes());
}
(Arch::AArch64, 4) => {
let half = u16::from_str_radix(tok, 16)
.map_err(|e| format!("invalid AArch64 halfword `{tok}`: {e}"))?;
out.extend_from_slice(&half.to_le_bytes());
}
_ => {
return Err(format!("unexpected hex token width `{tok}` for {:?}", arch));
}
}
}
if out.is_empty() {
return Err("empty raw instruction bytes column".to_string());
}
Ok(out)
}
/// Parse disassembly lines from `llvm-objdump --disassemble` (raw bytes are
/// emitted by default; never pass `--show-raw-insn` to `llvm-objdump`) or
/// GNU `objdump -d --show-raw-insn`.
pub fn parse_objdump_output(
arch: Arch,
leg: DisasmLeg,
stdout: &str,
) -> Result<Vec<DisasmInsn>, String> {
struct RawDisasmLine {
offset: u64,
bytes: Vec<u8>,
asm_col: String,
}
let mut raw_insns: Vec<RawDisasmLine> = Vec::new();
let mut base_offset: Option<u64> = None;
for raw_line in stdout.lines() {
let trimmed = raw_line.trim_end();
if trimmed.is_empty() {
continue;
}
let Some((addr_part, rest)) = trimmed.split_once(':') else {
continue;
};
let addr_str = addr_part.trim();
// Skip section/file headers and `<symbol>:` lines.
if addr_str.is_empty() || !addr_str.bytes().all(|b| b.is_ascii_hexdigit()) {
continue;
}
let abs_offset = u64::from_str_radix(addr_str, 16)
.map_err(|e| format!("invalid hex offset `{addr_str}`: {e}"))?;
let after_colon = rest.trim_start_matches([' ', '\t']);
if after_colon.is_empty() {
continue;
}
// Split raw hex bytes column from disassembly text column.
let (hex_col, asm_col) = split_hex_and_asm(after_colon);
if hex_col.is_empty() {
continue;
}
let bytes = parse_raw_insn_bytes(arch, hex_col)?;
// GNU `objdump` wraps instructions longer than 7 bytes onto a
// continuation line with an empty disassembly column.
if asm_col.is_empty() {
if let Some(prev) = raw_insns.last_mut() {
prev.bytes.extend_from_slice(&bytes);
continue;
}
return Err(format!(
"orphan continuation line at offset 0x{abs_offset:x} in {:?}",
leg
));
}
let origin = *base_offset.get_or_insert(abs_offset);
let rel_offset = abs_offset.saturating_sub(origin);
raw_insns.push(RawDisasmLine { offset: rel_offset, bytes, asm_col: asm_col.to_string() });
}
// Parse disassembly text only after all continuation lines have appended
// their raw bytes so prefix inspection sees the full instruction encoding.
let insns = raw_insns
.into_iter()
.map(|raw| {
let (mnemonic, operands, locked, is_bad) =
parse_asm_text(arch, &raw.asm_col, &raw.bytes);
DisasmInsn { offset: raw.offset, bytes: raw.bytes, mnemonic, operands, locked, is_bad }
})
.collect();
Ok(insns)
}
fn split_hex_and_asm(s: &str) -> (&str, &str) {
if let Some((left, right)) = s.split_once('\t') {
return (left.trim(), right.trim());
}
// Fallback when tabs are expanded to spaces: consume leading hex tokens
// until the first non-hex token.
let bytes = s.as_bytes();
let mut i = 0;
let mut last_hex_end = 0;
while i < bytes.len() {
while i < bytes.len() && bytes[i] == b' ' {
i += 1;
}
let start = i;
while i < bytes.len() && bytes[i] != b' ' {
i += 1;
}
let tok = &s[start..i];
let is_hex_tok = !tok.is_empty()
&& (tok.len() == 2 || tok.len() == 4 || tok.len() == 8)
&& tok.bytes().all(|b| b.is_ascii_hexdigit());
if is_hex_tok {
last_hex_end = i;
} else {
return (s[..last_hex_end].trim(), s[start..].trim());
}
}
(s[..last_hex_end].trim(), "")
}
fn is_x86_rex_prefix_token(lower: &str) -> bool {
lower == "rex"
|| lower.strip_prefix("rex.").is_some_and(|flags| {
!flags.is_empty() && flags.bytes().all(|b| matches!(b, b'w' | b'r' | b'x' | b'b'))
})
}
fn is_x86_strippable_prefix(lower: &str) -> bool {
matches!(lower, "cs" | "ds" | "es" | "ss" | "fs" | "gs" | "notrack" | "addr32")
|| is_x86_rex_prefix_token(lower)
}
struct X86PrefixInfo {
count_66: usize,
rex_w_overrides_66: bool,
vex_has_ud_prefix: bool,
}
/// True iff the opcode bytes at `tail` belong to a `d32`/`d64` GPR instruction
/// where an active `REX.W` architecturally overrides `0x66` to 64-bit operand
/// size (excluding branches, 8-bit opcodes, indirect `jmp`/`call`, `ret`, and
/// VEX/EVEX).
fn opcode_uses_rex_w_over_66(tail: &[u8]) -> bool {
let Some(&o) = tail.first() else {
return false;
};
match o {
// 2-byte `0x0F` GPR opcodes where `REX.W` overrides `0x66` (must
// precede `0x00..=0x3F`).
0x0F => tail.get(1).is_some_and(|&o2| {
matches!(
o2,
0x40..=0x4F
| 0xA3..=0xA5
| 0xAB..=0xAD
| 0xAF
| 0xB1
| 0xB3
| 0xB6..=0xBF
| 0xC1
| 0xC8..=0xCF
)
}),
// Default-64-bit stack push/pop (`REX.W` overrides `0x66`).
0x50..=0x5F => true,
// 1-byte ALU `r/m{16,32,64}` and accumulator forms (`o & 7` in 1,3,5).
0x00..=0x3F => matches!(o & 7, 1 | 3 | 5),
// Standard `d32` GPR opcodes (`movsxd`, `imul`, ALU/test/xchg/mov/lea,
// `movabs`, shifts, Group 3 `0xF7`).
0x63
| 0x69
| 0x6B
| 0x81
| 0x83
| 0x85
| 0x87
| 0x89
| 0x8B
| 0x8D
| 0x90..=0x99
| 0xA9
| 0xB8..=0xBF
| 0xC1
| 0xC7
| 0xD1
| 0xD3
| 0xF7 => true,
// Group 5 (`0xFF`): `inc` (0), `dec` (1), and `push` (6); excludes
// indirect `call`/`jmp`.
0xFF => tail.get(1).is_some_and(|&m| matches!((m >> 3) & 7, 0 | 1 | 6)),
_ => false,
}
}
/// Inspect the leading x86-64 legacy/REX prefix run of `bytes` (before the
/// first non-prefix opcode byte).
fn scan_x86_legacy_prefixes(bytes: &[u8]) -> X86PrefixInfo {
let mut count_66 = 0usize;
let mut active_rex: Option<u8> = None;
let mut has_vex_forbidden_prefix = false;
let mut idx = 0usize;
while idx < bytes.len() {
let b = bytes[idx];
match b {
0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 | 0x67 => {
active_rex = None;
idx += 1;
}
0xF0 | 0xF2 | 0xF3 => {
has_vex_forbidden_prefix = true;
active_rex = None;
idx += 1;
}
0x66 => {
count_66 += 1;
has_vex_forbidden_prefix = true;
active_rex = None;
idx += 1;
}
0x40..=0x4F => {
has_vex_forbidden_prefix = true;
active_rex = Some(b);
idx += 1;
}
_ => break,
}
}
if idx >= bytes.len() {
return X86PrefixInfo { count_66: 0, rex_w_overrides_66: false, vex_has_ud_prefix: false };
}
let tail = &bytes[idx..];
let is_vex = matches!(tail.first(), Some(0xC4 | 0xC5));
let vex_has_ud_prefix = is_vex && has_vex_forbidden_prefix;
let has_active_rex_w = active_rex.is_some_and(|r| (r & 0x08) != 0);
let rex_w_overrides_66 = !is_vex && has_active_rex_w && opcode_uses_rex_w_over_66(tail);
X86PrefixInfo { count_66, rex_w_overrides_66, vex_has_ud_prefix }
}
/// Count how many leading `data16` prefix tokens appear before the real
/// instruction mnemonic (skipping `lock` and strippable x86-64 prefixes).
fn count_leading_data16_tokens(mut cursor: &str) -> usize {
let mut count = 0usize;
loop {
let mut parts = cursor.splitn(2, char::is_whitespace);
let first = parts.next().unwrap_or("");
let rest = parts.next().unwrap_or("").trim_start();
let lower = first.to_ascii_lowercase();
if rest.is_empty() {
return count;
}
if lower == "data16" {
count += 1;
cursor = rest;
} else if lower == "lock" || is_x86_strippable_prefix(&lower) {
cursor = rest;
} else {
return count;
}
}
}
/// True iff the text following a leading `data16` prefix token resolves (after
/// any further `data16` or strippable x86-64 prefix tokens) to a legal NOP
/// encoding (`nop`/`nopw`/`nopl`/`nopq` or accumulator self-`xchg`).
fn data16_rest_is_nop(mut cursor: &str, raw_bytes: &[u8]) -> bool {
loop {
let mut parts = cursor.splitn(2, char::is_whitespace);
let first = parts.next().unwrap_or("");
let rest = parts.next().unwrap_or("").trim_start();
let lower = first.to_ascii_lowercase();
if lower.is_empty() {
return false;
}
if !rest.is_empty() && (lower == "data16" || is_x86_strippable_prefix(&lower)) {
cursor = rest;
continue;
}
return matches!(lower.as_str(), "nop" | "nopw" | "nopl" | "nopq")
|| crate::is_x86_nop_self_xchg(&lower, rest, raw_bytes);
}
}
fn parse_asm_text(arch: Arch, asm: &str, raw_bytes: &[u8]) -> (String, String, bool, bool) {
// Strip trailing `// ...` or ` # ...` comments while keeping `#0x10`.
let clean = strip_asm_comment(asm).trim();
if clean.is_empty() {
return (String::new(), String::new(), false, true);
}
let mut locked = false;
let mut cursor = clean;
let mut vex_ud_prefix = false;
// On x86-64, external disassemblers emit leading prefix tokens (`lock`,
// `cs`/`ds`/`es`/`ss`/`fs`/`gs`, CET `notrack`, `addr32`, explicit
// `rex`/`rex.*`, `rep`/`repz`/`repe` before `ret`, and redundant `data16`).
// Never sanitize `#UD` legacy/REX prefixes (`0x66`/`0xF0`/`0xF2`/`0xF3`/
// `REX`) preceding VEX (`0xC4`/`0xC5`); mark them `is_bad = true`. Strip
// leading `data16` only when architecturally redundant: overridden by
// active `REX.W` on a GPR opcode that honors `REX.W` over `0x66`, a
// duplicate `0x66` on a 16-bit opcode (`leading_data16 < count_66`), or on
// a legal NOP encoding. Leave unmodeled `0x66` prefixes (e.g., `data16 je`,
// `data16 add al,al`, `66 48 74 02`, `66 48 00 c0`, or bare `data16`)
// unstripped so they remain `is_bad = true`.
if arch == Arch::X86_64 {
let pfx_info = scan_x86_legacy_prefixes(raw_bytes);
vex_ud_prefix = pfx_info.vex_has_ud_prefix;
if !vex_ud_prefix {
let leading_data16 = count_leading_data16_tokens(cursor);
let redundant_data16 = pfx_info.rex_w_overrides_66
|| (leading_data16 > 0 && leading_data16 < pfx_info.count_66);
loop {
let mut parts = cursor.splitn(2, char::is_whitespace);
let first = parts.next().unwrap_or("");
let rest = parts.next().unwrap_or("").trim_start();
let lower = first.to_ascii_lowercase();
if lower == "lock" {
locked = true;
if rest.is_empty() {
break;
}
cursor = rest;
continue;
}
if !rest.is_empty() && is_x86_strippable_prefix(&lower) {
cursor = rest;
continue;
}
if !rest.is_empty()
&& lower == "data16"
&& (redundant_data16 || data16_rest_is_nop(rest, raw_bytes))
{
cursor = rest;
continue;
}
if !rest.is_empty() && matches!(lower.as_str(), "rep" | "repz" | "repe") {
let next_tok = rest.split_whitespace().next().unwrap_or("");
if next_tok.eq_ignore_ascii_case("ret") || next_tok.eq_ignore_ascii_case("retq")
{
cursor = rest;
continue;
}
}
break;
}
}
}
let mut parts = cursor.splitn(2, char::is_whitespace);
let mnemonic = parts.next().unwrap_or("").to_ascii_lowercase();
let operands = parts.next().unwrap_or("").trim().to_string();
// Bare `data16`, unconsumed `data16` on non-NOP/non-`REX.W`-overridden
// opcodes, `#UD` legacy/REX-prefixed VEX encodings, and GNU `objdump`
// `#UD` operand diagnostics (`lea eax,(bad)`, `vmovhps (bad),xmm0`) are
// marked `is_bad = true`.
let ops_lower = operands.to_ascii_lowercase();
let is_bad = vex_ud_prefix
|| matches!(
mnemonic.as_str(),
"" | "<unknown>" | "(bad)" | ".byte" | ".word" | ".short" | ".long" | ".inst" | "udf"
)
|| ops_lower.contains("(bad)")
|| ops_lower.contains("<unknown>")
|| (arch == Arch::X86_64 && mnemonic == "data16");
(mnemonic, operands, locked, is_bad)
}
fn strip_asm_comment(s: &str) -> &str {
// Preserve `#0x10` immediates on AArch64; strip only `//` comments or
// ` # ` separated comments.
let s = s.split("//").next().unwrap_or(s);
if let Some(idx) = s.find(" # ") {
&s[..idx]
} else {
s
}
}
/// Exclusively create (`O_CREAT | O_EXCL` via `create_new(true)`) a fresh
/// temporary ELF file in `dir` and write `elf_bytes` without following
/// symlinks or clobbering pre-existing files.
pub fn create_exclusive_temp_file(
dir: &Path,
prefix: &str,
elf_bytes: &[u8],
) -> Result<PathBuf, String> {
let pid = std::process::id();
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
for attempt in 0..MAX_TEMP_CREATE_ATTEMPTS {
let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
let path =
dir.join(format!("anneal-isa-oracle-{prefix}-{pid}-{nanos:x}-{seq}-{attempt}.o"));
let mut opts = OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
match opts.open(&path) {
Ok(mut file) => {
if let Err(e) = file.write_all(elf_bytes) {
let _ = fs::remove_file(&path);
return Err(format!("failed to write temp ELF {}: {e}", path.display()));
}
return Ok(path);
}
Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
Err(e) => {
return Err(format!("failed to create exclusive temp ELF {}: {e}", path.display()));
}
}
}
Err(format!(
"exhausted {MAX_TEMP_CREATE_ATTEMPTS} exclusive temp ELF creation attempts in {}",
dir.display()
))
}
/// Write `elf_bytes` to a freshly created exclusive temporary `.o` file,
/// invoke `f`, and remove the temporary file before returning.
fn with_temp_elf<T>(
prefix: &str,
elf_bytes: &[u8],
f: impl FnOnce(&Path) -> Result<T, String>,
) -> Result<T, String> {
let dir = std::env::temp_dir();
let path = create_exclusive_temp_file(&dir, prefix, elf_bytes)?;
let res = f(&path);
let _ = fs::remove_file(&path);
res
}
/// Disassemble raw instruction bytes via `llvm-objdump --disassemble`.
///
/// Never passes `--show-raw-insn`, because `llvm-objdump` emits raw bytes by
/// default and rejects `--show-raw-insn`. Passes `--disassemble-zeroes` so
/// zero-filled runs are not elided.
pub fn run_llvm_objdump_bytes(
llvm_objdump_bin: &str,
arch: Arch,
bytes: &[u8],
) -> Result<Vec<DisasmInsn>, String> {
let elf = build_minimal_elf64(arch, bytes);
with_temp_elf("llvm", &elf, |path| run_llvm_objdump_file(llvm_objdump_bin, arch, path, None))
}
/// Disassemble an ELF file (optionally restricted to `section`) via
/// `llvm-objdump --disassemble --disassemble-zeroes`.
pub fn run_llvm_objdump_file(
llvm_objdump_bin: &str,
arch: Arch,
elf_path: &Path,
section: Option<&str>,
) -> Result<Vec<DisasmInsn>, String> {
let mut cmd = Command::new(llvm_objdump_bin);
cmd.arg("--disassemble").arg("--disassemble-zeroes");
if arch == Arch::X86_64 {
cmd.arg("--x86-asm-syntax=intel");
}
if let Some(sec) = section {
cmd.arg(format!("--section={sec}"));
}
cmd.arg(elf_path);
let out = cmd.output().map_err(|e| format!("failed to spawn `{llvm_objdump_bin}`: {e}"))?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
return Err(format!(
"`{llvm_objdump_bin}` failed (status {}): {}",
out.status,
stderr.trim()
));
}
let stdout = String::from_utf8_lossy(&out.stdout);
parse_objdump_output(arch, DisasmLeg::LlvmObjdump, &stdout)
}
/// Disassemble raw instruction bytes via GNU `objdump -d --show-raw-insn -z`.
pub fn run_gnu_objdump_bytes(
gnu_objdump_bin: &str,
arch: Arch,
bytes: &[u8],
) -> Result<Vec<DisasmInsn>, String> {
let elf = build_minimal_elf64(arch, bytes);
with_temp_elf("gnu", &elf, |path| run_gnu_objdump_file(gnu_objdump_bin, arch, path, None))
}
/// Disassemble an ELF file (optionally restricted to `section`) via GNU
/// `objdump -d --show-raw-insn -z`.
pub fn run_gnu_objdump_file(
gnu_objdump_bin: &str,
arch: Arch,
elf_path: &Path,
section: Option<&str>,
) -> Result<Vec<DisasmInsn>, String> {
let mut cmd = Command::new(gnu_objdump_bin);
cmd.arg("-d").arg("--show-raw-insn").arg("-z");
if arch == Arch::X86_64 {
cmd.arg("-M").arg("intel");
}
if let Some(sec) = section {
cmd.arg("-j").arg(sec);
}
cmd.arg(elf_path);
let out = cmd.output().map_err(|e| format!("failed to spawn `{gnu_objdump_bin}`: {e}"))?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
return Err(format!(
"`{gnu_objdump_bin}` failed (status {}): {}",
out.status,
stderr.trim()
));
}
let stdout = String::from_utf8_lossy(&out.stdout);
parse_objdump_output(arch, DisasmLeg::GnuObjdump, &stdout)
}