use crate::StackUsage;
use core::ptr::{read_volatile, write_volatile};
use core::sync::atomic::{AtomicUsize, Ordering};
unsafe extern "C" {
static _ram_start: u32;
static _stack_start: u32;
static _stack_end: u32;
static __euninit: u32;
}
#[cfg(all(unprobe_v8m, feature = "hardfault-handler"))]
const RESERVE: usize = 1024;
const PAINT_MARGIN: usize = 1024;
const PAINT: u32 = 0x5354_4b21;
static PAINTED: AtomicUsize = AtomicUsize::new(0);
static LIMIT: AtomicUsize = AtomicUsize::new(0);
fn bounds() -> Option<(usize, usize)> {
let ram_start = &raw const _ram_start as usize;
let top = &raw const _stack_start as usize;
let euninit = &raw const __euninit as usize;
let stack_end = &raw const _stack_end as usize;
let mut bottom = euninit;
if (euninit..top).contains(&stack_end) {
bottom = stack_end;
}
(ram_start <= euninit && bottom < top).then_some((bottom, top))
}
#[inline(always)]
fn sp() -> usize {
let sp: usize;
unsafe {
core::arch::asm!("mov {}, sp", out(reg) sp, options(nomem, nostack, preserves_flags))
};
sp
}
pub fn setup(paint: bool) {
let Some((bottom, top)) = bounds() else {
return;
};
let sp = sp();
if !(bottom < sp && sp <= top && sp - bottom >= 8 * 1024) {
return;
}
#[cfg(all(unprobe_v8m, feature = "hardfault-handler"))]
unsafe {
let current: usize;
core::arch::asm!("mrs {}, MSPLIM", out(reg) current, options(nomem, nostack, preserves_flags));
if current == 0 {
let limit = bottom + RESERVE;
core::arch::asm!("msr MSPLIM, {}", in(reg) limit, options(nomem, nostack, preserves_flags));
LIMIT.store(limit, Ordering::Relaxed);
}
}
if paint {
let start = (bottom + 3) & !3;
let end = (sp - PAINT_MARGIN) & !3;
let mut p = start;
while p < end {
unsafe { write_volatile(p as *mut u32, PAINT) };
p += 4;
}
PAINTED.store(start, Ordering::Relaxed);
}
}
#[cfg(feature = "hardfault-handler")]
pub fn limit() -> usize {
LIMIT.load(Ordering::Relaxed)
}
pub fn usage() -> Option<StackUsage> {
let start = PAINTED.load(Ordering::Relaxed);
if start == 0 {
return None;
}
let (bottom, top) = bounds()?;
let mut p = start;
while p < top && unsafe { read_volatile(p as *const u32) } == PAINT {
p += 4;
}
let floor = match LIMIT.load(Ordering::Relaxed) {
0 => bottom,
limit => limit,
};
Some(StackUsage {
used: top - p,
size: top - floor,
})
}