Skip to main content

litz_cli/
heap.rs

1//! Static memory and heap facts read from a firmware ELF.
2//!
3//! The chip model has no allocator: firmware `malloc` runs inside the guest
4//! and the host never sees an allocation. What the image itself declares does
5//! not need a running guest, though: the section table says how much RAM the
6//! static data occupies, and the linked heap symbols say where the heap starts
7//! and ends. This module reads those directly, without the `object` crate, so
8//! `litz heap` answers offline and cannot drift from the image it describes.
9//!
10//! Runtime free/used heap needs a sample from the running firmware; that is a
11//! separate, backend-specific facility and is not guessed here.
12
13use std::path::Path;
14
15const SHT_PROGBITS: u32 = 1;
16const SHT_SYMTAB: u32 = 2;
17const SHT_NOBITS: u32 = 8;
18const SHF_ALLOC: u64 = 0x2;
19
20/// Heap-region symbols an ESP-IDF linker script may leave in the image.
21const HEAP_SYMBOLS: [&str; 6] = [
22    "_heap_start",
23    "__heap_start",
24    "heap_start",
25    "_heap_end",
26    "__heap_end",
27    "heap_end",
28];
29
30struct Section {
31    name: String,
32    kind: u32,
33    addr: u64,
34    size: u64,
35    alloc: bool,
36}
37
38/// Explain a firmware's static RAM and heap bounds, or why it cannot.
39pub fn report(path: &Path) -> Result<String, String> {
40    let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
41    let elf = Elf::parse(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
42
43    let mut out = String::new();
44    out.push_str(&format!(
45        "{}: ELF{} {}-endian\n",
46        path.display(),
47        elf.bits,
48        if elf.little { "little" } else { "big" }
49    ));
50
51    let mut ram = 0u64;
52    out.push_str("  section                 size        addr\n");
53    for section in &elf.sections {
54        if !section.alloc || !is_ram(section) {
55            continue;
56        }
57        if section.kind == SHT_PROGBITS || section.kind == SHT_NOBITS {
58            ram += section.size;
59        }
60        out.push_str(&format!(
61            "  {:<20} {:>8}  0x{:08x}\n",
62            section.name, section.size, section.addr
63        ));
64    }
65    if ram == 0 {
66        out.push_str("  (no allocated RAM sections)\n");
67    } else {
68        out.push_str(&format!("  static RAM: {ram} bytes\n"));
69    }
70
71    let mut bounds = Vec::new();
72    for name in HEAP_SYMBOLS {
73        if let Some(address) = elf.symbol(name) {
74            bounds.push((name, address));
75        }
76    }
77    if bounds.is_empty() {
78        out.push_str(
79            "  heap bounds: no _heap_start/_heap_end symbol in the image; the heap is \
80             allocated at runtime or the ELF is stripped\n",
81        );
82    } else {
83        for (name, address) in &bounds {
84            out.push_str(&format!("  {name} = 0x{address:08x}\n"));
85        }
86        let start = bounds
87            .iter()
88            .find(|(name, _)| name.contains("start"))
89            .map(|(_, address)| *address);
90        let end = bounds
91            .iter()
92            .find(|(name, _)| name.contains("end"))
93            .map(|(_, address)| *address);
94        if let (Some(start), Some(end)) = (start, end)
95            && end > start
96        {
97            out.push_str(&format!("  heap region: {} bytes\n", end - start));
98        }
99    }
100    Ok(out)
101}
102
103/// Whether a section is loaded into RAM. The ESP linker names its RAM
104/// sections `.data`, `.bss`, `.dram*`, `.iram*`, `.rtc*`; flash-resident
105/// `.rodata`/`.text` are allocated but not RAM, and `.flash*` is explicitly
106/// excluded.
107fn is_ram(section: &Section) -> bool {
108    let name = section.name.as_str();
109    if name.starts_with(".rodata") || name.starts_with(".text") || name.starts_with(".flash") {
110        return false;
111    }
112    matches!(section.kind, SHT_PROGBITS | SHT_NOBITS)
113        && (name.starts_with(".data")
114            || name.starts_with(".bss")
115            || name.starts_with(".dram")
116            || name.starts_with(".iram")
117            || name.starts_with(".rtc")
118            || name == ".noinit")
119}
120
121struct Elf {
122    bits: u32,
123    little: bool,
124    sections: Vec<Section>,
125    /// (name, address) in symbol-table order.
126    symbols: Vec<(String, u64)>,
127}
128
129impl Elf {
130    fn parse(bytes: &[u8]) -> Result<Elf, String> {
131        if bytes.len() < 16 || !bytes.starts_with(b"\x7fELF") {
132            return Err("not an ELF image".into());
133        }
134        let bits = match bytes[4] {
135            1 => 32,
136            2 => 64,
137            other => return Err(format!("unknown ELF class {other}")),
138        };
139        let little = match bytes[5] {
140            1 => true,
141            2 => false,
142            other => return Err(format!("unknown ELF data encoding {other}")),
143        };
144        let read = |offset: usize, len: usize| -> Result<u64, String> {
145            let slice = bytes
146                .get(offset..offset + len)
147                .ok_or_else(|| "truncated ELF header".to_string())?;
148            let mut value = 0u64;
149            for (index, byte) in slice.iter().enumerate() {
150                let shift = if little { index } else { len - 1 - index } * 8;
151                value |= u64::from(*byte) << shift;
152            }
153            Ok(value)
154        };
155        let (shoff, shentsize, shnum, shstrndx) = if bits == 32 {
156            (read(32, 4)?, read(46, 2)?, read(48, 2)?, read(50, 2)?)
157        } else {
158            (read(40, 8)?, read(58, 2)?, read(60, 2)?, read(62, 2)?)
159        };
160        if shoff == 0 || shnum == 0 {
161            return Err("the image has no section table".into());
162        }
163        let shoff = shoff as usize;
164        let entry = shentsize.max(1) as usize;
165        let index = |n: u64| shoff.checked_add(n as usize * entry);
166
167        let mut raw = Vec::with_capacity(shnum as usize);
168        for n in 0..shnum {
169            let at = index(n).ok_or_else(|| "section table out of range".to_string())?;
170            let (name, kind, flags, addr, offset, size, link) = if bits == 32 {
171                (
172                    read(at, 4)?,
173                    read(at + 4, 4)?,
174                    read(at + 8, 4)?,
175                    read(at + 12, 4)?,
176                    read(at + 16, 4)?,
177                    read(at + 20, 4)?,
178                    read(at + 24, 4)?,
179                )
180            } else {
181                (
182                    read(at, 4)?,
183                    read(at + 4, 4)?,
184                    read(at + 8, 8)?,
185                    read(at + 16, 8)?,
186                    read(at + 24, 8)?,
187                    read(at + 32, 8)?,
188                    read(at + 40, 4)?,
189                )
190            };
191            raw.push((name, kind, flags, addr, offset, size, link));
192        }
193
194        let shstr = raw
195            .get(shstrndx as usize)
196            .ok_or_else(|| "the section-name table is missing".to_string())?;
197        let strtab = section_bytes(bytes, shstr.4, shstr.5)?;
198        let name_at = |offset: u64| -> String {
199            let start = offset as usize;
200            let end = strtab[start..]
201                .iter()
202                .position(|b| *b == 0)
203                .map(|n| start + n)
204                .unwrap_or(strtab.len());
205            String::from_utf8_lossy(&strtab[start..end]).into_owned()
206        };
207
208        let mut sections = Vec::with_capacity(raw.len());
209        let mut symbols = Vec::new();
210        for (name, kind, flags, addr, offset, size, link) in &raw {
211            sections.push(Section {
212                name: name_at(*name),
213                kind: *kind as u32,
214                addr: *addr,
215                size: *size,
216                alloc: flags & SHF_ALLOC != 0,
217            });
218            if *kind as u32 == SHT_SYMTAB {
219                let table = section_bytes(bytes, *offset, *size)?;
220                let strings = raw
221                    .get(*link as usize)
222                    .map(|s| section_bytes(bytes, s.4, s.5))
223                    .transpose()?
224                    .unwrap_or(&[][..]);
225                let stride = if bits == 32 { 16 } else { 24 };
226                for entry in table.chunks_exact(stride) {
227                    let name_offset = u32::from_le_bytes(entry[0..4].try_into().unwrap()) as usize;
228                    let value = if bits == 32 {
229                        u32::from_le_bytes(entry[4..8].try_into().unwrap()) as u64
230                    } else {
231                        u64::from_le_bytes(entry[8..16].try_into().unwrap())
232                    };
233                    let name = symbol_name(strings, name_offset);
234                    if !name.is_empty() {
235                        symbols.push((name, value));
236                    }
237                }
238            }
239        }
240        Ok(Elf {
241            bits,
242            little,
243            sections,
244            symbols,
245        })
246    }
247
248    fn symbol(&self, name: &str) -> Option<u64> {
249        self.symbols
250            .iter()
251            .find(|(symbol, _)| symbol == name)
252            .map(|(_, address)| *address)
253    }
254}
255
256fn section_bytes(bytes: &[u8], offset: u64, size: u64) -> Result<&[u8], String> {
257    let start = offset as usize;
258    let end = start
259        .checked_add(size as usize)
260        .ok_or_else(|| "section out of range".to_string())?;
261    bytes
262        .get(start..end)
263        .ok_or_else(|| "section out of range".to_string())
264}
265
266fn symbol_name(strings: &[u8], offset: usize) -> String {
267    let Some(rest) = strings.get(offset..) else {
268        return String::new();
269    };
270    let end = rest.iter().position(|b| *b == 0).unwrap_or(rest.len());
271    String::from_utf8_lossy(&rest[..end]).into_owned()
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277
278    /// A hand-built ELF32 little-endian image with `.data`, `.bss`, `.text`
279    /// and a symbol table carrying `_heap_start`/`_heap_end`.
280    fn sample_elf() -> Vec<u8> {
281        // Layout: header (52), section table at 52 (7 * 40), names at 332,
282        // symtab at 400 (3 * 16), strtab at 448.
283        let mut data = vec![0u8; 512];
284        data[0..4].copy_from_slice(b"\x7fELF");
285        data[4] = 1; // 32-bit
286        data[5] = 1; // little
287        data[6] = 1;
288        let put16 =
289            |data: &mut [u8], at: usize, v: u16| data[at..at + 2].copy_from_slice(&v.to_le_bytes());
290        let put32 =
291            |data: &mut [u8], at: usize, v: u32| data[at..at + 4].copy_from_slice(&v.to_le_bytes());
292        put32(&mut data, 32, 52); // e_shoff
293        put16(&mut data, 46, 40); // e_shentsize
294        put16(&mut data, 48, 7); // e_shnum
295        put16(&mut data, 50, 4); // e_shstrndx
296
297        let names = b"\0.text\0.data\0.bss\0.shstrtab\0.symtab\0.strtab\0";
298        data[332..332 + names.len()].copy_from_slice(names);
299
300        let mut section = |n: usize,
301                           name: u32,
302                           kind: u32,
303                           flags: u32,
304                           addr: u32,
305                           off: u32,
306                           size: u32,
307                           link: u32| {
308            let at = 52 + n * 40;
309            put32(&mut data, at, name);
310            put32(&mut data, at + 4, kind);
311            put32(&mut data, at + 8, flags);
312            put32(&mut data, at + 12, addr);
313            put32(&mut data, at + 16, off);
314            put32(&mut data, at + 20, size);
315            put32(&mut data, at + 24, link);
316        };
317        // name offsets in `names`
318        section(0, 0, 0, 0, 0, 0, 0, 0);
319        section(1, 1, SHT_PROGBITS, 0x6, 0x4000_0000, 0, 100, 0); // .text
320        section(2, 7, SHT_PROGBITS, 0x3, 0x3ffb_0000, 0, 800, 0); // .data
321        section(3, 13, SHT_NOBITS, 0x3, 0x3ffb_0320, 0, 1600, 0); // .bss
322        section(4, 18, 3, 0, 0, 332, names.len() as u32, 0); // .shstrtab
323        section(5, 28, SHT_SYMTAB, 0, 0, 400, 48, 6); // .symtab
324        section(6, 36, 3, 0, 0, 448, 32, 0); // .strtab
325
326        let strings = b"\0_heap_start\0_heap_end\0";
327        data[448..448 + strings.len()].copy_from_slice(strings);
328        let mut symbol = |n: usize, name: u32, value: u32| {
329            let at = 400 + n * 16;
330            put32(&mut data, at, name);
331            put32(&mut data, at + 4, value);
332            put32(&mut data, at + 8, 0);
333        };
334        symbol(0, 0, 0);
335        symbol(1, 1, 0x3ffb_0a00);
336        symbol(2, 13, 0x3ffc_0000);
337        data
338    }
339
340    #[test]
341    fn a_report_sums_static_ram_and_finds_the_heap_region() {
342        let dir = build_dir().join(format!("heap-{}", std::process::id()));
343        std::fs::create_dir_all(&dir).unwrap();
344        let path = dir.join("firmware.elf");
345        std::fs::write(&path, sample_elf()).unwrap();
346
347        let text = report(&path).unwrap();
348        assert!(text.contains(".data"), "{text}");
349        assert!(text.contains(".bss"), "{text}");
350        assert!(!text.contains(".text"), "code is not RAM: {text}");
351        assert!(text.contains("static RAM: 2400 bytes"), "{text}");
352        assert!(text.contains("_heap_start = 0x3ffb0a00"), "{text}");
353        assert!(text.contains("heap region: 62976 bytes"), "{text}");
354        std::fs::remove_dir_all(&dir).unwrap();
355    }
356
357    #[test]
358    fn a_non_elf_file_is_refused() {
359        let dir = build_dir();
360        std::fs::create_dir_all(&dir).unwrap();
361        let path = dir.join(format!("heap-not-elf-{}.bin", std::process::id()));
362        std::fs::write(&path, b"not an elf").unwrap();
363        assert!(report(&path).is_err());
364        let _ = std::fs::remove_file(path);
365    }
366
367    fn build_dir() -> std::path::PathBuf {
368        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../build")
369    }
370}