rusty_rtos_kernel_core/name.rs
1//! A task's name, stored the way the C kernel stores it.
2//!
3//! `prvInitialiseNewTask` copies at most `configMAX_TASK_NAME_LEN`
4//! characters into the TCB and writes a NUL at the last index, so a longer
5//! name is silently truncated and the trace prints the truncated form. A
6//! `&'static str` would have been simpler and wrong: the oracle's line for a
7//! long name is the truncated one, and the diff is the gate.
8
9use core::fmt;
10use core::str;
11
12/// The largest `configMAX_TASK_NAME_LEN` this build supports.
13///
14/// The C default is 16 and the `Posix_GCC` demo uses 12; a configuration
15/// asking for more than this is refused by [`Name::new`] rather than
16/// truncated silently at a limit nobody wrote down.
17pub const NAME_CAPACITY: usize = 16;
18
19// `as_str` validates a FIXED 16-byte window because that is the smallest one
20// `run_utf8_validation` will take its word-at-a-time ASCII path for. While the
21// capacity equals that window, `end <= WINDOW` is provably true and the
22// widening branch folds away — which is why `as_str` needs no `if` at run
23// time and why the test below has no wide-window case.
24//
25// Raise the capacity above 16 and that stops being true: the widening path
26// goes live, untested, on the hot path that prints two names per context
27// switch. This makes that a build failure instead.
28const _: () = assert!(
29 NAME_CAPACITY <= 16,
30 "NAME_CAPACITY above 16 makes as_str's widening branch live again: give it a test case, and re-measure the trace rows, before raising this."
31);
32
33/// A task name: at most [`NAME_CAPACITY`] bytes, truncated to the
34/// configuration's `MAX_TASK_NAME_LEN` exactly as C truncates it.
35///
36/// # Why this is aligned to eight ON A 64-BIT HOST ONLY
37///
38/// `as_str` validates a sixteen-byte window so that `run_utf8_validation`
39/// takes its word-at-a-time ASCII path instead of walking the name a byte at
40/// a time. That path has TWO conditions and the window size is only one of
41/// them: `core`'s loop reads two `usize`s at a time and declines unless the
42/// slice is `usize`-ALIGNED (`align_offset(size_of::<usize>()) == 0`).
43///
44/// Nothing said so, and on the host the alignment was absent. `Tcb` holds a
45/// `Name` as its first field and is four-aligned deliberately -- see
46/// `WaitFrame`, whose `Split64` fields exist to keep it that way -- and
47/// `Slot<Tcb>` puts a `u32` generation in front of it, so `bytes` landed at
48/// offset four of every slot. Measured with callgrind on a sixteen-byte
49/// window holding `CNT_INC`:
50///
51/// | window offset | Ir per `from_utf8` |
52/// |---|---:|
53/// | 0 (`usize`-aligned) | **46** |
54/// | 4 (what `Slot<Tcb>` gave it) | **143** |
55/// | 1 | 161 |
56///
57/// `bench/kernel-ir` measured 142.7 in production -- offset four to within a
58/// third of an instruction. The optimisation was documented, tested, and off.
59///
60/// # ★ And it was off only on the HOST, which is why it survived
61///
62/// `usize` is FOUR bytes on every target this kernel ships to, so offset four
63/// is already `usize`-aligned there and the ASCII path was being taken all
64/// along. The defect existed only where `usize` is eight -- the 64-bit host
65/// that runs the sim and the conformance suite. That is the pointer-width
66/// asymmetry this project has paid for before (`docs/LEDGER.md`), and it is
67/// why the alignment is requested with a `cfg_attr` rather than outright:
68/// asking for eight unconditionally would grow `Tcb` on a 32-bit target, and
69/// spend real firmware RAM to fix a host-only cost.
70///
71/// So this buys the sim and `kairos conform --all` about ten percent of their
72/// instructions and buys firmware nothing, by design. It changes no layout a
73/// target sees.
74#[derive(Clone, Copy, PartialEq, Eq)]
75#[cfg_attr(target_pointer_width = "64", repr(align(8)))]
76pub struct Name {
77 bytes: [u8; NAME_CAPACITY],
78 len: u8,
79}
80
81// `as_str`'s fast path depends on the window being `usize`-aligned, and a
82// layout change removes that silently -- which is exactly what happened here.
83// Fail the build instead.
84//
85// ONLY on the 64-bit host, because that is the only place the attribute above
86// promises anything. `Name`'s own alignment is ONE -- every field is a `u8` --
87// so on a 32-bit target the alignment does not come from this type at all: it
88// comes from the container. `Tcb` holds a `Name` at offset zero and is itself
89// four-aligned (`WaitFrame`'s `Split64` fields are what keep it so), and
90// `Slot<Tcb>` puts a `u32` in front, so the window lands on a multiple of four
91// -- which IS `usize`-aligned where `usize` is four bytes. That is why the
92// defect never existed on a target, and why asking for four here would only
93// grow `Tcb` for nothing.
94//
95// This assertion was written the other way round first, unconditionally, and
96// it failed the rv32 build immediately: `align_of::<Name>()` is 1, not 4. The
97// failure is the reason the paragraph above exists.
98#[cfg(target_pointer_width = "64")]
99const _: () = assert!(
100 core::mem::align_of::<Name>() >= core::mem::size_of::<usize>(),
101 "Name must be usize-aligned on the host or as_str's word-at-a-time UTF-8 path stops being taken and every name a trace prints costs three times what it should."
102);
103
104impl Default for Name {
105 fn default() -> Self {
106 Self {
107 bytes: [0; NAME_CAPACITY],
108 len: 0,
109 }
110 }
111}
112
113impl Name {
114 /// Copy `name`, truncated the way `prvInitialiseNewTask` truncates:
115 /// at most `max_len - 1` bytes, because the C array's last slot is the
116 /// NUL. `max_len` of 0 yields an empty name, as C's loop would.
117 ///
118 /// Truncation happens on a character boundary, so the result is always
119 /// valid UTF-8 — C truncates on a byte, but every name in the corpus is
120 /// ASCII and a name that is not is a configuration error, not a silent
121 /// mojibake.
122 #[must_use]
123 // In line at both callers (`rusty-compiler-leverage` A3): win 24, -20 B of
124 // flash. `#[inline]` alone was a hint LLVM declined at this size.
125 #[inline(always)]
126 pub fn new(name: &str, max_len: usize) -> Self {
127 let limit = max_len.saturating_sub(1).min(NAME_CAPACITY).min(name.len());
128 // Walk back to a character boundary; for ASCII this is `limit`.
129 let mut end = limit;
130 while end > 0 && !name.is_char_boundary(end) {
131 end = end.saturating_sub(1);
132 }
133 let src = name.as_bytes().get(..end).unwrap_or(&[]);
134 let mut bytes = [0u8; NAME_CAPACITY];
135 // A zip, NOT `copy_from_slice`. The slice version lowers to `memcpy`
136 // and reads like the better choice -- but its length-mismatch arm
137 // panics with TWO FORMATTED INTEGERS, and that drags
138 // `core::fmt::Formatter::pad_integral` (596 B), `Display for usize`
139 // (362 B) and `str::count::do_count_chars` (376 B) into a `no_std`
140 // kernel that formats nothing anywhere else. Measured at **1,052
141 // bytes** of flash for a branch that cannot be taken: `dst` is
142 // `bytes[..src.len()]`, so the lengths are equal by construction and
143 // LLVM still would not prove it.
144 //
145 // The zip has no panicking arm at all, so none of that machinery is
146 // reachable. It copies at most NAME_CAPACITY (16) bytes.
147 for (d, s) in bytes.iter_mut().zip(src.iter()) {
148 *d = *s;
149 }
150 Self {
151 bytes,
152 len: u8::try_from(end).unwrap_or(0),
153 }
154 }
155
156 /// The name as it will be printed.
157 ///
158 /// In line on purpose, and with the clamp below: a trace prints two
159 /// names on every context switch, and out of line each one paid a call
160 /// and a frame to hand back a slice of a field the caller already had.
161 #[must_use]
162 #[inline(always)]
163 pub fn as_str(&self) -> &str {
164 // `Name::new` is the only constructor and it writes a `len` no
165 // larger than the buffer, so the clamp changes no value. It says so
166 // to the compiler, which otherwise carries a bounds check and an
167 // `Option` into every read of a name -- and a trace prints two of
168 // them on every context switch.
169 let end = usize::from(self.len).min(NAME_CAPACITY);
170 // Validate a WINDOW, not the used prefix.
171 //
172 // `run_utf8_validation` only reaches its word-at-a-time ASCII path
173 // when two `usize`s remain, so an eleven-byte task name -- which is
174 // every name in this corpus -- is checked a byte at a time. The
175 // profile put `from_utf8` at 9,776,286 instructions over 113,645
176 // calls, 86 each, and that is where they went.
177 //
178 // Sixteen bytes is the smallest window that reaches the fast path.
179 // The answer is unchanged because the tail is NULs: `Name::new`
180 // starts from a zeroed array and writes only a prefix, `Default` is
181 // all zeros, `bytes` is private and nothing else writes it. A NUL
182 // is valid UTF-8, so widening the check cannot change its verdict.
183 const WINDOW: usize = 16;
184 let window = if end <= WINDOW { WINDOW } else { NAME_CAPACITY };
185 match str::from_utf8(self.bytes.get(..window).unwrap_or(&[])) {
186 // Every byte is ASCII or NUL, so `end` is a character boundary
187 // and this is a length test rather than a scan.
188 Ok(all) => all.get(..end).unwrap_or(""),
189 Err(_) => "",
190 }
191 }
192
193 /// Whether this name is `other`.
194 ///
195 /// Compares BYTES. Two `str`s are equal exactly when their bytes are, so
196 /// this answers what `self.as_str() == other` answered — without the
197 /// UTF-8 validation that makes a `&str`, which is the only thing that
198 /// pulled `core::str::from_utf8` into a kernel built with `NoTrace`.
199 /// Measured on `bench/kernel-flash`: **534 bytes**, 3.2 % of the arm, for
200 /// one comparison in `task_get_handle`.
201 #[must_use]
202 // A3: ONE caller in the linked kernel, so this pays a prologue and epilogue
203 // for a single call. Inlining moves the body rather than duplicating it.
204 #[inline(always)]
205 pub fn matches(&self, other: &str) -> bool {
206 let end = usize::from(self.len).min(NAME_CAPACITY);
207 self.bytes.get(..end) == Some(other.as_bytes())
208 }
209
210 /// How many bytes the name occupies.
211 #[must_use]
212 pub const fn len(&self) -> usize {
213 self.len as usize
214 }
215
216 /// Whether the name is empty.
217 #[must_use]
218 pub const fn is_empty(&self) -> bool {
219 self.len == 0
220 }
221}
222
223impl fmt::Debug for Name {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 fmt::Debug::fmt(self.as_str(), f)
226 }
227}
228
229impl fmt::Display for Name {
230 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231 f.write_str(self.as_str())
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238
239 #[test]
240 fn short_names_survive_whole() {
241 assert_eq!(Name::new("CNT_INC", 12).as_str(), "CNT_INC");
242 assert_eq!(Name::new("Tmr Svc", 12).as_str(), "Tmr Svc");
243 assert_eq!(Name::new("IDLE", 12).as_str(), "IDLE");
244 }
245
246 #[test]
247 fn long_names_truncate_like_the_c_kernel() {
248 // configMAX_TASK_NAME_LEN counts the NUL, so 12 keeps 11 characters.
249 assert_eq!(Name::new("ABCDEFGHIJKLMNOP", 12).as_str(), "ABCDEFGHIJK");
250 assert_eq!(Name::new("ABCDEFGHIJKLMNOP", 12).len(), 11);
251 }
252
253 #[test]
254 fn degenerate_limits_are_errors_not_panics() {
255 assert!(Name::new("anything", 0).is_empty());
256 assert!(Name::new("anything", 1).is_empty());
257 assert_eq!(Name::new("anything", 2).as_str(), "a");
258 assert_eq!(Name::new("", 12).as_str(), "");
259 }
260
261 /// `as_str` validates a sixteen-byte window and slices the answer out
262 /// of it, which is only right while the bytes past `len` stay valid
263 /// UTF-8. They are NULs today because `new` starts from a zeroed array
264 /// and writes only a prefix. Pin that: a `new` that left the tail dirty
265 /// would make `as_str` answer `""` for every name, and the conformance
266 /// gate would report a diff in twenty-two scenarios at once with no
267 /// clue which line caused it.
268 #[test]
269 fn the_tail_stays_valid_so_as_str_can_check_a_whole_window() {
270 for (text, limit) in [("StrTrig", 12), ("", 12), ("a", 2), ("IDLE", 12)] {
271 let n = Name::new(text, limit);
272 assert!(
273 str::from_utf8(n.bytes.get(..16).unwrap_or(&[])).is_ok(),
274 "the sixteen-byte window must be valid UTF-8, not just the prefix"
275 );
276 assert!(
277 n.bytes
278 .get(n.len()..)
279 .unwrap_or(&[])
280 .iter()
281 .all(|b| *b == 0),
282 "the tail past `len` must be NUL"
283 );
284 }
285 // A name that FILLS the capacity still reads back whole. This used
286 // to assert `len() > 16` to prove it exercised `as_str`'s WIDE
287 // window -- and when `NAME_CAPACITY` came down to 16 that assertion
288 // failed, correctly: at capacity 16 the wide window cannot be
289 // reached, because `end` is clamped to the capacity and the window
290 // IS the capacity. The branch folds at compile time and the case it
291 // guarded no longer exists.
292 //
293 // The guard below is what replaces it. If anyone raises the capacity
294 // above the window, the widening path becomes live again and this
295 // test must grow a case for it — so the coupling fails the build
296 // rather than going quietly untested.
297 // `NAME_CAPACITY - 1`, not `NAME_CAPACITY`: `max_len` counts the C
298 // array's NUL slot, exactly as `prvInitialiseNewTask` does, so a
299 // configuration asking for 16 gets 15 characters. Asserting 16 here
300 // is the mistake this comment exists to stop being made twice.
301 let full = Name::new(&"A".repeat(NAME_CAPACITY), NAME_CAPACITY);
302 assert_eq!(full.len(), NAME_CAPACITY - 1);
303 assert_eq!(full.as_str(), "A".repeat(NAME_CAPACITY - 1));
304 // And the buffer CAN be filled to the last byte, when the caller asks
305 // for more than the capacity — `as_str` reads `len` rather than
306 // scanning for a NUL, so a name with no terminator still reads back.
307 // This is also the case that keeps `end == WINDOW` reachable.
308 let brim = Name::new(&"B".repeat(NAME_CAPACITY * 2), usize::MAX);
309 assert_eq!(brim.len(), NAME_CAPACITY);
310 assert_eq!(brim.as_str(), "B".repeat(NAME_CAPACITY));
311 }
312
313 #[test]
314 fn a_name_longer_than_the_capacity_is_capped() {
315 let long = "x".repeat(NAME_CAPACITY * 2);
316 let n = Name::new(&long, usize::MAX);
317 assert_eq!(n.len(), NAME_CAPACITY);
318 }
319
320 /// `is_empty` is `len == 0` both ways round -- a name with characters is
321 /// not empty (plan P5: `is_empty -> true` survived every oracle, because
322 /// nothing asked a non-empty name).
323 #[test]
324 fn a_name_with_characters_is_not_empty() {
325 assert!(!Name::new("IDLE", 12).is_empty());
326 assert!(Name::new("", 12).is_empty());
327 }
328
329 /// Both formatters print the name -- `Display` bare, `Debug` quoted, as
330 /// a `str` would (plan P5: both survived replaced by `Ok(())`).
331 #[test]
332 fn display_and_debug_print_the_name() {
333 let n = Name::new("Tmr Svc", 12);
334 assert_eq!(std::format!("{n}"), "Tmr Svc");
335 assert_eq!(std::format!("{n:?}"), "\"Tmr Svc\"");
336 }
337}