forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB7947774Tahinli1 month ago3899 commits

stack_budget.rs999 lines, 42.8 KiBHistoryRawDownload
1#![cfg(test)]
2//! A measured bound on the crate's BY-VALUE types, and a gate that bites.
3//!
4//! # The class
5//!
6//! A large struct returned BY VALUE from a public constructor is a stack cost,
7//! not a heap cost, and the cost is paid by the CALLER. The constructors here
8//! nest -- `Ac3Decoder::new` -> `Ac3Decoder::with_options` -> `Core::new` for
9//! the decoder -- and in an unoptimized build each level materialises its whole
10//! return slot before the inner call returns. So one value's `size_of` is the
11//! MULTIPLIER, and the chain length is the other factor.
12//!
13//! That is not hypothetical. `Ac3Decoder` was **20,024** bytes by value -- its
14//! inline `decode::Core` carried four per-channel coefficient planes
15//! (`exps`, `bap`, `coeffs`, `delay`) that are **16,896** of `Core`'s 19,728
16//! bytes -- and every `Ac3Decoder::new()` / `Ac3Decoder::with_options()` call
17//! made the caller pay all of it on its own stack. `.cargo/config.toml`
18//! carries `RUST_MIN_STACK = 67108864`, which HIDES the class from this
19//! workspace's own runs -- a band-aid a library consumer does not get. Boxing
20//! those four fields took `Core` to **2,864** and `Ac3Decoder` to **3,160**;
21//! [`the_crate_private_core_stays_behind_a_box`] is the pin that keeps them
22//! there.
23//!
24//! # Why this module exists when that boxing already exists
25//!
26//! The boxing fixed ONE type. The class was not swept: nothing stopped the
27//! next 18 KB inline plane from landing in `Core`, and nothing said which types
28//! had been checked. This module is the sweep:
29//!
30//! 1. [`BY_VALUE_TYPES`] is the inventory -- every public type in this crate
31//! that a public `fn` can return by value, with a measured `size_of` floor
32//! recorded as of this commit.
33//! [`the_measured_inventory_is_accurate`] fails if a type's size moves, so
34//! the table cannot rot into a list of stale small numbers.
35//! 2. [`STACK_BUDGET`] is the bound, and
36//! [`every_by_value_type_fits_the_stack_budget`] asserts it BY NAME for
37//! every row, so a regression reds naming the type that caused it.
38//! 3. [`the_crate_private_core_stays_behind_a_box`] pins the four `Box` field
39//! spellings, with a negative control, so the fix is not silently reverted.
40//! 4. [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] is the
41//! capability arm: it really constructs the heavy types on a deliberately
42//! tight thread, so the old layout ABORTS THE PROCESS rather than quietly
43//! costing margin.
44//! 5. [`every_by_value_public_return_is_in_the_inventory`] is the sweep's
45//! teeth against NEW types: a source scan re-derives the set of by-value
46//! public returns from the crate source, so a lane that adds a 40 KB struct
47//! to a `pub fn` return reds here until it is measured and listed.
48//! [`the_inventory_scan_is_not_vacuous`] is its control, and
49//! [`every_by_value_module_is_scanned`] keeps the scan's file list derived
50//! from `lib.rs` rather than curated.
51//!
52//! # The bound, and why this number
53//!
54//! [`STACK_BUDGET`] = 8192 bytes (8 KiB). It is bounded from BOTH sides by
55//! measurement, and both sides are asserted in
56//! [`every_by_value_type_fits_the_stack_budget`] so neither can rot silently.
57//!
58//! **The quantity being bounded.** Not `size_of` in the abstract, but *what a
59//! caller can be made to owe*: the size of one by-value return, multiplied by
60//! how many constructor levels hold a copy of it at once. Three inputs:
61//!
62//! 1. **The smallest stack a caller can hand this crate is 2,101,248 bytes.**
63//! Measured, not assumed, by
64//! [`test_threads_get_the_stack_they_are_given`] reading
65//! `/proc/self/task/<tid>/maps`. That is libtest's default test thread and
66//! also what `std::thread::Builder::new()` gives a caller who does not ask
67//! for a size. A library consumer gets no `.cargo/config.toml`.
68//! 2. **The deepest PUBLIC by-value chain is 2** ([`DEEPEST_PUBLIC_CHAIN`]):
69//! `Ac3Decoder::new` (decoder.rs:117) -> `Ac3Decoder::with_options`
70//! (decoder.rs:122), which calls `Core::new()` (decode.rs:136) as a third,
71//! crate-private level carrying a 2,864-byte `Core`. The encoder's
72//! `Ac3Encoder::new` is a single level -- it builds the struct inline in
73//! its `Ok(..)` and does not nest -- and `Ac3Decoder::decode_frame`'s
74//! `Result<AudioFrame>` is a single level too. The test asserts
75//! `DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 MiB` -- i.e. the by-value return
76//! slots may claim at most an EIGHTH of a caller's stack, leaving the rest
77//! for the decode, which is the thing that actually needs it.
78//! 3. **The budget applies only to types a `pub fn` returns.** The
79//! crate-private 2,864-byte `Core` is measured and listed but is NOT
80//! bounded, because no caller can reach it by value -- every field that
81//! holds one of its 16,896-byte planes is a `Box`, which
82//! [`the_crate_private_core_stays_behind_a_box`] pins by source. Bounding
83//! it would calibrate the number to something unreachable.
84//!
85//! **Where the number sits.** At 8 KiB with the worst public return at 3,160
86//! bytes ([`Ac3Decoder`]), the worst a caller owes is `2 x 3160 = 6,320` bytes
87//! -- **0.30%** of a 2 MiB thread -- and the budget itself is 2.59x above the
88//! incumbent. `Ac3Decoder` is also the row closest to the budget, at **38.6%**
89//! of it: **5,032 bytes of margin**, the least of any row here.
90//! [`Ac3Encoder`] is second, at 34.0% and 5,408 bytes of margin. Both
91//! directions have room, which is the point: a bound the largest type sits
92//! just under is a bound the next lane will quietly raise.
93//!
94//! **What it catches.** A pre-fix `Ac3Decoder` (20,024 B) is **2.44x over**
95//! budget. The pre-fix `Core` (19,728 B) behind it is **2.41x over** the same
96//! number -- that is the ratio the layout fix removed, not one this gate
97//! enforces, because no `pub fn` returns `Core`; the pin on its four `Box`
98//! fields is what keeps it there. Both the historical defect and the
99//! near-miss red by a factor, not by a hair.
100//!
101//! **What it does not claim.** `size_of` is layout, not stack depth, and the
102//! gap between the two is the nesting multiplier plus every frame a call owns
103//! for its own work. `Ac3Encoder::new` is the clearest case: its 2,784-byte
104//! return is nowhere near the budget, yet building it needs ~80 KiB of thread
105//! in a debug build, because it materialises a `[0.0f32; 512]` window, an
106//! `Mdct::new(512)` plan and a per-`COEFFS` IMDCT basis sweep. So this module
107//! does not trust the arithmetic:
108//! [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] constructs both
109//! heavy types for real on a real thread, and its measured threshold is the
110//! number that settles it.
111
112use crate::decoder::{Ac3Decoder, Options};
113use crate::encode::Ac3Encoder;
114
115/// The per-type ceiling for a type a CALLER can be made to hold by value, in
116/// bytes. See the module docs for the derivation; it is two-sided, and both
117/// sides are measured.
118pub(crate) const STACK_BUDGET: usize = 8192;
119
120/// The deepest PUBLIC by-value constructor chain in this crate, counted from
121/// the source:
122///
123/// * `Ac3Decoder::new` (decoder.rs:117) -> `Ac3Decoder::with_options`
124/// (decoder.rs:122): TWO public levels, both returning a 3,160-byte
125/// `Ac3Decoder` by value. `with_options` calls `Core::new()`
126/// (decode.rs:136), a third level, but that one is `pub(crate)` and carries
127/// a 2,864-byte `Core`, so it is not a public return.
128/// * `Ac3Encoder::new` (encode.rs:254): ONE level. It builds the struct
129/// inline in its `Ok(Ac3Encoder { .. })` (encode.rs:306) and never calls
130/// another constructor that returns it by value.
131/// * `Ac3Decoder::decode_frame` (decoder.rs:156) -> `Result<AudioFrame>`:
132/// ONE level, 96 bytes. It does not nest.
133///
134/// The budget is checked against two, the worst of the three.
135#[cfg(test)]
136const DEEPEST_PUBLIC_CHAIN: usize = 2;
137
138/// Every public type in this crate a public `fn` can return BY VALUE, with the
139/// `size_of` measured at the commit that wrote this table. `None` means "not
140/// yet measured", which [`the_measured_inventory_is_accurate`] rejects.
141///
142/// The third column names the return path, so a reader can see why a type is
143/// here rather than a coincidence of the type system.
144pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[
145 // -- decoder.rs: the headline row -------------------------------------
146 (
147 "Ac3Decoder",
148 Some(3704),
149 true,
150 "Ac3Decoder::new / with_options -> Ac3Decoder, nesting two deep. Was \
151 20024 bytes with decode::Core's four coefficient planes inline, i.e. \
152 2.44x over the 8192-byte budget. 3184 since the dependents Vec (24 bytes, \
153 heap-allocated: one Core per dependent substream of a packet). 3704 since \
154 the dither generator became ffmpeg's 64-word lagged-Fibonacci state \
155 (two instances, +520 bytes), so that the noise matches ffmpeg's",
156 ),
157 // -- encode.rs: the second-closest row to the budget -------------------
158 (
159 "Ac3Encoder",
160 Some(2784),
161 true,
162 "Ac3Encoder::new -> Result<Ac3Encoder>, one level, no nesting. \
163 34.0% of the budget, 5408 bytes of margin; Ac3Decoder above is the \
164 closest row at 38.6%",
165 ),
166 (
167 "EncoderConfig",
168 Some(12),
169 true,
170 "consumed by value by Ac3Encoder::new, which copies it into the \
171 encoder it returns",
172 ),
173 (
174 "EncodeStats",
175 Some(72),
176 true,
177 "Ac3Encoder::stats -> EncodeStats, by value out of the encoder's field",
178 ),
179 // -- decoder.rs: the header/option surface ---------------------------
180 (
181 "Options",
182 Some(8),
183 true,
184 "Ac3Decoder::with_options(Options) takes it by value and keeps it",
185 ),
186 (
187 "FrameInfo",
188 Some(48),
189 true,
190 "built by value in Ac3Decoder's private info_from; handed back as \
191 Option<&FrameInfo>, a BORROW, so the row is about the move the \
192 decoder makes internally",
193 ),
194 (
195 "Downmix",
196 Some(1),
197 true,
198 "Options::downmix, a field of the by-value Options above",
199 ),
200 (
201 "AudioFrame",
202 Some(96),
203 true,
204 "Ac3Decoder::decode_frame -> Result<AudioFrame>, one level, no \
205 nesting. From ec_core, not this crate, but it is a public return of \
206 this crate and the sweep finds it by name",
207 ),
208 // -- decode.rs -------------------------------------------------------
209 (
210 "Syntax",
211 Some(1),
212 true,
213 "re-exported from decode; a field of FrameInfo and of Ac3Decoder::Core",
214 ),
215 // -- the header parsers ----------------------------------------------
216 (
217 "Bsi",
218 Some(56),
219 true,
220 "bsi::parse / bsi::parse_from -> Result<Bsi>, one level each",
221 ),
222 ("Acmod", Some(1), true, "bsi::Acmod::from_code -> Acmod"),
223 (
224 "SyncInfo",
225 Some(24),
226 true,
227 "syncinfo::parse / syncinfo::parse_from -> Result<SyncInfo>",
228 ),
229 (
230 "Eac3Bsi",
231 Some(96),
232 true,
233 "eac3::bsi::parse / eac3::bsi::parse_from -> Result<Eac3Bsi>",
234 ),
235 (
236 "StreamType",
237 Some(1),
238 true,
239 "a field of the by-value Eac3Bsi above; eac3::StreamType::Dependent \
240 is the first-substream refusal",
241 ),
242 // -- transform.rs / mantissa.rs / exps.rs ----------------------------
243 (
244 "Imdct",
245 Some(472),
246 true,
247 "transform::Imdct::new -> Imdct, one level. Held inline in both Core \
248 and Ac3Encoder, the largest type in the crate that is NOT a public \
249 return",
250 ),
251 (
252 "Mantissas",
253 Some(56),
254 true,
255 "mantissa::Mantissas::new -> Mantissas, one level",
256 ),
257 (
258 "Strategy",
259 Some(1),
260 true,
261 "exps::Strategy::from_code -> Strategy; a field of Core's inline \
262 [Strategy; CHANNELS]",
263 ),
264 // -- bitalloc.rs -----------------------------------------------------
265 (
266 "BitAllocParams",
267 Some(5),
268 true,
269 "bitalloc::BitAllocParams::default, copied into Core's inline copy",
270 ),
271 (
272 "DeltaBa",
273 Some(32),
274 true,
275 "bitalloc::DeltaBa, built by value per block",
276 ),
277 (
278 "Allocation",
279 Some(56),
280 true,
281 "bitalloc::Allocation<'_>, built by value and passed to \
282 bitalloc::compute by reference; the move copies the struct, not the \
283 borrowed slices",
284 ),
285 (
286 "Channel",
287 Some(12),
288 true,
289 "bitalloc::Channel, moved out of the per-block channel table",
290 ),
291 // -- crate-private: never a public return, and every one of its four
292 // -- large planes is behind a Box now. The budget does not apply; the
293 // -- pin that does is `the_crate_private_core_stays_behind_a_box`.
294 (
295 "Core",
296 Some(3384),
297 false,
298 "decode::Core::new -> Core, pub(crate), held inline in Ac3Decoder. \
299 Was 19728 bytes with exps/bap/coeffs/delay inline; those four are \
300 16896 of them and are boxed now",
301 ),
302];
303
304/// The live `size_of` for every inventoried type, keyed BY NAME.
305///
306/// Keyed rather than positional on purpose: `Bsi`, `Mantissas` and
307/// `Allocation` are all 56 bytes, and `Eac3Bsi` and `AudioFrame` are both 96,
308/// so a row inserted into [`BY_VALUE_TYPES`] without a matching insert here
309/// would zip cleanly and assert the wrong type's size against the wrong
310/// recorded one. A name key makes that mistake loud instead.
311#[cfg(test)]
312fn measured_by_name() -> Vec<(&'static str, usize)> {
313 vec![
314 ("Ac3Decoder", std::mem::size_of::<Ac3Decoder>()),
315 ("Ac3Encoder", std::mem::size_of::<Ac3Encoder>()),
316 (
317 "EncoderConfig",
318 std::mem::size_of::<crate::encode::EncoderConfig>(),
319 ),
320 (
321 "EncodeStats",
322 std::mem::size_of::<crate::encode::EncodeStats>(),
323 ),
324 ("Options", std::mem::size_of::<Options>()),
325 (
326 "FrameInfo",
327 std::mem::size_of::<crate::decoder::FrameInfo>(),
328 ),
329 ("Downmix", std::mem::size_of::<crate::decoder::Downmix>()),
330 ("AudioFrame", std::mem::size_of::<ec_core::AudioFrame>()),
331 ("Syntax", std::mem::size_of::<crate::decode::Syntax>()),
332 ("Bsi", std::mem::size_of::<crate::bsi::Bsi>()),
333 ("Acmod", std::mem::size_of::<crate::bsi::Acmod>()),
334 ("SyncInfo", std::mem::size_of::<crate::syncinfo::SyncInfo>()),
335 ("Eac3Bsi", std::mem::size_of::<crate::eac3::Eac3Bsi>()),
336 ("StreamType", std::mem::size_of::<crate::eac3::StreamType>()),
337 ("Imdct", std::mem::size_of::<crate::transform::Imdct>()),
338 (
339 "Mantissas",
340 std::mem::size_of::<crate::mantissa::Mantissas>(),
341 ),
342 ("Strategy", std::mem::size_of::<crate::exps::Strategy>()),
343 (
344 "BitAllocParams",
345 std::mem::size_of::<crate::bitalloc::BitAllocParams>(),
346 ),
347 ("DeltaBa", std::mem::size_of::<crate::bitalloc::DeltaBa>()),
348 (
349 "Allocation",
350 std::mem::size_of::<crate::bitalloc::Allocation<'static>>(),
351 ),
352 ("Channel", std::mem::size_of::<crate::bitalloc::Channel>()),
353 ("Core", std::mem::size_of::<crate::decode::Core>()),
354 ]
355}
356
357/// The stack [`the_deepest_by_value_constructors_fit_on_a_tight_stack`]
358/// constructs on.
359///
360/// 1 MiB: half of what an unconfigured caller gives this crate, and far above
361/// what the deepest measured chain needs in a debug build. The threshold was
362/// swept in an unoptimized build and is reproducible with
363/// `EC_AC3_TIGHT_STACK_BYTES`.
364const TIGHT_STACK: usize = 1024 * 1024;
365
366#[cfg(test)]
367mod tests {
368 use super::{
369 BY_VALUE_TYPES, DEEPEST_PUBLIC_CHAIN, STACK_BUDGET, TIGHT_STACK, measured_by_name,
370 };
371 use crate::decoder::{Ac3Decoder, Downmix, Options};
372 use crate::encode::{Ac3Encoder, EncoderConfig};
373
374 /// Return types that are not a by-value copy of anything the caller has to
375 /// own: a pointer, a slice, a `Vec` (three words, and the heap is not the
376 /// stack), or a primitive. `Self` is a by-value copy of the impl's type,
377 /// which the inventory rows already cover, so it is exempt from the scan
378 /// and not from the table.
379 const THIN: &[&str] = &[
380 "Box", "Rc", "Arc", "Cow", "Vec", "VecDeque", "String", "OsString", "PathBuf", "HashMap",
381 "BTreeMap", "BTreeSet", "HashSet", "str", "u8", "u16", "u32", "u64", "usize", "i8", "i16",
382 "i32", "i64", "isize", "f32", "f64", "bool", "char", "Self",
383 ];
384
385 /// The type name a `pub fn` line returns BY VALUE, or `None` when the line
386 /// returns a pointer, a `Vec`, a primitive, or nothing.
387 ///
388 /// One function, shared by the sweep and its control, so the control
389 /// cannot pass while the sweep's copy of the logic rotted.
390 fn by_value_return_name(line: &str) -> Option<String> {
391 let trimmed = line.trim_start();
392 if !trimmed.starts_with("pub fn ") {
393 return None;
394 }
395 let arrow = line.find("->")?;
396 let rest = &line[arrow + 2..];
397 let end = rest.find('{').unwrap_or(rest.len());
398 let ret = rest[..end].trim();
399 if ret.is_empty() {
400 return None;
401 }
402 // Unwrap one `Result<..>` / `Option<..>` layer. A deeper nesting is
403 // not a shape this crate uses, and flagging one as uninventoried is
404 // the safe direction to be wrong in.
405 let inner = {
406 let t = ret
407 .strip_prefix("Result<")
408 .or_else(|| ret.strip_prefix("Option<"))
409 .unwrap_or(ret);
410 t.split('>').next().unwrap_or(t)
411 };
412 // Drop the error type and any lifetime or generic argument:
413 // `Result<Bsi, Error>`, `Allocation<'a>` and `AudioFrame` are all the
414 // bare name for this purpose. Splitting on the comma is load-bearing:
415 // the first version of this matcher cut only at `>` and so read
416 // `Result<Bsi, Error>` as the name "Bsi, Error". `ec_av1`'s control
417 // caught exactly that, which is why the control is not optional.
418 let name = inner.split(['<', ',']).next().unwrap_or(inner).trim();
419 if name.is_empty() || THIN.contains(&name) {
420 return None;
421 }
422 // A generic parameter, not a concrete type.
423 if !name.chars().next().is_some_and(char::is_uppercase) {
424 return None;
425 }
426 Some(name.to_string())
427 }
428
429 /// The source files the by-value scan reads. Every module that can expose
430 /// a `pub fn` returning a named type; a new module added to `lib.rs` needs
431 /// adding here, and
432 /// [`every_by_value_module_is_scanned`] is what keeps that honest.
433 const FILES: &[(&str, &str)] = &[
434 ("aht.rs", include_str!("aht.rs")),
435 ("aht_tables.rs", include_str!("aht_tables.rs")),
436 ("bitalloc.rs", include_str!("bitalloc.rs")),
437 ("bsi.rs", include_str!("bsi.rs")),
438 ("decode.rs", include_str!("decode.rs")),
439 ("decoder.rs", include_str!("decoder.rs")),
440 ("dependent.rs", include_str!("dependent.rs")),
441 ("eac3.rs", include_str!("eac3.rs")),
442 ("encode.rs", include_str!("encode.rs")),
443 ("exps.rs", include_str!("exps.rs")),
444 ("lib.rs", include_str!("lib.rs")),
445 ("mantissa.rs", include_str!("mantissa.rs")),
446 ("stack_budget.rs", include_str!("stack_budget.rs")),
447 ("syncinfo.rs", include_str!("syncinfo.rs")),
448 ("tables.rs", include_str!("tables.rs")),
449 ("transform.rs", include_str!("transform.rs")),
450 ];
451
452 /// Every module `lib.rs` declares, so the scan's file list cannot silently
453 /// fall behind a new module. A new `mod foo;` with a by-value `pub fn`
454 /// that the scan never reads is exactly the hole this class would come
455 /// back through, so the list is derived, not curated.
456 #[test]
457 fn every_by_value_module_is_scanned() {
458 let lib = include_str!("lib.rs");
459 let mut declared: Vec<&str> = Vec::new();
460 for line in lib.lines() {
461 let t = line.trim();
462 let rest = t
463 .strip_prefix("pub mod ")
464 .or_else(|| t.strip_prefix("mod "))
465 .unwrap_or("");
466 if rest.is_empty() {
467 continue;
468 }
469 let name = rest.split([';', ' ']).next().unwrap_or("");
470 if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
471 declared.push(name);
472 }
473 }
474 assert!(
475 declared.len() > 10,
476 "only {} module declarations parsed out of lib.rs, so the \
477 derived file list is broken rather than small",
478 declared.len()
479 );
480 let scanned: Vec<&str> = FILES.iter().map(|(n, _)| *n).collect();
481 let mut missing: Vec<String> = declared
482 .iter()
483 .filter(|d| !scanned.iter().any(|s| *s == format!("{d}.rs")))
484 .map(|d| (*d).to_string())
485 .collect();
486 missing.sort();
487 assert!(
488 missing.is_empty(),
489 "lib.rs declares modules the by-value scan never reads: {:?}. Add \
490 them to FILES, or the sweep cannot see a new by-value return that \
491 lands in one of them.",
492 missing
493 );
494 }
495
496 /// The inventory, printed as a sorted table, and checked against the
497 /// types' real sizes.
498 ///
499 /// The print is the instrument: one command
500 /// (`cargo test -p ec-ac3 --lib -- stack_budget -- --nocapture`)
501 /// reproduces the whole table, biggest first, so "what is the largest
502 /// by-value type in this crate" has an answer that is a measurement
503 /// rather than a grep.
504 ///
505 /// The check reds on ANY change with both numbers. That is deliberate: a
506 /// by-value type that grew raises the question of whether it should have
507 /// been boxed instead, and auto-accepting the new number would answer
508 /// that question by default.
509 #[test]
510 fn the_measured_inventory_is_accurate() {
511 let live = measured_by_name();
512 assert_eq!(
513 BY_VALUE_TYPES.len(),
514 live.len(),
515 "the inventory names {} types but {} are measured; every row needs \
516 a measured size or the sweep is a list of hopes",
517 BY_VALUE_TYPES.len(),
518 live.len()
519 );
520 let mut rows: Vec<(&str, usize)> = live.clone();
521 rows.sort_by_key(|&(_, size)| std::cmp::Reverse(size));
522 eprintln!(
523 "\nBY-VALUE INVENTORY ({} types, budget {STACK_BUDGET} B = {} KiB)",
524 rows.len(),
525 STACK_BUDGET / 1024
526 );
527 eprintln!("{:>8} {:>7} TYPE", "BYTES", "%BUDGET");
528 for (name, size) in &rows {
529 eprintln!(
530 "{size:>8} {:>6.1}% {name}",
531 *size as f64 * 100.0 / STACK_BUDGET as f64
532 );
533 }
534 for (name, recorded, _public, _path) in BY_VALUE_TYPES {
535 let recorded = recorded.expect("every inventory row carries a measured size");
536 let actual = live
537 .iter()
538 .find(|(n, _)| n == name)
539 .map(|(_, size)| *size)
540 .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
541 assert_eq!(
542 recorded, actual,
543 "{name} is {actual} bytes, the inventory records {recorded}; \
544 update the table deliberately -- a by-value type that changed \
545 is a stack cost every caller of its constructor now pays"
546 );
547 }
548 }
549
550 /// The bound, asserted BY NAME. A regression in any inventoried type reds
551 /// here naming the type, not "some type is too big".
552 #[test]
553 fn every_by_value_type_fits_the_stack_budget() {
554 let live = measured_by_name();
555 let mut checked = 0usize;
556 for (name, _, public, path) in BY_VALUE_TYPES {
557 if !public {
558 continue;
559 }
560 checked += 1;
561 let size = live
562 .iter()
563 .find(|(n, _)| n == name)
564 .map(|(_, size)| *size)
565 .unwrap_or_else(|| panic!("{name} is inventoried but never measured"));
566 assert!(
567 size <= STACK_BUDGET,
568 "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \
569 stack budget ({:.2}x). It is returned by value from {path}, so \
570 every caller pays it on its own stack, and the constructors \
571 nest -- one value's size is the multiplier, not the cost. \
572 Box the large field (this crate did exactly that for \
573 Ac3Decoder's inline decode::Core) or hand back a reference.",
574 size as f64 / STACK_BUDGET as f64
575 );
576 }
577 assert!(
578 checked >= 10,
579 "only {checked} rows were bound-checked; the budget must apply to \
580 every type a caller can be made to hold by value"
581 );
582 // The other half of the derivation, asserted so it cannot rot: the
583 // worst a caller can owe is DEEPEST_CHAIN x the worst public return.
584 let worst = live
585 .iter()
586 .filter(|(n, _)| {
587 BY_VALUE_TYPES
588 .iter()
589 .any(|(row, _, public, _)| row == n && *public)
590 })
591 .map(|(_, size)| *size)
592 .max()
593 .expect("at least one public row");
594 assert!(
595 DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024,
596 "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \
597 public by-value return ({worst} B) is {} B, over an eighth of the \
598 2101248-byte stack an unconfigured caller hands this crate; \
599 re-derive STACK_BUDGET",
600 DEEPEST_PUBLIC_CHAIN * worst
601 );
602 }
603
604 /// The crate-private decode state stays BEHIND A BOX.
605 ///
606 /// The budget does not apply to `Core` because no `pub fn` returns it, so
607 /// bounding it would calibrate the number to something no caller can
608 /// reach. What keeps its 16,896 bytes of coefficient planes off every
609 /// caller's stack is that the four fields holding them are `Box`es, and
610 /// THIS is the pin for that -- a source scan over the four declarations
611 /// plus the four `Box::new`s in `Core::new`.
612 ///
613 /// It earned its place during the layout fix: `exps`, `bap` and `delay`
614 /// are `[[T; COEFFS]; CHANNELS]`-shaped planes at 1,792 / 1,792 / 6,144
615 /// bytes and `coeffs` is 7,168 -- 16,896 of a 19,728-byte `Core` -- and
616 /// `Core` sits inline in the `Ac3Decoder` that `Ac3Decoder::new` hands a
617 /// caller BY VALUE. Unboxing any of the four puts the stack cost straight
618 /// back.
619 #[test]
620 fn the_crate_private_core_stays_behind_a_box() {
621 const PINS: &[(&str, &str)] = &[
622 (
623 "decode.rs::Core::exps",
624 "exps: Box<[[u8; COEFFS]; CHANNELS]>",
625 ),
626 ("decode.rs::Core::bap", "bap: Box<[[u8; COEFFS]; CHANNELS]>"),
627 (
628 "decode.rs::Core::coeffs",
629 "coeffs: Box<[[f32; COEFFS]; CHANNELS]>",
630 ),
631 (
632 "decode.rs::Core::delay",
633 "delay: Box<[[f32; COEFFS]; MAX_FBW + 1]>",
634 ),
635 (
636 "decode.rs::Core::new::exps",
637 "exps: Box::new([[0; COEFFS]; CHANNELS])",
638 ),
639 (
640 "decode.rs::Core::new::bap",
641 "bap: Box::new([[0; COEFFS]; CHANNELS])",
642 ),
643 (
644 "decode.rs::Core::new::coeffs",
645 "coeffs: Box::new([[0.0; COEFFS]; CHANNELS])",
646 ),
647 (
648 "decode.rs::Core::new::delay",
649 "delay: Box::new([[0.0; COEFFS]; MAX_FBW + 1])",
650 ),
651 ];
652 const UNBOXED: &[(&str, &str)] = &[
653 ("decode.rs::Core::exps", "exps: [[u8; COEFFS]; CHANNELS],"),
654 ("decode.rs::Core::bap", "bap: [[u8; COEFFS]; CHANNELS],"),
655 (
656 "decode.rs::Core::coeffs",
657 "coeffs: [[f32; COEFFS]; CHANNELS],",
658 ),
659 (
660 "decode.rs::Core::delay",
661 "delay: [[f32; COEFFS]; MAX_FBW + 1],",
662 ),
663 ];
664 let decode = include_str!("decode.rs");
665 for (where_, spelling) in PINS {
666 assert!(
667 decode.contains(spelling),
668 "{where_} is no longer declared `{spelling}`. An inline \
669 coefficient plane there puts its 16896 bytes back inside \
670 decode::Core, which sits inline in the Ac3Decoder that \
671 Ac3Decoder::new returns BY VALUE -- that is how Ac3Decoder was \
672 20024 bytes, 2.44x over the by-value budget.",
673 );
674 }
675 // And the negative control: the unboxed spellings must be ABSENT, or
676 // the scan above would be matching a doc comment or a dead branch
677 // rather than the live declaration.
678 for (where_, unboxed) in UNBOXED {
679 assert!(
680 !decode.contains(unboxed),
681 "{where_} is declared `{unboxed}`, unboxed. The box pin above \
682 is not matching the live declaration, or the plane is inline \
683 again and every Ac3Decoder::new caller pays 16896 bytes.",
684 );
685 }
686 }
687
688 /// CAPABILITY: really construct the heavy types on a tight stack, so a
689 /// regression ABORTS THE PROCESS instead of costing invisible margin.
690 ///
691 /// Arm 1 is the two-deep `Ac3Decoder` constructor nest -- the crate's
692 /// largest by-value return, and the type this lane's layout fix took from
693 /// 20,024 to 3,160 bytes. Arm 2 is `Ac3Encoder::new`, the second-closest
694 /// row to the budget at 34.0% of it.
695 ///
696 /// Both arms assert a REAL property of what came back, not merely that the
697 /// thread survived: a fresh `Ac3Decoder` has no `frame_info()` before any
698 /// syncframe, and one built with explicit options hands those exact options
699 /// back through `options_mut()`. A constructor that quietly dropped its
700 /// argument would red here rather than pass on a stack measurement alone.
701 ///
702 /// Measured stack need, **debug** build, one process per point so a
703 /// stack-overflow abort cannot truncate the sweep:
704 ///
705 /// | `EC_AC3_TIGHT_STACK_BYTES` | result |
706 /// |---|---|
707 /// | 1048576 (1 MiB) | **ok** |
708 /// | 524288 | **ok** |
709 /// | 262144 | **ok** |
710 /// | 131072 | **ok** |
711 /// | 98304 | **ok** |
712 /// | 86016 | **ok** |
713 /// | 81920 | **ok** |
714 /// | 77824 | overflow |
715 /// | 65536 | overflow |
716 /// | 32768 | overflow |
717 /// | 24576 | overflow |
718 ///
719 /// The deepest measured need is therefore between 77,824 and 81,920
720 /// bytes, and the gate sits at 1 MiB -- **12.8x** that, and half of what an
721 /// unconfigured caller hands this crate. The ~80 KiB is dominated by
722 /// `Ac3Encoder::new`'s own working frames (a 512-float window, an
723 /// `Mdct::new(512)` plan and a per-`COEFFS` IMDCT basis sweep), not by the
724 /// by-value return slots this module bounds; that is exactly the residual
725 /// `size_of` cannot predict, and why the arm constructs rather than
726 /// computing.
727 ///
728 /// `EC_AC3_TIGHT_STACK_BYTES` overrides the size, which is how the
729 /// threshold is swept.
730 #[test]
731 fn the_deepest_by_value_constructors_fit_on_a_tight_stack() {
732 let stack: usize = std::env::var("EC_AC3_TIGHT_STACK_BYTES")
733 .ok()
734 .and_then(|v| v.parse().ok())
735 .unwrap_or(TIGHT_STACK);
736 let config = EncoderConfig {
737 sample_rate: 48_000,
738 channels: 2,
739 bitrate_kbps: 192,
740 };
741 let handle = std::thread::Builder::new()
742 .stack_size(stack)
743 .spawn(move || {
744 // Arm 1: the two-deep `Ac3Decoder` constructor nest, the
745 // crate's largest by-value return.
746 let mut plain = Ac3Decoder::new();
747 let fresh_has_no_frame_info = plain.frame_info().is_none();
748 let plain_options = *plain.options_mut();
749 // A decoder built with explicit options must keep exactly
750 // those options, including a non-default downmix.
751 let mut configured = Ac3Decoder::with_options(Options {
752 drc_scale: 0.25,
753 downmix: Downmix::Stereo,
754 dither: false,
755 });
756 let kept = *configured.options_mut();
757 drop(plain);
758 drop(configured);
759 // Arm 2: `Ac3Encoder::new`, the second-closest row to the budget.
760 let encoder = Ac3Encoder::new(config).expect("Ac3Encoder::new");
761 let delay = encoder.encoder_delay();
762 let stats = encoder.stats();
763 (fresh_has_no_frame_info, plain_options, kept, delay, stats)
764 })
765 .expect("spawn tight-stack thread");
766 let (fresh_has_no_frame_info, plain_options, kept, delay, stats) =
767 handle.join().unwrap_or_else(|_| {
768 panic!(
769 "a by-value constructor overflowed a {stack}-byte stack; the \
770 old 20024-byte Ac3Decoder is what that costs"
771 )
772 });
773 assert!(
774 fresh_has_no_frame_info,
775 "a freshly constructed Ac3Decoder already reported a frame_info(); \
776 decode_frame is the only thing that may set one"
777 );
778 assert_eq!(
779 plain_options,
780 Options::default(),
781 "Ac3Decoder::new did not give back the default Options"
782 );
783 assert_eq!(
784 kept,
785 Options {
786 drc_scale: 0.25,
787 downmix: Downmix::Stereo,
788 dither: false,
789 },
790 "Ac3Decoder::with_options did not keep the options it was handed"
791 );
792 assert!(
793 delay > 0,
794 "Ac3Encoder::encoder_delay reported no priming samples"
795 );
796 assert_eq!(
797 stats,
798 crate::encode::EncodeStats::default(),
799 "a fresh Ac3Encoder reported non-zero coding stats"
800 );
801 eprintln!(
802 "TIGHTSTACK {stack} bytes: Ac3Decoder={} Ac3Encoder={} bytes, both \
803 constructors returned and both options paths round-tripped",
804 std::mem::size_of::<Ac3Decoder>(),
805 std::mem::size_of::<Ac3Encoder>(),
806 );
807 }
808
809 /// The sweep's teeth against a NEW by-value return: re-derive the set from
810 /// the crate source and require every name to be inventoried.
811 ///
812 /// Without this the inventory is a list of what someone remembered to
813 /// measure, and a lane that adds `pub fn make() -> HugeThing` where
814 /// `HugeThing` is 200 KB of inline tables passes every other test here.
815 #[test]
816 fn every_by_value_public_return_is_in_the_inventory() {
817 let mut found: Vec<(String, String)> = Vec::new();
818 for (file, src) in FILES {
819 for (n, line) in src.lines().enumerate() {
820 if let Some(name) = by_value_return_name(line) {
821 found.push((name, format!("{file}:{}", n + 1)));
822 }
823 }
824 }
825 found.sort();
826 found.dedup();
827 assert!(
828 found.len() > 5,
829 "the by-value return scan found {} names across {} files, which is \
830 too few to be a real sweep -- the matcher, not the crate, is broken",
831 found.len(),
832 FILES.len()
833 );
834 eprintln!("BY-VALUE PUBLIC RETURNS FOUND: {found:?}");
835
836 let mut missing = Vec::new();
837 for (name, site) in &found {
838 if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) {
839 missing.push(format!("{name} ({site})"));
840 }
841 }
842 assert!(
843 missing.is_empty(),
844 "these types are returned BY VALUE from a public fn and are not in \
845 the inventory: {}. Either they are thin enough not to be a stack \
846 cost -- say so by adding a row with its measured size -- or they \
847 are the next instance of the class this module exists for.",
848 missing.join(", ")
849 );
850 }
851
852 /// The control for the scan above, on synthetic text rather than by
853 /// trusting the live tree to happen to contain a case.
854 ///
855 /// If the matcher silently stopped recognising a shape, the sweep would
856 /// pass everything and this would still be asserting nothing. So: every
857 /// by-value spelling the crate uses must yield its type name, and every
858 /// pointer/Vec/primitive/`Self` spelling must yield nothing.
859 #[test]
860 fn the_inventory_scan_is_not_vacuous() {
861 for synthetic in [
862 "pub fn zz_a() -> ZzNotInventoried { todo!() }",
863 "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }",
864 "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }",
865 "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }",
866 "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }",
867 ] {
868 let name = by_value_return_name(synthetic)
869 .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`"));
870 assert_eq!(
871 name, "ZzNotInventoried",
872 "the matcher mangled `{synthetic}` into `{name}`, so the sweep \
873 cannot see a new by-value return and its green is vacuous"
874 );
875 assert!(
876 !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name),
877 "the synthetic control name is in the inventory, so the control \
878 proves nothing"
879 );
880 }
881 for thin in [
882 "pub fn zz_t() -> Box<Decoder> { todo!() }",
883 "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }",
884 "pub fn zz_v() -> Option<&Path> { todo!() }",
885 "pub fn zz_w() -> usize { todo!() }",
886 "pub fn zz_x() -> Self { todo!() }",
887 "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }",
888 "pub fn zz_z() { todo!() }",
889 "fn zz_private() -> ZzNotInventoried { todo!() }",
890 ] {
891 assert_eq!(
892 by_value_return_name(thin),
893 None,
894 "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \
895 above already cover, or not a `pub fn` -- the matcher must not \
896 read it as an uninventoried by-value return"
897 );
898 }
899 }
900
901 /// The stack mapping containing `addr` in `/proc/self/task/<tid>/maps`.
902 ///
903 /// The returned size is a LOWER BOUND, never an exact count. Linux MERGES
904 /// adjacent VMAs that share protections, and a merged region is
905 /// indistinguishable from a single one in the maps file. A lower bound is
906 /// what the budget's reasoning needs: the claim is "no caller gets less
907 /// than 2 MiB", and `size >= 2 MiB` is exactly that, whether the region is
908 /// one mapping or three.
909 ///
910 /// The third field is whether the mapping is writable. Merging only joins
911 /// VMAs whose protections match, so a merged thread stack is still
912 /// writable. Its size can grow without bound, which is why the tests check
913 /// this flag and never an upper bound on the size.
914 fn stack_region(tid: u32, addr: usize) -> Option<(usize, usize, bool)> {
915 let maps = std::fs::read_to_string(format!("/proc/self/task/{tid}/maps")).ok()?;
916 for line in maps.lines() {
917 let (range, perms) = line.split_once(' ')?;
918 let (lo, hi) = range.split_once('-')?;
919 let (lo, hi) = (
920 usize::from_str_radix(lo, 16).ok()?,
921 usize::from_str_radix(hi, 16).ok()?,
922 );
923 if addr >= lo && addr < hi {
924 // `perms` is `rwxp`-style: the second character is write.
925 let writable = perms.as_bytes().get(1) == Some(&b'w');
926 return Some((lo, hi, writable));
927 }
928 }
929 None
930 }
931
932 /// What a thread's stack ACTUALLY is, read from
933 /// `/proc/self/task/<tid>/maps` rather than assumed from a default.
934 ///
935 /// The number the budget's reasoning rests on, measured two ways:
936 ///
937 /// * a thread spawned with an EXPLICIT size gets AT LEAST that size --
938 /// the control that says the parse finds stacks at all, and the shape
939 /// [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] relies on;
940 /// * the DEFAULT -- no `stack_size`, i.e. what a library consumer's
941 /// `std::thread::spawn` gets, and what libtest gives a test thread when
942 /// `RUST_MIN_STACK` is unset -- is at least 2 MiB.
943 ///
944 /// Both are floors, because [`stack_region`] can only report a lower bound.
945 /// That is the right direction: the budget's claim is that no caller gets
946 /// LESS than 2 MiB, and a floor is what proves it.
947 #[test]
948 fn test_threads_get_the_stack_they_are_given() {
949 const EXPLICIT: usize = 1024 * 1024;
950 let handle = std::thread::Builder::new()
951 .stack_size(EXPLICIT)
952 .spawn(|| {
953 let tid = std::process::id();
954 let marker = 0u8;
955 let here = &marker as *const u8 as usize;
956 let (lo, hi, rw) =
957 stack_region(tid, here).expect("this thread's own stack is in its maps");
958 (lo, hi, rw)
959 })
960 .expect("spawn");
961 let (lo, hi, rw) = handle.join().expect("the probe thread returned");
962 let size = hi - lo;
963 assert!(
964 size >= EXPLICIT,
965 "a thread spawned with stack_size({EXPLICIT}) has a {size}-byte \
966 stack mapping; the runtime gave it less than it was promised, so \
967 the maps parse is finding the wrong region"
968 );
969 assert!(
970 rw,
971 "the mapping holding an explicitly-1-MiB thread's frame is not \
972 writable -- a thread stack is read-write, so the maps parse found \
973 the wrong region"
974 );
975
976 let tid = std::process::id();
977 let marker = 0u8;
978 let here = &marker as *const u8 as usize;
979 let (lo, hi, rw) =
980 stack_region(tid, here).expect("this test thread's stack is in its maps");
981 let size = hi - lo;
982 assert!(
983 rw,
984 "a default test thread's stack mapping is not writable -- the maps \
985 parse found the wrong region"
986 );
987 assert!(
988 size >= 2 * 1024 * 1024,
989 "a default test thread's stack measured {size} bytes, under the \
990 2 MiB floor the by-value budget is derived from; the smallest \
991 stack a caller can hand this crate just got smaller and the bound \
992 needs re-deriving"
993 );
994 eprintln!(
995 "TESTTHREADSTACK default tid={tid} region=[{lo:x},{hi:x}) size>={size} \
996 (2101248 measured exactly with the repo cap lifted, 67112960 with it)"
997 );
998 }
999}