cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! A stated-facts [`Kernel`]: the answers its tables hold, and nothing the kernel would do. A call
//! with no row panics, except under [`FakeKernel::over`], which passes it to the real kernel.
//!
//! Rows are plain data: a path or pid is looked up by `==`, and a later row replaces an earlier one.
//! The one exception is the any-pid row, which matches a path of exactly two components: a decimal
//! pid, then the file (`4242/cgroup`). `self/<file>` and `<pid>/task/<tid>/<file>` are not matched.

use std::io;
use std::os::fd::{AsRawFd, BorrowedFd, OwnedFd, RawFd};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::Mutex;

use rustix::io::Errno;
use rustix::process::{Pid, PidfdFlags};

use super::Kernel;
use crate::identity::{pidfd_pid_in, HostKernel, PidfdTarget, ProcDir, ProcOpenFailure, ReadFailure, Record};

pub(crate) struct FakeKernel<'a> {
    /// What answers a call the tables have nothing for. `None`: such a call panics.
    real: Option<&'a dyn Kernel>,
    open_proc: Option<Errno>,
    reads: Mutex<Vec<ReadRow>>,
    /// The any-pid rows: a file name and what every read of `<pid>/<file>` answers when no row of
    /// `reads` does. Behind a `Mutex` so a test can state one through `&self` after the kernel is
    /// shared.
    any_pid_reads: Mutex<Vec<AnyPidRow>>,
    /// The generation of the latest any-pid row stated.
    any_pid_generation: AtomicU64,
    /// How many times each path has been read.
    read_counts: Mutex<Vec<(String, usize)>>,
    /// The listing of any `/proc`: the pids, or the call that failed and its raw errno.
    pids: Mutex<Option<Listing>>,
    /// A pid, the number of earlier listings of its threads before the row answers, and the answer.
    tids: Mutex<Vec<TidsRow>>,
    signal_probes: Vec<(Pid, Result<(), Errno>)>,
    /// A pid, the flags the row answers (`None`: any), and the answer.
    pidfd_opens: Vec<(Pid, Option<PidfdFlags>, PidfdRow)>,
    /// A pid, the path whose earlier read the row waits for (`None`: no wait), and the answer.
    pidfs_inos: Vec<PidfsRow>,
    /// The descriptors this kernel has handed out, so that `pidfs_ino` can tell whose they are.
    opened: Mutex<Vec<Opened>>,
    /// How many times `pidfs_ino` has been asked, whoever answered.
    pidfs_ino_calls: AtomicUsize,
    peeks: Mutex<WaitRows>,
    consumes: Mutex<WaitRows>,
}

/// `waitid` rows, in the order they were stated: a pid, and what one call through a pidfd that names
/// it answers.
type WaitRows = Vec<(u32, Result<Option<Record>, Errno>)>;

/// The first row of `rows` for the process `pidfd` names, which it removes. Each row answers one
/// call. The pidfd's pid is read from the host's `/proc` only when there are rows to match, and a
/// pidfd whose target is reaped matches none.
fn take_wait_row(rows: &Mutex<WaitRows>, pidfd: BorrowedFd<'_>) -> Option<Result<Option<Record>, Errno>> {
    let mut rows = rows.lock().expect("no panic holds the rows");
    if rows.is_empty() {
        return None;
    }
    let pid = match ProcDir::open()
        .map_err(crate::identity::ViewUnreadable::from)
        .and_then(|dir| pidfd_pid_in(&HostKernel, &dir, pidfd))
    {
        Ok(PidfdTarget::Pid(pid)) => pid,
        Ok(PidfdTarget::Reaped) => return None,
        Err(why) => panic!("FakeKernel could not read the pid of a pidfd it holds rows for: {why:?}"),
    };
    let at = rows.iter().position(|(row, _)| *row == pid)?;
    Some(rows.remove(at).1)
}

/// The call of a read or listing that a row's errno answers for.
#[derive(Clone, Copy)]
enum ReadCall {
    Open,
    Read,
}

