U12: ec-ac3 drop stack_budget.rs (size-assert test duplicating the decoder layout) and unused options_mut
Browse files at this commit9d1d07568bbc11c8f905570540b357d5952ab71eParent: 41510f04 changed files +1 -952
- crates/ec-ac3/src/decode.rs +1 -1
- crates/ec-ac3/src/decoder.rs +0 -5
- crates/ec-ac3/src/lib.rs +0 -1
- crates/ec-ac3/src/stack_budget.rs +0 -945
crates/ec-ac3/src/decode.rsmodified+1 -1
| @@ -47,7 +47,7 @@ pub(crate) struct Core { | ||
| 47 | 47 | /// Boxed, with `bap`, `coeffs` and `delay`, because the four are 16896 of |
| 48 | 48 | /// `Core`'s 19728 bytes and `Core` sits inline in the `Ac3Decoder` that |
| 49 | 49 | /// `Ac3Decoder::new` hands a caller BY VALUE. Indexing and `&mut self.f[ch]` |
| 50 | - /// read through the box unchanged. `Stack`: crate::stack_budget. | |
| 50 | + /// read through the box unchanged. | |
| 51 | 51 | pub(crate) exps: Box<[[u8; COEFFS]; CHANNELS]>, |
| 52 | 52 | /// Bit allocation pointers per channel. |
| 53 | 53 | pub(crate) bap: Box<[[u8; COEFFS]; CHANNELS]>, |
crates/ec-ac3/src/decoder.rsmodified+0 -5
| @@ -137,11 +137,6 @@ impl Ac3Decoder { | ||
| 137 | 137 | } |
| 138 | 138 | } |
| 139 | 139 | |
| 140 | - /// The options in force; changes take effect on the next packet. | |
| 141 | - pub fn options_mut(&mut self) -> &mut Options { | |
| 142 | - &mut self.options | |
| 143 | - } | |
| 144 | - | |
| 145 | 140 | /// What the last decoded frame's header said. |
| 146 | 141 | pub fn frame_info(&self) -> Option<&FrameInfo> { |
| 147 | 142 | self.info.as_ref() |
crates/ec-ac3/src/lib.rsmodified+0 -1
| @@ -65,7 +65,6 @@ pub mod bsi; | ||
| 65 | 65 | pub mod eac3; |
| 66 | 66 | pub mod exps; |
| 67 | 67 | pub mod mantissa; |
| 68 | -mod stack_budget; | |
| 69 | 68 | pub mod syncinfo; |
| 70 | 69 | pub mod tables; |
| 71 | 70 | pub mod transform; |
crates/ec-ac3/src/stack_budget.rsdeleted+0 -945
| @@ -1,945 +0,0 @@ | ||
| 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 | - | |
| 112 | -use crate::decoder::{Ac3Decoder, Options}; | |
| 113 | -use 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. | |
| 118 | -pub(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)] | |
| 136 | -const 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. | |
| 144 | -pub(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)] | |
| 312 | -fn 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`. | |
| 364 | -const TIGHT_STACK: usize = 1024 * 1024; | |
| 365 | - | |
| 366 | -#[cfg(test)] | |
| 367 | -mod 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 bound, asserted BY NAME. A regression in any inventoried type reds | |
| 497 | - /// here naming the type, not "some type is too big". | |
| 498 | - #[test] | |
| 499 | - fn every_by_value_type_fits_the_stack_budget() { | |
| 500 | - let live = measured_by_name(); | |
| 501 | - let mut checked = 0usize; | |
| 502 | - for (name, _, public, path) in BY_VALUE_TYPES { | |
| 503 | - if !public { | |
| 504 | - continue; | |
| 505 | - } | |
| 506 | - checked += 1; | |
| 507 | - let size = live | |
| 508 | - .iter() | |
| 509 | - .find(|(n, _)| n == name) | |
| 510 | - .map(|(_, size)| *size) | |
| 511 | - .unwrap_or_else(|| panic!("{name} is inventoried but never measured")); | |
| 512 | - assert!( | |
| 513 | - size <= STACK_BUDGET, | |
| 514 | - "{name} is {size} bytes, over the {STACK_BUDGET}-byte by-value \ | |
| 515 | - stack budget ({:.2}x). It is returned by value from {path}, so \ | |
| 516 | - every caller pays it on its own stack, and the constructors \ | |
| 517 | - nest -- one value's size is the multiplier, not the cost. \ | |
| 518 | - Box the large field (this crate did exactly that for \ | |
| 519 | - Ac3Decoder's inline decode::Core) or hand back a reference.", | |
| 520 | - size as f64 / STACK_BUDGET as f64 | |
| 521 | - ); | |
| 522 | - } | |
| 523 | - assert!( | |
| 524 | - checked >= 10, | |
| 525 | - "only {checked} rows were bound-checked; the budget must apply to \ | |
| 526 | - every type a caller can be made to hold by value" | |
| 527 | - ); | |
| 528 | - // The other half of the derivation, asserted so it cannot rot: the | |
| 529 | - // worst a caller can owe is DEEPEST_CHAIN x the worst public return. | |
| 530 | - let worst = live | |
| 531 | - .iter() | |
| 532 | - .filter(|(n, _)| { | |
| 533 | - BY_VALUE_TYPES | |
| 534 | - .iter() | |
| 535 | - .any(|(row, _, public, _)| row == n && *public) | |
| 536 | - }) | |
| 537 | - .map(|(_, size)| *size) | |
| 538 | - .max() | |
| 539 | - .expect("at least one public row"); | |
| 540 | - assert!( | |
| 541 | - DEEPEST_PUBLIC_CHAIN * worst * 8 <= 2 * 1024 * 1024, | |
| 542 | - "the deepest public chain ({DEEPEST_PUBLIC_CHAIN}) times the worst \ | |
| 543 | - public by-value return ({worst} B) is {} B, over an eighth of the \ | |
| 544 | - 2101248-byte stack an unconfigured caller hands this crate; \ | |
| 545 | - re-derive STACK_BUDGET", | |
| 546 | - DEEPEST_PUBLIC_CHAIN * worst | |
| 547 | - ); | |
| 548 | - } | |
| 549 | - | |
| 550 | - /// The crate-private decode state stays BEHIND A BOX. | |
| 551 | - /// | |
| 552 | - /// The budget does not apply to `Core` because no `pub fn` returns it, so | |
| 553 | - /// bounding it would calibrate the number to something no caller can | |
| 554 | - /// reach. What keeps its 16,896 bytes of coefficient planes off every | |
| 555 | - /// caller's stack is that the four fields holding them are `Box`es, and | |
| 556 | - /// THIS is the pin for that -- a source scan over the four declarations | |
| 557 | - /// plus the four `Box::new`s in `Core::new`. | |
| 558 | - /// | |
| 559 | - /// It earned its place during the layout fix: `exps`, `bap` and `delay` | |
| 560 | - /// are `[[T; COEFFS]; CHANNELS]`-shaped planes at 1,792 / 1,792 / 6,144 | |
| 561 | - /// bytes and `coeffs` is 7,168 -- 16,896 of a 19,728-byte `Core` -- and | |
| 562 | - /// `Core` sits inline in the `Ac3Decoder` that `Ac3Decoder::new` hands a | |
| 563 | - /// caller BY VALUE. Unboxing any of the four puts the stack cost straight | |
| 564 | - /// back. | |
| 565 | - #[test] | |
| 566 | - fn the_crate_private_core_stays_behind_a_box() { | |
| 567 | - const PINS: &[(&str, &str)] = &[ | |
| 568 | - ( | |
| 569 | - "decode.rs::Core::exps", | |
| 570 | - "exps: Box<[[u8; COEFFS]; CHANNELS]>", | |
| 571 | - ), | |
| 572 | - ("decode.rs::Core::bap", "bap: Box<[[u8; COEFFS]; CHANNELS]>"), | |
| 573 | - ( | |
| 574 | - "decode.rs::Core::coeffs", | |
| 575 | - "coeffs: Box<[[f32; COEFFS]; CHANNELS]>", | |
| 576 | - ), | |
| 577 | - ( | |
| 578 | - "decode.rs::Core::delay", | |
| 579 | - "delay: Box<[[f32; COEFFS]; MAX_FBW + 1]>", | |
| 580 | - ), | |
| 581 | - ( | |
| 582 | - "decode.rs::Core::new::exps", | |
| 583 | - "exps: Box::new([[0; COEFFS]; CHANNELS])", | |
| 584 | - ), | |
| 585 | - ( | |
| 586 | - "decode.rs::Core::new::bap", | |
| 587 | - "bap: Box::new([[0; COEFFS]; CHANNELS])", | |
| 588 | - ), | |
| 589 | - ( | |
| 590 | - "decode.rs::Core::new::coeffs", | |
| 591 | - "coeffs: Box::new([[0.0; COEFFS]; CHANNELS])", | |
| 592 | - ), | |
| 593 | - ( | |
| 594 | - "decode.rs::Core::new::delay", | |
| 595 | - "delay: Box::new([[0.0; COEFFS]; MAX_FBW + 1])", | |
| 596 | - ), | |
| 597 | - ]; | |
| 598 | - const UNBOXED: &[(&str, &str)] = &[ | |
| 599 | - ("decode.rs::Core::exps", "exps: [[u8; COEFFS]; CHANNELS],"), | |
| 600 | - ("decode.rs::Core::bap", "bap: [[u8; COEFFS]; CHANNELS],"), | |
| 601 | - ( | |
| 602 | - "decode.rs::Core::coeffs", | |
| 603 | - "coeffs: [[f32; COEFFS]; CHANNELS],", | |
| 604 | - ), | |
| 605 | - ( | |
| 606 | - "decode.rs::Core::delay", | |
| 607 | - "delay: [[f32; COEFFS]; MAX_FBW + 1],", | |
| 608 | - ), | |
| 609 | - ]; | |
| 610 | - let decode = include_str!("decode.rs"); | |
| 611 | - for (where_, spelling) in PINS { | |
| 612 | - assert!( | |
| 613 | - decode.contains(spelling), | |
| 614 | - "{where_} is no longer declared `{spelling}`. An inline \ | |
| 615 | - coefficient plane there puts its 16896 bytes back inside \ | |
| 616 | - decode::Core, which sits inline in the Ac3Decoder that \ | |
| 617 | - Ac3Decoder::new returns BY VALUE -- that is how Ac3Decoder was \ | |
| 618 | - 20024 bytes, 2.44x over the by-value budget.", | |
| 619 | - ); | |
| 620 | - } | |
| 621 | - // And the negative control: the unboxed spellings must be ABSENT, or | |
| 622 | - // the scan above would be matching a doc comment or a dead branch | |
| 623 | - // rather than the live declaration. | |
| 624 | - for (where_, unboxed) in UNBOXED { | |
| 625 | - assert!( | |
| 626 | - !decode.contains(unboxed), | |
| 627 | - "{where_} is declared `{unboxed}`, unboxed. The box pin above \ | |
| 628 | - is not matching the live declaration, or the plane is inline \ | |
| 629 | - again and every Ac3Decoder::new caller pays 16896 bytes.", | |
| 630 | - ); | |
| 631 | - } | |
| 632 | - } | |
| 633 | - | |
| 634 | - /// CAPABILITY: really construct the heavy types on a tight stack, so a | |
| 635 | - /// regression ABORTS THE PROCESS instead of costing invisible margin. | |
| 636 | - /// | |
| 637 | - /// Arm 1 is the two-deep `Ac3Decoder` constructor nest -- the crate's | |
| 638 | - /// largest by-value return, and the type this lane's layout fix took from | |
| 639 | - /// 20,024 to 3,160 bytes. Arm 2 is `Ac3Encoder::new`, the second-closest | |
| 640 | - /// row to the budget at 34.0% of it. | |
| 641 | - /// | |
| 642 | - /// Both arms assert a REAL property of what came back, not merely that the | |
| 643 | - /// thread survived: a fresh `Ac3Decoder` has no `frame_info()` before any | |
| 644 | - /// syncframe, and one built with explicit options hands those exact options | |
| 645 | - /// back through `options_mut()`. A constructor that quietly dropped its | |
| 646 | - /// argument would red here rather than pass on a stack measurement alone. | |
| 647 | - /// | |
| 648 | - /// Measured stack need, **debug** build, one process per point so a | |
| 649 | - /// stack-overflow abort cannot truncate the sweep: | |
| 650 | - /// | |
| 651 | - /// | `EC_AC3_TIGHT_STACK_BYTES` | result | | |
| 652 | - /// |---|---| | |
| 653 | - /// | 1048576 (1 MiB) | **ok** | | |
| 654 | - /// | 524288 | **ok** | | |
| 655 | - /// | 262144 | **ok** | | |
| 656 | - /// | 131072 | **ok** | | |
| 657 | - /// | 98304 | **ok** | | |
| 658 | - /// | 86016 | **ok** | | |
| 659 | - /// | 81920 | **ok** | | |
| 660 | - /// | 77824 | overflow | | |
| 661 | - /// | 65536 | overflow | | |
| 662 | - /// | 32768 | overflow | | |
| 663 | - /// | 24576 | overflow | | |
| 664 | - /// | |
| 665 | - /// The deepest measured need is therefore between 77,824 and 81,920 | |
| 666 | - /// bytes, and the gate sits at 1 MiB -- **12.8x** that, and half of what an | |
| 667 | - /// unconfigured caller hands this crate. The ~80 KiB is dominated by | |
| 668 | - /// `Ac3Encoder::new`'s own working frames (a 512-float window, an | |
| 669 | - /// `Mdct::new(512)` plan and a per-`COEFFS` IMDCT basis sweep), not by the | |
| 670 | - /// by-value return slots this module bounds; that is exactly the residual | |
| 671 | - /// `size_of` cannot predict, and why the arm constructs rather than | |
| 672 | - /// computing. | |
| 673 | - /// | |
| 674 | - /// `EC_AC3_TIGHT_STACK_BYTES` overrides the size, which is how the | |
| 675 | - /// threshold is swept. | |
| 676 | - #[test] | |
| 677 | - fn the_deepest_by_value_constructors_fit_on_a_tight_stack() { | |
| 678 | - let stack: usize = std::env::var("EC_AC3_TIGHT_STACK_BYTES") | |
| 679 | - .ok() | |
| 680 | - .and_then(|v| v.parse().ok()) | |
| 681 | - .unwrap_or(TIGHT_STACK); | |
| 682 | - let config = EncoderConfig { | |
| 683 | - sample_rate: 48_000, | |
| 684 | - channels: 2, | |
| 685 | - bitrate_kbps: 192, | |
| 686 | - }; | |
| 687 | - let handle = std::thread::Builder::new() | |
| 688 | - .stack_size(stack) | |
| 689 | - .spawn(move || { | |
| 690 | - // Arm 1: the two-deep `Ac3Decoder` constructor nest, the | |
| 691 | - // crate's largest by-value return. | |
| 692 | - let mut plain = Ac3Decoder::new(); | |
| 693 | - let fresh_has_no_frame_info = plain.frame_info().is_none(); | |
| 694 | - let plain_options = *plain.options_mut(); | |
| 695 | - // A decoder built with explicit options must keep exactly | |
| 696 | - // those options, including a non-default downmix. | |
| 697 | - let mut configured = Ac3Decoder::with_options(Options { | |
| 698 | - drc_scale: 0.25, | |
| 699 | - downmix: Downmix::Stereo, | |
| 700 | - dither: false, | |
| 701 | - }); | |
| 702 | - let kept = *configured.options_mut(); | |
| 703 | - drop(plain); | |
| 704 | - drop(configured); | |
| 705 | - // Arm 2: `Ac3Encoder::new`, the second-closest row to the budget. | |
| 706 | - let encoder = Ac3Encoder::new(config).expect("Ac3Encoder::new"); | |
| 707 | - let delay = encoder.encoder_delay(); | |
| 708 | - let stats = encoder.stats(); | |
| 709 | - (fresh_has_no_frame_info, plain_options, kept, delay, stats) | |
| 710 | - }) | |
| 711 | - .expect("spawn tight-stack thread"); | |
| 712 | - let (fresh_has_no_frame_info, plain_options, kept, delay, stats) = | |
| 713 | - handle.join().unwrap_or_else(|_| { | |
| 714 | - panic!( | |
| 715 | - "a by-value constructor overflowed a {stack}-byte stack; the \ | |
| 716 | - old 20024-byte Ac3Decoder is what that costs" | |
| 717 | - ) | |
| 718 | - }); | |
| 719 | - assert!( | |
| 720 | - fresh_has_no_frame_info, | |
| 721 | - "a freshly constructed Ac3Decoder already reported a frame_info(); \ | |
| 722 | - decode_frame is the only thing that may set one" | |
| 723 | - ); | |
| 724 | - assert_eq!( | |
| 725 | - plain_options, | |
| 726 | - Options::default(), | |
| 727 | - "Ac3Decoder::new did not give back the default Options" | |
| 728 | - ); | |
| 729 | - assert_eq!( | |
| 730 | - kept, | |
| 731 | - Options { | |
| 732 | - drc_scale: 0.25, | |
| 733 | - downmix: Downmix::Stereo, | |
| 734 | - dither: false, | |
| 735 | - }, | |
| 736 | - "Ac3Decoder::with_options did not keep the options it was handed" | |
| 737 | - ); | |
| 738 | - assert!( | |
| 739 | - delay > 0, | |
| 740 | - "Ac3Encoder::encoder_delay reported no priming samples" | |
| 741 | - ); | |
| 742 | - assert_eq!( | |
| 743 | - stats, | |
| 744 | - crate::encode::EncodeStats::default(), | |
| 745 | - "a fresh Ac3Encoder reported non-zero coding stats" | |
| 746 | - ); | |
| 747 | - eprintln!( | |
| 748 | - "TIGHTSTACK {stack} bytes: Ac3Decoder={} Ac3Encoder={} bytes, both \ | |
| 749 | - constructors returned and both options paths round-tripped", | |
| 750 | - std::mem::size_of::<Ac3Decoder>(), | |
| 751 | - std::mem::size_of::<Ac3Encoder>(), | |
| 752 | - ); | |
| 753 | - } | |
| 754 | - | |
| 755 | - /// The sweep's teeth against a NEW by-value return: re-derive the set from | |
| 756 | - /// the crate source and require every name to be inventoried. | |
| 757 | - /// | |
| 758 | - /// Without this the inventory is a list of what someone remembered to | |
| 759 | - /// measure, and a lane that adds `pub fn make() -> HugeThing` where | |
| 760 | - /// `HugeThing` is 200 KB of inline tables passes every other test here. | |
| 761 | - #[test] | |
| 762 | - fn every_by_value_public_return_is_in_the_inventory() { | |
| 763 | - let mut found: Vec<(String, String)> = Vec::new(); | |
| 764 | - for (file, src) in FILES { | |
| 765 | - for (n, line) in src.lines().enumerate() { | |
| 766 | - if let Some(name) = by_value_return_name(line) { | |
| 767 | - found.push((name, format!("{file}:{}", n + 1))); | |
| 768 | - } | |
| 769 | - } | |
| 770 | - } | |
| 771 | - found.sort(); | |
| 772 | - found.dedup(); | |
| 773 | - assert!( | |
| 774 | - found.len() > 5, | |
| 775 | - "the by-value return scan found {} names across {} files, which is \ | |
| 776 | - too few to be a real sweep -- the matcher, not the crate, is broken", | |
| 777 | - found.len(), | |
| 778 | - FILES.len() | |
| 779 | - ); | |
| 780 | - eprintln!("BY-VALUE PUBLIC RETURNS FOUND: {found:?}"); | |
| 781 | - | |
| 782 | - let mut missing = Vec::new(); | |
| 783 | - for (name, site) in &found { | |
| 784 | - if !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| n == name) { | |
| 785 | - missing.push(format!("{name} ({site})")); | |
| 786 | - } | |
| 787 | - } | |
| 788 | - assert!( | |
| 789 | - missing.is_empty(), | |
| 790 | - "these types are returned BY VALUE from a public fn and are not in \ | |
| 791 | - the inventory: {}. Either they are thin enough not to be a stack \ | |
| 792 | - cost -- say so by adding a row with its measured size -- or they \ | |
| 793 | - are the next instance of the class this module exists for.", | |
| 794 | - missing.join(", ") | |
| 795 | - ); | |
| 796 | - } | |
| 797 | - | |
| 798 | - /// The control for the scan above, on synthetic text rather than by | |
| 799 | - /// trusting the live tree to happen to contain a case. | |
| 800 | - /// | |
| 801 | - /// If the matcher silently stopped recognising a shape, the sweep would | |
| 802 | - /// pass everything and this would still be asserting nothing. So: every | |
| 803 | - /// by-value spelling the crate uses must yield its type name, and every | |
| 804 | - /// pointer/Vec/primitive/`Self` spelling must yield nothing. | |
| 805 | - #[test] | |
| 806 | - fn the_inventory_scan_is_not_vacuous() { | |
| 807 | - for synthetic in [ | |
| 808 | - "pub fn zz_a() -> ZzNotInventoried { todo!() }", | |
| 809 | - "pub fn zz_b() -> Result<ZzNotInventoried, Error> { todo!() }", | |
| 810 | - "pub fn zz_c() -> Result<ZzNotInventoried> { todo!() }", | |
| 811 | - "pub fn zz_d() -> Option<ZzNotInventoried> { todo!() }", | |
| 812 | - "pub fn zz_e() -> ZzNotInventoried<'a> { todo!() }", | |
| 813 | - ] { | |
| 814 | - let name = by_value_return_name(synthetic) | |
| 815 | - .unwrap_or_else(|| panic!("the matcher does not recognise `{synthetic}`")); | |
| 816 | - assert_eq!( | |
| 817 | - name, "ZzNotInventoried", | |
| 818 | - "the matcher mangled `{synthetic}` into `{name}`, so the sweep \ | |
| 819 | - cannot see a new by-value return and its green is vacuous" | |
| 820 | - ); | |
| 821 | - assert!( | |
| 822 | - !BY_VALUE_TYPES.iter().any(|(n, _, _, _)| *n == name), | |
| 823 | - "the synthetic control name is in the inventory, so the control \ | |
| 824 | - proves nothing" | |
| 825 | - ); | |
| 826 | - } | |
| 827 | - for thin in [ | |
| 828 | - "pub fn zz_t() -> Box<Decoder> { todo!() }", | |
| 829 | - "pub fn zz_u() -> Result<Vec<u8>, Error> { todo!() }", | |
| 830 | - "pub fn zz_v() -> Option<&Path> { todo!() }", | |
| 831 | - "pub fn zz_w() -> usize { todo!() }", | |
| 832 | - "pub fn zz_x() -> Self { todo!() }", | |
| 833 | - "pub fn zz_y() -> Result<Arc<Decoder>, Error> { todo!() }", | |
| 834 | - "pub fn zz_z() { todo!() }", | |
| 835 | - "fn zz_private() -> ZzNotInventoried { todo!() }", | |
| 836 | - ] { | |
| 837 | - assert_eq!( | |
| 838 | - by_value_return_name(thin), | |
| 839 | - None, | |
| 840 | - "`{thin}` is a pointer, a Vec, a primitive, a `Self` the rows \ | |
| 841 | - above already cover, or not a `pub fn` -- the matcher must not \ | |
| 842 | - read it as an uninventoried by-value return" | |
| 843 | - ); | |
| 844 | - } | |
| 845 | - } | |
| 846 | - | |
| 847 | - /// The stack mapping containing `addr` in `/proc/self/task/<tid>/maps`. | |
| 848 | - /// | |
| 849 | - /// The returned size is a LOWER BOUND, never an exact count. Linux MERGES | |
| 850 | - /// adjacent VMAs that share protections, and a merged region is | |
| 851 | - /// indistinguishable from a single one in the maps file. A lower bound is | |
| 852 | - /// what the budget's reasoning needs: the claim is "no caller gets less | |
| 853 | - /// than 2 MiB", and `size >= 2 MiB` is exactly that, whether the region is | |
| 854 | - /// one mapping or three. | |
| 855 | - /// | |
| 856 | - /// The third field is whether the mapping is writable. Merging only joins | |
| 857 | - /// VMAs whose protections match, so a merged thread stack is still | |
| 858 | - /// writable. Its size can grow without bound, which is why the tests check | |
| 859 | - /// this flag and never an upper bound on the size. | |
| 860 | - fn stack_region(tid: u32, addr: usize) -> Option<(usize, usize, bool)> { | |
| 861 | - let maps = std::fs::read_to_string(format!("/proc/self/task/{tid}/maps")).ok()?; | |
| 862 | - for line in maps.lines() { | |
| 863 | - let (range, perms) = line.split_once(' ')?; | |
| 864 | - let (lo, hi) = range.split_once('-')?; | |
| 865 | - let (lo, hi) = ( | |
| 866 | - usize::from_str_radix(lo, 16).ok()?, | |
| 867 | - usize::from_str_radix(hi, 16).ok()?, | |
| 868 | - ); | |
| 869 | - if addr >= lo && addr < hi { | |
| 870 | - // `perms` is `rwxp`-style: the second character is write. | |
| 871 | - let writable = perms.as_bytes().get(1) == Some(&b'w'); | |
| 872 | - return Some((lo, hi, writable)); | |
| 873 | - } | |
| 874 | - } | |
| 875 | - None | |
| 876 | - } | |
| 877 | - | |
| 878 | - /// What a thread's stack ACTUALLY is, read from | |
| 879 | - /// `/proc/self/task/<tid>/maps` rather than assumed from a default. | |
| 880 | - /// | |
| 881 | - /// The number the budget's reasoning rests on, measured two ways: | |
| 882 | - /// | |
| 883 | - /// * a thread spawned with an EXPLICIT size gets AT LEAST that size -- | |
| 884 | - /// the control that says the parse finds stacks at all, and the shape | |
| 885 | - /// [`the_deepest_by_value_constructors_fit_on_a_tight_stack`] relies on; | |
| 886 | - /// * the DEFAULT -- no `stack_size`, i.e. what a library consumer's | |
| 887 | - /// `std::thread::spawn` gets, and what libtest gives a test thread when | |
| 888 | - /// `RUST_MIN_STACK` is unset -- is at least 2 MiB. | |
| 889 | - /// | |
| 890 | - /// Both are floors, because [`stack_region`] can only report a lower bound. | |
| 891 | - /// That is the right direction: the budget's claim is that no caller gets | |
| 892 | - /// LESS than 2 MiB, and a floor is what proves it. | |
| 893 | - #[test] | |
| 894 | - fn test_threads_get_the_stack_they_are_given() { | |
| 895 | - const EXPLICIT: usize = 1024 * 1024; | |
| 896 | - let handle = std::thread::Builder::new() | |
| 897 | - .stack_size(EXPLICIT) | |
| 898 | - .spawn(|| { | |
| 899 | - let tid = std::process::id(); | |
| 900 | - let marker = 0u8; | |
| 901 | - let here = &marker as *const u8 as usize; | |
| 902 | - let (lo, hi, rw) = | |
| 903 | - stack_region(tid, here).expect("this thread's own stack is in its maps"); | |
| 904 | - (lo, hi, rw) | |
| 905 | - }) | |
| 906 | - .expect("spawn"); | |
| 907 | - let (lo, hi, rw) = handle.join().expect("the probe thread returned"); | |
| 908 | - let size = hi - lo; | |
| 909 | - assert!( | |
| 910 | - size >= EXPLICIT, | |
| 911 | - "a thread spawned with stack_size({EXPLICIT}) has a {size}-byte \ | |
| 912 | - stack mapping; the runtime gave it less than it was promised, so \ | |
| 913 | - the maps parse is finding the wrong region" | |
| 914 | - ); | |
| 915 | - assert!( | |
| 916 | - rw, | |
| 917 | - "the mapping holding an explicitly-1-MiB thread's frame is not \ | |
| 918 | - writable -- a thread stack is read-write, so the maps parse found \ | |
| 919 | - the wrong region" | |
| 920 | - ); | |
| 921 | - | |
| 922 | - let tid = std::process::id(); | |
| 923 | - let marker = 0u8; | |
| 924 | - let here = &marker as *const u8 as usize; | |
| 925 | - let (lo, hi, rw) = | |
| 926 | - stack_region(tid, here).expect("this test thread's stack is in its maps"); | |
| 927 | - let size = hi - lo; | |
| 928 | - assert!( | |
| 929 | - rw, | |
| 930 | - "a default test thread's stack mapping is not writable -- the maps \ | |
| 931 | - parse found the wrong region" | |
| 932 | - ); | |
| 933 | - assert!( | |
| 934 | - size >= 2 * 1024 * 1024, | |
| 935 | - "a default test thread's stack measured {size} bytes, under the \ | |
| 936 | - 2 MiB floor the by-value budget is derived from; the smallest \ | |
| 937 | - stack a caller can hand this crate just got smaller and the bound \ | |
| 938 | - needs re-deriving" | |
| 939 | - ); | |
| 940 | - eprintln!( | |
| 941 | - "TESTTHREADSTACK default tid={tid} region=[{lo:x},{hi:x}) size>={size} \ | |
| 942 | - (2101248 measured exactly with the repo cap lifted, 67112960 with it)" | |
| 943 | - ); | |
| 944 | - } | |
| 945 | -} |