Skip to main content

h8_asm/
image.rs

1//! Checked search and mutation of flat, big-endian firmware images.
2
3/// A signature or erased-space request.
4#[derive(Debug, Clone, Copy)]
5#[non_exhaustive]
6pub enum Needle<'a> {
7    /// Exact bytes; an empty pattern matches nothing.
8    Bytes(&'a [u8]),
9    /// A big-endian 32-bit value.
10    Word(u32),
11    /// A run of erased (`0xff`) bytes with an aligned start.
12    FreeRun {
13        /// Required number of bytes; zero matches nothing.
14        len: usize,
15        /// Start alignment in bytes; zero matches nothing.
16        align: usize,
17    },
18    /// Big-endian `(value, mask)` words, matched at even offsets.
19    Masked(&'a [(u16, u16)]),
20}
21
22/// Finds the first complete match at or after `start`.
23/// Unaligned exact byte/word matches are permitted; masked instructions are
24/// searched only at even offsets. A match does not prove a code boundary.
25pub fn find(image: &[u8], needle: Needle<'_>, start: usize) -> Option<usize> {
26    match needle {
27        Needle::Bytes(pattern) => {
28            if pattern.is_empty() {
29                return None;
30            }
31            image
32                .get(start..)?
33                .windows(pattern.len())
34                .position(|bytes| bytes == pattern)
35                .map(|offset| start + offset)
36        }
37        Needle::Word(word) => find(image, Needle::Bytes(&word.to_be_bytes()), start),
38        Needle::FreeRun { len, align } => find_free_space(image, len, align, start),
39        Needle::Masked(pattern) => {
40            if pattern.is_empty() {
41                return None;
42            }
43            let len = pattern.len() * 2;
44            let end = image.len().checked_sub(len)?;
45            let start = start.checked_add(start % 2)?;
46            (start..=end).step_by(2).find(|&at| {
47                pattern.iter().enumerate().all(|(index, &(value, mask))| {
48                    let word =
49                        u16::from_be_bytes([image[at + index * 2], image[at + index * 2 + 1]]);
50                    word & mask == value & mask
51                })
52            })
53        }
54    }
55}
56
57/// Finds an erased (`0xff`) run with its start aligned during the search.
58/// Zero length/alignment and overflowing or out-of-bounds requests return `None`.
59pub fn find_free_space(image: &[u8], len: usize, align: usize, start: usize) -> Option<usize> {
60    if len == 0 || align == 0 {
61        return None;
62    }
63    let end = image.len().checked_sub(len)?;
64    let remainder = start % align;
65    let start = start.checked_add(if remainder == 0 { 0 } else { align - remainder })?;
66    (start..=end)
67        .step_by(align)
68        .find(|&at| image[at..at + len].iter().all(|&byte| byte == 0xff))
69}
70
71/// Reads a byte, or returns `None` when outside the image.
72pub fn read_u8(image: &[u8], at: usize) -> Option<u8> {
73    image.get(at).copied()
74}
75
76/// Reads a complete big-endian word without overflowing the input offset.
77pub fn read_u16(image: &[u8], at: usize) -> Option<u16> {
78    let bytes = image.get(at..)?.get(..2)?;
79    Some(u16::from_be_bytes([bytes[0], bytes[1]]))
80}
81
82/// Reads a complete big-endian longword without overflowing the input offset.
83pub fn read_u32(image: &[u8], at: usize) -> Option<u32> {
84    let bytes = image.get(at..)?.get(..4)?;
85    Some(u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
86}
87
88/// Why a checked image edit was refused.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum ImageError {
91    /// The complete edit does not fit in the image.
92    OutOfBounds,
93    /// An insertion would overwrite bytes other than erased flash (`0xff`).
94    NotFree,
95}
96
97/// Overwrites bytes only after the complete range is checked.
98/// Errors leave the image unchanged. Empty writes at the end are permitted.
99pub fn write(image: &mut [u8], at: usize, bytes: &[u8]) -> Result<(), ImageError> {
100    let destination = image
101        .get_mut(at..)
102        .and_then(|rest| rest.get_mut(..bytes.len()))
103        .ok_or(ImageError::OutOfBounds)?;
104    destination.copy_from_slice(bytes);
105    Ok(())
106}
107
108/// Inserts into erased space, returning the flat-image offset on success.
109/// Bounds and the whole erased range are checked before any byte is written.
110pub fn insert(image: &mut [u8], at: usize, bytes: &[u8]) -> Result<usize, ImageError> {
111    let destination = image
112        .get_mut(at..)
113        .and_then(|rest| rest.get_mut(..bytes.len()))
114        .ok_or(ImageError::OutOfBounds)?;
115    if destination.iter().any(|&byte| byte != 0xff) {
116        return Err(ImageError::NotFree);
117    }
118    destination.copy_from_slice(bytes);
119    Ok(at)
120}
121
122/// Geometry of fixed-size opcode-dispatch records with big-endian pointers.
123#[derive(Debug, Clone, Copy)]
124pub struct CommandTable {
125    /// Flat-image offset of the first record.
126    pub base: usize,
127    /// Record size in bytes.
128    pub stride: usize,
129    /// Offset of the opcode byte inside each record.
130    pub opcode_off: usize,
131    /// Offset of the flags byte inside each record.
132    pub flags_off: usize,
133    /// Offset of the four-byte big-endian handler inside each record.
134    pub handler_off: usize,
135    /// Flags byte marking the terminating record (not returned by the scan).
136    pub term_flag: u8,
137    /// Maximum number of records to inspect, including the terminator.
138    pub max_records: usize,
139}
140
141/// One dispatch record, with its pointer retained exactly as stored.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub struct CommandRecord {
144    /// Record offset in the image.
145    pub off: usize,
146    /// Dispatch opcode.
147    pub opcode: u8,
148    /// Record flags.
149    pub flags: u8,
150    /// Big-endian handler value.
151    pub handler: u32,
152}
153
154/// A malformed or incomplete command table.
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub enum TableError {
157    /// Fields overlap, extend outside a record, or a size/count is zero.
158    InvalidGeometry,
159    /// A record is truncated or the table starts outside the image.
160    OutOfBounds,
161    /// No terminator was found within `max_records`.
162    MissingTerminator,
163    /// No record has the requested opcode.
164    NotFound,
165}
166
167impl CommandTable {
168    /// Reads all records up to a required terminator. No partial result is returned.
169    pub fn walk(&self, image: &[u8]) -> Result<Vec<CommandRecord>, TableError> {
170        let handler_end = self
171            .handler_off
172            .checked_add(4)
173            .ok_or(TableError::InvalidGeometry)?;
174        if self.stride == 0
175            || self.max_records == 0
176            || self.opcode_off >= self.stride
177            || self.flags_off >= self.stride
178            || handler_end > self.stride
179            || self.opcode_off == self.flags_off
180            || (self.handler_off..handler_end).contains(&self.opcode_off)
181            || (self.handler_off..handler_end).contains(&self.flags_off)
182        {
183            return Err(TableError::InvalidGeometry);
184        }
185        let mut records = Vec::new();
186        let mut at = self.base;
187        for _ in 0..self.max_records {
188            let record = image
189                .get(at..)
190                .and_then(|rest| rest.get(..self.stride))
191                .ok_or(TableError::OutOfBounds)?;
192            let flags = record[self.flags_off];
193            if flags == self.term_flag {
194                return Ok(records);
195            }
196            let pointer = &record[self.handler_off..handler_end];
197            records.push(CommandRecord {
198                off: at,
199                opcode: record[self.opcode_off],
200                flags,
201                handler: u32::from_be_bytes([pointer[0], pointer[1], pointer[2], pointer[3]]),
202            });
203            at += self.stride; // the complete record was checked against image.len()
204        }
205        Err(TableError::MissingTerminator)
206    }
207
208    /// Finds the first matching opcode in a fully validated, terminated table.
209    pub fn find(&self, image: &[u8], opcode: u8) -> Result<CommandRecord, TableError> {
210        self.walk(image)?
211            .into_iter()
212            .find(|record| record.opcode == opcode)
213            .ok_or(TableError::NotFound)
214    }
215
216    /// Changes one handler and optionally its flags, after validating the table.
217    /// Errors leave the entire image unchanged.
218    pub fn replace(
219        &self,
220        image: &mut [u8],
221        opcode: u8,
222        handler: u32,
223        flags: Option<u8>,
224    ) -> Result<(), TableError> {
225        let record = self.find(image, opcode)?;
226        let at = record.off + self.handler_off;
227        image[at..at + 4].copy_from_slice(&handler.to_be_bytes());
228        if let Some(flags) = flags {
229            image[record.off + self.flags_off] = flags;
230        }
231        Ok(())
232    }
233}