impl ReadCall {
    fn failure(self, errno: i32) -> ReadFailure {
        let error = io::Error::from_raw_os_error(errno);
        match self {
            ReadCall::Open => ReadFailure::Open(error),
            ReadCall::Read => ReadFailure::Read(error),
        }
    }
}

/// What a read row answers: the bytes, or the call that failed and its raw errno.
type ReadAnswer = Result<Vec<u8>, (ReadCall, i32)>;

/// What `hidepid` does to another user's task: its `cgroup` open fails with `ENOENT`.
const HIDEPID_ROW: (&str, Result<&[u8], i32>) = ("cgroup", Err(libc::ENOENT));

/// An any-pid row: the file, the generation that stated it, and the answer.
type AnyPidRow = (String, u64, ReadAnswer);

/// An any-pid row stated through [`FakeKernel::state_every_pid_read`]. Dropping it restores the
/// file's earlier row (none, a builder's, or an outer guard's). Guards drop innermost first.
#[must_use = "the row is replaced by the one before it when this is dropped"]
pub(crate) struct StatedRow<'k, 'a> {
    kernel: &'k FakeKernel<'a>,
    file: String,
    generation: u64,
    before: Option<(u64, ReadAnswer)>,
}

impl Drop for StatedRow<'_, '_> {
    fn drop(&mut self) {
        let current = self.kernel.replace_any_pid_row(&self.file, self.before.take());
        debug_assert!(
            current.is_some_and(|(generation, _)| generation == self.generation),
            "a stated any-pid row is dropped while it is still the file's row: guards drop innermost first"
        );
    }
}

/// What a listing answers: the ids, or the call that failed and its raw errno.
type Listing = Result<Vec<u32>, (ReadCall, i32)>;

/// A read row: the path, the number of earlier reads of it before the row answers, and the answer.
type ReadRow = (String, usize, ReadAnswer);

/// A thread listing row: the pid, the number of earlier listings of its threads before the row answers,
/// and the answer (`Err` as for a read row).
type TidsRow = (u32, usize, Listing);

/// A `pidfs_ino` row: the pid, the path whose earlier read it waits for, and the answer.
type PidfsRow = (Pid, Option<String>, Result<Option<u64>, Errno>);

/// A pidfd this kernel opened: its number, the pid, and how many times each path had been read then.
struct Opened {
    fd: RawFd,
    pid: Pid,
    reads: Vec<(String, usize)>,
}

/// What a `pidfd_open` row answers, on every call.
enum PidfdRow {
    Errno(Errno),
    /// The first call hands out the test's own fd, whose number the test may have stated rows
    /// about; each later one a duplicate of it.
    Fd {
        first: Mutex<Option<OwnedFd>>,
        spare: OwnedFd,
    },
}

impl<'a> FakeKernel<'a> {
    /// A kernel with no rows.
    pub(crate) fn new() -> Self {
        FakeKernel {
            real: None,
            open_proc: None,
            reads: Mutex::new(Vec::new()),
            any_pid_reads: Mutex::new(Vec::new()),
            any_pid_generation: AtomicU64::new(0),
            read_counts: Mutex::new(Vec::new()),
            pids: Mutex::new(None),
            tids: Mutex::new(Vec::new()),
            signal_probes: Vec::new(),
            pidfd_opens: Vec::new(),
            pidfs_inos: Vec::new(),
            opened: Mutex::new(Vec::new()),
            pidfs_ino_calls: AtomicUsize::new(0),
            peeks: Mutex::new(Vec::new()),
            consumes: Mutex::new(Vec::new()),
        }
    }

    /// The next peek through a pidfd that names `pid` answers `answer`: `Ok(None)` is a child that
    /// has not exited. A peek of another process's pidfd is not this row's.
    pub(crate) fn on_peek(self, pid: u32, answer: Result<Option<Record>, Errno>) -> Self {
        self.state_peek(pid, answer);
        self
    }

    /// [`on_peek`](Self::on_peek) after the kernel is shared: for a child whose pid the test learns
    /// only once the spawn under test has made it.
    pub(crate) fn state_peek(&self, pid: u32, answer: Result<Option<Record>, Errno>) {
        self.peeks.lock().expect("no panic holds the rows").push((pid, answer));
    }

    /// The next consume through a pidfd that names `pid` answers `answer`, and takes nothing from the
    /// real process.
    pub(crate) fn on_consume(self, pid: u32, answer: Result<Option<Record>, Errno>) -> Self {
        self.consumes
            .lock()
            .expect("no panic holds the rows")
            .push((pid, answer));
        self
    }

    /// How many stated peek rows have not answered yet.
    pub(crate) fn peeks_left(&self) -> usize {
        self.peeks.lock().expect("no panic holds the rows").len()
    }

    /// Whether every stated peek and consume row has answered.
    pub(crate) fn all_rows_taken(&self) -> bool {
        self.peeks_left() == 0 && self.consumes.lock().expect("no panic holds the rows").is_empty()
    }

    /// How many times the kernel has been asked for a pidfd's `pidfs_ino`: an identity read of a
    /// held pidfd, whose pid no row can name beforehand, asks it.
    pub(crate) fn pidfs_ino_calls(&self) -> usize {
        self.pidfs_ino_calls.load(Ordering::Relaxed)
    }

    /// A kernel that answers its rows and passes every other call to `real`.
    pub(crate) fn over(real: &'a dyn Kernel) -> Self {
        FakeKernel {
            real: Some(real),
            ..Self::new()
        }
    }

    /// A kernel over `real` whose `/proc` is this namespace's own and lists `pid` alone, and whose
    /// `stat` read of it fails with the raw `errno`: what a whole-table scan meets in one pid.
    pub(crate) fn listing_unreadable_pid(real: &'a dyn Kernel, pid: u32, errno: i32) -> Self {
        Self::over(real)
            .same_view()
            .on_pids(Ok(&[pid]))
            .on_read(&format!("{pid}/stat"), Err(errno))
    }

    /// Reading `path` under any `/proc` answers `answer`: the bytes, or the raw errno of its
    /// `openat2`. For a symlink the bytes are its target.
    pub(crate) fn on_read(self, path: &str, answer: Result<&[u8], i32>) -> Self {
        self.on_read_after(path, 0, answer)
    }

    /// A kernel over `real` whose `/proc` refuses every task's `cgroup` as `hidepid` does a task of
    /// another user: `ENOENT`.
    pub(crate) fn hidepid(real: &'a dyn Kernel) -> Self {
        let (file, answer) = HIDEPID_ROW;
        Self::over(real).on_every_pid_read(file, answer)
    }

    /// [`hidepid`](Self::hidepid)'s row, after the kernel is shared; see
    /// [`state_every_pid_read`](Self::state_every_pid_read).
    pub(crate) fn hide_every_pid_cgroup(&self) -> StatedRow<'_, 'a> {
        let (file, answer) = HIDEPID_ROW;
        self.state_every_pid_read(file, answer)
    }

    /// Reading `file` of any pid under any `/proc` answers `answer`: the bytes, or the raw errno of
    /// its `openat2`. A row for one path ([`on_read`](Self::on_read)) answers before it. A test that
    /// cannot name a pid beforehand (a forked probe's) states this row.
    pub(crate) fn on_every_pid_read(self, file: &str, answer: Result<&[u8], i32>) -> Self {
        self.state_any_pid_row(file, answer);
        self
    }

    /// [`on_every_pid_read`](Self::on_every_pid_read) after the kernel is shared; the row is
    /// restored when the returned guard is dropped.
    pub(crate) fn state_every_pid_read(&self, file: &str, answer: Result<&[u8], i32>) -> StatedRow<'_, 'a> {
        let (generation, before) = self.state_any_pid_row(file, answer);
        StatedRow {
            kernel: self,
            file: file.to_owned(),
            generation,
            before,
        }
    }

