1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
//! Recording mock + fault injection for `aligned-vmem` (cfg `aligned_vmem_mock`).
//!
//! Mirrors [`numa-shim`](https://crates.io/crates/numa-shim)'s proven
//! recording-mock pattern: a thread-local call log plus scripted failures, so
//! any consumer can deterministically test its OOM-handling on any target
//! (including macOS and miri) WITHOUT exhausting real commit charge.
//!
//! When the `aligned_vmem_mock` cfg is set:
//! - reservation entry points still chain to the real `std::alloc`/OS backend
//! (so the returned [`crate::Reservation`] is genuinely usable), but record a
//! [`Call`] and honour a scripted [`fail_next_reserve`] first;
//! - decommit / recommit / commit_range record a [`Call`] and honour
//! [`fail_next_commit`] WITHOUT touching the OS.
//!
//! ```text
//! aligned_vmem::mock::fail_next_commit(1);
//! // SAFETY: `base` is a live reservation.
//! let ok = unsafe { aligned_vmem::recommit(base, 0, PAGE) };
//! assert!(!ok);
//! assert_eq!(aligned_vmem::mock::drain().len(), 1);
//! ```
//!
//! Runnable form: `tests/mock.rs`.
//!
//! # Cross-thread drops split the Reserve/Release pair (task #959)
//!
//! The log behind [`drain`] is a `thread_local!`: a [`Call`] lands in
//! the log of the thread the call runs ON, not the thread the
//! reservation was created on. [`crate::Reservation`] is `Send` (see
//! the `unsafe impl Send for Reservation` and its `SAFETY` comment in
//! `src/reservation.rs` — a reservation owns its bytes exclusively, with no
//! thread affinity), so a test can create a reservation on thread A,
//! move it to thread B, and drop it there. `Reservation`'s `Drop` then
//! records `Call::Release` in thread B's log while the paired
//! `Call::Reserve` stays in thread A's log; neither thread's `drain()`
//! ever sees both halves, and a naive "every Reserve has a Release"
//! leak check on thread A would misread the reservation as leaked.
//! This is the thread-local log working as designed — not unsoundness,
//! not a leak. Practical rule: [`drain`] on the thread where the drop
//! happened; a test that moves a `Reservation` across threads must not
//! expect one `drain()` to contain the Reserve/Release pair.
//!
//! # Build-time cfg flag (task #962)
//!
//! This backend is enabled via the `aligned_vmem_mock` cfg flag
//! (`RUSTFLAGS="--cfg aligned_vmem_mock"`), following the same pattern as
//! this repo's `cfg(loom)`/`cfg(kani)` flags. A `--cfg` flag cannot be
//! silently unified into a build by another crate downstream — that was the
//! whole point of the conversion (task #715, task #658).
//!
//! # Recording contract edge cases
//!
//! Reentrant calls (e.g., `reserve_aligned` called from within an allocator
//! invoked by this mock's own `record` function) are silently dropped by
//! design — see the `record` function's `# Reentrancy safety` section.
//!
//! While a pathological TLS-teardown ordering could theoretically interact
//! with this, the current implementation's use of `try_with` for the
//! vector-backed log key (`CALLS`) makes that practically unreachable under
//! today's std teardown order: the `RefCell<Vec>` is the only key that can
//! ever be torn down mid-access, and it is protected via `try_with` rather
//! than ordinary `.with(...)` (the `RECORDING` guard is a `Cell<bool>` with
//! no `Drop` impl, so it is const-initialized and never runs a destructor).
//!
//! A well-formed empty-range `recommit`/`commit_range` call (`start == end`)
//! is treated as a no-op and is **not** recorded in the mock call log, unlike
//! other well-formed calls to the same functions (the early-return happens
//! before `mock::record` is called — see those functions' implementations
//! in `src/api/recommit.rs` and `src/api/commit_range.rs`).
use ;
use crateVmemError;
/// One recorded invocation of a public `aligned-vmem` function under the mock.
///
/// task #715 (rust-intel audit MEDIUM §C1a): every struct-like variant below
/// ALSO carries its own `#[non_exhaustive]` (the enum-level one above only
/// reserves the right to add whole VARIANTS — adding a FIELD to an existing
/// variant is still semver-major for every downstream `Call::Reserve { size,
/// align }` match without the variant-level marker too; `ReserveLazy` already
/// grew `initial_commit` after `Reserve`/`ReserveHuge` were designed, so this
/// is not a hypothetical). `Call` is new in 0.2.0 (0.1.0 had no mock
/// backend at all) and 0.2.0 has not shipped yet (task #658), so this is
/// decided now, before its own first publish — adding the marker
/// retroactively after 0.2.0 ships would itself be the breaking change this
/// is meant to prevent.
// Constructors for external crates to build expected call vectors.
thread_local!
/// Drain and return every recorded [`Call`] since the last drain (or test
/// start). Clears the log.
///
/// Returns THIS thread's log only: a [`Call::Release`] recorded by a
/// `Reservation` dropped on another thread is not visible here — see
/// the module-level "Cross-thread drops" section for the mechanism.
///
/// task #1021/R4-9: holds the `RefCell` borrow only for the `mem::take`
/// call, not for the returned `Vec`'s lifetime — this prevents a
/// reentrancy panic if the returned `Vec`'s allocation itself triggers
/// a nested `record` call (the `RECORDING` guard protects `record` from
/// recursion within itself, but does not protect `drain` from allocating
/// while holding the borrow).
/// Clear the recorded call log AND both fault counters — call at the start of a
/// test to isolate it from any residue on the current thread.
/// Arm the reserve fault injector: the next `n` reservation attempts
/// ([`crate::try_reserve_aligned`] and its `lazy`/`huge` variants) return
/// `Err(VmemError::os_refusal_unknown_code())` without allocating. `n == 0` disarms.
/// Arm the commit fault injector: the next `n` commit attempts
/// ([`crate::recommit`] / [`crate::commit_range`]) return failure without
/// touching the OS, simulating commit-charge exhaustion. `n == 0` disarms.
/// Internal: record a call into the thread-local log.
///
/// # Reentrancy safety (task #945/M-1)
///
/// This function is called from within the `GlobalAlloc` implementation path.
/// When `Vec::push` needs to grow its buffer, it allocates through the global
/// allocator, which may call back into this crate again. Without a guard, this
/// would attempt to mutably borrow `CALLS` twice on the same thread, causing a
/// `BorrowMutError` panic inside an allocator — undefined behavior in that
/// context.
///
/// We guard against this with a `RECORDING` flag: if already set (indicating a
/// reentrant call), we silently drop the recording rather than corrupting state
/// or panicking. The reentrant call's own recording is lost, but the outer
/// recording remains intact and the allocator path completes safely.
///
/// This is the same hazard class already documented for the miri backend in
/// the crate-level module header (see `lib.rs`'s "A consumer that installs
/// itself as `#[global_allocator]` cannot use this crate under miri..."
/// paragraph — the mock backend has the same issue for the same reason).
///
/// # Thread-local storage teardown safety (task #945/M-2)
///
/// `Reservation::drop` calls this function (via `release` in `lib.rs`). If a
/// `Reservation` is owned by a `thread_local!` elsewhere in a consumer's code,
/// its destructor runs during TLS teardown, in unspecified order relative to
/// `CALLS`'s own destructor. `LocalKey::with` panics if the thread-local value
/// has already been destroyed on that thread — a panic during `Drop` becomes
/// an abort if anything else is unwinding.
///
/// We use `try_with` (instead of `with`) to silently become a no-op when
/// `CALLS` has already been destroyed, avoiding the teardown-order panic.
///
/// Note: no RAII guard is used to clear `RECORDING` on panic, because the only
/// way `Vec::push` can panic is allocation failure, which aborts the process
/// regardless. A non-allocation panic in `push` is virtually impossible (the
/// only path would be `Clone` impl on `Call` panicking, which cannot happen
/// here). The added complexity of a guard is not worth it for a case that
/// either never occurs or always aborts.
pub
/// Internal: consume one armed reserve fault, returning the error to raise.
pub
/// Internal: consume one armed commit fault, returning the error to raise.
pub