Stack high-water mark
Paint a task stack and find how much of it was never touched. An easy embedded C problem (Inside an RTOS kernel), run and graded in the browser.
easy · Inside an RTOS kernel · rtos · stack · debugging
To find out how much stack a task really needs, kernels fill the stack with a known pattern when the task is created, then later count how much of the pattern is still intact. The stack grows down, so the untouched part is at the low end, starting at stack[0].
stack_paint(stack, words): fill every word withSTACK_FILL.stack_unused(stack, words): count how many words fromstack[0]upwards still hold the pattern, stopping at the first one that does not. This is the high-water mark: the least free space the task has had.
A used word can happen to hold the value 0xA5A5A5A5, so do not count matching words above the first changed one.
Starter code
void stack_paint(uint32_t *stack, int words) {
for (int i = 0; i < words; i++) stack[i] = STACK_FILL;
}
int stack_unused(const uint32_t *stack, int words) {
int n = 0;
for (int i = 0; i < words; i++)
if (stack[i] == STACK_FILL) n++;
return n;
}Example tests
The mark only moves down
uint32_t s[32];
stack_paint(s, 32);
printf("%d", stack_unused(s, 32));
use(s, 32, 10);
printf(" %d", stack_unused(s, 32));
use(s, 32, 6);
printf(" %d", stack_unused(s, 32));
use(s, 32, 31);
printf(" %d\n", stack_unused(s, 32));Expected output:
32 22 22 1A local that holds the fill value
uint32_t s[32];
stack_paint(s, 32);
use(s, 32, 20);
s[20] = STACK_FILL; // a variable that happens to hold the pattern
printf("%d\n", stack_unused(s, 32));Expected output:
12Learn it first
- Inside an RTOS kernel · Task control blocks, ready lists, the tick and the context switch.
More Inside an RTOS kernel problems
- A new task's first stack frame · Build the stack a task needs so that the first switch to it starts it at its entry point.
- The context switch · Save one task's registers on its own stack and restore the next task's, as PendSV does.