    /// Makes `answer` the file's any-pid row. Returns its generation and the row replaced.
    fn state_any_pid_row(&self, file: &str, answer: Result<&[u8], i32>) -> (u64, Option<(u64, ReadAnswer)>) {
        let generation = self.any_pid_generation.fetch_add(1, Ordering::Relaxed) + 1;
        let answer = answer.map(<[u8]>::to_vec).map_err(|errno| (ReadCall::Open, errno));
        (generation, self.replace_any_pid_row(file, Some((generation, answer))))
    }

    /// `None` removes the row. Returns the row replaced.
    fn replace_any_pid_row(&self, file: &str, row: Option<(u64, ReadAnswer)>) -> Option<(u64, ReadAnswer)> {
        debug_assert!(
            !file.is_empty() && !file.contains('/'),
            "an any-pid row names a file, not a path"
        );
        let mut rows = self.any_pid_reads.lock().expect("no panic holds the rows");
        let before = rows
            .iter()
            .position(|(f, ..)| f == file)
            .map(|at| rows.remove(at))
            .map(|(_, generation, answer)| (generation, answer));
        if let Some((generation, answer)) = row {
            rows.push((file.to_owned(), generation, answer));
        }
        before
    }

    /// Reading `path` under any `/proc` opens it, and its `read(2)` (a symlink's `readlinkat`) fails
    /// with the raw `errno`.
    pub(crate) fn on_read_failing_after_open(self, path: &str, errno: i32) -> Self {
        self.push_read(path, 0, Err((ReadCall::Read, errno)));
        self
    }

    /// From the read of `path` that follows `earlier_reads` reads of it, answers `answer`, as
    /// [`on_read`](Self::on_read) does. Of the rows whose count has been reached, the one with the
    /// highest count wins.
    pub(crate) fn on_read_after(self, path: &str, earlier_reads: usize, answer: Result<&[u8], i32>) -> Self {
        self.push_read(
            path,
            earlier_reads,
            answer.map(<[u8]>::to_vec).map_err(|errno| (ReadCall::Open, errno)),
        );
        self
    }

    /// [`on_read`](Self::on_read) after the kernel is shared.
    pub(crate) fn state_read(&self, path: &str, answer: Result<&[u8], i32>) {
        self.push_read(
            path,
            0,
            answer.map(<[u8]>::to_vec).map_err(|errno| (ReadCall::Open, errno)),
        );
    }

    fn push_read(&self, path: &str, earlier_reads: usize, answer: ReadAnswer) {
        self.reads
            .lock()
            .expect("no panic holds the rows")
            .push((path.to_owned(), earlier_reads, answer));
    }

    /// Listing any `/proc` answers `answer`: the pids, or the raw errno of its `openat2`.
    pub(crate) fn on_pids(self, answer: Result<&[u32], i32>) -> Self {
        self.state_pids(answer);
        self
    }

    /// [`on_pids`](Self::on_pids) after the kernel is shared.
    pub(crate) fn state_pids(&self, answer: Result<&[u32], i32>) {
        *self.pids.lock().expect("no panic holds the rows") =
            Some(answer.map(<[u32]>::to_vec).map_err(|errno| (ReadCall::Open, errno)));
    }

    /// Listing any `/proc` opens it, and the listing itself (the directory's setup, or `getdents64`)
    /// fails with the raw `errno`.
    pub(crate) fn on_pids_failing_after_open(self, errno: i32) -> Self {
        *self.pids.lock().expect("no panic holds the rows") = Some(Err((ReadCall::Read, errno)));
        self
    }

    /// Listing the threads of `pid` answers `answer`: the thread ids, or the raw errno of the
    /// `openat2` of its `task` directory.
    pub(crate) fn on_tids(self, pid: u32, answer: Result<&[u32], i32>) -> Self {
        self.on_tids_after(pid, 0, answer)
    }

    /// From the listing of `pid`'s threads that follows `earlier_lists` listings of them, answers
    /// `answer`, as [`on_tids`](Self::on_tids) does. Of the rows whose count has been reached, the one
    /// with the highest count wins.
    pub(crate) fn on_tids_after(self, pid: u32, earlier_lists: usize, answer: Result<&[u32], i32>) -> Self {
        self.push_tids(
            pid,
            earlier_lists,
            answer.map(<[u32]>::to_vec).map_err(|errno| (ReadCall::Open, errno)),
        );
        self
    }

