Skip to content

Add stack analysis tool #313

@sosthene-nitrokey

Description

@sosthene-nitrokey

With -Z emit-stack-sizes we can get the stack sizes of each function in the final firmware. This could be used to analyze stack usage to fix stack-overflows. This could be made into a small util. Currently this issue will be used to document the (hacky) process:

Steps:

  1. use nightly
  2. add to the linker script SECTIONS (need to be added to runners/embedded/ld/cortex-m-rt_0.6.15_link.x):
  /* `INFO` makes the section not allocatable so it won't be loaded into memory */
  .stack_sizes (INFO) :
  {
    KEEP(*(.stack_sizes));
  }
  1. add strip = false to release profile
  2. compile with RUSTFLAGS="-Z emit-stack-sizes" make flash-develop EXTRA_FEATURES=... (from utils/nrf-builder)
  3. use the following script to get the functions (path may need to be adjusted):
#!/usr/bin/env cargo

//! ```cargo
//! [package]
//! edition = "2021"
//! [dependencies]
//! stack-sizes = "0.5.0"
//! ```

use std::fs::read;

use stack_sizes::analyze_executable;
fn main() {
    let path = "../nitrokey-3-firmware/target/thumbv7em-none-eabihf/release/nrf52_runner";
    let data = read(path).unwrap();
    let functions = analyze_executable(&data).unwrap();
    let mut sorted: Vec<_> = functions.defined.into_values().collect();
    sorted.sort_by_key(|f| f.stack().unwrap_or(0));
    println!("{sorted:#?}");
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions