safeptrace 0.5.8

Safe, ergonomic Rust wrappers around the Linux ptrace(2) API.
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
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

#[cfg(all(not(sanitized), target_arch = "x86_64"))]
mod retired_tid {
    use super::*;

    const NAME: &str = "notifier::test::retired_tid::explicit_unregistered_retired_target_refuses_numeric_requests";
    const INNER: &str = "SAFEPTRACE_RETIRED_TARGET_INNER";
    const FORCE: &str = "SAFEPTRACE_RETIRED_TARGET_FORCE";
    const KEEP_WARM: &str = "SAFEPTRACE_RETIRED_TARGET_KEEP_AUTH_WARM";
    const STOP_PROOF: &str = "SAFEPTRACE_RETIRED_TARGET_STOP_PROOF";
    const STOP_PROOF_ROW: &str = "ACTUAL_TID_REUSE_STOP_PROOF_REFUSED ";
    const MARKER: &str = "ACTUAL_EXPLICIT_UNREGISTERED_RETIRED_TARGET_EXERCISED";

    struct FixtureDirectory(std::path::PathBuf);

    impl Drop for FixtureDirectory {
        fn drop(&mut self) {
            // Only the uniquely created directory owned by this invocation.
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    /// Creates a new directory under `base` named `<prefix>-<nonce>`, or
    /// `<prefix>-<nonce>-<n>` for the first `n` that is still free. Neither
    /// the clock nor the PID is unique here: the parallel inner instances
    /// of these tests run in separate PID namespaces, with the same small
    /// PID, and can read the same clock nanoseconds. The atomic
    /// `create_dir` is what makes the directory this invocation's own.
    fn create_unique_dir(
        base: &std::path::Path,
        prefix: &str,
        nonce: u128,
    ) -> std::io::Result<std::path::PathBuf> {
        for attempt in 0..1024_u32 {
            let name = match attempt {
                0 => format!("{prefix}-{nonce}"),
                _ => format!("{prefix}-{nonce}-{attempt}"),
            };
            let directory = base.join(name);
            match fs::create_dir(&directory) {
                Ok(()) => return Ok(directory),
                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
                Err(error) => return Err(error),
            }
        }
        Err(std::io::ErrorKind::AlreadyExists.into())
    }

    fn clock_nonce() -> u128 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    }

    /// Two fixtures that read the same clock nanoseconds, as parallel inner
    /// instances can, still get distinct directories of their own.
    #[test]
    fn fixture_directories_stay_distinct_at_the_same_nanos() {
        let base = FixtureDirectory(
            create_unique_dir(
                &env::temp_dir(),
                "safeptrace-retired-same-nanos",
                clock_nonce(),
            )
            .unwrap(),
        );
        let first = create_unique_dir(&base.0, "safeptrace-retired", 7).unwrap();
        let second = create_unique_dir(&base.0, "safeptrace-retired", 7).unwrap();
        assert_ne!(first, second);
        assert!(first.is_dir() && second.is_dir());
    }

    fn fixture() -> (FixtureDirectory, std::ffi::CString) {
        let directory = FixtureDirectory(
            create_unique_dir(&env::temp_dir(), "safeptrace-retired", clock_nonce()).unwrap(),
        );
        let source = directory.0.join("fixture.c");
        let program = directory.0.join("fixture");
        fs::write(&source, include_bytes!("retired_tid_fixture.c")).unwrap();
        let mut compile = Command::new("cc");
        compile
            .args([
                "-std=gnu11",
                "-O2",
                "-pthread",
                "-Wall",
                "-Wextra",
                "-Werror",
            ])
            .arg(&source)
            .arg("-o")
            .arg(&program)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        let output = crate::test_fork::spawn(&mut compile)
            .and_then(|child| child.wait_with_output())
            .expect("compile owned syscall fixture with the Linux build prerequisites");
        assert!(
            output.status.success(),
            "owned fixture compiler: {output:?}"
        );
        let program = std::ffi::CString::new(program.as_os_str().as_encoded_bytes()).unwrap();
        (directory, program)
    }

    fn raw_request(request: libc::c_uint, pid: Pid, data: usize) {
        assert_eq!(
            unsafe {
                libc::ptrace(
                    request,
                    pid.as_raw(),
                    std::ptr::null_mut::<libc::c_void>(),
                    data as *mut libc::c_void,
                )
            },
            0,
            "actual owned ptrace request {request} on {pid}: {}",
            Errno::last()
        );
    }

    fn raw_wait(pid: Pid) -> (Pid, i32) {
        let mut status = 0;
        let mut result = 0;
        legacy_owner_until(|| {
            result = unsafe {
                libc::waitpid(
                    pid.as_raw(),
                    &mut status,
                    libc::__WALL | libc::__WNOTHREAD | libc::WNOHANG,
                )
            };
            assert!(result >= 0, "actual owned wait: {}", Errno::last());
            result != 0
        });
        (Pid::from_raw(result), status)
    }

    #[test]
    fn cached_stop_authentication_refuses_actual_retired_tid_reuse() {
        for forced in [false, true] {
            let output = run_exact_in_pid_namespace_bounded(
                NAME,
                &[
                    (INNER, "1"),
                    (FORCE, if forced { "1" } else { "0" }),
                    (KEEP_WARM, "1"),
                ],
            )
            .expect("start real warm-cache exec/exact-reuse control");
            assert!(output.status.success(), "warm cache reuse: {output:?}");
            assert_eq!(
                String::from_utf8_lossy(&output.stdout)
                    .lines()
                    .filter(|line| *line == "ACTUAL_WARM_AUTH_CACHE_TID_REUSE_REFUSED")
                    .count(),
                1,
                "warm cache control omitted completed physical reuse proof: {output:?}"
            );
        }
        emit_completion_marker("ACTUAL_WARM_AUTH_CACHE_TID_REUSE_REFUSED");
    }

    /// The stop proof that lets a legacy consume skip its status read never
    /// accepts a reused number. A replacement thread holds the former TID and
    /// sits in a ptrace stop of this same thread, so GETEVENTMSG on the
    /// number succeeds; the retained descriptor of the retired original has
    /// no task, so the proof fails, the status read refuses with ECHILD, and
    /// the replacement's stop is left unconsumed.
    #[test]
    fn legacy_stop_proof_refuses_actual_retired_tid_reuse() {
        let output = run_exact_in_pid_namespace_bounded(
            NAME,
            &[(INNER, "1"), (FORCE, "1"), (STOP_PROOF, "1")],
        )
        .expect("start real forced-legacy exec/exact-reuse control");
        assert!(output.status.success(), "stop proof reuse: {output:?}");
        let stdout = String::from_utf8_lossy(&output.stdout);
        let rows: Vec<_> = stdout
            .lines()
            .filter(|line| line.starts_with(STOP_PROOF_ROW))
            .collect();
        assert_eq!(
            rows.len(),
            1,
            "stop proof control omitted its completed reuse row: {output:?}"
        );
        emit_completion_marker(rows[0]);
    }

    #[test]
    fn explicit_unregistered_retired_target_refuses_numeric_requests() {
        if env::var_os(INNER).is_none() {
            for forced in [false, true] {
                let output = run_exact_in_pid_namespace_bounded(
                    NAME,
                    &[(INNER, "1"), (FORCE, if forced { "1" } else { "0" })],
                )
                .expect("start real owned exec/exact-reuse control");
                assert!(
                    output.status.success(),
                    "retired target control: {output:?}"
                );
                let stdout = String::from_utf8_lossy(&output.stdout);
                let rows: Vec<_> = stdout
                    .lines()
                    .filter(|line| line.starts_with("RETIRED_EXPLICIT_TARGET_REFUSAL "))
                    .collect();
                assert_eq!(
                    rows.len(),
                    1,
                    "missing actual retirement/reuse cell: {stdout}"
                );
                assert!(rows[0].contains(&format!("forced={forced}")));
                print!("{stdout}");
                eprint!("{}", String::from_utf8_lossy(&output.stderr));
            }
            emit_completion_marker(MARKER);
            return;
        }
        let forced = env::var(FORCE).as_deref() == Ok("1");
        let (_directory, executable) = fixture();
        let [start, release] = legacy_pipe();
        let start_number = std::ffi::CString::new(start.as_raw_fd().to_string()).unwrap();
        let root = match unsafe { fork() }.unwrap() {
            ForkResult::Parent { child } => child,
            ForkResult::Child => {
                assert_eq!(
                    unsafe { libc::fcntl(start.as_raw_fd(), libc::F_SETFD, 0) },
                    0
                );
                unsafe {
                    libc::execl(
                        executable.as_ptr(),
                        executable.as_ptr(),
                        c"--guest".as_ptr(),
                        start_number.as_ptr(),
                        std::ptr::null::<libc::c_char>(),
                    );
                    libc::_exit(127);
                }
            }
        };
        drop(start);
        let mut root_cleanup = TraceeCleanupGuard::new(root).unwrap();
        let _force = forced.then(|| LegacyThreadGroup::new(root));
        // Public SEIZE deliberately omits TRACEEXEC. This fixture does not
        // manufacture a new option requirement for interrupt/ptrace calls.
        let options =
            Options::PTRACE_O_TRACECLONE | Options::PTRACE_O_TRACEEXIT | Options::PTRACE_O_EXITKILL;
        let running = Running::seize_on_ptracer_thread(root.into(), options).unwrap();
        assert_eq!(
            unsafe { libc::write(release.as_raw_fd(), b"s".as_ptr().cast(), 1) },
            1
        );
        drop(release);
        let (parent, event) = running
            .wait_sync_on_ptracer_thread()
            .wait()
            .unwrap()
            .assume_stopped();
        let crate::Event::NewChild(crate::ChildOp::Clone, member) = event else {
            panic!("expected the genuine original CLONE event");
        };
        let former = Pid::from(member.pid());
        let (stopped, event) = member
            .wait_sync_on_ptracer_thread()
            .wait()
            .unwrap()
            .assume_stopped();
        assert_eq!(event, crate::Event::Stop);
        let original = stopped.1.event().clone();
        let generation = stopped.generation();
        let owner = stopped.1.ptracer_owner.clone().unwrap();
        let native = stopped
            .terminal_cleanup_on_ptracer_thread()
            .shared()
            .has_thread_pidfd()
            .unwrap();
        if forced {
            assert!(!native);
        }
        assert!(owner.is_current().unwrap());
        assert_eq!(original.current_tracer_pid(), Ok(owner.tid));
        assert_eq!(original.identity().unwrap().pidfd_is_live(), Ok(true));
        assert_eq!(
            original.event().worker_state.load(Ordering::Acquire),
            WORKER_NOT_STARTED
        );
        assert!(!*original.event().terminal_reaping.read());
        let warm_epoch = env::var_os(KEEP_WARM).map(|_| {
            owner.force_directory_proof.store(true, Ordering::Relaxed);
            original
                .event()
                .numeric_auth_force_directory
                .store(true, Ordering::Relaxed);
            // Warm the positive proof through genuine SDK requests at the
            // original consumed newborn stop. A controlled raw resume below
            // deliberately leaves that epoch valid, so the later refusal
            // must come from the fresh original-target inode lookup.
            stopped.getsiginfo().unwrap();
            stopped.getregs().unwrap();
            let epoch = original.event().numeric_auth_epoch.load(Ordering::Acquire);
            assert_eq!(
                original
                    .event()
                    .numeric_auth_checked_epoch
                    .load(Ordering::Acquire),
                epoch
            );
            epoch
        });
        let old_running = if warm_epoch.is_some() {
            raw_request(libc::PTRACE_CONT, former, 0);
            Running::from_token(stopped.0, stopped.1)
        } else {
            stopped.resume(None).unwrap()
        };
        let parent_running = parent.resume(None).unwrap();
        let mut replacement = Pid::from_raw(0);
        let deadline = Instant::now() + TRACEE_WAIT_TIMEOUT;
        for _ in 0..12 {
            assert!(Instant::now() < deadline);
            // There are no background wait owners: both SDK waits above
            // consumed their actual stops through the synchronous claim.
            let (pid, status) = raw_wait(Pid::from_raw(-1));
            assert!(libc::WIFSTOPPED(status));
            assert_ne!(status >> 16, libc::PTRACE_EVENT_EXEC);
            if pid == root && status >> 16 == libc::PTRACE_EVENT_CLONE {
                let mut child = 0usize;
                raw_request(
                    libc::PTRACE_GETEVENTMSG,
                    root,
                    (&mut child as *mut usize) as usize,
                );
                replacement = Pid::from_raw(child as i32);
                break;
            }
            raw_request(libc::PTRACE_CONT, pid, 0);
        }
        assert_eq!(
            replacement, former,
            "actual clone3 same-group former TID reuse"
        );
        let stop_proof_row = env::var_os(STOP_PROOF).map(|_| {
            assert!(forced, "the stop proof serves only legacy procfs identities");
            let identity = original.identity().unwrap();
            let event = original.event();
            assert!(matches!(identity.pidfd, ThreadHandle::Procfs { .. }));
            assert!(event.legacy_wait_owner.get().is_some());
            // The replacement's newborn stop, reported by the number and not
            // consumed.
            let reported = legacy_owner_observe(former, WaitPidFlag::WSTOPPED);
            assert!(libc::WIFSTOPPED(reported));
            assert_eq!(reported >> 16, libc::PTRACE_EVENT_STOP);
            // The number names a task in a ptrace stop of THIS thread, while
            // the retained PID object of the original has no task.
            assert!(nix::sys::ptrace::getevent(former).is_ok());
            assert_eq!(identity.pidfd_is_live(), Ok(false));
            let reads = RETAINED_STATUS_READS.with(Cell::get);
            let accepted = LEGACY_STOP_PROOFS_ACCEPTED.with(Cell::get);
            let refused = LEGACY_STOP_PROOFS_REFUSED.with(Cell::get);
            let progress = event.legacy_wait.lock();
            let result = try_consume_legacy_status(identity, event, None);
            drop(progress);
            let reads = RETAINED_STATUS_READS.with(Cell::get) - reads;
            let accepted = LEGACY_STOP_PROOFS_ACCEPTED.with(Cell::get) - accepted;
            let refused = LEGACY_STOP_PROOFS_REFUSED.with(Cell::get) - refused;
            assert_eq!(result, Err(Errno::ECHILD));
            assert_eq!((reads, accepted, refused), (1, 0, 1));
            let still = legacy_owner_observe(former, WaitPidFlag::WSTOPPED);
            assert_eq!(still, reported, "the refused attempt consumed a status");
            format!(
                "{STOP_PROOF_ROW}former_tid={former} replacement_tid={replacement} replacement_stop=EVENT_STOP geteventmsg_on_number=ok original_pidfd_live=false try_consume={result:?} status_reads={reads} proofs_accepted={accepted} proofs_refused={refused} replacement_stop_unconsumed=true"
            )
        });
        let (pid, newborn) = raw_wait(replacement);
        assert_eq!(pid, replacement);
        assert!(libc::WIFSTOPPED(newborn));
        assert_eq!(newborn >> 16, libc::PTRACE_EVENT_STOP);
        assert_eq!(original.identity().unwrap().pidfd_is_live(), Ok(false));
        assert_eq!(
            unsafe {
                libc::syscall(
                    libc::SYS_pidfd_send_signal,
                    original.identity().unwrap().pidfd.as_raw_fd(),
                    0,
                    std::ptr::null::<libc::siginfo_t>(),
                    0,
                )
            },
            -1
        );
        assert_eq!(Errno::last(), Errno::ESRCH);
        assert!(matches!(
            original.current_tracer_pid(),
            Err(Errno::ESRCH | Errno::ENOENT)
        ));
        assert_eq!(
            original.event().worker_state.load(Ordering::Acquire),
            WORKER_NOT_STARTED
        );
        assert!(
            !*original.event().terminal_reaping.read(),
            "no notifier has closed the old gate"
        );
        assert!(owner.is_current().unwrap());
        assert_eq!(old_running.generation(), generation);
        let fresh = Stopped::new_unchecked_on_ptracer_thread(replacement.into()).unwrap();
        assert!(!*original.event().terminal_reaping.read());
        assert_eq!(
            original.event().worker_state.load(Ordering::Acquire),
            WORKER_NOT_STARTED
        );
        let fresh_generation = fresh.generation();
        assert_ne!(fresh_generation, generation);
        assert_eq!(fresh.1.event().current_tracer_pid(), Ok(owner.tid));
        let siginfo = fresh.getsiginfo().unwrap();
        let registers = fresh.getregs().unwrap();
        let old = generation.assume_stopped();
        if let Some(epoch) = warm_epoch {
            assert_eq!(
                original.event().numeric_auth_epoch.load(Ordering::Acquire),
                epoch
            );
            assert_eq!(
                original
                    .event()
                    .numeric_auth_checked_epoch
                    .load(Ordering::Acquire),
                epoch,
                "the old positive authentication must still match its epoch"
            );
        }
        #[cfg(feature = "memory")]
        {
            use std::io::IoSlice;

            use reverie_memory::Addr;
            use reverie_memory::AddrMut;
            use reverie_memory::MemoryAccess;
            use reverie_memory::RemoteIoVec;

            // The replacement is parked on its genuine writable clone stack.
            // The stale token still names the same numeric TID, with its old
            // gate open: only the retained generation guard can refuse this
            // permission-respecting native write before touching these bytes.
            let address = (registers.rsp as usize).checked_sub(16).unwrap();
            let mut before = [0u8; 8];
            fresh
                .read_exact(Addr::from_raw(address).unwrap(), &mut before)
                .unwrap();
            let changed = before.map(|byte| byte ^ 0xff);
            let remote = [RemoteIoVec::new(AddrMut::from_raw(address).unwrap(), 8).unwrap()];
            let mut stale_memory = generation.assume_stopped();
            assert_eq!(
                stale_memory.write_native_user_vectored(
                    former.as_raw(),
                    &[IoSlice::new(&changed)],
                    &remote,
                ),
                Err(Errno::ESRCH)
            );
            assert_eq!(stale_memory.generation(), generation);
            let mut after = [0u8; 8];
            fresh
                .read_exact(Addr::from_raw(address).unwrap(), &mut after)
                .unwrap();
            assert_eq!(after, before, "stale native write changed the replacement");
        }
        for _ in 0..2 {
            assert!(matches!(old.getsiginfo(), Err(Error::Died(_))));
            assert!(matches!(old.getregs(), Err(Error::Died(_))));
            let sample = old.observation().sample(false);
            assert_eq!(sample.siginfo().unwrap().unwrap_err(), Errno::ESRCH);
            assert_eq!(old_running.generation(), generation);
            let after = fresh.getsiginfo().unwrap();
            assert_eq!(after.si_signo, siginfo.si_signo);
            assert_eq!(after.si_code, siginfo.si_code);
            assert_eq!(unsafe { after.si_pid() }, unsafe { siginfo.si_pid() });
            assert_eq!(fresh.getregs().unwrap(), registers);
            let mut pending = 0;
            assert_eq!(
                unsafe {
                    libc::waitpid(
                        replacement.as_raw(),
                        &mut pending,
                        libc::__WALL | libc::__WNOTHREAD | libc::WNOHANG,
                    )
                },
                0
            );
        }
        // The same real retired-generation fixture must refuse syscall resume
        // without losing the old capability or touching its live replacement.
        let (old, error) = old.syscall_retaining(None).unwrap_err();
        assert_eq!(error, Errno::ESRCH);
        assert_eq!(old.generation(), generation);
        assert_eq!(fresh.getregs().unwrap(), registers);
        let (retained, error) = old.resume_retaining(None).unwrap_err();
        assert_eq!(error, Errno::ESRCH);
        assert_eq!(retained.generation(), generation);
        assert_eq!(fresh.getregs().unwrap(), registers);
        let fresh_running = fresh.resume(None).unwrap();
        for _ in 0..2 {
            assert_eq!(old_running.interrupt(), Err(Errno::ESRCH));
            let mut pending = 0;
            assert_eq!(
                unsafe {
                    libc::waitpid(
                        replacement.as_raw(),
                        &mut pending,
                        libc::__WALL | libc::__WNOTHREAD | libc::WNOHANG,
                    )
                },
                0,
                "retired request stopped the replacement"
            );
        }
        // The fresh ORIGINAL replacement capability still produces a real
        // interrupt stop, proving that refusal did not break actual progress.
        fresh_running.interrupt().unwrap();
        let (pid, actual_stop) = raw_wait(replacement);
        assert_eq!(pid, replacement);
        assert!(libc::WIFSTOPPED(actual_stop));
        assert_eq!(actual_stop >> 16, libc::PTRACE_EVENT_STOP);
        let current = fresh_generation.assume_stopped();
        assert_eq!(
            current.getsiginfo().unwrap().si_code,
            libc::SIGTRAP | (libc::PTRACE_EVENT_STOP << 8)
        );
        drop((
            current,
            retained,
            old_running,
            fresh_running,
            parent_running,
        ));
        pidfd_send_signal(&root_cleanup.pidfd, libc::SIGKILL).unwrap();
        let mut root_reaped = false;
        let mut member_reaped = false;
        let deadline = Instant::now() + TRACEE_WAIT_TIMEOUT;
        while !root_reaped || !member_reaped {
            assert!(Instant::now() < deadline);
            let (pid, status) = raw_wait(Pid::from_raw(-1));
            if libc::WIFSTOPPED(status) {
                raw_request(libc::PTRACE_CONT, pid, 0);
                continue;
            }
            assert!(libc::WIFSIGNALED(status));
            assert_eq!(libc::WTERMSIG(status), libc::SIGKILL);
            if pid == root {
                root_reaped = true;
            } else {
                assert_eq!(pid, replacement);
                member_reaped = true;
            }
        }
        root_cleanup.disarm();
        assert!(!std::path::Path::new(&format!("/proc/{root}")).exists());
        assert!(!std::path::Path::new(&format!("/proc/{replacement}")).exists());
        let mut last = 0;
        assert_eq!(
            unsafe {
                libc::waitpid(
                    -1,
                    &mut last,
                    libc::__WALL | libc::__WNOTHREAD | libc::WNOHANG,
                )
            },
            -1
        );
        assert_eq!(Errno::last(), Errno::ECHILD);
        if let Some(epoch) = warm_epoch {
            assert_eq!(
                original.event().numeric_auth_epoch.load(Ordering::Acquire),
                epoch
            );
            assert_eq!(
                original
                    .event()
                    .numeric_auth_checked_epoch
                    .load(Ordering::Acquire),
                epoch
            );
            emit_completion_marker("ACTUAL_WARM_AUTH_CACHE_TID_REUSE_REFUSED");
        }
        if let Some(row) = stop_proof_row {
            emit_completion_marker(&row);
        }
        emit_completion_marker(&format!(
            "RETIRED_EXPLICIT_TARGET_REFUSAL native={native} forced={forced} former_tid={former} exact_reuse=true same_ptracer=true old_gate_open=true old_worker_unstarted=true actual_original_retired=ESRCH retired_numeric_requests=ESRCH replacement_siginfo_and_registers_preserved=true actual_fresh_interrupt=EVENT_STOP actual_group_kill=SIGKILL root_and_member_reaped=true final_ECHILD=true"
        ));
    }
}