    /// [`on_tids`](Self::on_tids) after the kernel is shared.
    pub(crate) fn state_tids(&self, pid: u32, answer: Result<&[u32], i32>) {
        self.push_tids(
            pid,
            0,
            answer.map(<[u32]>::to_vec).map_err(|errno| (ReadCall::Open, errno)),
        );
    }

    fn push_tids(&self, pid: u32, earlier_lists: usize, answer: Listing) {
        self.tids
            .lock()
            .expect("no panic holds the rows")
            .push((pid, earlier_lists, answer));
    }

    /// Listing the threads of `pid` opens its `task` directory, and the listing itself fails with the
    /// raw `errno`.
    pub(crate) fn on_tids_failing_after_open(self, pid: u32, errno: i32) -> Self {
        self.push_tids(pid, 0, Err((ReadCall::Read, errno)));
        self
    }

    /// `self/status` shows the pid in one namespace: `/proc` is this namespace's own.
    pub(crate) fn same_view(self) -> Self {
        self.on_read("self/status", Ok(b"NSpid:\t4242\n"))
    }

    /// `self/status` shows the pid in two namespaces: `/proc` is an outer namespace's.
    pub(crate) fn diverged_view(self) -> Self {
        self.diverged_view_after(0)
    }

    /// [`diverged_view`](Self::diverged_view) from the read of `self/status` that follows
    /// `earlier_reads` reads of it.
    pub(crate) fn diverged_view_after(self, earlier_reads: usize) -> Self {
        self.on_read_after("self/status", earlier_reads, Ok(b"NSpid:\t4242\t1\n"))
    }

    /// `self/status` cannot be read (`EIO`).
    pub(crate) fn unreadable_view(self) -> Self {
        self.unreadable_view_after(0)
    }

    /// [`unreadable_view`](Self::unreadable_view) from the read of `self/status` that follows
    /// `earlier_reads` reads of it.
    pub(crate) fn unreadable_view_after(self, earlier_reads: usize) -> Self {
        self.on_read_after("self/status", earlier_reads, Err(libc::EIO))
    }

    /// `kill(target, 0)` answers `answer`.
    pub(crate) fn on_signal_probe(mut self, target: Pid, answer: Result<(), Errno>) -> Self {
        self.signal_probes.push((target, answer));
        self
    }

    /// `pidfd_open` of `pid`, with any flags, answers `answer` on every call. An fd the test opened
    /// itself is handed out as it is on the first call, and as a duplicate of it on each later one.
    pub(crate) fn on_pidfd_open(self, pid: u32, answer: Result<OwnedFd, Errno>) -> Self {
        self.pidfd_open_row(pid, None, answer)
    }

    /// [`on_pidfd_open`](Self::on_pidfd_open) for opens with exactly `flags`.
    pub(crate) fn on_pidfd_open_flags(self, pid: u32, flags: PidfdFlags, answer: Result<OwnedFd, Errno>) -> Self {
        self.pidfd_open_row(pid, Some(flags), answer)
    }

    fn pidfd_open_row(mut self, pid: u32, flags: Option<PidfdFlags>, answer: Result<OwnedFd, Errno>) -> Self {
        let target = Self::target(pid);
        let row = match answer {
            Ok(fd) => PidfdRow::Fd {
                spare: fd.try_clone().expect("the row's fd duplicates"),
                first: Mutex::new(Some(fd)),
            },
            Err(errno) => PidfdRow::Errno(errno),
        };
        self.pidfd_opens.push((target, flags, row));
        self
    }

    /// A pidfd this kernel opened for `pid` has `pidfs_ino` `answer`: `Some(inode)` on pidfs, `None`
    /// on a kernel whose pidfds have none, or an errno.
    pub(crate) fn on_pidfs_ino(mut self, pid: u32, answer: Result<Option<u64>, Errno>) -> Self {
        self.pidfs_inos.push((Self::target(pid), None, answer));
        self
    }

