use serde::Serialize;
use crate::disasm::Arch;
use crate::error::{Error, Result};
pub const X86_NOP: u8 = 0x90;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PatchInput {
Asm(String),
Bytes(Vec<u8>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PatchPreview {
pub addr: u64,
pub file_off: Option<u64>,
pub old: Vec<u8>,
pub new: Vec<u8>,
pub size_ok: bool,
}
impl PatchPreview {
#[must_use]
pub fn old_hex(&self) -> String {
hex_of(&self.old)
}
#[must_use]
pub fn new_hex(&self) -> String {
hex_of(&self.new)
}
}
impl Serialize for PatchPreview {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut st = serializer.serialize_struct("PatchPreview", 6)?;
st.serialize_field("va", &self.addr)?;
st.serialize_field("va_hex", &crate::addr_hex(self.addr))?;
st.serialize_field("file_off", &self.file_off)?;
st.serialize_field("old_hex", &self.old_hex())?;
st.serialize_field("new_hex", &self.new_hex())?;
st.serialize_field("size_ok", &self.size_ok)?;
st.end()
}
}
fn hex_of(bytes: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for &b in bytes {
out.push(DIGITS[(b >> 4) as usize] as char);
out.push(DIGITS[(b & 0x0f) as usize] as char);
}
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PatchFileFormat {
Json,
Ips,
}
pub fn parse_patch_format(s: &str) -> Result<PatchFileFormat> {
match s.to_lowercase().as_str() {
"json" => Ok(PatchFileFormat::Json),
"ips" => Ok(PatchFileFormat::Ips),
_ => Err(Error::Invalid(format!(
"bad patch format: {s:?} (expected json or ips)"
))),
}
}
pub fn parse_patch_bytes(text: &str) -> Result<Vec<u8>> {
let mut out = Vec::new();
for tok in text.split_whitespace() {
if tok.len() != 2 || !tok.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(Error::Invalid(format!(
"bad --bytes token {tok:?}: expected two hex digits (e.g. \"90 90\")"
)));
}
let byte = u8::from_str_radix(tok, 16).map_err(|_| {
Error::Invalid(format!(
"bad --bytes token {tok:?}: expected two hex digits (e.g. \"90 90\")"
))
})?;
out.push(byte);
}
if out.is_empty() {
return Err(Error::Invalid(
"empty --bytes: expected whitespace-separated hex pairs (e.g. \"90 90\")".to_string(),
));
}
Ok(out)
}
pub fn assemble_x86(arch: Arch, va: u64, text: &str) -> Result<Vec<u8>> {
let bitness = match arch {
Arch::X86_64 => 64,
Arch::X86_32 => 32,
_ => {
return Err(Error::Unsupported(format!(
"patch --asm is x86-only (binary arch is {})",
crate::db::arch_name(arch)
)));
}
};
let text = text.trim();
let (head, tail) = match text.find(char::is_whitespace) {
Some(i) => (text[..i].to_string(), text[i..].trim().to_string()),
None => (text.to_string(), String::new()),
};
let mut asm = iced_x86::code_asm::CodeAssembler::new(bitness)
.map_err(|e| Error::Invalid(format!("cannot assemble {text:?} at {va:#x}: {e}")))?;
match head.to_ascii_lowercase().as_str() {
"nop" if tail.is_empty() => asm.nop(),
"ret" if tail.is_empty() => asm.ret(),
"int3" if tail.is_empty() => asm.int3(),
"jmp" if !tail.is_empty() && !tail.contains(char::is_whitespace) => {
let target = crate::parse_addr(&tail)?;
asm.jmp(target)
}
"call" if !tail.is_empty() && !tail.contains(char::is_whitespace) => {
let target = crate::parse_addr(&tail)?;
asm.call(target)
}
_ => {
return Err(Error::Invalid(format!(
"unsupported --asm {text:?}: expected nop, ret, int3, jmp ADDR, or call ADDR (use --bytes for arbitrary encodings)"
)));
}
}
.map_err(|e| Error::Invalid(format!("cannot assemble {text:?} at {va:#x}: {e}")))?;
asm.assemble(va)
.map_err(|e| Error::Invalid(format!("cannot encode {text:?} at {va:#x}: {e}")))
}
pub fn ips_bytes(file_off: u64, new_bytes: &[u8]) -> Result<Vec<u8>> {
if new_bytes.is_empty() || new_bytes.len() > 0xffff {
return Err(Error::Invalid(format!(
"IPS patch of {} bytes is out of range (1..=65535)",
new_bytes.len()
)));
}
let Some(off) = u32::try_from(file_off).ok().filter(|&o| o <= 0x00ff_ffff) else {
return Err(Error::Invalid(format!(
"file offset {file_off:#x} exceeds the IPS 24-bit range"
)));
};
let mut out = Vec::with_capacity(5 + 5 + new_bytes.len() + 3);
out.extend_from_slice(b"PATCH");
out.extend_from_slice(&off.to_be_bytes()[1..]);
out.extend_from_slice(&(new_bytes.len() as u16).to_be_bytes());
out.extend_from_slice(new_bytes);
out.extend_from_slice(b"EOF");
Ok(out)
}
pub fn reject_output_is_binary(binary: &std::path::Path, out: &std::path::Path) -> Result<()> {
if crate::same_file(binary, out) {
return Err(Error::Invalid(
"--out must not be the analyzed binary".to_string(),
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bytes_parse_accepts_pairs_and_rejects_junk() {
assert_eq!(parse_patch_bytes("90 90").expect("pairs"), vec![0x90, 0x90]);
assert_eq!(
parse_patch_bytes(" E9\t0b 00 00 00 ").expect("ws/case"),
vec![0xE9, 0x0b, 0, 0, 0]
);
for bad in ["", " ", "9", "900", "zz", "90 ??", "0x90"] {
assert!(parse_patch_bytes(bad).is_err(), "{bad:?} must fail");
}
}
#[test]
fn format_parse_is_case_insensitive() {
assert_eq!(
parse_patch_format("json").expect("json"),
PatchFileFormat::Json
);
assert_eq!(
parse_patch_format("IPS").expect("ips"),
PatchFileFormat::Ips
);
assert!(parse_patch_format("bsdiff").is_err());
}
#[test]
fn asm_encodes_fixed_and_branch_insns() {
assert_eq!(
assemble_x86(Arch::X86_64, 0x1000, "nop").expect("nop"),
vec![0x90]
);
assert_eq!(
assemble_x86(Arch::X86_64, 0x1000, " RET ").expect("ret"),
vec![0xC3]
);
assert_eq!(
assemble_x86(Arch::X86_64, 0x1000, "int3").expect("int3"),
vec![0xCC]
);
assert_eq!(
assemble_x86(Arch::X86_64, 0x1000, "jmp 0x1010").expect("jmp"),
vec![0xEB, 0x0E]
);
assert_eq!(
assemble_x86(Arch::X86_32, 0x1000, "call 0x1010").expect("call"),
vec![0xE8, 0x0B, 0x00, 0x00, 0x00]
);
}
#[test]
fn asm_rejects_other_archs_and_mnemonics() {
let e = assemble_x86(Arch::Aarch64, 0x1000, "nop").expect_err("arm");
assert!(matches!(e, Error::Unsupported(_)), "{e}");
for bad in [
"",
"mov eax, 1",
"jmp",
"jmp 0x1 0x2",
"nop 5",
"jecxz 0x10",
] {
assert!(
matches!(
assemble_x86(Arch::X86_64, 0x1000, bad),
Err(Error::Invalid(_))
),
"{bad:?} must fail"
);
}
}
#[test]
fn ips_layout_is_header_offset_len_data_eof() {
let bytes = ips_bytes(0x120, &[0x90, 0x90]).expect("ips");
assert_eq!(
bytes.as_slice(),
b"PATCH\x00\x01\x20\x00\x02\x90\x90EOF".as_slice()
);
assert!(ips_bytes(0x1_000_000, &[0x90]).is_err(), "24-bit cap");
assert!(ips_bytes(0, &[]).is_err(), "empty payload");
}
#[test]
fn preview_serializes_spec_shape() {
let v = serde_json::to_value(PatchPreview {
addr: 0x401000,
file_off: Some(0x400),
old: vec![0x74, 0x02],
new: vec![0x90, 0x90],
size_ok: true,
})
.expect("serializes");
assert_eq!(
v,
serde_json::json!({
"va": 0x401000u64,
"va_hex": "0x401000",
"file_off": 0x400u64,
"old_hex": "7402",
"new_hex": "9090",
"size_ok": true,
})
);
}
}