Page 104 - The Art of Designing Embedded Systems
P. 104
Firmware Musings 91
maybe infrequently crash in horrible ways. And RAM is still an expensive
resource, so erring on the side of safety drives recurring costs up.
With an RTOS the problem is multiplied, since every task has its own
stack.
It’s feasible, though tedious, to compute stack requirements when
coding in assembly language by counting calls and pushes. C-and even
worse, C++-obscures these details. Runtime calls further distance our
understanding of stack use. Recursion, of course, can blow stack require-
ments sky-high.
Any of a number of problems can cause the stack to grow to the point
where the entire system crashes. It’s tough to go back and analyze the fail-
ure after the crash, as the program will often write all over itself or the vari-
ables, removing all clues.
The best defense is a strong offense. Odds are your stack estimate
will be wrong, so instrument the code from the very beginning so you’ll
know, for sure, just how much stack is needed.
In the startup code or whenever you define a task, fill the task’s stack
with a unique signature such as Ox55AA (Figure 5-3). Then, probe the
stacks occasionally using your debugger and see just how many of the as-
signed locations have been used (the Ox55AA will be gone).
Knowledge is power.
Also consider building a stack monitor into your code. A stack mon-
itor is just a few lines of assembly language that compares the stack pointer
+- Top
FIGURE 5-3 Proactively fill the stack with Ox55AA to find overrun prob-
lems. Note that the lower three words have been unused.

