cortex_m_stack/
lib.rs

1#![no_std]
2#![doc = include_str!(concat!("../", env!("CARGO_PKG_README")))]
3
4use core::{arch::asm, mem::size_of, ops::Range};
5
6/// The value used to paint the stack.
7pub const STACK_PAINT_VALUE: u32 = 0xCCCC_CCCC;
8
9/// The [Range] currently in use for the stack.
10///
11/// Note: the stack is defined in reverse, as it runs from 'start' to 'end' downwards.
12/// Hence this range is technically empty because `start >= end`.
13///
14/// If you want to use this range to do range-like things, use [stack_rev] instead.
15#[inline]
16pub const fn stack() -> Range<*mut u32> {
17    unsafe extern "C" {
18        static mut _stack_start: u32;
19        static mut _stack_end: u32;
20    }
21
22    core::ptr::addr_of_mut!(_stack_start)..core::ptr::addr_of_mut!(_stack_end)
23}
24
25/// The [Range] currently in use for the stack,
26/// defined in reverse such that [Range] operations are viable.
27///
28/// Hence the `end` of this [Range] is where the stack starts.
29#[inline]
30pub const fn stack_rev() -> Range<*mut u32> {
31    stack().end..stack().start
32}
33
34/// Convenience function to fetch the current stack pointer.
35#[inline]
36pub fn current_stack_ptr() -> *mut u32 {
37    let res;
38    unsafe { asm!("mov {}, sp", out(reg) res) };
39    res
40}
41
42/// The number of bytes that are reserved for the stack at compile time.
43#[inline]
44pub const fn stack_size() -> u32 {
45    // Safety: start >= end. If this is not the case your linker did something wrong.
46    (unsafe { stack().start.byte_offset_from_unsigned(stack().end) }) as u32
47}
48
49/// The number of bytes of the stack that are currently in use.
50#[inline]
51pub fn current_stack_in_use() -> u32 {
52    // Safety: start >= end. If this is not the case your linker did something wrong.
53    (unsafe { stack().start.byte_offset_from_unsigned(current_stack_ptr()) }) as u32
54}
55
56/// The number of bytes of the stack that are currently free.
57///
58/// If the stack has overflowed, this function returns 0.
59#[inline]
60pub fn current_stack_free() -> u32 {
61    stack_size().saturating_sub(current_stack_in_use())
62}
63
64/// What fraction of the stack is currently in use.
65#[inline]
66pub fn current_stack_fraction() -> f32 {
67    current_stack_in_use() as f32 / stack_size() as f32
68}
69
70/// Paint the part of the stack that is currently not in use.
71///
72/// **Note:** this can take some time, and an ISR could possibly interrupt this process,
73/// dirtying up your freshly painted stack.
74/// If you wish to prevent this, run this inside a critical section using [cortex_m::interrupt::free].
75///
76/// Runs in *O(n)* where *n* is the size of the stack.
77/// This function is inefficient in the sense that it repaints the entire stack,
78/// even the parts that still have the [STACK_PAINT_VALUE].
79#[inline(never)]
80pub fn repaint_stack() {
81    unsafe {
82        asm!(
83            "0:",
84            "cmp sp, r0",
85            "bls 1f",
86            "stmia r0!, {{r1}}",
87            "b 0b",
88            "1:",
89            in("r0") stack().end,
90            in("r1") STACK_PAINT_VALUE,
91        )
92    };
93}
94
95/// Finds the number of bytes that have not been overwritten on the stack since the last repaint.
96///
97/// In other words: shows the worst case free stack space since [repaint_stack] was last called.
98///
99/// This measurement can only ever be an ESTIMATE, and not a guarantee, as the amount of
100/// stack can change immediately, even during an interrupt while we are measuring, or
101/// by a devious user or compiler that re-paints the stack, obscuring the max
102/// measured value. This measurement MUST NOT be used for load-bearing-safety
103/// safety guarantees, only as a (generally accurate but non-guaranteed) measurement.
104///
105/// Runs in *O(n)* where *n* is the size of the stack.
106pub fn stack_painted() -> u32 {
107    let res: *const u32;
108    // SAFETY: As per the [rust reference], inline asm is allowed to look below the
109    // stack pointer. We read the values between the end of stack and the current stack 
110    // pointer, which are all valid locations.
111    //
112    // In the case of interruption, there could be false negatives where we don't see
113    // stack that was used "behind" our cursor, however this is fine because we do not
114    // rely on this number for any safety-bearing contents, only as a metrics estimate.
115    //
116    // [rust reference]: https://doc.rust-lang.org/reference/inline-assembly.html#r-asm.rules.stack-below-sp
117    unsafe {
118        asm!(
119            "0:",
120            "cmp sp, {ptr}",
121            "bls 1f",
122            "ldr {value}, [{ptr}]",
123            "cmp {value}, {paint}",
124            "bne 1f",
125            "add {ptr}, #4",
126            "b 0b",
127            "1:",
128            ptr = inout(reg) stack().end => res,
129            value = out(reg) _,
130            paint = in(reg) STACK_PAINT_VALUE,
131            options(nostack, readonly)
132        )
133    };
134    // Safety: res >= stack.end() because we start at stack.end()
135    (unsafe { res.byte_offset_from_unsigned(stack().end) }) as u32
136}
137
138/// Finds the number of bytes that have not been overwritten on the stack since the last repaint using binary search.
139///
140/// In other words: shows the worst case free stack space since [repaint_stack] was last called.
141///
142/// Uses binary search to find the point after which the stack is written.
143/// This will assume that the stack is written in a consecutive fashion.
144/// Writing somewhere out-of-order into the painted stack will not be detected.
145///
146/// Runs in *O(log(n))* where *n* is the size of the stack.
147///
148/// **Danger:** if the current (active) stack contains the [STACK_PAINT_VALUE] this computation may be very incorrect.
149///
150/// # Safety
151/// This function aliases the inactive stack, which is considered to be Undefined Behaviour.
152/// Do not use if you care about such things.
153pub unsafe fn stack_painted_binary() -> u32 {
154    // Safety: we should be able to read anywhere on the stack using this,
155    // but this is considered UB because we are aliasing memory out of nowhere.
156    // Will probably still work though.
157    let slice = unsafe {
158        &*core::ptr::slice_from_raw_parts(stack().end, current_stack_free() as usize / 4)
159    };
160    (slice.partition_point(|&word| word == STACK_PAINT_VALUE) * size_of::<u32>()) as u32
161}