#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum Needle<'a> {
Bytes(&'a [u8]),
Word(u32),
FreeRun {
len: usize,
align: usize,
},
Masked(&'a [(u16, u16)]),
}
pub fn find(image: &[u8], needle: Needle<'_>, start: usize) -> Option<usize> {
match needle {
Needle::Bytes(pattern) => {
if pattern.is_empty() {
return None;
}
image
.get(start..)?
.windows(pattern.len())
.position(|bytes| bytes == pattern)
.map(|offset| start + offset)
}
Needle::Word(word) => find(image, Needle::Bytes(&word.to_be_bytes()), start),
Needle::FreeRun { len, align } => find_free_space(image, len, align, start),
Needle::Masked(pattern) => {
if pattern.is_empty() {
return None;
}
let len = pattern.len() * 2;
let end = image.len().checked_sub(len)?;
let start = start.checked_add(start % 2)?;
(start..=end).step_by(2).find(|&at| {
pattern.iter().enumerate().all(|(index, &(value, mask))| {
let word =
u16::from_be_bytes([image[at + index * 2], image[at + index * 2 + 1]]);
word & mask == value & mask
})
})
}
}
}
pub fn find_free_space(image: &[u8], len: usize, align: usize, start: usize) -> Option<usize> {
if len == 0 || align == 0 {
return None;
}
let end = image.len().checked_sub(len)?;
let remainder = start % align;
let start = start.checked_add(if remainder == 0 { 0 } else { align - remainder })?;
(start..=end)
.step_by(align)
.find(|&at| image[at..at + len].iter().all(|&byte| byte == 0xff))
}
pub fn read_u8(image: &[u8], at: usize) -> Option<u8> {
image.get(at).copied()
}
pub fn read_u16(image: &[u8], at: usize) -> Option<u16> {
let bytes = image.get(at..)?.get(..2)?;
Some(u16::from_be_bytes([bytes[0], bytes[1]]))
}
pub fn read_u32(image: &[u8], at: usize) -> Option<u32> {
let bytes = image.get(at..)?.get(..4)?;
Some(u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageError {
OutOfBounds,
NotFree,
}
pub fn write(image: &mut [u8], at: usize, bytes: &[u8]) -> Result<(), ImageError> {
let destination = image
.get_mut(at..)
.and_then(|rest| rest.get_mut(..bytes.len()))
.ok_or(ImageError::OutOfBounds)?;
destination.copy_from_slice(bytes);
Ok(())
}
pub fn insert(image: &mut [u8], at: usize, bytes: &[u8]) -> Result<usize, ImageError> {
let destination = image
.get_mut(at..)
.and_then(|rest| rest.get_mut(..bytes.len()))
.ok_or(ImageError::OutOfBounds)?;
if destination.iter().any(|&byte| byte != 0xff) {
return Err(ImageError::NotFree);
}
destination.copy_from_slice(bytes);
Ok(at)
}
#[derive(Debug, Clone, Copy)]
pub struct CommandTable {
pub base: usize,
pub stride: usize,
pub opcode_off: usize,
pub flags_off: usize,
pub handler_off: usize,
pub term_flag: u8,
pub max_records: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommandRecord {
pub off: usize,
pub opcode: u8,
pub flags: u8,
pub handler: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TableError {
InvalidGeometry,
OutOfBounds,
MissingTerminator,
NotFound,
}
impl CommandTable {
pub fn walk(&self, image: &[u8]) -> Result<Vec<CommandRecord>, TableError> {
let handler_end = self
.handler_off
.checked_add(4)
.ok_or(TableError::InvalidGeometry)?;
if self.stride == 0
|| self.max_records == 0
|| self.opcode_off >= self.stride
|| self.flags_off >= self.stride
|| handler_end > self.stride
|| self.opcode_off == self.flags_off
|| (self.handler_off..handler_end).contains(&self.opcode_off)
|| (self.handler_off..handler_end).contains(&self.flags_off)
{
return Err(TableError::InvalidGeometry);
}
let mut records = Vec::new();
let mut at = self.base;
for _ in 0..self.max_records {
let record = image
.get(at..)
.and_then(|rest| rest.get(..self.stride))
.ok_or(TableError::OutOfBounds)?;
let flags = record[self.flags_off];
if flags == self.term_flag {
return Ok(records);
}
let pointer = &record[self.handler_off..handler_end];
records.push(CommandRecord {
off: at,
opcode: record[self.opcode_off],
flags,
handler: u32::from_be_bytes([pointer[0], pointer[1], pointer[2], pointer[3]]),
});
at += self.stride; }
Err(TableError::MissingTerminator)
}
pub fn find(&self, image: &[u8], opcode: u8) -> Result<CommandRecord, TableError> {
self.walk(image)?
.into_iter()
.find(|record| record.opcode == opcode)
.ok_or(TableError::NotFound)
}
pub fn replace(
&self,
image: &mut [u8],
opcode: u8,
handler: u32,
flags: Option<u8>,
) -> Result<(), TableError> {
let record = self.find(image, opcode)?;
let at = record.off + self.handler_off;
image[at..at + 4].copy_from_slice(&handler.to_be_bytes());
if let Some(flags) = flags {
image[record.off + self.flags_off] = flags;
}
Ok(())
}
}