    /// [`on_pidfs_ino`](Self::on_pidfs_ino) for the pidfds of `pid` opened after `path` was read
    /// once: from then on this row answers in place of the plain one.
    pub(crate) fn on_pidfs_ino_after_read(mut self, pid: u32, path: &str, answer: Result<Option<u64>, Errno>) -> Self {
        self.pidfs_inos.push((Self::target(pid), Some(path.to_owned()), answer));
        self
    }

    /// Live `pid` on a host before Linux 6.9: its pidfd opens as `pidfd` and has no inode of its
    /// own, so the process is told by its `/proc` `starttime`. Rows of its own that follow replace
    /// these.
    ///
    /// `pidfd` is what a send or a pidfd proof reaches: a stand-in (`/dev/null`) fits a row that stops
    /// before either; a row about what a proof reads of `pid`, or whom a signal hits, passes the
    /// process's own.
    pub(crate) fn live_without_pidfs(self, pid: u32, pidfd: OwnedFd) -> Self {
        self.on_pidfd_open(pid, Ok(pidfd)).on_pidfs_ino(pid, Ok(None))
    }

    fn target(pid: u32) -> Pid {
        Pid::from_raw(pid as i32).expect("a row names a positive pid")
    }

    /// Opening `/proc` fails as its `openat2` answering `errno`.
    pub(crate) fn open_proc_fails(mut self, errno: Errno) -> Self {
        self.open_proc = Some(errno);
        self
    }

    /// Notes a read of `path` and returns how many reads of it came before.
    fn count_read(&self, path: &str) -> usize {
        let mut counts = self.read_counts.lock().expect("no panic holds the counts");
        match counts.iter_mut().find(|(p, _)| p == path) {
            Some((_, n)) => {
                *n += 1;
                *n - 1
            }
            None => {
                counts.push((path.to_owned(), 1));
                0
            }
        }
    }

    /// The read row that answers a read or readlink of `path`, if any.
    fn answer(&self, path: &str) -> Option<Result<Vec<u8>, ReadFailure>> {
        let earlier = self.count_read(path);
        let answered = |answer: &ReadAnswer| match answer {
            Ok(bytes) => Ok(bytes.clone()),
            Err((call, errno)) => Err(call.failure(*errno)),
        };
        let stated = {
            let reads = self.reads.lock().expect("no panic holds the rows");
            reads
                .iter()
                .filter(|(p, from, _)| p == path && *from <= earlier)
                .max_by_key(|(_, from, _)| *from)
                .map(|(_, _, answer)| answered(answer))
        };
        if let Some(answer) = stated {
            return Some(answer);
        }
        let (pid, file) = path.split_once('/')?;
        if pid.is_empty() || !pid.bytes().all(|b| b.is_ascii_digit()) {
            return None;
        }
        let rows = self.any_pid_reads.lock().expect("no panic holds the rows");
        rows.iter()
            .find(|(f, ..)| f == file)
            .map(|(_, _, answer)| answered(answer))
    }

    fn real(&self, call: &str) -> &'a dyn Kernel {
        self.real.unwrap_or_else(|| panic!("FakeKernel has no row for {call}"))
    }
}

