Repository navigation
Description
Problem
Large stack scratch buffers silently overflow the stack on small-RAM targets. E.g. drawPolygon's Exact kernel needs a ~989 B frame on AVR; an Uno sketch with a 16x16 canvas has ~950 B free stack, and it corrupts memory (verified in simavr). Moving scratch to function statics / SingletonThreadLocal doesn't scale: storage is per template instantiation (drawPolygon alone has 4 kernel instantiations on AVR → ~3.2 KB of .bss).
A design investigation compared 7 strategies (stack + tiered defaults, static macro, thread-local/Singleton, single-lease arena, heap per call, caller-provided scratch, side stack). Measured AVR costs (989 B scratch, avr-gcc 7.3 -Os, gc-sections):
| backing | AVR flash | AVR bss | peak-RAM model |
|---|---|---|---|
| stack | +16 | 0 | frame |
static / Singleton |
~0 / +18 | per instantiation | sum |
| malloc per call | +612 | heap | live users |
| retained grow-only vector | +1148 | heap forever | sum |
| side stack (bump + check + pop) | +34 (+22 with high-water mark) | capacity | deepest nesting |
Proposed solution: fl::scratch<T> backed by a fixed-capacity side stack
New fl/stl/scratch.h (+ .cpp.hpp holding the non-template arena so --gc-sections drops it when unused):
#ifndef FL_SCRATCH_STACK_BYTES // 0 => fl::scratch<T> is a plain stack object
# if FL_PLATFORM_HAS_SMALL_STACK && !FASTLED_MULTITHREADED
# define FL_SCRATCH_STACK_BYTES <platform default>
# else
# define FL_SCRATCH_STACK_BYTES 0
# endif
#endif
template <typename T> class scratch; // non-copyable, non-movable, T trivially destructible
// explicit operator bool() -> false only when the side stack is exhausted
// operator* / operator->
fl::size scratch_high_water();- Capacity 0 →
T mValue;member (zero overhead; big/multithreaded targets). - Capacity > 0 → aligned bump of a 16-bit top index in a static arena; destructor restores the saved top; debug assert on non-LIFO release;
static_assert(sizeof(T) <= FL_SCRATCH_STACK_BYTES); exhaustion →false+FL_WARNin debug (callers no-op). Never grows (cf. the use-after-realloc bug recorded inStbvTempBuffer). - Not ISR-safe: documented as forbidden in ISRs.
- Platform defaults: AVR / LPC804 / Teensy LC / nRF51 / STM32G03x / low-density F1 → 0 (keep stack; opt in with
-DFL_SCRATCH_STACK_BYTES=N); ESP8266 → ~4.5 KB (fixed 4 KB loop stack, plenty of.bss). - Tests on host with the side-stack backend forced: nested LIFO, exhaustion returns false without writing past capacity, high-water mark, non-LIFO debug assert, compile-time size check.
Follow-ups: drawPolygon adoption and other large stack users (separate issues).
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
feat(stl): fl::scratch<T> fixed-capacity side stack for large scratch…