Skip to main content

litz_engine/
image.rs

1//! How a firmware file is laid out in flash.
2//!
3//! ESP toolchains produce two shapes of `.bin`. An *application* image is just
4//! the app; the runner writes it at `flash.app` and starts it directly. A
5//! *merged* image is what `esptool.py merge_bin` and micropython.org publish:
6//! the second-stage bootloader at offset 0, the partition table at 0x8000 and
7//! the app at 0x10000, all in one file. Writing that at `flash.app` corrupts
8//! it — the bootloader bytes land in the app region — so the runner has to
9//! tell them apart before it loads anything.
10//!
11//! The test is structural rather than name-based: a file with the bootloader
12//! magic at byte 0 and the partition-table magic at 0x8000 is merged, as is a
13//! file longer than the app offset with an ESP image header at 0x10000. A bare
14//! application image has the header at byte 0 and nothing at 0x8000. ESP-IDF's
15//! separate `bootloader.bin` and `partition-table.bin` are not `firmware`;
16//! they are named by `[sim] bootloader` and `[sim] partition_table`.
17
18/// Where the pieces of a merged image sit, from the ESP-IDF layout.
19pub const BOOTLOADER_OFFSET: usize = 0x0;
20pub const PARTITION_TABLE_OFFSET: usize = 0x8000;
21/// The classic ESP32's bootloader lives at 0x1000, so a factory image for it
22/// is the same merged layout shifted by that base: the file starts at flash
23/// 0x1000 and its partition table sits at file offset 0x7000.
24pub const PARTITION_TABLE_OFFSET_CLASSIC: usize = 0x7000;
25pub const APP_OFFSET: usize = 0x1_0000;
26
27/// The first byte of every ESP application or bootloader image.
28const IMAGE_MAGIC: u8 = 0xE9;
29/// The first two bytes of every partition-table entry.
30const PARTITION_MAGIC: [u8; 2] = [0xAA, 0x50];
31
32/// The shortest prefix that can carry an ESP image header: magic, segment
33/// count and entry point.
34const MIN_IMAGE: usize = 4;
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum FirmwareLayout {
38    /// Bootloader, partition table and application in one file, starting at 0.
39    Merged,
40    /// An application image on its own.
41    Application,
42}
43
44/// Classify a firmware file.
45///
46/// `Err` only for something that cannot be an ESP image at all; an unusual but
47/// long-enough file is treated as an application, which is what a bare image
48/// always is.
49pub fn detect(bytes: &[u8]) -> Result<FirmwareLayout, String> {
50    if bytes.len() < MIN_IMAGE {
51        return Err(format!(
52            "firmware is {} bytes; an ESP image needs at least {MIN_IMAGE}",
53            bytes.len()
54        ));
55    }
56
57    let bootloader_at_zero = bytes[0] == IMAGE_MAGIC;
58    let partition_table_at_0x8000 = bytes.len() >= PARTITION_TABLE_OFFSET + PARTITION_MAGIC.len()
59        && bytes[PARTITION_TABLE_OFFSET..PARTITION_TABLE_OFFSET + PARTITION_MAGIC.len()]
60            == PARTITION_MAGIC;
61    let app_at_0x10000 = bytes.len() > APP_OFFSET && bytes[APP_OFFSET] == IMAGE_MAGIC;
62    // A classic-ESP32 factory image starts at flash 0x1000, so its partition
63    // table is at file offset 0x7000 rather than 0x8000.
64    let partition_table_at_classic = bytes.len()
65        >= PARTITION_TABLE_OFFSET_CLASSIC + PARTITION_MAGIC.len()
66        && bytes[PARTITION_TABLE_OFFSET_CLASSIC
67            ..PARTITION_TABLE_OFFSET_CLASSIC + PARTITION_MAGIC.len()]
68            == PARTITION_MAGIC;
69
70    // Both halves of the first test are needed: an app that happens to contain
71    // 0xAA50 at 0x8000 is still an app, and a lone 0xE9 is still a short app.
72    if (bootloader_at_zero && (partition_table_at_0x8000 || partition_table_at_classic))
73        || app_at_0x10000
74    {
75        Ok(FirmwareLayout::Merged)
76    } else {
77        Ok(FirmwareLayout::Application)
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84
85    fn merged() -> Vec<u8> {
86        let mut bytes = vec![0xFF; APP_OFFSET + 0x100];
87        bytes[BOOTLOADER_OFFSET] = IMAGE_MAGIC;
88        bytes[PARTITION_TABLE_OFFSET..PARTITION_TABLE_OFFSET + 2].copy_from_slice(&PARTITION_MAGIC);
89        bytes[APP_OFFSET] = IMAGE_MAGIC;
90        bytes
91    }
92
93    #[test]
94    fn a_classic_esp32_factory_image_is_merged() {
95        let mut bytes = vec![0xff; 0x1_1000];
96        bytes[0] = IMAGE_MAGIC;
97        bytes[PARTITION_TABLE_OFFSET_CLASSIC] = PARTITION_MAGIC[0];
98        bytes[PARTITION_TABLE_OFFSET_CLASSIC + 1] = PARTITION_MAGIC[1];
99        assert_eq!(detect(&bytes).unwrap(), FirmwareLayout::Merged);
100    }
101
102    #[test]
103    fn a_bootloader_and_partition_table_at_their_offsets_is_merged() {
104        assert_eq!(detect(&merged()).unwrap(), FirmwareLayout::Merged);
105    }
106
107    #[test]
108    fn an_app_header_past_the_app_offset_is_merged_even_without_the_first_test() {
109        let mut bytes = merged();
110        // A merged file whose first byte is not the bootloader magic: the app
111        // at 0x10000 is enough on its own.
112        bytes[BOOTLOADER_OFFSET] = 0x00;
113        bytes[PARTITION_TABLE_OFFSET..PARTITION_TABLE_OFFSET + 2].fill(0xFF);
114        assert_eq!(detect(&bytes).unwrap(), FirmwareLayout::Merged);
115    }
116
117    #[test]
118    fn a_bare_application_image_is_an_application() {
119        let mut bytes = vec![0u8; 0x1000];
120        bytes[0] = IMAGE_MAGIC;
121        assert_eq!(detect(&bytes).unwrap(), FirmwareLayout::Application);
122    }
123
124    #[test]
125    fn a_large_application_without_a_header_at_the_app_offset_is_an_application() {
126        let mut bytes = vec![0u8; APP_OFFSET + 0x100];
127        bytes[0] = IMAGE_MAGIC;
128        assert_eq!(detect(&bytes).unwrap(), FirmwareLayout::Application);
129    }
130
131    #[test]
132    fn empty_and_too_short_files_are_refused() {
133        assert!(detect(&[]).is_err());
134        assert!(detect(&[IMAGE_MAGIC]).is_err());
135    }
136}