Skip to main content

nros_node/executor/
storage.rs

1//! Per-entry [`Executor`](super::spin::Executor)
2//! storage.
3//!
4//! The executor's sized tables (callback table + arena + scheduling-context
5//! tables + the node/session/dispatch tables) used to be inline fields sized by
6//! build-time consts baked into `nros-node` — one size for every entry sharing a
7//! compiled `nros-node`, and, worse, a size that every function MOVING an
8//! `Executor` had to make room for on its stack. Here the ENTRY supplies its own
9//! storage, sized to its topology, so a fat native entry and a lean embedded
10//! entry in one workspace each get the right size with no workspace-global env,
11//! and the `Executor` VALUE stays a small fixed header.
12//!
13//! Per the "C/C++ is a thin wrapper of Rust" principle the PUBLIC API stays
14//! generic-free: the entry hands a raw, 8-aligned `&mut [MaybeUninit<u64>]` backing
15//! (sized via [`executor_storage_u64_len`]); `nros-node` carves it privately into
16//! the typed sub-slices ([`carve`]). The only `unsafe` is that carve, validated
17//! against the `#[repr(C)]` reference [`ExecutorStorage`] layout by unit test.
18
19use core::{
20    alloc::Layout,
21    mem::{MaybeUninit, align_of, needs_drop, size_of},
22    ops::{Deref, DerefMut},
23};
24
25use super::{
26    arena::CallbackMeta,
27    monitor::{AliveSlot, MAX_VIOLATIONS, Violation},
28    node_record::NodeRecord,
29    sched_context::{SchedContext, SchedContextId, SporadicState},
30    spin::{ComponentSlot, MAX_REMAPS, RemapRule},
31    types::SlotTag,
32};
33use crate::session::ConcreteSession;
34
35/// Issue 1812 — the parameter services' carved home. A zero-sized stand-in
36/// where the services are not compiled, so the region costs nothing there and
37/// `carve` still has one type to place.
38#[cfg(feature = "param-store")]
39pub(crate) type ParamHome = crate::param_store::ParamHome;
40#[cfg(not(feature = "param-store"))]
41pub(crate) type ParamHome = ();
42
43#[cfg(feature = "alloc")]
44type SporadicAtomic = (
45    portable_atomic_util::Arc<super::sched_context::AtomicSporadicState>,
46    super::spin::OpaqueTimerHandle,
47);
48
49/// phase-272 — `(node name, namespace, sched context, rank)`, keyed by the
50/// node's fully-qualified identity. phase-509 P2 -- the rank (0 = most urgent,
51/// the contract's, normalised by codegen) rides in what was the tuple's tail
52/// padding, so the entry is no larger.
53pub(crate) type NodeSchedEntry = (
54    heapless::String<64>,
55    heapless::String<64>,
56    SchedContextId,
57    u8,
58);
59/// phase-273 — [`NodeSchedEntry`] plus the callback-group name that narrows it.
60pub(crate) type GroupSchedEntry = (
61    heapless::String<64>,
62    heapless::String<64>,
63    heapless::String<32>,
64    SchedContextId,
65);
66/// Issue 0436 — `(rmw name, locator)` for one extra session.
67pub(crate) type ExtraSessionId = (heapless::String<32>, heapless::String<128>);
68/// Phase 228.C — one callback-group name in a sched task executor's filter.
69pub(crate) type GroupName = heapless::String<32>;
70
71/// The node half of an [`ActiveGroup`] key: a hash of `(name, namespace)`.
72///
73/// FNV-1a, 64-bit, over `name` then `\0` then the normalised namespace. The
74/// separator matters: without it `("ab", "c")` and `("a", "bc")` hash alike,
75/// and a node name may legally contain any of the namespace's characters.
76///
77/// FNV because the tree already depends on it (heapless's `FnvIndexMap`), it
78/// is `const`-friendly and allocation-free, and this runs on the registration
79/// path of every entity on an MCU. A 64-bit collision across the handful of
80/// nodes in one image is not a risk worth a bigger key: at 32 entries the
81/// probability is around 3e-17.
82///
83/// ONE home, deliberately. Both ends of the comparison call this —
84/// `set_active_groups` hashing what the sched task declared, and `create_entity`
85/// hashing the node an entity belongs to. Two hashers that agree by
86/// inspection is exactly the defect class issue 1172 is filed under.
87pub(crate) fn node_identity_hash(name: &str, namespace: &str) -> u64 {
88    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
89    const PRIME: u64 = 0x0000_0100_0000_01b3;
90    let norm_ns = if namespace.is_empty() { "/" } else { namespace };
91    let mut h = OFFSET;
92    for b in name
93        .as_bytes()
94        .iter()
95        .chain(core::iter::once(&0u8))
96        .chain(norm_ns.as_bytes())
97    {
98        h ^= *b as u64;
99        h = h.wrapping_mul(PRIME);
100    }
101    h
102}
103
104/// One entry of a sched task's active-group filter: `(node identity hash, group)`.
105///
106/// issue 1172 — the filter used to be the GROUP NAME ALONE, which cannot tell
107/// node A's `ctrl` from node B's `ctrl`. Two nodes may legitimately declare the
108/// same group id on different sched tasks and nothing rejects it, so a sched task filter
109/// was admitting entities it did not own. The sibling table for the
110/// sched-context path (`group_sched_table`, `bind_group_sched`) has been
111/// node-qualified all along; only this one was not.
112///
113/// The node half is a HASH of `(name, namespace)` rather than the strings.
114/// Storing them would cost 184 B per entry against this table's 48 B, and the
115/// table is CARVED one entry per node slot — +144 B per slot, which is 4.6 KB
116/// of static executor arena at 32 slots. The group name stays readable because
117/// a refused filter should be able to say WHICH group it refused.
118///
119/// The hash has exactly one home, [`node_identity_hash`], and both ends of the
120/// comparison call it — codegen never hashes anything, it emits plain strings.
121/// A second hasher would be this phase's own defect in a new place.
122pub(crate) type ActiveGroup = (u64, GroupName);
123
124// ============================================================================
125// CarvedVec — a `heapless::Vec` whose capacity lives in the caller's backing
126// ============================================================================
127
128/// A push-only vector over CARVED storage: the elements live in the caller's
129/// backing, the `Executor` holds only a fat pointer and a fill cursor.
130///
131/// phase-409 (issue 0961) — this is the shape phase-271 gave the six sized
132/// tables, generalised so the other nine can use it too. It exists because
133/// `heapless::Vec<T, N>` puts `N * size_of::<T>()` bytes INSIDE the struct, so
134/// every knob that sets an `N` also sets the stack frame of every function that
135/// moves an `Executor`: `MAX_CBS` 14 -> 36 (a handle-count fix) added ~3.7 KiB
136/// to `Executor::open_in`'s prologue on a part whose main thread has 32 KiB in
137/// total.
138///
139/// Deliberately `MaybeUninit<T>` rather than `Option<T>`, for three reasons:
140/// [`as_slice`](Self::as_slice) can hand back the `&[T]` the public
141/// `Executor::nodes()` accessor already returns; `carve` writes NOTHING at open
142/// (the `memclr` in issue 0961's fault was the executor's tables being zeroed);
143/// and the layout matches `heapless::Vec`'s, so the storage cost is the same
144/// bytes in a different place.
145///
146/// Occupied slots are `[0, len)` and IN PUSH ORDER — several callers index by
147/// insertion position (`NodeId` IS an index into `nodes`; `session_idx` is an
148/// index into `extra_sessions`), so this must never gain a `swap_remove`.
149pub(crate) struct CarvedVec<'s, T> {
150    slots: &'s mut [MaybeUninit<T>],
151    len: usize,
152}
153
154impl<'s, T> CarvedVec<'s, T> {
155    /// Wrap carved, UNINITIALISED storage as an empty vector.
156    fn new(slots: &'s mut [MaybeUninit<T>]) -> Self {
157        Self { slots, len: 0 }
158    }
159
160    /// Slots this vector can hold — the entry's sizing, not a build-time const.
161    pub(crate) fn capacity(&self) -> usize {
162        self.slots.len()
163    }
164
165    /// Append `value`, returning it in `Err` when full (`heapless::Vec::push`).
166    pub(crate) fn push(&mut self, value: T) -> Result<(), T> {
167        if self.len == self.capacity() {
168            return Err(value);
169        }
170        self.slots[self.len].write(value);
171        self.len += 1;
172        Ok(())
173    }
174
175    /// Remove and return the OLDEST element (index 0), shifting the rest down
176    /// one so push order is kept. O(len); phase-474 I1's violation ring is its
177    /// one caller, at `MAX_VIOLATIONS` (default 8) slots.
178    pub(crate) fn pop_front(&mut self) -> Option<T> {
179        if self.len == 0 {
180            return None;
181        }
182        // SAFETY: `[0, len)` is initialised; slot 0 is read out exactly once
183        // and then overwritten by the shift (or left outside `[0, len - 1)`).
184        let first = unsafe { self.slots[0].assume_init_read() };
185        let base = self.slots.as_mut_ptr();
186        // SAFETY: both ranges lie inside `slots`; `copy` handles the overlap.
187        unsafe { core::ptr::copy(base.add(1), base, self.len - 1) };
188        self.len -= 1;
189        Some(first)
190    }
191
192    /// Drop every element and reset the cursor.
193    pub(crate) fn clear(&mut self) {
194        let len = core::mem::replace(&mut self.len, 0);
195        if needs_drop::<T>() {
196            for slot in &mut self.slots[..len] {
197                // SAFETY: `[0, len)` was initialised by `push` and is dropped
198                // exactly once — `len` is reset above before this loop runs, so
199                // a panicking `T::drop` cannot make a second pass see it.
200                unsafe { slot.assume_init_drop() };
201            }
202        }
203    }
204
205    /// The initialised prefix.
206    pub(crate) fn as_slice(&self) -> &[T] {
207        // SAFETY: `push` initialises `[0, len)` and nothing shortens `len`
208        // without dropping (see `clear`).
209        unsafe { &*(&self.slots[..self.len] as *const [MaybeUninit<T>] as *const [T]) }
210    }
211
212    /// The initialised prefix, mutably.
213    pub(crate) fn as_mut_slice(&mut self) -> &mut [T] {
214        // SAFETY: as [`as_slice`](Self::as_slice).
215        unsafe { &mut *(&mut self.slots[..self.len] as *mut [MaybeUninit<T>] as *mut [T]) }
216    }
217}
218
219impl<T> Deref for CarvedVec<'_, T> {
220    type Target = [T];
221    fn deref(&self) -> &[T] {
222        self.as_slice()
223    }
224}
225
226impl<T> DerefMut for CarvedVec<'_, T> {
227    fn deref_mut(&mut self) -> &mut [T] {
228        self.as_mut_slice()
229    }
230}
231
232impl<T> Drop for CarvedVec<'_, T> {
233    fn drop(&mut self) {
234        // The backing is the CALLER's memory, so nothing drops these elements
235        // for us — and one of these tables is `extra_sessions`, whose elements
236        // close RMW sessions. A `Drop` impl on the vector (rather than a pass in
237        // `Executor::drop`) keeps the ORDER the inline `heapless::Vec`s had:
238        // `Executor`'s fields drop in declaration order, so the primary
239        // `session` still closes before the extras.
240        self.clear();
241    }
242}
243
244// ============================================================================
245// Layout
246// ============================================================================
247
248/// The typed reference layout the [`carve`] mirrors. `#[repr(C)]` so its field
249/// offsets are the deterministic declaration-order layout the const-fn below
250/// reproduces; a unit test asserts they agree. Only referenced by tests.
251#[cfg(test)]
252#[repr(C)]
253pub(crate) struct ExecutorStorage<
254    const CBS: usize,
255    const SC: usize,
256    const ARENA: usize,
257    const NODES: usize,
258    const PARAMS: usize,
259    const HOMES: usize,
260    const EXTRA: usize = { extra_session_slots(ExecutorSizing::DEFAULT) },
261> {
262    arena: [MaybeUninit<u8>; ARENA],
263    entries: [Option<CallbackMeta>; CBS],
264    sched_contexts: [Option<SchedContext>; SC],
265    sched_context_bindings: [SchedContextId; CBS],
266    sporadic_states: [Option<SporadicState>; SC],
267    #[cfg(feature = "alloc")]
268    sporadic_atomic_states: [Option<SporadicAtomic>; SC],
269    remaps: [Option<RemapRule>; MAX_REMAPS],
270    // phase-409 — the nine that phase-271 left inline.
271    nodes: [MaybeUninit<NodeRecord>; NODES],
272    // Issue 1982 -- one per OTHER backend, at most one per node.
273    extra_sessions: [MaybeUninit<ConcreteSession>; EXTRA],
274    extra_session_ids: [MaybeUninit<ExtraSessionId>; EXTRA],
275    node_sched_table: [MaybeUninit<NodeSchedEntry>; NODES],
276    component_slots: [MaybeUninit<ComponentSlot>; NODES],
277    active_groups: [MaybeUninit<ActiveGroup>; NODES],
278    group_sched_table: [MaybeUninit<GroupSchedEntry>; CBS],
279    monitor_violations: [MaybeUninit<Violation>; MAX_VIOLATIONS],
280    alive_slots: [AliveSlot; SC],
281    slot_tags: [SlotTag; CBS],
282    // phase-382 W3' — the parameter store, LAST.
283    params: [MaybeUninit<nros_params::ParameterSlot>; PARAMS],
284    // issue 1812 — the parameter services' home, after the store.
285    param_home: [MaybeUninit<ParamHome>; HOMES],
286}
287
288/// The typed, mutable sub-slices an [`Executor`](super::spin::Executor) borrows
289/// from a carved backing. Element memory is initialised by [`carve`] for the
290/// `Option`/`SchedContextId` tables; the [`CarvedVec`] tables are handed over
291/// UNINITIALISED and fill on push.
292pub(crate) struct ExecutorSlices<'s> {
293    pub(crate) arena: &'s mut [MaybeUninit<u8>],
294    pub(crate) entries: &'s mut [Option<CallbackMeta>],
295    pub(crate) sched_contexts: &'s mut [Option<SchedContext>],
296    pub(crate) sched_context_bindings: &'s mut [SchedContextId],
297    pub(crate) sporadic_states: &'s mut [Option<SporadicState>],
298    #[cfg(feature = "alloc")]
299    pub(crate) sporadic_atomic_states: &'s mut [Option<SporadicAtomic>],
300    /// Issue 0563 — the SEVENTH sized table. phase-271 moved six of these out
301    /// of `Executor` and into caller-owned storage; the remap table was left
302    /// inline and grew to 6664 bytes of an 11632-byte struct (57%), which is
303    /// what made constructing an executor a ~9.3 KB STACK temporary and
304    /// overflowed the Zephyr Cortex-M main stack in issue 0552.
305    ///
306    /// Issue 1971 -- [`ExecutorSizing::remaps`] slots, the RUNTIME table
307    /// (`--ros-args -r` and hand-declared rules). It was a fixed 16 here,
308    /// 6,464 B on thumbv7em in every backing, once per sched task on a sched-task image,
309    /// holding the launch's rules too; those are now one flash table every
310    /// executor reads (`super::launch_remap`), and bare metal carves 0.
311    pub(crate) remaps: &'s mut [Option<RemapRule>],
312    // phase-409 (issue 0961) — the remaining nine, same reasoning one campaign
313    // later. `MAX_CBS` 14 -> 36 put ~3.7 KiB of `group_sched_table` on the stack
314    // of every function that moves an `Executor`.
315    pub(crate) nodes: CarvedVec<'s, NodeRecord>,
316    pub(crate) extra_sessions: CarvedVec<'s, ConcreteSession>,
317    pub(crate) extra_session_ids: CarvedVec<'s, ExtraSessionId>,
318    pub(crate) node_sched_table: CarvedVec<'s, NodeSchedEntry>,
319    pub(crate) component_slots: CarvedVec<'s, ComponentSlot>,
320    pub(crate) active_groups: CarvedVec<'s, ActiveGroup>,
321    pub(crate) group_sched_table: CarvedVec<'s, GroupSchedEntry>,
322    pub(crate) monitor_violations: CarvedVec<'s, Violation>,
323    /// Alive supervision, one record per SC. Initialised by [`carve`] like the
324    /// SC tables above it: a zeroed record is the correct starting state.
325    pub(crate) alive_slots: &'s mut [AliveSlot],
326    /// phase-476 W0 — one lifetime tag per callback slot, parallel to
327    /// `entries`. Initialised by [`carve`] to the default (generation 0, no
328    /// owner), which is what a never-used slot is.
329    pub(crate) slot_tags: &'s mut [SlotTag],
330    /// phase-382 W3' — the EIGHTH sized table phase-382 planned and the region
331    /// issue 1706 asked for: the parameter store's slots, handed over
332    /// UNINITIALISED. The executor initialises them the first time something
333    /// declares a parameter (`nros_params::ParameterTable::init_in`), so an
334    /// image that carves a store and never declares pays the `.bss` and no
335    /// boot time. Empty when the sizing carves no store, which is every image
336    /// the build does not know to build one ([`ExecutorSizing::params`]).
337    pub(crate) params: &'s mut [MaybeUninit<nros_params::ParameterSlot>],
338    /// Issue 1812 — the parameter SERVICES' home ([`ParamHome`]): one when the
339    /// sizing carves a store, none otherwise. Handed over UNINITIALISED, like
340    /// `params`; `ParamHome::init_in` builds the state in it the first time
341    /// something asks for the store.
342    pub(crate) param_home: &'s mut [MaybeUninit<ParamHome>],
343}
344
345/// Byte offsets of each field within the backing + total size/align. Computed
346/// identically by [`executor_storage_layout`] and [`carve`] (single source of
347/// truth), reproducing `#[repr(C)]` declaration-order layout.
348struct FieldOffsets {
349    arena: usize,
350    entries: usize,
351    sched_contexts: usize,
352    sched_context_bindings: usize,
353    sporadic_states: usize,
354    #[cfg(feature = "alloc")]
355    sporadic_atomic_states: usize,
356    remaps: usize,
357    nodes: usize,
358    extra_sessions: usize,
359    extra_session_ids: usize,
360    node_sched_table: usize,
361    component_slots: usize,
362    active_groups: usize,
363    group_sched_table: usize,
364    monitor_violations: usize,
365    alive_slots: usize,
366    slot_tags: usize,
367    params: usize,
368    param_home: usize,
369    size: usize,
370    align: usize,
371}
372
373/// The placement arithmetic and its data types live in `nros-executor-layout`
374/// so a HOST build script can evaluate them for a target it is not
375/// compiling. Re-exported here because this is where every consumer already
376/// looks, and because `NATIVE` — the only part that names the types — has to
377/// live in the crate that owns them.
378pub use nros_executor_layout::{Counts as RegionCounts, RegionUnit, RegionUnits};
379
380/// What THIS compiler says, for the target it is compiling.
381///
382/// The one thing the shared crate cannot provide: it would have to name the
383/// types, and they live here.
384pub const NATIVE_UNITS: RegionUnits = RegionUnits {
385    callback_meta: unit_of::<Option<CallbackMeta>>(),
386    sched_context: unit_of::<Option<SchedContext>>(),
387    sched_context_id: unit_of::<SchedContextId>(),
388    sporadic_state: unit_of::<Option<SporadicState>>(),
389    #[cfg(feature = "alloc")]
390    sporadic_atomic: unit_of::<Option<SporadicAtomic>>(),
391    #[cfg(not(feature = "alloc"))]
392    sporadic_atomic: RegionUnit { size: 0, align: 1 },
393    remap_rule: unit_of::<Option<RemapRule>>(),
394    node_record: unit_of::<NodeRecord>(),
395    concrete_session: unit_of::<ConcreteSession>(),
396    extra_session_id: unit_of::<ExtraSessionId>(),
397    node_sched_entry: unit_of::<NodeSchedEntry>(),
398    component_slot: unit_of::<ComponentSlot>(),
399    group_name: unit_of::<ActiveGroup>(),
400    group_sched_entry: unit_of::<GroupSchedEntry>(),
401    violation: unit_of::<Violation>(),
402    alive_slot: unit_of::<AliveSlot>(),
403    slot_tag: unit_of::<SlotTag>(),
404    parameter_slot: unit_of::<nros_params::ParameterSlot>(),
405    param_home: unit_of::<ParamHome>(),
406};
407
408/// Publish the backing's TOTAL size as a symbol whose storage size
409/// IS the number, so a build script can recover it from the rlib without running
410/// anything. `nros-sizes-build::extract_sizes` reads exactly this shape, the way
411/// `nros-c` recovers `EXECUTOR_OPAQUE_U64S`.
412///
413/// **The total rather than the per-region units, and that is a decision.** The
414/// units alone would be more robust — they do not vary with the executor knobs,
415/// so a probe cache keyed by (target, features) is correct for them, and the
416/// caller supplies `alloc` and the counts explicitly. But the backing is
417/// `arena + tables`, and `ARENA_SIZE` is DERIVED in this crate's build script
418/// from `MAX_CBS`, `RX_BUF_SIZE` and `ACTION_CLIENTS`. A consumer computing from
419/// units would have to re-implement that derivation — a second implementation,
420/// which is the whole thing this design refuses. So the consumer probes the one
421/// number, and keys its probe directory by the executor env, because unlike the
422/// units this DOES vary with it.
423///
424/// Behind a feature and OFF by default: it is `#[used]`, and a shipped image
425/// should not carry a static that exists only to be measured. The probe enables
426/// it for its own nested build, which is a separate compilation from the linked
427/// one.
428#[cfg(feature = "layout-size-markers")]
429#[used]
430#[unsafe(no_mangle)]
431#[doc(hidden)]
432pub static __NROS_LU_SZ_executor_backing: [u8;
433    crate::executor::backing::EXECUTOR_BACKING_DEFAULT_U64S * 8] =
434    [0u8; crate::executor::backing::EXECUTOR_BACKING_DEFAULT_U64S * 8];
435
436const fn unit_of<T>() -> RegionUnit {
437    RegionUnit {
438        size: size_of::<T>(),
439        align: align_of::<T>(),
440    }
441}
442
443/// Issue 1982 -- extra-session slots for `sizing`: one per node slot at most,
444/// and no more than the image's other backends
445/// ([`crate::config::MAX_EXTRA_SESSIONS`]; 0 for a one-RMW image).
446// The cap is a build constant, `usize::MAX` or 0 on some builds, so the
447// comparison is constant there; it is the one place the cap is applied.
448#[allow(clippy::absurd_extreme_comparisons)]
449pub(crate) const fn extra_session_slots(sizing: ExecutorSizing) -> usize {
450    if crate::config::MAX_EXTRA_SESSIONS < sizing.nodes {
451        crate::config::MAX_EXTRA_SESSIONS
452    } else {
453        sizing.nodes
454    }
455}
456
457/// The counts this build was configured with, for `sizing`.
458/// Issue 2541 -- the callback slots `sizing` carves: its `cbs`, but never more
459/// than the slot masks can name (`MAX_CALLBACK_SLOTS`). A table sized past
460/// one `u64` mask registered a 65th callback and dispatched it through
461/// `1u64 << 64`. Capped HERE, for both the layout and the carve, so the two
462/// agree, every loop over the entries stays within the masks, and the
463/// registration past the capacity is the full table's `ExecutorFull`.
464pub(crate) const fn callback_slots(sizing: ExecutorSizing) -> usize {
465    if sizing.cbs < super::spin::MAX_CALLBACK_SLOTS {
466        sizing.cbs
467    } else {
468        super::spin::MAX_CALLBACK_SLOTS
469    }
470}
471
472const fn counts_for(sizing: ExecutorSizing) -> RegionCounts {
473    RegionCounts {
474        cbs: callback_slots(sizing),
475        sc: sizing.sc,
476        nodes: sizing.nodes,
477        extra_sessions: extra_session_slots(sizing),
478        arena: sizing.arena,
479        remaps: sizing.remaps,
480        violations: MAX_VIOLATIONS,
481        alloc: cfg!(feature = "alloc"),
482        params: sizing.params,
483        param_home: param_homes(sizing),
484    }
485}
486
487/// Issue 1812 — how many parameter-service homes a `sizing` carves: one exactly
488/// when it carves a store. The services are what the store is FOR on an image
489/// that declares parameters, so the two travel together, and an image whose
490/// build knows of no store pays for neither (issue 1702's rule).
491pub(crate) const fn param_homes(sizing: ExecutorSizing) -> usize {
492    if sizing.params > 0 { 1 } else { 0 }
493}
494
495const fn compute_offsets(sizing: ExecutorSizing) -> FieldOffsets {
496    compute_offsets_with(sizing, &NATIVE_UNITS)
497}
498
499/// Adapter over the shared arithmetic: same numbers, named the way `carve`
500/// wants them. The placement itself is `nros_executor_layout::offsets` — one
501/// implementation, so an external evaluation cannot drift from this one.
502///
503/// By reference: the unit table crossed clippy's 256-byte pass-by-value line
504/// when phase-476 W0 added `slot_tag`.
505const fn compute_offsets_with(sizing: ExecutorSizing, units: &RegionUnits) -> FieldOffsets {
506    let o = nros_executor_layout::offsets(counts_for(sizing), *units);
507    FieldOffsets {
508        arena: o.arena,
509        entries: o.entries,
510        sched_contexts: o.sched_contexts,
511        sched_context_bindings: o.sched_context_bindings,
512        sporadic_states: o.sporadic_states,
513        #[cfg(feature = "alloc")]
514        sporadic_atomic_states: o.sporadic_atomic_states,
515        remaps: o.remaps,
516        nodes: o.nodes,
517        extra_sessions: o.extra_sessions,
518        extra_session_ids: o.extra_session_ids,
519        node_sched_table: o.node_sched_table,
520        component_slots: o.component_slots,
521        active_groups: o.active_groups,
522        group_sched_table: o.group_sched_table,
523        monitor_violations: o.monitor_violations,
524        alive_slots: o.alive_slots,
525        slot_tags: o.slot_tags,
526        params: o.params,
527        param_home: o.param_home,
528        size: o.size,
529        align: o.align,
530    }
531}
532
533/// Byte [`Layout`] of the backing, evaluated against a SUPPLIED unit table.
534///
535/// The public half of the split. `executor_storage_layout` is this
536/// with `NATIVE_UNITS`; an external consumer that has recovered the
537/// units for another target (a build script probing an rlib, the way `nros-c`
538/// recovers `EXECUTOR_OPAQUE_U64S`) gets the same arithmetic rather than a
539/// second implementation of it.
540///
541/// The OFFSETS stay private: only `carve` needs them, and it runs in the crate
542/// that owns the types. A consumer sizing a reservation needs the total.
543pub const fn executor_storage_layout_with(sizing: ExecutorSizing, units: RegionUnits) -> Layout {
544    let o = compute_offsets_with(sizing, &units);
545    // SAFETY: as `executor_storage_layout` — `align` is a max of alignments and
546    // `size` is rounded up to it.
547    unsafe { Layout::from_size_align_unchecked(o.size, o.align) }
548}
549
550/// Byte [`Layout`] of the backing a `sizing`-sized executor needs.
551/// Public + non-generic so the macro / FFI can size a raw backing.
552pub const fn executor_storage_layout(sizing: ExecutorSizing) -> Layout {
553    let o = compute_offsets(sizing);
554    // SAFETY: `align` is a power of two (a `max` of `align_of` results) and `size`
555    // is rounded up to it; both are non-zero.
556    unsafe { Layout::from_size_align_unchecked(o.size, o.align) }
557}
558
559/// Number of `u64` words a backing must hold for a `sizing`-sized executor.
560/// `u64` backing is 8-aligned, which covers every field (all `align_of ≤ 8`;
561/// asserted in tests), so the entry never hand-aligns. The macro emits
562/// `[MaybeUninit<u64>; executor_storage_u64_len(sizing)]`.
563pub const fn executor_storage_u64_len(sizing: ExecutorSizing) -> usize {
564    executor_storage_layout(sizing).size().div_ceil(8)
565}
566
567/// Per-entry executor sizing — the entity counts an [`Executor`](super::spin::Executor)
568/// is built to hold. **Public + non-generic** (the "C/C++ is a thin wrapper"
569/// principle): the entry / macro / FFI supplies these as plain `usize`s rather
570/// than as type/const generics C can't name. Used to size + carve the backing.
571///
572/// `cbs` is capped at the executor's callback slot capacity
573/// (`crate::config::CALLBACK_SLOT_CAPACITY`, the width of its slot masks) when
574/// the backing is carved.
575#[derive(Clone, Copy)]
576pub struct ExecutorSizing {
577    /// Callback-table slots (`entries`, the per-entry SC bindings, and the
578    /// per-callback-group sched table). At most
579    /// `crate::config::CALLBACK_SLOT_CAPACITY`.
580    pub cbs: usize,
581    /// Scheduling-context slots (`sched_contexts`, the sporadic state tables
582    /// and alive supervision's per-SC records).
583    pub sc: usize,
584    /// Bump-allocator arena size in bytes.
585    pub arena: usize,
586    /// Node slots. One worst-case extra session, extra-session id,
587    /// node-sched binding, component slot and callback-group filter entry per
588    /// Node, so ONE count covers all six tables (that is the
589    /// upper bound each of them already assumed under `MAX_NODES`).
590    pub nodes: usize,
591    /// Parameter-store slots carved from the backing.
592    ///
593    /// The default is [`nros_params::IMPLIED_STORE_SLOTS`]: the store's full
594    /// `MAX_PARAMETERS` when the build KNOWS the image builds one (the
595    /// contract declares a parameter, the bringup declares `param_services`,
596    /// or the launch seeds a `<param>`), and ZERO otherwise. Zero is not a
597    /// degraded mode: an executor that carved no store and is asked for one
598    /// allocates it from the heap exactly as before, with a named
599    /// refusal if the heap cannot hold it.
600    ///
601    /// Conditional rather than fixed, and that is a measured decision:
602    /// a fixed `MAX_PARAMETERS` region adds the whole
603    /// store (280,832 B on armv7m at the default 32 slots) to every image's
604    /// backing — Rust `EXECUTOR_BACKING`, every C/C++ `rclc_executor_t`, every
605    /// sched task slot — which is the rejected `.bss` static, everywhere.
606    pub params: usize,
607    /// RUNTIME remap-table slots: `--ros-args -r` rules and
608    /// rules a hand-written caller declares with `declare_remap`. The launch
609    /// file's rules are not here (one flash table, `super::launch_remap`).
610    /// The default is [`crate::config::RUNTIME_REMAPS`]
611    /// (`NROS_EXECUTOR_RUNTIME_REMAPS`: 16 on a target with process
612    /// arguments, 0 on bare metal), the same for every tier. A full or absent table is `declare_remap`'s named refusal, never
613    /// a silently dropped rule.
614    pub remaps: usize,
615}
616
617impl ExecutorSizing {
618    /// The build-time default (`MAX_CBS`/`MAX_SC`/`ARENA_SIZE`/`MAX_NODES`
619    /// consts) — the backward-compatible size the `alloc` convenience
620    /// constructors leak.
621    pub const DEFAULT: Self = Self {
622        cbs: crate::config::MAX_CBS,
623        sc: crate::config::MAX_SC,
624        arena: crate::config::ARENA_SIZE,
625        nodes: crate::config::MAX_NODES,
626        params: nros_params::IMPLIED_STORE_SLOTS,
627        remaps: MAX_REMAPS,
628    };
629
630    /// `u64` words a backing must hold for this sizing (see
631    /// [`executor_storage_u64_len`]).
632    pub const fn u64_len(&self) -> usize {
633        executor_storage_u64_len(*self)
634    }
635
636    /// Refuse, at COMPILE time, a sizing whose arena is below
637    /// what this image's declared entities are modelled to need.
638    ///
639    /// For a caller that supplies its own `const` sizing for the image's ONE
640    /// executor (`open_in` over a `static` sized with [`u64_len`](Self::u64_len)),
641    /// so its arena is held to the same model the build-time default is:
642    ///
643    /// ```ignore
644    /// const SIZING: nros::ExecutorSizing = nros::ExecutorSizing { .. };
645    /// const _: () = SIZING.assert_covers_model("SIZING.arena");
646    /// ```
647    ///
648    /// Opt-in, deliberately: an executor that holds a SUBSET of the image (one
649    /// sched task of a sched-task boot) legitimately carries less than the whole model,
650    /// and only its author knows which kind it is. See
651    /// [`arena_oracle`](super::arena_oracle) for the arms and why each is or is
652    /// not checked here.
653    pub const fn assert_covers_model(&self, source: &'static str) {
654        super::arena_oracle::assert_covers_model(self.arena, source)
655    }
656}
657
658/// The exact `#[repr(C)]` byte layout the C/C++ FFI's inline executor buffer must
659/// hold: an [`Executor`](super::spin::Executor)`<'static>` header immediately
660/// followed by a default-sized ([`ExecutorSizing::DEFAULT`]) storage backing.
661///
662/// The FFI keeps the executor inline (heap-free — matching the Rust no-alloc
663/// requirement) and carves its per-entry tables from the SAME buffer's
664/// [`backing`](Self::backing) tail. Because that buffer is **pinned** — the C
665/// caller allocates it, it is initialised in place, and it is only ever reached
666/// through a stable `rclc_executor_t*` (never moved after init) — the resulting
667/// self-borrow (the header's slices pointing into the same struct's tail) is
668/// sound. The FFI probes `size_of` of THIS type (not bare `Executor`) to size
669/// its `_opaque` array, and reinterprets `_opaque` as `*mut ExecutorInlineStorage`
670/// (the executor stays at offset 0, so existing offset-0 accessors are unchanged).
671///
672/// Moving the last nine tables into the backing moves bytes from
673/// `exec` to `backing` and leaves this total roughly where it was; what changes
674/// is the STACK, because the header is what `open_in` builds and returns by
675/// value.
676#[repr(C)]
677pub struct ExecutorInlineStorage {
678    /// The executor, written in place (offset 0) by `from_session_ptr_in`.
679    pub exec: MaybeUninit<super::spin::Executor<'static>>,
680    /// The carved backing the executor's slices borrow (the buffer's tail).
681    ///
682    /// [`INLINE_BACKING_U64S`] words: the image's whole
683    /// executor, or none at all on a sched-task image, whose sched tasks each carve a
684    /// backing of their own size ([`sched_task_sizing`]).
685    pub backing: [MaybeUninit<u64>; INLINE_BACKING_U64S],
686}
687
688/// The sizing an inline backing is carved at: the image's
689/// ([`ExecutorSizing::DEFAULT`]), or `None` on an image whose executors are
690/// sized per sched task ([`crate::config::SCHED_TASK_SIZINGS`] is non-empty). There the
691/// inline backing is EMPTY -- one whole-image backing per sched task context is the
692/// cost this issue removes -- and an executor opened over a context alone
693/// (`rclc_executor_init`, `nros_cpp_init`) is refused, naming the per-sched-task
694/// road, rather than carved short.
695pub const INLINE_SIZING: Option<ExecutorSizing> = if crate::config::SCHED_TASK_SIZINGS.is_empty() {
696    Some(ExecutorSizing::DEFAULT)
697} else {
698    None
699};
700
701/// The inline backing's length in `u64` words.
702pub const INLINE_BACKING_U64S: usize = match INLINE_SIZING {
703    Some(s) => s.u64_len(),
704    None => 0,
705};
706
707/// The [`ExecutorSizing`] one sched task's executor is carved at: its
708/// own callback slots, node slots, arena and declared parameters, and the
709/// image's scheduling-context count. A sched task that declares parameters on an
710/// image that carves no store carves none either (the store is built from
711/// the heap there, as it is for the image's one executor).
712pub const fn sched_task_executor_sizing(t: &crate::config::SchedTaskSizing) -> ExecutorSizing {
713    let store = nros_params::IMPLIED_STORE_SLOTS;
714    ExecutorSizing {
715        cbs: t.cbs,
716        sc: crate::config::MAX_SC,
717        arena: t.arena,
718        nodes: t.nodes,
719        params: match t.params {
720            None => store,
721            Some(n) if n < store => n,
722            Some(_) => store,
723        },
724        // Issue 1971 -- the runtime table is the image's, per executor: the
725        // launch's rules are the shared flash table, not a per-sched-task count.
726        remaps: MAX_REMAPS,
727    }
728}
729
730/// The sizing of the sched task named `name`, `None` when the image
731/// sizes no sched task of that name.
732pub fn sched_task_sizing(name: &str) -> Option<ExecutorSizing> {
733    crate::config::SCHED_TASK_SIZINGS
734        .iter()
735        .find(|t| t.name == name)
736        .map(sched_task_executor_sizing)
737}
738
739/// The backing bytes the `index`-th sched task's executor carves, `0`
740/// past the last sched task. What `nros::sizes::SCHED_TASK_BACKING_SIZE_<i>` publishes to
741/// the C/C++ header.
742pub const fn sched_task_backing_bytes(index: usize) -> usize {
743    let sched_tasks = crate::config::SCHED_TASK_SIZINGS;
744    if index < sched_tasks.len() {
745        sched_task_executor_sizing(&sched_tasks[index]).u64_len() * 8
746    } else {
747        0
748    }
749}
750
751/// The sizing of the
752/// ONE executor a level runner opens per core: every level's callbacks, nodes,
753/// arena and declared parameters, summed over the image's sched tasks (each row of
754/// the sched task table is one level). `None` when the image sizes no sched task.
755pub const fn levels_executor_sizing() -> Option<ExecutorSizing> {
756    let sched_tasks = crate::config::SCHED_TASK_SIZINGS;
757    if sched_tasks.is_empty() {
758        return None;
759    }
760    let store = nros_params::IMPLIED_STORE_SLOTS;
761    let (mut cbs, mut arena, mut nodes, mut params) = (0usize, 0usize, 0usize, 0usize);
762    let mut i = 0;
763    while i < sched_tasks.len() {
764        let t = &sched_tasks[i];
765        cbs += t.cbs;
766        arena += t.arena;
767        nodes += t.nodes;
768        params += match t.params {
769            None => store,
770            Some(n) => n,
771        };
772        i += 1;
773    }
774    // Issue 2041 -- each sched task's arena carries the per-EXECUTOR base overhead
775    // once (`arena_model::BASE_OVERHEAD`), because issue 1970 sized a sched task as
776    // its own executor. The levels share ONE executor, so the base is paid
777    // once: summing it per level handed the island's executor 29,820 B where
778    // the image's own model (`NROS_EXECUTOR_ARENA_BYTES`) is 25,724 -- exactly
779    // the two extra bases. See [`levels_arena_bytes`].
780    let arena = levels_arena_bytes(arena, sched_tasks.len());
781    // One executor dispatches at most `MAX_CALLBACK_SLOTS` slots, which the
782    // image's own counts size (issue 2541, `crate::config::SLOT_WORDS`), and
783    // `callback_slots` caps any table at it.
784    Some(ExecutorSizing {
785        cbs,
786        sc: crate::config::MAX_SC,
787        arena,
788        nodes,
789        params: if params < store { params } else { store },
790        remaps: MAX_REMAPS,
791    })
792}
793
794/// Issue 2041 -- the ONE level executor's arena from the sum of its `levels`
795/// sched tasks' arenas: every sched task's model includes the per-executor base overhead,
796/// and one executor pays it once, so `levels - 1` of them come off. With the
797/// sched tasks partitioning the image's entities this is the image's own model, the
798/// number `NROS_EXECUTOR_ARENA_BYTES` derives to.
799pub(crate) const fn levels_arena_bytes(sched_task_arena_sum: usize, levels: usize) -> usize {
800    let extra = crate::config::arena_model::BASE_OVERHEAD * levels.saturating_sub(1);
801    sched_task_arena_sum.saturating_sub(extra)
802}
803
804/// The backing bytes [`levels_executor_sizing`]
805/// carves, `0` on an image that sizes no sched task. What
806/// `nros::sizes::LEVELS_BACKING_SIZE` publishes to the C/C++ header.
807pub const fn levels_backing_bytes() -> usize {
808    match levels_executor_sizing() {
809        Some(s) => s.u64_len() * 8,
810        None => 0,
811    }
812}
813
814/// Carve an 8-aligned `u64` backing into the typed executor slices.
815///
816/// # Safety
817/// - `backing.len() * 8` must be ≥ `executor_storage_layout(sizing).size()`.
818/// - The returned slices alias `backing`; it must outlive them (the `'s` bound)
819///   and not be otherwise accessed while they live.
820///
821/// The `Option`/binding tables are initialised here (`entries`/SC tables →
822/// `None`, bindings → `SchedContextId(0)`), so the returned `&mut [T]` reference
823/// validly-init memory. The [`CarvedVec`] tables are handed over empty and
824/// UNINITIALISED — nothing reads past their fill cursor.
825pub(crate) unsafe fn carve<'s>(
826    backing: &'s mut [MaybeUninit<u64>],
827    sizing: ExecutorSizing,
828) -> ExecutorSlices<'s> {
829    let ExecutorSizing {
830        cbs: _,
831        sc,
832        arena,
833        nodes: node_slots,
834        params: param_slots,
835        remaps: remap_slots,
836    } = sizing;
837    let cbs = callback_slots(sizing);
838    let extra_slots = extra_session_slots(sizing);
839    let o = compute_offsets(sizing);
840    // Fail-loud on EVERY profile (not `debug_assert!`): embedded release builds
841    // strip debug-assertions, and a backing that is too small is silent memory
842    // corruption — the carved `entries`/`sched_contexts` tables run past the end
843    // of `backing` into whatever .bss follows (e.g. a C carrier's `__nros_c_inst`),
844    // leaving a NULL `drop_fn` that faults in `Executor::drop`. This is exactly
845    // how a STALE config-header mirror (C buffer sized from an out-of-date
846    // `NROS_*_STORAGE_SIZE`) manifested as a `jalr -> 0` on threadx-riscv64 (#131).
847    // Panic here instead, at open, with the two sizes named.
848    assert!(
849        backing.len() * 8 >= o.size,
850        "executor backing too small: {} bytes < {} required — the storage buffer \
851         (NROS_*_STORAGE_SIZE) disagrees with the executor layout; rebuild clean so \
852         the generated config header matches",
853        backing.len() * 8,
854        o.size
855    );
856    let base = backing.as_mut_ptr() as *mut u8;
857
858    // One `CarvedVec` over `$n` slots at byte offset `$at`. No element writes —
859    // the vector starts empty. Expanded inside the `unsafe` block below;
860    // SAFETY there: `compute_offsets` placed `$n` `$ty`s at `$at`, aligned and
861    // inside the asserted `o.size`, and each region is placed exactly once, so
862    // the slices do not alias.
863    macro_rules! carved {
864        ($at:expr, $n:expr, $ty:ty) => {{
865            let p = base.add($at) as *mut MaybeUninit<$ty>;
866            CarvedVec::new(region_slice(p, $n))
867        }};
868    }
869
870    unsafe {
871        // arena — no init needed (MaybeUninit).
872        let arena_s = region_slice(base.add(o.arena) as *mut MaybeUninit<u8>, arena);
873
874        let entries_p = base.add(o.entries) as *mut Option<CallbackMeta>;
875        let mut i = 0;
876        while i < cbs {
877            entries_p.add(i).write(None);
878            i += 1;
879        }
880        let entries_s = region_slice(entries_p, cbs);
881
882        let sc_p = base.add(o.sched_contexts) as *mut Option<SchedContext>;
883        let mut i = 0;
884        while i < sc {
885            sc_p.add(i).write(None);
886            i += 1;
887        }
888        let sched_contexts_s = region_slice(sc_p, sc);
889
890        let bind_p = base.add(o.sched_context_bindings) as *mut SchedContextId;
891        let mut i = 0;
892        while i < cbs {
893            bind_p.add(i).write(SchedContextId(0));
894            i += 1;
895        }
896        let bindings_s = region_slice(bind_p, cbs);
897
898        let sp_p = base.add(o.sporadic_states) as *mut Option<SporadicState>;
899        let mut i = 0;
900        while i < sc {
901            sp_p.add(i).write(None);
902            i += 1;
903        }
904        let sporadic_s = region_slice(sp_p, sc);
905
906        #[cfg(feature = "alloc")]
907        let atomic_s = {
908            let ap = base.add(o.sporadic_atomic_states) as *mut Option<SporadicAtomic>;
909            let mut i = 0;
910            while i < sc {
911                ap.add(i).write(None);
912                i += 1;
913            }
914            region_slice(ap, sc)
915        };
916
917        let remaps_p = base.add(o.remaps) as *mut Option<RemapRule>;
918        let mut i = 0;
919        while i < remap_slots {
920            remaps_p.add(i).write(None);
921            i += 1;
922        }
923        let remaps_s = region_slice(remaps_p, remap_slots);
924
925        let alive_p = base.add(o.alive_slots) as *mut AliveSlot;
926        let mut i = 0;
927        while i < sc {
928            alive_p.add(i).write(AliveSlot::default());
929            i += 1;
930        }
931        let alive_s = region_slice(alive_p, sc);
932
933        let tags_p = base.add(o.slot_tags) as *mut SlotTag;
934        let mut i = 0;
935        while i < cbs {
936            tags_p.add(i).write(SlotTag::default());
937            i += 1;
938        }
939        let tags_s = region_slice(tags_p, cbs);
940
941        // phase-382 W3' — no init: the slots are `MaybeUninit` until the
942        // first declaration initialises them through `ParameterTable::init_in`.
943        let params_s = region_slice(
944            base.add(o.params) as *mut MaybeUninit<nros_params::ParameterSlot>,
945            param_slots,
946        );
947        // issue 1812 — no init either: `ParamHome::init_in` builds it in place.
948        let home_s = region_slice(
949            base.add(o.param_home) as *mut MaybeUninit<ParamHome>,
950            param_homes(sizing),
951        );
952
953        ExecutorSlices {
954            arena: arena_s,
955            entries: entries_s,
956            sched_contexts: sched_contexts_s,
957            sched_context_bindings: bindings_s,
958            sporadic_states: sporadic_s,
959            #[cfg(feature = "alloc")]
960            sporadic_atomic_states: atomic_s,
961            remaps: remaps_s,
962            nodes: carved!(o.nodes, node_slots, NodeRecord),
963            extra_sessions: carved!(o.extra_sessions, extra_slots, ConcreteSession),
964            extra_session_ids: carved!(o.extra_session_ids, extra_slots, ExtraSessionId),
965            node_sched_table: carved!(o.node_sched_table, node_slots, NodeSchedEntry),
966            component_slots: carved!(o.component_slots, node_slots, ComponentSlot),
967            active_groups: carved!(o.active_groups, node_slots, ActiveGroup),
968            group_sched_table: carved!(o.group_sched_table, cbs, GroupSchedEntry),
969            monitor_violations: carved!(o.monitor_violations, MAX_VIOLATIONS, Violation),
970            alive_slots: alive_s,
971            slot_tags: tags_s,
972            params: params_s,
973            param_home: home_s,
974        }
975    }
976}
977
978/// One carved region as a slice — the ONLY way `carve` builds one (issue 1771).
979///
980/// `slice::from_raw_parts_mut` requires an ALIGNED, non-null pointer even for
981/// a zero-length slice, and an empty region's offset is not always aligned:
982/// `nros_executor_layout::offsets` deliberately leaves `off` where it is for a
983/// region with no slots (the parameter store in an image without one, the
984/// atomic sporadic states without `alloc`), so the total does not grow by
985/// padding nothing uses. On thumbv7m that offset is misaligned for
986/// `ParameterSlot`, and the debug precondition check panicked at boot. An
987/// empty region needs no address at all, so it gets a dangling one.
988///
989/// # Safety
990/// For `n > 0`, `p` points at `n` properly aligned `T`s inside the backing
991/// that no other live slice covers.
992unsafe fn region_slice<'s, T>(p: *mut T, n: usize) -> &'s mut [T] {
993    if n == 0 {
994        return &mut [];
995    }
996    // SAFETY: the caller's contract, for a non-empty region.
997    unsafe { core::slice::from_raw_parts_mut(p, n) }
998}
999
1000#[cfg(test)]
1001mod tests {
1002    use nros_params::ParameterServerOps as _; // phase-515 R10 stage 2
1003
1004    use super::*;
1005
1006    /// Issue 2041 -- the level executor pays the per-executor base once. Three
1007    /// sched tasks priced as the reference island's (each with its own base) sum to
1008    /// the image's model plus two bases; the levels arena is the image's.
1009    #[test]
1010    fn the_levels_arena_pays_the_executor_base_once() {
1011        let base = crate::config::arena_model::BASE_OVERHEAD;
1012        let (a, b, c) = (4_080, 5_104, 11_120);
1013        let image_model = a + b + c + base;
1014        let sched_task_sum = (a + base) + (b + base) + (c + base);
1015        assert_eq!(levels_arena_bytes(sched_task_sum, 3), image_model);
1016        assert_eq!(
1017            levels_arena_bytes(a + base, 1),
1018            a + base,
1019            "one level, one base"
1020        );
1021        assert_eq!(levels_arena_bytes(0, 0), 0, "no level, nothing to subtract");
1022    }
1023
1024    /// issue 1197 — the arithmetic must actually READ `units`, not quietly keep
1025    /// calling `size_of::<T>()` behind a parameter it ignores.
1026    ///
1027    /// A parameter that is accepted and unused is exactly how a "data-driven"
1028    /// refactor passes its own tests while delivering nothing: `NATIVE` would
1029    /// still be right, every existing assertion would still hold, and the
1030    /// external consumer this exists for would get the HOST's layout back.
1031    /// So this feeds a table that could not have come from this compiler and
1032    /// checks the answer moves by the amount that table implies.
1033    #[test]
1034    fn the_placement_reads_the_unit_table_it_is_given() {
1035        let sizing = ExecutorSizing {
1036            cbs: 1,
1037            sc: 0,
1038            arena: 0,
1039            nodes: 0,
1040            params: 0,
1041            remaps: MAX_REMAPS,
1042        };
1043        let native = executor_storage_layout_with(sizing, NATIVE_UNITS);
1044
1045        // One region is scaled by `cbs`: `callback_meta`. Grow ONLY it, by a
1046        // multiple of its own alignment so no padding shifts, and the total must
1047        // grow by exactly one element's worth.
1048        let mut fatter = NATIVE_UNITS;
1049        let grown_by = fatter.callback_meta.align * 4;
1050        fatter.callback_meta.size += grown_by;
1051        let widened = executor_storage_layout_with(sizing, fatter);
1052
1053        assert_eq!(
1054            widened.size(),
1055            native.size() + grown_by,
1056            "growing one cbs-scaled unit by {grown_by} must grow the backing by \
1057             the same, or the table is being ignored"
1058        );
1059
1060        // And a table of ZEROES must collapse the tables entirely, leaving only
1061        // the arena. This is the direction that catches a `size_of` still being
1062        // read for some region the parameter was threaded past.
1063        let zeroed = RegionUnits {
1064            callback_meta: RegionUnit { size: 0, align: 1 },
1065            sched_context: RegionUnit { size: 0, align: 1 },
1066            sched_context_id: RegionUnit { size: 0, align: 1 },
1067            sporadic_state: RegionUnit { size: 0, align: 1 },
1068            sporadic_atomic: RegionUnit { size: 0, align: 1 },
1069            remap_rule: RegionUnit { size: 0, align: 1 },
1070            node_record: RegionUnit { size: 0, align: 1 },
1071            concrete_session: RegionUnit { size: 0, align: 1 },
1072            extra_session_id: RegionUnit { size: 0, align: 1 },
1073            node_sched_entry: RegionUnit { size: 0, align: 1 },
1074            component_slot: RegionUnit { size: 0, align: 1 },
1075            group_name: RegionUnit { size: 0, align: 1 },
1076            group_sched_entry: RegionUnit { size: 0, align: 1 },
1077            violation: RegionUnit { size: 0, align: 1 },
1078            alive_slot: RegionUnit { size: 0, align: 1 },
1079            slot_tag: RegionUnit { size: 0, align: 1 },
1080            parameter_slot: RegionUnit { size: 0, align: 1 },
1081            param_home: RegionUnit { size: 0, align: 1 },
1082        };
1083        let arena_only = executor_storage_layout_with(
1084            ExecutorSizing {
1085                cbs: CBS,
1086                sc: SC,
1087                arena: 4096,
1088                nodes: 4,
1089                params: 3,
1090                remaps: MAX_REMAPS,
1091            },
1092            zeroed,
1093        );
1094        assert_eq!(
1095            arena_only.size(),
1096            4096,
1097            "with every unit zero-sized the backing is the arena and nothing else"
1098        );
1099    }
1100
1101    const CBS: usize = crate::config::MAX_CBS;
1102    const SC: usize = crate::config::MAX_SC;
1103    const ARENA: usize = crate::config::ARENA_SIZE;
1104    const NODES: usize = crate::config::MAX_NODES;
1105    const DEFAULT: ExecutorSizing = ExecutorSizing::DEFAULT;
1106    /// phase-382 W3' — a store carved in the layout tests whatever this build
1107    /// implies (`DEFAULT.params` is 0 in a unit-test build: nothing declares a
1108    /// parameter), so the region is placed and checked on every run.
1109    const PARAMS: usize = 3;
1110    const WITH_STORE: ExecutorSizing = ExecutorSizing {
1111        params: PARAMS,
1112        ..DEFAULT
1113    };
1114    /// The build's own default. Its `params` is `nros_params::IMPLIED_STORE_SLOTS`.
1115    const DEFAULT_PARAMS: usize = DEFAULT.params;
1116
1117    #[test]
1118    fn layout_matches_typed_repr_c() {
1119        // The manual const-fn layout must equal the compiler's `#[repr(C)]` layout
1120        // of the typed storage — proof the carve offsets are the real field offsets.
1121        let got = executor_storage_layout(DEFAULT);
1122        let want = Layout::new::<
1123            ExecutorStorage<CBS, SC, ARENA, NODES, DEFAULT_PARAMS, { param_homes(DEFAULT) }>,
1124        >();
1125        assert_eq!(got.size(), want.size(), "size");
1126        assert_eq!(got.align(), want.align(), "align");
1127        // phase-382 W3' — and with a store carved, which is the layout every
1128        // image that declares a parameter links.
1129        let got = executor_storage_layout(WITH_STORE);
1130        let want = Layout::new::<ExecutorStorage<CBS, SC, ARENA, NODES, PARAMS, 1>>();
1131        assert_eq!(got.size(), want.size(), "size with a carved store");
1132        assert_eq!(got.align(), want.align(), "align with a carved store");
1133    }
1134
1135    /// phase-382 W3' — the negative control for the CONDITIONAL region: zero
1136    /// store slots must leave the backing byte-for-byte what it was before the
1137    /// region existed. `nros_executor_layout::offsets` skips the placement
1138    /// entirely at zero (an aligned-up `off` would be padding an image with no
1139    /// store paid for nothing), so the total is the one the seventeen older
1140    /// regions produce on their own — computed here by zeroing the unit, which
1141    /// is the layout the region cannot reach.
1142    #[test]
1143    fn a_backing_that_carves_no_store_does_not_grow() {
1144        let none = ExecutorSizing {
1145            params: 0,
1146            ..DEFAULT
1147        };
1148        let mut no_unit = NATIVE_UNITS;
1149        no_unit.parameter_slot = RegionUnit { size: 0, align: 1 };
1150        no_unit.param_home = RegionUnit { size: 0, align: 1 };
1151        assert_eq!(
1152            executor_storage_layout(none).size(),
1153            executor_storage_layout_with(WITH_STORE, no_unit).size(),
1154            "a backing with no store slots must cost exactly the backing without the region"
1155        );
1156        assert_eq!(
1157            executor_storage_layout(none).align(),
1158            executor_storage_layout_with(WITH_STORE, no_unit).align(),
1159        );
1160        // And a store costs at least its slots, charged to the backing.
1161        let grown =
1162            executor_storage_layout(WITH_STORE).size() - executor_storage_layout(none).size();
1163        assert!(
1164            grown >= PARAMS * size_of::<nros_params::ParameterSlot>(),
1165            "{PARAMS} store slots cost {grown} B, less than {PARAMS} x {} B",
1166            size_of::<nros_params::ParameterSlot>()
1167        );
1168        // The layout's slot IS the store's slot, so a carved table is exactly
1169        // a `ParameterStorage<PARAMS>`'s worth of slots.
1170        assert_eq!(
1171            PARAMS * size_of::<nros_params::ParameterSlot>(),
1172            size_of::<nros_params::ParameterStorage<PARAMS>>()
1173        );
1174    }
1175
1176    /// phase-409 — and the FIELD offsets, one by one. The size/align check above
1177    /// is the one phase-271 shipped, and it does not distinguish a REORDER that
1178    /// happens to pad the same: with sixteen regions instead of seven, "the
1179    /// totals agree" stopped being adequate evidence that `carve` hands out the
1180    /// region it names. A mismatch here is `nodes` being handed
1181    /// `extra_sessions`' memory, which is not a size bug and no total would show.
1182    #[test]
1183    fn every_carved_region_starts_where_repr_c_puts_it() {
1184        type Ref = ExecutorStorage<CBS, SC, ARENA, NODES, PARAMS, 1>;
1185        let o = compute_offsets(WITH_STORE);
1186        macro_rules! same {
1187            ($f:ident) => {
1188                assert_eq!(
1189                    o.$f,
1190                    core::mem::offset_of!(Ref, $f),
1191                    concat!("offset of `", stringify!($f), "`")
1192                );
1193            };
1194        }
1195        same!(arena);
1196        same!(entries);
1197        same!(sched_contexts);
1198        same!(sched_context_bindings);
1199        same!(sporadic_states);
1200        #[cfg(feature = "alloc")]
1201        same!(sporadic_atomic_states);
1202        same!(remaps);
1203        same!(nodes);
1204        same!(extra_sessions);
1205        same!(extra_session_ids);
1206        same!(node_sched_table);
1207        same!(component_slots);
1208        same!(active_groups);
1209        same!(group_sched_table);
1210        same!(monitor_violations);
1211        same!(alive_slots);
1212        same!(slot_tags);
1213        // phase-382 W3' — the store, last.
1214        same!(params);
1215        // issue 1812 — and the services' home after it.
1216        same!(param_home);
1217    }
1218
1219    #[test]
1220    fn u64_backing_covers_all_field_aligns() {
1221        assert!(align_of::<Option<CallbackMeta>>() <= 8);
1222        assert!(align_of::<Option<SchedContext>>() <= 8);
1223        assert!(align_of::<SchedContextId>() <= 8);
1224        assert!(align_of::<Option<SporadicState>>() <= 8);
1225        // phase-409 — the nine that moved. A type whose alignment exceeds 8
1226        // would make the `u64` backing insufficient for the whole carve, not
1227        // just for its own table.
1228        assert!(align_of::<NodeRecord>() <= 8);
1229        assert!(align_of::<ConcreteSession>() <= 8);
1230        assert!(align_of::<ExtraSessionId>() <= 8);
1231        assert!(align_of::<NodeSchedEntry>() <= 8);
1232        assert!(align_of::<ComponentSlot>() <= 8);
1233        assert!(align_of::<ActiveGroup>() <= 8);
1234        assert!(align_of::<AliveSlot>() <= 8);
1235        assert!(align_of::<GroupSchedEntry>() <= 8);
1236        assert!(align_of::<Violation>() <= 8);
1237        // phase-382 W3' — the store's slot.
1238        assert!(align_of::<nros_params::ParameterSlot>() <= 8);
1239        assert!(executor_storage_layout(DEFAULT).align() <= 8);
1240        assert!(executor_storage_layout(WITH_STORE).align() <= 8);
1241    }
1242
1243    /// phase-409 (issue 0961) — every knob-scaled table's per-slot cost is
1244    /// charged to the BACKING, which is where the caller put it, and not to the
1245    /// `Executor` value, which is what `open_in` builds on the stack and
1246    /// returns by value.
1247    ///
1248    /// Deltas rather than absolute sizes, the shape
1249    /// ~~`the_default_subscription_buffer_is_unchanged`~~ uses: a total says
1250    /// nothing about which knob moved it, while the difference between two
1251    /// sizings isolates exactly one knob's per-slot width.
1252    #[test]
1253    fn every_knob_scaled_table_is_charged_to_the_backing() {
1254        let base = executor_storage_layout(DEFAULT).size();
1255
1256        let one_more_node = executor_storage_layout(ExecutorSizing {
1257            nodes: DEFAULT.nodes + 1,
1258            ..DEFAULT
1259        })
1260        .size();
1261        let per_node = size_of::<NodeRecord>()
1262            + size_of::<ConcreteSession>()
1263            + size_of::<ExtraSessionId>()
1264            + size_of::<NodeSchedEntry>()
1265            + size_of::<ComponentSlot>()
1266            + size_of::<ActiveGroup>();
1267        assert!(
1268            one_more_node - base >= per_node,
1269            "one more Node slot must cost its six tables ({per_node} B) in the \
1270             backing; it cost {}",
1271            one_more_node - base
1272        );
1273
1274        // `arena` is its own field, so `..DEFAULT` holds it while `cbs` moves —
1275        // which isolates the callback-indexed tables. `group_sched_table` is the
1276        // one that coupled `NROS_EXECUTOR_MAX_CBS` to the main thread's stack.
1277        let one_more_cb = executor_storage_layout(ExecutorSizing {
1278            cbs: DEFAULT.cbs + 1,
1279            ..DEFAULT
1280        })
1281        .size();
1282        assert!(
1283            one_more_cb - base >= size_of::<GroupSchedEntry>(),
1284            "one more callback slot must cost a `group_sched_table` entry \
1285             ({} B) in the backing; it cost {}",
1286            size_of::<GroupSchedEntry>(),
1287            one_more_cb - base
1288        );
1289    }
1290
1291    /// Issue 1971 -- the runtime remap table is a sizing count: an executor
1292    /// sized 0 (bare metal) carves none, and each slot costs one rule.
1293    #[cfg(feature = "alloc")]
1294    #[test]
1295    fn the_remap_table_is_carved_at_the_sizing_count() {
1296        const DEFAULT: ExecutorSizing = ExecutorSizing::DEFAULT;
1297        let at = |remaps| executor_storage_layout(ExecutorSizing { remaps, ..DEFAULT }).size();
1298        let rule = size_of::<Option<RemapRule>>();
1299        assert!(at(0) + rule * 4 <= at(4) && at(4) <= at(0) + rule * 4 + 8);
1300        assert!(at(0) + rule * MAX_REMAPS <= at(MAX_REMAPS));
1301
1302        const SIZING: ExecutorSizing = ExecutorSizing {
1303            remaps: 3,
1304            arena: 64,
1305            params: 0,
1306            ..DEFAULT
1307        };
1308        // Heap-allocate, as `carve_yields_right_lengths_and_inits` does: the
1309        // DEFAULT callback/sched-context counts make this backing larger than
1310        // `clippy::large_stack_arrays` allows, and its size is not what is
1311        // under test.
1312        let mut backing = alloc::vec![const { MaybeUninit::<u64>::uninit() }; SIZING.u64_len()]
1313            .into_boxed_slice();
1314        // SAFETY: the backing is `u64_len()` words, and it outlives `slices`.
1315        let slices = unsafe { carve(&mut backing, SIZING) };
1316        assert_eq!(slices.remaps.len(), 3);
1317        assert!(slices.remaps.iter().all(Option::is_none));
1318    }
1319
1320    /// The other half of the same claim, and the one issue 0961 is about: the
1321    /// VALUE does not move.
1322    ///
1323    /// A CEILING rather than an equality, because the header's exact size is a
1324    /// target + feature detail — measured 1016 B on the `std` lane and 2048 B
1325    /// under `--all-features`, and the difference is almost entirely the primary
1326    /// session (`SessionStore` is 16 B over `MockSession`, 536 B over
1327    /// `CffiSession`) plus the retired OS-priority worker pool (phase-509 P11).
1328    /// The session is allowed for BY NAME below, so what is left is a tight
1329    /// budget on the header proper.
1330    ///
1331    /// It is a ceiling on the same number at every knob value, which is the
1332    /// property under test: 1016 B at BOTH the shipped defaults and the island's
1333    /// `MAX_CBS=36` / `MAX_NODES=6`. Before this phase it was 5072 B and
1334    /// 12768 B respectively.
1335    ///
1336    /// If this fires for a field you MEANT to add, the fix is almost always to
1337    /// carve it rather than to raise the ceiling: `Executor::open_in` builds
1338    /// this value on the stack and returns it by value, and `nros_cpp_init`
1339    /// holds the returned value, so every byte is charged to two frames of every
1340    /// image's boot path.
1341    #[test]
1342    fn the_executor_value_does_not_scale_with_the_knobs() {
1343        let value = size_of::<super::super::spin::Executor<'static>>();
1344        // Two things in the header are legitimately large and are NOT scaled by
1345        // `MAX_CBS` / `MAX_NODES`, so they get named allowances rather than a
1346        // looser ceiling for every build:
1347        //   * the primary session, held by value (that is what owning a session
1348        //     means), whose size is the backend's, not a knob's;
1349        //   * phase-436 W6's wake-source table, a fixed `MAX_WAKE_SOURCES`
1350        //     array of two-pointer slots. It is exempted for the same reason
1351        //     the two above are — it does not scale with `MAX_CBS` or
1352        //     `MAX_NODES` — and it is named rather than folded into the base
1353        //     so that raising `MAX_WAKE_SOURCES` shows up as a cost here
1354        //     instead of eating another feature's headroom. The rest of
1355        //     phase-436's header fields (the park bookkeeping scalars) are
1356        //     NOT exempted and fit inside the 1280 as they should.
1357        //   * phase-462 W2's age-monitor state table, an inline
1358        //     `MAX_AGE_MONITORS` array, named for the same reason as the
1359        //     wake-source table: `AgeState` grew from one byte to eight when
1360        //     the silence rule gained its lease, and that 56 B belongs on this
1361        //     line where the next field added to it is visible, not silently
1362        //     inside the 1280. Its sibling `[MonitorState; MAX_MONITORS]`
1363        //     predates the allowance idiom and its first 8 rows stay folded
1364        //     into the base; naming it whole would mean re-tuning the base
1365        //     literal against a size that is target-dependent.
1366        //   * phase-496 W1 made both tables KNOBS (`NROS_EXECUTOR_MAX_MONITORS`
1367        //     / `..._AGE_MONITORS`, derived from the contract's row counts).
1368        //     They stay inline on purpose -- the spin loop indexes them in
1369        //     parallel with a `&'static` spec table -- so they are exempt the
1370        //     same way, by NAMED allowance: the age table whole (above), the
1371        //     rate table by its rows past the 8 the base already absorbed. A
1372        //     contract with 14 rate rows grows this value by exactly those six
1373        //     rows and nothing else can hide inside that allowance.
1374        //   * issue 1496's released-region table was a FIXED 8-entry
1375        //     `heapless::Vec` named here; issue 1667 replaced it with an
1376        //     intrusive free list whose nodes live in the freed arena bytes, so
1377        //     what remains in this value is one `usize` head, named below.
1378        //   * phase-474 I1/I2's `ViolationCounts`: the violation ring's total,
1379        //     dropped and pre-arm counters and the monitors' arming state, nine
1380        //     scalars that scale with no knob. Named so the next field added to
1381        //     them shows up here rather than eating another feature's headroom.
1382        //   * phase-474 I7's `ReportQueue`: the verdicts waiting for the
1383        //     `/diagnostics` sink (a fixed `REPORT_QUEUE` of four) and what the
1384        //     hand-over cost. Scales with no knob; named for the same reason.
1385        //   * phase-476 W0's `slot_tags`: the TABLE is carved (it scales with
1386        //     `MAX_CBS` and lives in the backing); what sits in this value is
1387        //     one slice reference, which scales with nothing.
1388        //   * phase-483 W3's `component_frame`: one optional pointer to the
1389        //     component-registration frame `nros::NodeContext` installs while a
1390        //     component's `register` runs. Scales with nothing.
1391        //   * phase-474 I11's `ReleaseGrid`: the spin loop's release grid (its
1392        //     period, next release and skipped count). Scales with nothing.
1393        //   * phase-436 A2b/A2c: whether a declared cadence is wait-paced (a
1394        //     `bool`) and the count of late wakes beyond the granule (a `u32`).
1395        //     Two scalars that scale with nothing, named so the next field added
1396        //     beside them shows up here.
1397        //   * phase-462 W3b's `hazard_table`: one `&'static` slice reference to
1398        //     the baked hazard table, whose per-hazard state lives in the
1399        //     table's own `static` cells. Scales with nothing.
1400        //   * phase-462 W4's mode tables: one `&'static` slice reference to the
1401        //     baked mode variants (each a pair of `&'static` table references,
1402        //     in the entry's statics, not here) and two `u16` mode ids. Scales
1403        //     with nothing -- a mode adds a table to the image, not to this
1404        //     value. phase-462 W4c adds the monotonic ms of the previous mode
1405        //     check (an `Option<u32>`), the window a mode switch is judged over.
1406        #[allow(unused_mut)]
1407        let mut ceiling =
1408            1280 + size_of::<super::super::spin::SessionStore>()
1409                + size_of::<super::super::monitor::ViolationCounts>()
1410                + size_of::<super::super::monitor::ReportQueue>()
1411                + size_of::<&mut [super::super::types::SlotTag]>()
1412                + size_of::<usize>()
1413                + size_of::<Option<core::ptr::NonNull<()>>>()
1414                + size_of::<super::super::spin::ReleaseGrid>()
1415                + size_of::<bool>()
1416                + size_of::<u32>()
1417                + size_of::<&'static [super::super::monitor::HazardSpec]>()
1418                + size_of::<&'static [super::super::monitor::ModeTables]>()
1419                // Issue 1971 -- the executor's own launch-remap borrow (a
1420                // `&'static` slice of `.rodata`; scales with nothing).
1421                + size_of::<Option<&'static [super::super::launch_remap::LaunchRemap]>>()
1422                + 2 * size_of::<u16>()
1423                + size_of::<Option<u32>>()
1424                // phase-509 P9b -- the executor's lock (RFC-0108 "As built in
1425                // P9b"): the port mutex's address and its take / give entries,
1426                // and (item 2) the port's thread-identity entry. The mutex
1427                // itself lives in the runner's scheduler backing; scales with
1428                // nothing.
1429                + size_of::<Option<super::super::exec_lock::ExecLock>>()
1430                // phase-509 P9b item 2 -- the head of the open callback
1431                // windows' list; the records live in the passes' frames, one
1432                // per window. One pointer, scales with nothing.
1433                + size_of::<*mut super::super::exec_lock::Running>()
1434                // Issue 2018 -- the registering level's own sched context id
1435                // (`Worker::registering_sched`), one byte that tipped the
1436                // worker's padding; scales with nothing.
1437                + size_of::<u32>()
1438                // Issue 2146 -- the deferred-dispatch queue: the deferred and
1439                // queued slot masks and the host's optional `(notifier, ctx)`.
1440                // Issue 2541 -- a mask is one `u64` per 64 callback slots
1441                // (`SLOT_WORDS`), so one word at 64 or fewer; cfg(test) takes
1442                // two. It is sized by the slot capacity, not by MAX_CBS.
1443                + 2 * size_of::<super::super::slot_mask::SlotMask>()
1444                + size_of::<Option<(super::super::types::DeferNotify, *mut core::ffi::c_void)>>()
1445                + size_of::<
1446                    [Option<super::super::spin::WakeSourceSlot>;
1447                        super::super::spin::MAX_WAKE_SOURCES],
1448                >()
1449                + size_of::<
1450                    [super::super::monitor::AgeState; super::super::monitor::MAX_AGE_MONITORS],
1451                >()
1452                + size_of::<
1453                    [super::super::monitor::MonitorState; super::super::monitor::MAX_MONITORS],
1454                >()
1455                .saturating_sub(size_of::<[super::super::monitor::MonitorState; 8]>());
1456        // phase-397 W2/W3 -- the mask of entry slots whose backend accepted an
1457        // entity waker and the mask W3 re-probes, plus W3's `u32` probe
1458        // counter. Issue 2060 adds a third mask, the slots whose status events
1459        // are polled every pass (`entity_status_polled`). Each is a slot mask,
1460        // sized as the deferred queue's above.
1461        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
1462        {
1463            ceiling += 3 * size_of::<super::super::slot_mask::SlotMask>() + size_of::<u32>();
1464        }
1465        // Issue 1938 -- `signal-fd-wake`'s worker: an fd, one `Arc` to its
1466        // context and the task handle. Scales with nothing; it sat unnamed and
1467        // alone took the `rmw-cffi` build 31 B over.
1468        #[cfg(all(feature = "signal-fd-wake", target_os = "linux"))]
1469        {
1470            ceiling += size_of::<Option<super::super::spin::WakeSignalFd>>();
1471        }
1472        // phase-382 W3' -- the parameter store's TABLE is carved (it scales
1473        // with `MAX_PARAMETERS` and lives in the backing); this value holds one
1474        // slice reference to it, which scales with nothing.
1475        #[cfg(feature = "param-store")]
1476        {
1477            ceiling += size_of::<&mut [MaybeUninit<nros_params::ParameterSlot>]>();
1478            // issue 1812 -- and one slice reference to the services' home,
1479            // which is carved for the same reason, plus the word that says
1480            // whether the state is carved or (with `alloc`) boxed. Neither
1481            // scales with a knob.
1482            ceiling += size_of::<&mut [MaybeUninit<ParamHome>]>();
1483            ceiling += size_of::<
1484                Option<
1485                    crate::param_store::Placed<'static, crate::param_store::ParamState<'static>>,
1486                >,
1487            >()
1488            .saturating_sub(size_of::<usize>());
1489            // issue 1938 -- the refused-allocation flag (issue 1706) and the
1490            // contract's declared parameters (phase-446 W6), two `&'static`
1491            // slices into the entry's baked tables. Neither scales with a knob.
1492            ceiling += size_of::<bool>() + size_of::<nros_params::DeclaredParams>();
1493        }
1494        // phase-425 W3b / phase-430 W1 -- `use_sim_time`'s state: the `/clock`
1495        // handle, the requested and stated flags, and the silence watch. None
1496        // scales with a knob. They sat unnamed inside the 1280 until a build
1497        // that also carried `param-services` and `lifecycle-services` went
1498        // 4 B over it, so they are named here like the rest.
1499        #[cfg(feature = "sim-time")]
1500        {
1501            ceiling += size_of::<Option<super::super::types::HandleId>>()
1502                + 2 * size_of::<bool>()
1503                + size_of::<crate::time_source::SilenceWatch>();
1504        }
1505        // The open waiting on the primary node (the `/diagnostics` reporter
1506        // armed before any node): one hook, its context word and argument.
1507        // Scales with nothing.
1508        ceiling += size_of::<Option<(super::super::spin::PrimaryNodeHook, usize, u32)>>();
1509        // `lifecycle-services`' runtime state is a HEAP table (RFC-0128 D1:
1510        // one machine per managed node); this value holds its `Vec` header,
1511        // which scales with nothing.
1512        #[cfg(feature = "lifecycle-services")]
1513        {
1514            ceiling += size_of::<alloc::vec::Vec<crate::lifecycle_services::LifecycleEntry>>();
1515        }
1516        assert!(
1517            value <= ceiling,
1518            "`Executor` is {value} B at MAX_CBS={CBS} / MAX_NODES={NODES}, over \
1519             the {ceiling} B this value is budgeted; a table that scales with a \
1520             knob has come back inline (issue 0961)."
1521        );
1522    }
1523
1524    /// issue 1771 — an empty region at a MISALIGNED offset is legal.
1525    ///
1526    /// The layout leaves an empty region's offset unaligned (no padding for
1527    /// nothing), and `carve` used to hand that pointer to
1528    /// `slice::from_raw_parts_mut`, whose debug precondition check aborts the
1529    /// image — on thumbv7m, where the offset is not a multiple of
1530    /// `ParameterSlot`'s alignment. x86_64 happened to align, so carve's own
1531    /// tests could not see it; this asks the helper at an offset that is
1532    /// misaligned on every target. Passing `p` straight to
1533    /// `from_raw_parts_mut` here aborts the test process (not catchable).
1534    #[test]
1535    fn an_empty_region_at_a_misaligned_offset_carves_to_an_empty_slice() {
1536        assert!(align_of::<nros_params::ParameterSlot>() > 1, "the premise");
1537        let mut backing = [0u64; 4];
1538        let p = (backing.as_mut_ptr() as *mut u8).wrapping_add(1)
1539            as *mut MaybeUninit<nros_params::ParameterSlot>;
1540        assert!(!p.is_aligned(), "the premise: the offset is misaligned");
1541        let s = unsafe { region_slice(p, 0) };
1542        assert!(s.is_empty());
1543        assert!(s.as_ptr().is_aligned());
1544    }
1545
1546    /// issue 1771 — `carve` itself, over layouts whose empty parameter region
1547    /// lands misaligned.
1548    ///
1549    /// Which knob values misalign `o.params` depends on every region before it,
1550    /// so a fixed config proves nothing on the next knob move: the mps2 talker
1551    /// panicked in one build and booted in another of the same leaf. Sweep the
1552    /// callback count and require that the sweep REACHES a misaligned offset
1553    /// (else this test has stopped asking the question), then carve each one.
1554    /// With the slice built straight from the pointer, the first misaligned
1555    /// case aborts the test process at the precondition check.
1556    #[cfg(feature = "alloc")]
1557    #[test]
1558    fn carve_survives_an_empty_parameter_region_at_any_alignment() {
1559        let align = align_of::<nros_params::ParameterSlot>();
1560        let mut misaligned = 0;
1561        for cbs in 1..=16 {
1562            let sizing = ExecutorSizing {
1563                cbs,
1564                sc: 1,
1565                arena: 1,
1566                nodes: 1,
1567                params: 0,
1568                remaps: MAX_REMAPS,
1569            };
1570            if !compute_offsets(sizing).params.is_multiple_of(align) {
1571                misaligned += 1;
1572            }
1573            let mut backing = alloc::vec![
1574                const { MaybeUninit::<u64>::uninit() };
1575                executor_storage_u64_len(sizing)
1576            ]
1577            .into_boxed_slice();
1578            let s = unsafe { carve(&mut backing, sizing) };
1579            assert!(s.params.is_empty());
1580            assert_eq!(s.entries.len(), cbs);
1581        }
1582        assert!(
1583            misaligned > 0,
1584            "no swept layout leaves the empty parameter region misaligned for \
1585             ParameterSlot (align {align}) — widen the sweep, or this test no \
1586             longer covers issue 1771"
1587        );
1588    }
1589
1590    /// Issue 1970 -- a sched task's sizing is its own counts, the image's
1591    /// scheduling contexts, and its declared parameters capped at the store
1592    /// the image carves (none when the image carves none).
1593    #[test]
1594    fn a_sched_task_is_carved_at_its_own_counts() {
1595        let t = crate::config::SchedTaskSizing {
1596            name: "estop",
1597            cbs: 3,
1598            arena: 8192,
1599            nodes: 2,
1600            params: Some(4),
1601        };
1602        let s = sched_task_executor_sizing(&t);
1603        assert_eq!((s.cbs, s.arena, s.nodes), (3, 8192, 2));
1604        // Issue 1971 -- the runtime remap table is the image's default on
1605        // every sched task; the launch's rules are the shared flash table.
1606        assert_eq!(s.remaps, MAX_REMAPS);
1607        assert_eq!(s.sc, crate::config::MAX_SC);
1608        let store = nros_params::IMPLIED_STORE_SLOTS;
1609        assert_eq!(s.params, 4.min(store));
1610        let unstated =
1611            sched_task_executor_sizing(&crate::config::SchedTaskSizing { params: None, ..t });
1612        assert_eq!(unstated.params, store);
1613        // A smaller sched task is a smaller backing.
1614        let image = ExecutorSizing::DEFAULT;
1615        if image.cbs >= 3 && image.arena >= 8192 && image.nodes >= 2 {
1616            assert!(s.u64_len() <= image.u64_len());
1617        }
1618    }
1619
1620    /// Issue 1970 -- an image that sizes no sched task keeps its inline backing,
1621    /// and publishes no sched task backing.
1622    #[test]
1623    fn an_image_sized_as_one_executor_keeps_the_inline_backing() {
1624        if crate::config::SCHED_TASK_SIZINGS.is_empty() {
1625            assert_eq!(INLINE_BACKING_U64S, ExecutorSizing::DEFAULT.u64_len());
1626            assert_eq!(sched_task_backing_bytes(0), 0);
1627            assert!(sched_task_sizing("anything").is_none());
1628        } else {
1629            assert_eq!(INLINE_BACKING_U64S, 0);
1630        }
1631    }
1632
1633    // phase-361 W8.e / issue 0594 — this test heap-allocates its backing array,
1634    // so it needs `alloc`. It compiled under `--no-default-features` only
1635    // because feature unification from another workspace member happened to
1636    // turn `nros-node/alloc` on; nothing does that now.
1637    #[cfg(feature = "alloc")]
1638    #[test]
1639    fn carve_yields_right_lengths_and_inits() {
1640        // Heap-allocate: the default test config (MAX_CBS/MAX_SC/ARENA_SIZE from
1641        // build.rs) makes this backing array tens of KB, well past
1642        // `clippy::large_stack_arrays`'s threshold — and the size here is
1643        // incidental (mirrors production config), not the point under test, so
1644        // boxing is the right fix rather than an allow.
1645        let mut backing =
1646            alloc::vec![const { MaybeUninit::<u64>::uninit() }; executor_storage_u64_len(DEFAULT)]
1647                .into_boxed_slice();
1648        let s = unsafe { carve(&mut backing, DEFAULT) };
1649        assert_eq!(s.arena.len(), ARENA);
1650        assert_eq!(s.entries.len(), CBS);
1651        assert_eq!(s.sched_contexts.len(), SC);
1652        assert_eq!(s.sched_context_bindings.len(), CBS);
1653        assert_eq!(s.sporadic_states.len(), SC);
1654        assert!(s.entries.iter().all(|e| e.is_none()));
1655        assert!(s.sched_context_bindings.iter().all(|b| b.0 == 0));
1656        // phase-409 — the CarvedVecs come back empty at their carved capacity.
1657        assert_eq!(s.nodes.capacity(), NODES);
1658        // Issue 1982 -- one per OTHER backend, capped at the node slots.
1659        let extra = extra_session_slots(DEFAULT);
1660        assert!(extra <= NODES);
1661        assert_eq!(s.extra_sessions.capacity(), extra);
1662        assert_eq!(s.extra_session_ids.capacity(), extra);
1663        assert_eq!(s.node_sched_table.capacity(), NODES);
1664        assert_eq!(s.component_slots.capacity(), NODES);
1665        assert_eq!(s.active_groups.capacity(), NODES);
1666        assert_eq!(s.group_sched_table.capacity(), CBS);
1667        assert_eq!(s.monitor_violations.capacity(), MAX_VIOLATIONS);
1668        // Alive supervision: one zeroed record per SC, carved rather than inline.
1669        assert_eq!(s.alive_slots.len(), SC);
1670        assert!(
1671            s.alive_slots
1672                .iter()
1673                .all(|a| a.dispatches == 0 && !a.state.opened)
1674        );
1675        assert_eq!(s.nodes.len(), 0);
1676        assert_eq!(s.group_sched_table.len(), 0);
1677        // phase-382 W3' — the store region, at this build's implied count.
1678        assert_eq!(s.params.len(), DEFAULT.params);
1679        // issue 1812 — and the services' home, present exactly with a store.
1680        assert_eq!(s.param_home.len(), param_homes(DEFAULT));
1681    }
1682
1683    /// phase-382 W3' — carve a store and USE it, with no allocator anywhere.
1684    ///
1685    /// Outside the `alloc` gate on purpose (phase-382's trap): the point of
1686    /// carving is a store an image without a heap can hold, and
1687    /// `carve_yields_right_lengths_and_inits` above needs `alloc` only for
1688    /// its own default-sized backing. The backing here is a STATIC sized for a
1689    /// minimal executor plus the store, so nothing in this test allocates.
1690    #[test]
1691    fn a_carved_store_is_usable_without_an_allocator() {
1692        const TINY: ExecutorSizing = ExecutorSizing {
1693            cbs: 1,
1694            sc: 1,
1695            arena: 64,
1696            nodes: 1,
1697            params: PARAMS,
1698            remaps: MAX_REMAPS,
1699        };
1700        const WORDS: usize = executor_storage_u64_len(TINY);
1701        static mut BACKING: [MaybeUninit<u64>; WORDS] = [MaybeUninit::uninit(); WORDS];
1702        // SAFETY: this test is the only reader of `BACKING`, and it takes the
1703        // one reference once.
1704        // The raw pointer is bound first, as in `backing::take`: clippy reads
1705        // `&mut *(&raw mut X)` as `deref_addrof`, and its rewrite is the
1706        // `static_mut_refs` hazard.
1707        let ptr = &raw mut BACKING;
1708        let backing: &'static mut [MaybeUninit<u64>; WORDS] = unsafe { &mut *ptr };
1709        // SAFETY: `backing` is exactly `executor_storage_u64_len(TINY)` words.
1710        let s = unsafe { carve(backing, TINY) };
1711        assert_eq!(s.params.len(), PARAMS, "the store's slots are carved");
1712        assert_eq!(s.param_home.len(), 1, "and the services' home with them");
1713        let table = nros_params::ParameterTable::init_in(s.params);
1714        assert_eq!(table.capacity(), PARAMS);
1715        assert_eq!(table.occupied(), 0, "carved slots start empty");
1716        let mut server = nros_params::ParameterServer::new_in(table);
1717        let key = nros_params::NodeKey::PRIMARY;
1718        for i in 0..PARAMS {
1719            let mut name = heapless::String::<8>::new();
1720            let _ = core::fmt::write(&mut name, format_args!("p{i}"));
1721            assert!(server.declare(key, &name, nros_params::ParameterValue::Integer(i as i64)));
1722        }
1723        assert!(
1724            !server.declare(key, "over", nros_params::ParameterValue::Bool(true)),
1725            "capacity is the carved length"
1726        );
1727        assert_eq!(server.get(key, "p1").and_then(|v| v.as_integer()), Some(1));
1728    }
1729
1730    /// Issue 1982 -- the extra-session tables are capped by the image's other
1731    /// backends, never above the node slots, and cost nothing when capped at
1732    /// zero.
1733    #[test]
1734    fn extra_session_slots_are_capped_by_the_backends_and_the_nodes() {
1735        let at = |nodes| extra_session_slots(ExecutorSizing { nodes, ..DEFAULT });
1736        // Through `black_box`: the cap is a build constant, and a comparison
1737        // against it would be judged constant rather than checked.
1738        let cap = core::hint::black_box(crate::config::MAX_EXTRA_SESSIONS);
1739        assert_eq!(at(0), 0);
1740        assert_eq!(at(3), cap.min(3));
1741        // A capped region shrinks the backing by its whole slots.
1742        let mut no_session = NATIVE_UNITS;
1743        no_session.concrete_session = RegionUnit { size: 0, align: 1 };
1744        no_session.extra_session_id = RegionUnit { size: 0, align: 1 };
1745        if cap == 0 {
1746            assert_eq!(
1747                executor_storage_layout(DEFAULT).size(),
1748                executor_storage_layout_with(DEFAULT, no_session).size(),
1749            );
1750        }
1751    }
1752
1753    #[test]
1754    fn carved_vec_pushes_in_order_and_refuses_when_full() {
1755        let mut slots = [const { MaybeUninit::<u32>::uninit() }; 3];
1756        let mut v = CarvedVec::new(&mut slots);
1757        assert_eq!(v.capacity(), 3);
1758        assert!(v.push(10).is_ok());
1759        assert!(v.push(20).is_ok());
1760        assert!(v.push(30).is_ok());
1761        // Order is load-bearing: `NodeId` IS an index into `nodes`.
1762        assert_eq!(v.as_slice(), &[10, 20, 30]);
1763        // Full is a REFUSAL that hands the value back, like `heapless::Vec`.
1764        assert_eq!(v.push(40), Err(40));
1765        v.clear();
1766        assert!(v.is_empty());
1767        assert!(v.push(50).is_ok());
1768        assert_eq!(v.as_slice(), &[50]);
1769    }
1770
1771    /// phase-474 I1 -- `pop_front` takes the OLDEST and keeps push order, which
1772    /// is what lets the violation ring evict its oldest entry when full.
1773    #[test]
1774    fn carved_vec_pop_front_keeps_order() {
1775        let mut slots = [const { MaybeUninit::<u32>::uninit() }; 3];
1776        let mut v = CarvedVec::new(&mut slots);
1777        assert_eq!(v.pop_front(), None);
1778        for x in [1, 2, 3] {
1779            assert!(v.push(x).is_ok());
1780        }
1781        assert_eq!(v.pop_front(), Some(1));
1782        assert!(v.push(4).is_ok());
1783        assert_eq!(v.as_slice(), &[2, 3, 4]);
1784        assert_eq!(v.pop_front(), Some(2));
1785        assert_eq!(v.pop_front(), Some(3));
1786        assert_eq!(v.pop_front(), Some(4));
1787        assert!(v.is_empty());
1788    }
1789
1790    /// The elements live in the CALLER's backing, so nothing drops them unless
1791    /// the vector does — and `extra_sessions` holds RMW sessions. Without this
1792    /// a bridge executor would leak every extra session it opened.
1793    #[test]
1794    fn carved_vec_drops_its_elements() {
1795        use core::sync::atomic::{AtomicUsize, Ordering};
1796        static DROPS: AtomicUsize = AtomicUsize::new(0);
1797        struct Counted;
1798        impl Drop for Counted {
1799            fn drop(&mut self) {
1800                DROPS.fetch_add(1, Ordering::SeqCst);
1801            }
1802        }
1803
1804        let mut slots = [const { MaybeUninit::<Counted>::uninit() }; 4];
1805        {
1806            let mut v = CarvedVec::new(&mut slots);
1807            assert!(v.push(Counted).is_ok());
1808            assert!(v.push(Counted).is_ok());
1809        }
1810        assert_eq!(
1811            DROPS.load(Ordering::SeqCst),
1812            2,
1813            "both pushed elements dropped — and only the pushed ones, not the \
1814             uninitialised tail"
1815        );
1816    }
1817}