In development. It changes without notice.
Topic
Platform Memory & Errors
Large blocks of memory, the record of an allocation that failed, names of errors, and where the compiler places a function or a variable.
What a running board reports of itself is in Diagnostics.
- See also
- Diagnostics, RTOS Facade
Files | |
| file | src/ |
| Compiler placement attributes (IRAM / RTC memory) with native fallbacks. | |
| file | src/ |
| Platform error-code to human-readable name helper. | |
| file | src/ |
| Platform error-code to human-readable name helper. | |
| file | src/ |
| Allocation-failure hook and ring-buffer implementation. | |
| file | src/ |
| Permanent recorder for failed heap allocations. | |
| file | src/ |
| Heap allocation facade with PSRAM-aware helpers. | |
| file | src/ |
| Replaceable nothrow allocation functions that really return nullptr. | |
| file | src/ |
| Contract note for the replaceable nothrow allocation functions. | |
Classes | |
| struct | kleidos:: |
| One recorded allocation failure. More about kleidos:: | |
| class | kleidos:: |
| Marks one allocation attempt that still has a fallback to try. More about kleidos:: | |
| struct | kleidos:: |
| Deleter for makeInternal objects — destroy, then freeInternal. More about kleidos:: | |
| struct | kleidos:: |
| Deleter for makeInternalArray blocks. More about kleidos:: | |
| struct | kleidos:: |
| Deleter for objects built by makeLarge — destroy, then freeLarge. More about kleidos:: | |
| struct | kleidos:: |
| Deleter for makeLargeArray blocks (trivially destructible elements). More about kleidos:: | |
Macros | |
| #define | KLEIDOS_ |
| Place a function or datum in IRAM on target; expands to nothing on host. | |
| #define | KLEIDOS_ |
| Place constant data in internal DRAM on target (default .rodata lives in flash and is read through the cache); expands to nothing on host. Pair with KLEIDOS_ | |
| #define | KLEIDOS_ |
| Place data in RTC slow memory so it survives deep sleep; no-op on host. | |
| #define | KLEIDOS_ |
| Like KLEIDOS_ | |
| #define | KLEIDOS_ |
| Define an external-RAM-resident global, proving at compile time that its value-initialized image is all-zero bytes. | |
Typedefs | |
| using | kleidos:: |
| Native-test hook: signature of the whole-heap allocation observer. | |
| template<typename T> | |
| using | kleidos:: |
| Owning handle to a makeInternal object (internal SRAM, correctly freed). | |
| template<typename T> | |
| using | kleidos:: |
| Owning handle to a makeInternalArray buffer. | |
| template<typename T> | |
| using | kleidos:: |
| Owning handle to a makeLarge object (PSRAM-preferred, correctly freed). | |
| template<typename T> | |
| using | kleidos:: |
| Owning handle to a makeLargeArray buffer. | |
Functions | |
| const char * | kleidos:: |
| Map a platform error code to a static, human-readable string. | |
| void | kleidos:: |
| Native-test hook: drive the recorder exactly as the allocator hook does. | |
| bool | kleidos:: |
| Install the allocation-failure hook. | |
| uint32_t | kleidos:: |
| Total number of allocation failures seen since boot. | |
| uint32_t | kleidos:: |
| Number of records currently retained in the ring. | |
| bool | kleidos:: |
| Read one retained record, oldest first. | |
| void | kleidos:: |
| Drop every retained record and reset the failure counter. | |
| int & | kleidos:: |
| Native-test hook: remaining large allocations allowed to succeed. | |
| void | kleidos:: |
| Native-test hook: install the large-allocation budget. | |
| size_t & | kleidos:: |
| Native-test hook: widest single block the host allocator will grant. | |
| void | kleidos:: |
| Native-test hook: install the widest grantable block. | |
| bool | kleidos:: |
Native-test hook: is size wider than the injected block ceiling? | |
| bool | kleidos:: |
| Native-test hook: charge one large allocation against the injectors. | |
| AllocObserver & | kleidos:: |
| Native-test hook: the installed allocation observer (null = off). | |
| void | kleidos:: |
| Native-test hook: install (or clear with nullptr) the observer. | |
| void | kleidos:: |
| Native-test hook: report one acquire / release to the observer. | |
| size_t & | kleidos:: |
| Native-test hook: size of the emulated PSRAM pool, in bytes. | |
| size_t & | kleidos:: |
| Native-test hook: largest block the emulated PSRAM pool still serves. | |
| uint32_t & | kleidos:: |
| Native-test hook: emulated PSRAM allocator calls issued since the last setTestPsram. | |
| void | kleidos:: |
| Native-test hook: install the emulated PSRAM pool and zero its counter. | |
| size_t | kleidos:: |
| Return the total PSRAM capacity in bytes. | |
| size_t | kleidos:: |
| Return the free PSRAM in bytes. | |
| bool | kleidos:: |
| True when usable PSRAM is present. | |
| void * | kleidos:: |
| Allocate from PSRAM (SPIRAM, 8-bit). | |
| void * | kleidos:: |
| Allocate a large buffer, preferring PSRAM and falling back to internal heap. | |
| void * | kleidos:: |
| Allocate a large buffer with an explicit alignment, PSRAM-preferred. | |
| void | kleidos:: |
| Free a buffer returned by allocLarge() or allocPsram(). | |
| void * | kleidos:: |
| Allocate a block that must stay in INTERNAL SRAM. | |
| void | kleidos:: |
| Free a buffer returned by allocInternal. | |
| template<typename T, typename... Args> | |
| InternalPtr< T > | kleidos:: |
Construct one T in INTERNAL SRAM, never throwing. | |
| template<typename T> | |
| InternalArrayPtr< T > | kleidos:: |
Allocate an uninitialized array of count scalar T pinned to INTERNAL SRAM. | |
| template<typename T, typename... Args> | |
| LargePtr< T > | kleidos:: |
Construct one T in a PSRAM-preferred block, never throwing. | |
| template<typename T> | |
| LargeArrayPtr< T > | kleidos:: |
Allocate an uninitialized array of count trivially-destructible T in a PSRAM-preferred block. | |
Variables | |
| constexpr uint32_t | kleidos:: |
| Number of failures retained; the oldest is overwritten first. | |
| constexpr uint32_t | kleidos:: |
| Bit position of MALLOC_ | |
| constexpr uint32_t | kleidos:: |
| Bit position of MALLOC_ | |
| constexpr uint32_t | kleidos:: |
| Capability mask carried by every PSRAM-preferred attempt. | |
| constexpr uint32_t | kleidos:: |
| Capability mask of the fallback attempt. | |
| constexpr size_t | kleidos:: |
| Alignment heap_ | |
Macro Definition Documentation
KLEIDOS_ EXT_ RAM_ BSS_ DEFINE #
Define an external-RAM-resident global, proving at compile time that its value-initialized image is all-zero bytes.
The ONLY supported spelling of an external-BSS definition: the raw placement attribute is private (KLEIDOS_) so a hand-written definition cannot skip the check, and the macro hardcodes the {} initializer so supplying one is a syntax error. It places into external RAM only on a build that actually has an external BSS segment, and expands to a plain definition everywhere else — the host, every board without PSRAM, and every board that has PSRAM but leaves CONFIG_
- Why the check exists
- .ext_ram.bss is a (NOLOAD) output section (esp_
system/ ld/ esp32/ sections.ld.in), yet the compiler still emits the input section as PROGBITS carrying real initializer bytes. The linker silently DISCARDS them and esp_ psram_ bss_ init() memsets the span to zero, so a global whose static image is not all-zero boots as all zeros — on the external-BSS board only, with no diagnostic from either tool.
GCC has exactly the predicate needed ("only zero initializers are allowed in
section"), but it fires only for section names beginning .bss., and IDF's EXT_
- Warning
- SECURITY: external RAM leaves the die. Only list-surface plaintext may be tagged — display names, usernames, origin domains, menu row descriptors. Never a password, PIN, passphrase, vault key, derived sub-key, device secret or TOTP shared secret.
- Note
- Silent no-op without CONFIG_
SPIRAM_ ALLOW_ BSS_ SEG_ EXTERNAL_ MEMORY=y. That option is set on the Core2 v1.3 only (the one board whose internal DRAM cannot hold the capacity-scaled view caches); the other PSRAM boards keep those statics internal on purpose — PSRAM reads are cache-mediated and far slower than DRAM for UI-hot row state, and they have tens of kilobytes of DRAM slack. A change to the option reaches a build only once its generated sdkconfig files are deleted. -
.ext_ram.bss is zero-filled by esp_
psram_ bss_ init() at boot, AFTER esp_ psram_ init(). Nothing defined here may be read by early-boot code or a static constructor that runs before PSRAM is up. It is ordinary RAM otherwise: it still has to be zeroized on the relock paths. - used on the twin is load-bearing: without it the unreferenced twin is discarded before the check runs and the guard disappears from -Og upward (device builds use -Os). The error is unsuppressible — it survives -w and -fpermissive — and needs no -Werror.
- The twin is armed on every device build, not only the boards that place into PSRAM, so the mistake is caught on whichever variant is at hand.
- Blind spot by design: a type with a non-constexpr user-provided constructor is accepted even if it sets non-zero fields. That is correct — such an object is dynamically initialized long after the PSRAM memset. A constexpr constructor yields a static image and IS checked.
- GCC-specific. Re-verify with a good/bad pair after a toolchain bump.
- Parameters
-
Name Meaning name Identifier of the global being defined. ... Its type, variadic so template-ids containing commas (e.g. std::array<T, N>) need no alias.
Typedef Documentation
AllocObserver #
Native-test hook: signature of the whole-heap allocation observer.
- Parameters
-
Name Meaning ptr Block just handed out, or just about to be released. size Size in bytes on an acquire; ignored on a release. acquired True when the block was acquired, false when released.
Function Documentation
allocInternal() #
Allocate a block that must stay in INTERNAL SRAM.
The explicit counterpart to allocLarge — use it when the block carries key material or credential plaintext, so "this never goes to PSRAM" is a greppable property of the call site rather than an unwritten assumption.
- Parameters
-
Name Meaning size Number of bytes to allocate.
- Returns
- Pointer to internal memory, or nullptr on allocation failure.
- See also
- allocLarge
allocLarge() #
Allocate a large buffer, preferring PSRAM and falling back to internal heap.
The PSRAM attempt is marked as having a fallback, so a miss is not entered in the allocation-failure ring: the block is about to be served from the internal heap, and a record that names a byte size which was satisfied is noise in the one instrument that reports real exhaustion.
- Parameters
-
Name Meaning size Number of bytes to allocate.
- Returns
- Pointer to allocated memory, or nullptr on allocation failure.
allocLargeAligned() #
Allocate a large buffer with an explicit alignment, PSRAM-preferred.
heap_
The PSRAM attempt carries the same fallback marking as allocLarge.
- Parameters
-
Name Meaning size Number of bytes to allocate. alignment Required alignment in bytes (a power of two).
- Returns
- Pointer to allocated memory, or nullptr on allocation failure.
allocPsram() #
Allocate from PSRAM (SPIRAM, 8-bit).
Issues no allocator call at all when the board reports no PSRAM: the request could only fail, and ESP-IDF reports every failed heap_
- Parameters
-
Name Meaning size Number of bytes to allocate.
- Returns
- Pointer to allocated PSRAM, or nullptr when PSRAM is absent or the allocation fails.
begin() #
Install the allocation-failure hook.
Idempotent; call once during startup, as early as possible so driver and radio bring-up allocations are already covered.
- Return values
-
Value Meaning true Hook is installed (or was already). false Registration was refused, or this is the native build.
failureCount() #
Total number of allocation failures seen since boot.
Counts every failure, including those whose record has since been overwritten, and saturates instead of wrapping.
- Returns
- Failure count; 0 on the native build.
freeInternal() #
Free a buffer returned by allocInternal.
- Parameters
-
Name Meaning ptr Pointer to free; nullptr is a no-op.
freeLarge() #
Free a buffer returned by allocLarge() or allocPsram().
- Parameters
-
Name Meaning ptr Pointer to free; nullptr is a no-op.
hasPsram() #
True when usable PSRAM is present.
Deliberately not cached: PSRAM joins the heap allocator during startup, so a value latched by an early allocation would disable external RAM for the whole session. The call walks the registered-heap list, which costs far less than the allocator attempt it replaces.
- Returns
- True when psramSizeBytes() > 0.
injectFailureForTest() #
Native-test hook: drive the recorder exactly as the allocator hook does.
The ESP-IDF hook cannot be reached off-target, which would leave the ring's filtering — the part that decides whether a real failure survives — untested. This feeds the same path with a synthetic failure. Compiled out on device.
- Parameters
-
Name Direction Meaning requestedBytes in Byte count the synthetic failure requested. caps in Requested MALLOC_CAP_* mask. functionName in Heap entry point name to store in the record.
makeInternal() #
Construct one T in INTERNAL SRAM, never throwing.
The secret-bearing counterpart of makeLarge, for an object too big to put on a task stack and too sensitive to put in PSRAM — a decrypted credential record is both. With no arguments the object is VALUE-initialized, so a type that relies on zeroed storage keeps that guarantee.
- Template Parameters
-
Name Meaning T Object type to construct.
- Parameters
-
Name Meaning args Constructor arguments (none ⇒ value-initialization).
- Returns
- Owning handle, or nullptr when the allocation failed.
makeInternalArray() #
Allocate an uninitialized array of count scalar T pinned to INTERNAL SRAM.
The secret-bearing counterpart of makeLargeArray — use it for crypto scratch that receives decrypted record content (passwords, notes, TOTP secrets), so the "never PSRAM" property is visible at the call site and survives a future refactor.
- Template Parameters
-
Name Meaning T Trivially destructible element type.
- Parameters
-
Name Meaning count Element count.
- Returns
- Owning handle, or nullptr when the allocation failed.
makeLarge() #
Construct one T in a PSRAM-preferred block, never throwing.
Drop-in for std::
- Warning
- SECURITY: the block may land in external RAM. Only list-surface plaintext may be routed here — never passwords, PINs, key material or TOTP secrets. Use allocInternal for those. Wiping is still the caller's job: PSRAM residency does not relax zeroization.
- Template Parameters
-
Name Meaning T Object type to construct.
- Parameters
-
Name Meaning args Constructor arguments (none ⇒ value-initialization).
- Returns
- Owning handle, or nullptr when the allocation failed.
makeLargeArray() #
Allocate an uninitialized array of count trivially-destructible T in a PSRAM-preferred block.
Drop-in for std::
- Warning
- SECURITY: same allow-list as makeLarge — the buffer may live in external RAM. Wipe secret-bearing content before the handle dies.
- Template Parameters
-
Name Meaning T Trivially destructible element type.
- Parameters
-
Name Meaning count Element count.
- Returns
- Owning handle, or nullptr when the allocation failed.
name() #
Map a platform error code to a static, human-readable string.
- Parameters
-
Name Meaning code ESP-IDF error code (esp_err_t or errno-style).
- Returns
- Pointer to a static string; returns "native" on the host build.
notifyTestAlloc() #
Native-test hook: report one acquire / release to the observer.
- Parameters
-
Name Meaning ptr Block acquired or released; a null acquire is not reported. size Size in bytes on an acquire. acquired True on an acquire, false on a release.
psramFreeBytes() #
Return the free PSRAM in bytes.
- Returns
- Free PSRAM bytes; 0 when PSRAM is absent (the emulated pool's remaining run on the native build).
psramSizeBytes() #
Return the total PSRAM capacity in bytes.
- Returns
- Total PSRAM size in bytes; 0 when PSRAM is absent (the emulated pool size on the native build).
recordAt() #
Read one retained record, oldest first.
- Parameters
-
Name Direction Meaning index in Zero-based index into the retained records; 0 is the oldest. out out Receives the record on success; untouched otherwise.
- Return values
-
Value Meaning true indexwas in range andoutwas filled.false indexwas out of range.
recordCount() #
Number of records currently retained in the ring.
- Returns
min(failureCount(), ::.kRecordCapacity)
setTestAllocObserver() #
Native-test hook: install (or clear with nullptr) the observer.
- Parameters
-
Name Meaning observer Observer to notify on every acquire / release, or nullptr.
setTestLargeAllocBudget() #
Native-test hook: install the large-allocation budget.
- Parameters
-
Name Meaning allowed Number of further large allocations to grant before failing them all; -1 disables injection.
setTestLargeAllocLimitBytes() #
Native-test hook: install the widest grantable block.
- Parameters
-
Name Meaning bytes Widest block the host allocator will hand out, for internal and large allocations alike; SIZE_MAXdisables injection.
setTestPsram() #
Native-test hook: install the emulated PSRAM pool and zero its counter.
- Parameters
-
Name Meaning capacityBytes Pool size; 0 models a board without PSRAM. largestBlockBytes Largest block the pool can still serve.
testAllocObserver() #
Native-test hook: the installed allocation observer (null = off).
The block-width injector above can only police what goes through THIS facade. A suite that has to make a claim about MEMORY — "no path asks this heap for more than one flash block" — needs to see the allocations that do not: a std::vector, a std::string, a bare new. So the facade reports every block it hands out to an observer the suite installs, and the suite's own global operator new reports into the same ledger. A gate that cannot see a path is the same defect as a gate that cannot fail.
- Returns
- Reference to the mutable observer slot.
testBlockWidthDenied() #
Native-test hook: is size wider than the injected block ceiling?
The width half of the injection, without the count budget: an internal allocation is charged against the fragmentation model but not against the "next N allocations fail" budget, which exists to steer specific large-allocation failure paths.
- Parameters
-
Name Meaning size Requested block size in bytes.
- Return values
-
Value Meaning true The caller must report an allocation failure. false The block fits the injected ceiling (always so while off).
testLargeAllocBudget() #
Native-test hook: remaining large allocations allowed to succeed.
The host allocator never runs out, so the out-of-memory branches that matter most on a 4 MB board — the ones that decide whether a half-finished vault mutation is reported as durable — would otherwise be unreachable from a unit test. A budget of n >= 0 lets the next n large allocations through and denies every one after that; -1 (the default) disables injection entirely, so suites that never touch it are unaffected. Compiled out on device.
- Returns
- Reference to the mutable budget.
testLargeAllocDenied() #
Native-test hook: charge one large allocation against the injectors.
- Parameters
-
Name Meaning size Requested block size in bytes.
- Return values
-
Value Meaning true The caller must report an allocation failure. false The allocation proceeds (always so while injection is off).
testLargeAllocLimitBytes() #
Native-test hook: widest single block the host allocator will grant.
The count-based budget above models an exhausted heap; this models a FRAGMENTED one, which is the state a PSRAM-less board actually reaches: the free total is comfortable, but no single run is wide enough for a capacity-sized block, so the same request fails forever while smaller ones keep succeeding. Any request above the limit is denied; the default SIZE_MAX grants every size, so suites that never touch it are unaffected. Compiled out on device.
The limit covers allocInternal as well as allocLarge, because fragmentation is a property of the DRAM heap and both come out of it on a board without PSRAM. Gating only the PSRAM-preferred path would leave the largest block on a path invisible to the suite that measures that path — which is exactly what hid the whole-vault re-encryption's internal crypto scratch, the widest request on the whole index path, from the capacity harness.
- Returns
- Reference to the mutable limit, in bytes.
testPsramAttemptCount() #
Native-test hook: emulated PSRAM allocator calls issued since the last setTestPsram.
Counts the calls the facade makes, which is what proves a PSRAM-less board spends nothing on an attempt that cannot succeed. Compiled out on device.
- Returns
- Reference to the mutable counter.
testPsramCapacityBytes() #
Native-test hook: size of the emulated PSRAM pool, in bytes.
Zero — the default — models the boards built without PSRAM, where hasPsram is false and the external attempt must never be issued. Compiled out on device.
- Returns
- Reference to the mutable pool size.
testPsramLargestBlockBytes() #
Native-test hook: largest block the emulated PSRAM pool still serves.
The pool is modeled as one contiguous run, so this doubles as its free size. A request above it is denied exactly as heap_
- Returns
- Reference to the mutable limit, in bytes.
Variable Documentation
kFallbackCaps #
Capability mask of the fallback attempt.
Byte-addressable with no residency requirement, which lets the allocator use its own preference order — internal DRAM first. A failure with this mask is the real exhaustion the failure ring exists to report.
kPsramCaps #
Capability mask carried by every PSRAM-preferred attempt.
Spelled from bit positions so the host build names the same mask the device does — a native test can assert on the exact value the debug console's allocation-failure record would print. The assert below pins it to the ESP-IDF macros.