impl Kernel for FakeKernel<'_> {
    fn pidfd_open(&self, target: Pid, flags: PidfdFlags) -> Result<OwnedFd, Errno> {
        let row = self
            .pidfd_opens
            .iter()
            .rev()
            .find(|(p, row_flags, _)| *p == target && row_flags.is_none_or(|f| f == flags));
        let opened = match row {
            Some((_, _, PidfdRow::Errno(errno))) => return Err(*errno),
            Some((_, _, PidfdRow::Fd { first, spare })) => {
                let first = first.lock().expect("no panic holds the row").take();
                first.unwrap_or_else(|| spare.try_clone().expect("the row's fd duplicates"))
            }
            None => self
                .real(&format!("pidfd_open of {target:?}"))
                .pidfd_open(target, flags)?,
        };
        let reads = self.read_counts.lock().expect("no panic holds the counts").clone();
        self.opened.lock().expect("no panic holds the opens").push(Opened {
            fd: opened.as_raw_fd(),
            pid: target,
            reads,
        });
        Ok(opened)
    }

    fn pidfs_ino(&self, fd: BorrowedFd<'_>) -> Result<Option<u64>, Errno> {
        self.pidfs_ino_calls.fetch_add(1, Ordering::Relaxed);
        let raw = fd.as_raw_fd();
        let opened = self.opened.lock().expect("no panic holds the opens");
        let Some(open) = opened.iter().rev().find(|o| o.fd == raw) else {
            return self.real("pidfs_ino of a descriptor it did not open").pidfs_ino(fd);
        };
        let read_before_open = |path: &str| open.reads.iter().any(|(p, n)| p == path && *n > 0);
        let rows = || self.pidfs_inos.iter().rev().filter(|(p, _, _)| *p == open.pid);
        let row = rows()
            .find(|(_, after, _)| after.as_deref().is_some_and(read_before_open))
            .or_else(|| rows().find(|(_, after, _)| after.is_none()));
        match row {
            Some((_, _, answer)) => *answer,
            None => self.real(&format!("pidfs_ino of {:?}", open.pid)).pidfs_ino(fd),
        }
    }

    fn open_proc(&self) -> Result<ProcDir, ProcOpenFailure> {
        match self.open_proc {
            Some(errno) => Err(ProcOpenFailure::opening(errno)),
            None => self.real("open_proc").open_proc(),
        }
    }

    fn read(&self, dir: &ProcDir, path: &str) -> Result<Vec<u8>, ReadFailure> {
        self.answer(path)
            .unwrap_or_else(|| self.real(&format!("read of {path}")).read(dir, path))
    }

    fn read_link(&self, dir: &ProcDir, path: &str) -> Result<Vec<u8>, ReadFailure> {
        self.answer(path)
            .unwrap_or_else(|| self.real(&format!("read_link of {path}")).read_link(dir, path))
    }

    fn pids(&self, dir: &ProcDir) -> Result<Vec<u32>, ReadFailure> {
        match &*self.pids.lock().expect("no panic holds the rows") {
            Some(Ok(pids)) => Ok(pids.clone()),
            Some(Err((call, errno))) => Err(call.failure(*errno)),
            None => self.real("pids").pids(dir),
        }
    }

    fn tids(&self, dir: &ProcDir, pid: u32) -> Result<Vec<u32>, ReadFailure> {
        let earlier = self.count_read(&format!("{pid}/task"));
        let row = {
            let tids = self.tids.lock().expect("no panic holds the rows");
            tids.iter()
                .filter(|(p, from, _)| *p == pid && *from <= earlier)
                .max_by_key(|(_, from, _)| *from)
                .map(|(_, _, answer)| answer.clone())
        };
        match row {
            Some(Ok(tids)) => Ok(tids),
            Some(Err((call, errno))) => Err(call.failure(errno)),
            None => self.real(&format!("tids of {pid}")).tids(dir, pid),
        }
    }

    fn signal_probe(&self, target: Pid) -> Result<(), Errno> {
        match self.signal_probes.iter().rev().find(|(p, _)| *p == target) {
            Some((_, answer)) => *answer,
            None => self.real(&format!("signal_probe of {target:?}")).signal_probe(target),
        }
    }

    fn peek(&self, pidfd: BorrowedFd<'_>) -> Result<Option<Record>, Errno> {
        match take_wait_row(&self.peeks, pidfd) {
            Some(answer) => answer,
            None => self.real("a peek").peek(pidfd),
        }
    }

    fn consume(&self, pidfd: BorrowedFd<'_>) -> Result<Option<Record>, Errno> {
        match take_wait_row(&self.consumes, pidfd) {
            Some(answer) => answer,
            None => self.real("a consume").consume(pidfd),
        }
    }
}