forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5ae8dcdTahinli1 month ago3858 commits

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