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, {ptr}",
85            "bls 1f",
86            "stmia {ptr}!, {{{paint}}}",
87            "b 0b",
88            "1:",
89            ptr = inout(reg) stack().end => _,
90            paint = in(reg) 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/// guarantees, only as a (generally accurate but non-guaranteed) measurement.
104///
105/// Runs in *O(n)* where *n* is the size of the stack.
106#[inline(never)]
107pub fn stack_painted() -> u32 {
108    let res: *const u32;
109    // SAFETY: As per the [rust reference], inline asm is allowed to look below the
110    // stack pointer. We read the values between the end of stack and the current stack
111    // pointer, which are all valid locations.
112    //
113    // In the case of interruption, there could be false negatives where we don't see
114    // stack that was used "behind" our cursor, however this is fine because we do not
115    // rely on this number for any safety-bearing contents, only as a metrics estimate.
116    //
117    // [rust reference]: https://doc.rust-lang.org/reference/inline-assembly.html#r-asm.rules.stack-below-sp
118    unsafe {
119        asm!(
120            "0:",
121            "cmp sp, {ptr}",
122            "bls 1f",
123            "ldr {value}, [{ptr}]",
124            "cmp {value}, {paint}",
125            "bne 1f",
126            "adds {ptr}, #4",
127            "b 0b",
128            "1:",
129            ptr = inout(reg) stack().end => res,
130            value = out(reg) _,
131            paint = in(reg) STACK_PAINT_VALUE,
132            options(nostack, readonly)
133        )
134    };
135    // Safety: res >= stack.end() because we start at stack.end()
136    (unsafe { res.byte_offset_from_unsigned(stack().end) }) as u32
137}
138
139/// Finds the number of bytes that have not been overwritten on the stack since the last repaint using binary search.
140///
141/// In other words: shows the worst case free stack space since [repaint_stack] was last called.
142///
143/// Uses binary search to find the point after which the stack is written.
144/// This will assume that the stack is written in a consecutive fashion.
145/// Writing somewhere out-of-order into the painted stack will not be detected.
146///
147/// Runs in *O(log(n))* where *n* is the size of the stack.
148///
149/// **Danger:** if the current (active) stack contains the [STACK_PAINT_VALUE] this computation may be very incorrect.
150///
151/// # Safety
152/// This function aliases the inactive stack, which is considered to be Undefined Behaviour.
153/// Do not use if you care about such things.
154pub unsafe fn stack_painted_binary() -> u32 {
155    // Safety: we should be able to read anywhere on the stack using this,
156    // but this is considered UB because we are aliasing memory out of nowhere.
157    // Will probably still work though.
158    let slice = unsafe {
159        &*core::ptr::slice_from_raw_parts(stack().end, current_stack_free() as usize / 4)
160    };
161    (slice.partition_point(|&word| word == STACK_PAINT_VALUE) * size_of::<u32>()) as u32
162}