cosca 0.8.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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
//! Linux: hold a forked child before `exec` until the parent holds its pidfd.
//!
//! std forks before cosca can open a pidfd, and `spawn()` does not return until `exec`. A child
//! that ran with no pidfd held on it would be one cosca neither leaves nor reaps by pid. So the
//! child opens a pidfd on itself in a `pre_exec` hook, sends it to the parent, and waits to be told
//! to go.
//!
//! ```text
//! child (pre_exec hook)                     helper thread (parent)
//! ---------------------                     ----------------------
//! close(parent end)
//! pidfd_open(getpid())
//! send PIDFD + the pidfd (SCM_RIGHTS) ---->  recvmsg(MSG_CMSG_CLOEXEC): exactly one fd; fd >= 3
//!   or ERRNO + errno, and abort
//! recv verdict                        <----  send GO     (the pidfd is held)
//!                                            shutdown(parent end)
//! GO: return Ok, std execs
//! EOF: return Err, std reports it and collects the child, which never ran the program
//! ```
//!
//! No pid number crosses from the child to the parent. The pidfd names the child in whatever pid
//! namespace either of them is, and it is opened by the child itself, so no reap and reuse of the
//! number can come before it.
//!
//! The child's own `pidfd_open` failing is classified as the pre-fork probe's is: a refusal is
//! [`Error::Unsupported`] naming `spawn`, anything else [`Error::Io`] naming `pidfd_open`.
//!
//! The channel is one `AF_UNIX` `SOCK_SEQPACKET` socketpair, `SOCK_CLOEXEC`, made under `spawn_lock`
//! (the witness parameter of [`Pending::open`]). A socket rather than pipes, to carry the pidfd, and
//! so the child can `send` with `MSG_NOSIGNAL`: a hook that wrote to a dead parent would otherwise
//! die of `SIGPIPE`, which std resets to the default in the child, and std reads a child that died
//! before `exec` as a success. Seqpacket, so each message arrives whole.
//!
//! # Every path ends, without a timeout
//!
//! The helper blocks in one place: `recvmsg` of the child's report. The child blocks in one place:
//! `recv` of the verdict. Each ends at the other side's message, or at EOF, and EOF comes from
//! `shutdown`, not from a close. A process forked without `exec`, by any thread in or outside
//! cosca, holds copies of both ends, and a close waits for every copy; a `shutdown` does not.
//!
//! - The parent closes its own copy of the child's end as soon as `spawn()` returns. With no other
//!   copy, the child's death or a failed hook then closes the last one, and the helper reads EOF
//!   by itself.
//! - A copy made by a fork without `exec` (any thread, in or outside cosca) outlives the child, so
//!   the parent can also force EOF: `shutdown` of the read side of its own end. It does so once
//!   nothing is left to report. A failed `spawn()` means that at once: std collected the child (by its own
//!   by-pid wait, see residuals b and c in [`child_exited_before_the_helper_finished`]), or never
//!   forked. A successful one means the child has execed or died, except that std returns
//!   before the child's hooks even run when this process has two of fds 0 to 2 closed (see
//!   [`ReportChannel`]). So the parent then waits for the helper to finish or the child to exit,
//!   watched through a pidfd opened on its number, and forces EOF only if the child exited first.
//!   The watch is never signalled through. See [`child_exited_before_the_helper_finished`] for the
//!   window that watch leaves open until #383.
//! - The helper shuts the parent's end when it is done, and when it unwinds. A child still waiting
//!   for its verdict reads EOF, which is abort: the helper never has to send one.
//!
//! Descriptors this module creates are moved above stdio by
//! [`above_stdio`](crate::above_stdio::above_stdio), which states what that does and does not
//! guarantee.
//!
//! [`ReportChannel`]: crate::containment::cgroup::channel::ReportChannel
//!
//! The helper is a scoped thread, joined before [`Handshake::run`] returns: nothing detached,
//! nothing global. Linux refuses a new thread to a thread whose pid namespace for children is not
//! its own (after `unshare` or `setns` of `CLONE_NEWPID`), so a spawn from such a thread fails,
//! naming that cause, before it forks.

use std::io;
use std::os::fd::{IntoRawFd, OwnedFd, RawFd};
use std::sync::Arc;

use rustix::io::Errno;
use rustix::net::{AddressFamily, RecvFlags, ReturnFlags, SendFlags, Shutdown, SocketFlags, SocketType};

use super::fd_channel::{above_stdio, above_stdio_keeping, publish_ends, register as register_hook, Shared};
use super::held_teardown::tear_down_pidfd;
use super::{SpawnFailure, SpawnLockGuard};
use crate::child::owned::teardown::{HandleTeardown, Past, Remains};
use crate::error::{ChildFate, Error};

const GO: u8 = 1;
/// A report's tag: the child's pidfd is attached as `SCM_RIGHTS`; the value is 0.
const REPORT_PIDFD: i32 = 1;
/// A report's tag: `pidfd_open` on itself failed in the child; the value is its errno.
const REPORT_ERRNO: i32 = 2;
/// A report is two native-endian `i32`s: its tag, then its value.
const REPORT_LEN: usize = 8;

/// The hook is registered; the channel is not yet made. See [`register`].
pub(crate) struct Pending {
    shared: Arc<Shared>,
}

/// The channel to one child. Consumed by [`run`](Self::run).
pub(crate) struct Handshake {
    parent_end: OwnedFd,
    child_end: OwnedFd,
    done: OwnedFd,
    shared: Arc<Shared>,
    /// How long a failed spawn's teardown waits for a child it killed before it warns that it is
    /// still waiting (see [`Handshake::warning_past`]).
    warn_after: Option<std::time::Duration>,
}

/// A spawned child, and the pidfd it sent while it was held before `exec`.
pub(crate) struct Held {
    pub(crate) child: std::process::Child,
    pub(crate) pidfd: OwnedFd,
}

/// Reap `child`, which never ran the program, through `pidfd`: it is dead or on its way out. Says
/// what became of it. With `warn_after`, the wait for its exit warns once it passes that long, and
/// goes on. std's `Child` reaps nothing on drop: the pidfd is the only reaper.
fn reap_unexecuted(child: std::process::Child, pidfd: OwnedFd, warn_after: Option<std::time::Duration>) -> ChildFate {
    end_unexecuted(Some(child.id()), pidfd, warn_after)
}

/// Give up on `child`: no pidfd reached this process, so there is none to reap it through. `why`
/// says what happened to the report.
fn abandon_unreported(child: std::process::Child, why: &str) {
    leave_unreaped(Some(child.id()), why);
}

/// What the helper thread learned.
enum Outcome {
    /// The child sent its pidfd and was told to go.
    Opened(OwnedFd),
    /// The child sent its pidfd, and every copy of its end was closed or shut before GO was sent:
    /// it never ran the program. A GO sent while any copy was still open is buffered, even if the
    /// child had already died: this thread holds a copy until `spawn()` returns. The spawn then
    /// succeeds with a child that dies without running the program, as any child may die.
    Gone(OwnedFd),
    /// The spawn cannot go on. The child was not told to go, so it aborts at EOF. Carries the
    /// child's pidfd if it sent one.
    Failed(Error, Option<OwnedFd>),
    /// EOF before any report: the child died before it could report, or never reached its hook.
    NoReport,
    /// [`Outcome::NoReport`], the EOF forced because the child's exit could not be watched. Carries
    /// what failed, and why.
    Unwatched(&'static str, io::Error),
}

/// Registers the hook on `cmd`, as its FIRST `pre_exec` hook where the caller can arrange it: the
/// child then reports itself before anything else in it can fail, so a child that dies later has
/// a pidfd held on it and is collected through that.
///
/// The channel is made later, under `spawn_lock`, by [`Pending::open`]; a hook whose channel was
/// never opened fails the spawn it belongs to rather than read fd numbers that mean nothing.
pub(crate) fn register(cmd: &mut std::process::Command) -> Pending {
    #[cfg(test)]
    let fault = fault::child_fault();
    // Taken on the spawning thread; the child cannot read thread-locals.
    #[cfg(test)]
    let scripted = fault::take_child_pidfd_open_failure();
    // SAFETY: the hook reads atomics and makes only direct syscalls (libc or rustix, see
    // `open_self`) on integers and fd numbers; `io::Error::from_raw_os_error` does not allocate.
    let shared = unsafe {
        register_hook(cmd, move |shared| {
            hold_child(
                shared,
                #[cfg(test)]
                fault,
                #[cfg(test)]
                scripted,
            )
        })
    };
    Pending { shared }
}

impl Pending {
    /// Makes the channel and publishes its fd numbers to the hook. The child's end sits at fd 3 or
    /// above: std's stdio setup `dup2`s onto 0, 1 and 2 before any hook runs. Both ends are
    /// `SOCK_CLOEXEC`, and `_lock` is the witness that no other cosca fork can inherit them.
    pub(crate) fn open(self, _lock: &SpawnLockGuard) -> Result<Handshake, Error> {
        let (parent_end, child_end) =
            rustix::net::socketpair(AddressFamily::UNIX, SocketType::SEQPACKET, SocketFlags::CLOEXEC, None)
                .map_err(|e| Error::Io(crate::error::io_context("socketpair", e.into())))?;
        // Written, not closed, when the helper is done: a forked copy cannot hold it off. Made
        // before the ends are published, so no failure here can leave stale numbers live.
        let done = rustix::event::eventfd(0, rustix::event::EventfdFlags::CLOEXEC)
            .map_err(|e| Error::Io(crate::error::io_context("eventfd", e.into())))?;
        #[cfg(test)]
        if let Some(errno) = fault::take_done_fd_failure() {
            return Err(Error::Io(crate::error::io_context("eventfd", errno.into())));
        }
        let done = above_stdio(done)?;
        let (child_end, parent_end) = publish_ends(&self.shared, child_end, parent_end)?;
        Ok(Handshake {
            parent_end,
            child_end,
            done,
            shared: self.shared,
            warn_after: None,
        })
    }
}

/// Shuts `fd`'s socket both ways, so every copy of either end reads EOF.
fn shut(fd: &OwnedFd) {
    // An `AF_UNIX` socketpair end is always connected: `shutdown` has nothing to refuse.
    if let Err(e) = rustix::net::shutdown(fd, Shutdown::Both) {
        log::warn!(
            "pidfd handshake: shutdown of the channel failed: {report}",
            report = crate::error::Report(&e)
        );
        debug_assert!(false, "shutdown of a socketpair end failed: {e}");
    }
}

/// Makes the helper's `recvmsg` on the parent's end read EOF, whatever copies of the child's end
/// exist: a shutdown of the read side, which a close of the other end's copies cannot do.
fn force_eof(parent_end: &OwnedFd) {
    // An `AF_UNIX` socketpair end is always connected: `shutdown` has nothing to refuse.
    if let Err(e) = rustix::net::shutdown(parent_end, Shutdown::Read) {
        log::warn!(
            "pidfd handshake: shutdown of the parent's end failed: {report}",
            report = crate::error::Report(&e)
        );
        debug_assert!(false, "shutdown of a socketpair end failed: {e}");
    }
}

/// Forces EOF on the parent's end when dropped while this thread unwinds.
struct ForceEofOnUnwind<'a>(&'a OwnedFd);

impl Drop for ForceEofOnUnwind<'_> {
    fn drop(&mut self) {
        if std::thread::panicking() {
            force_eof(self.0);
        }
    }
}

/// Shuts the parent's end, then says the helper is done, when dropped, unwinding included.
struct ShutOnDrop<'a> {
    parent_end: &'a OwnedFd,
    done: &'a OwnedFd,
    #[cfg(test)]
    seams: &'a fault::HelperSeams,
}

impl Drop for ShutOnDrop<'_> {
    fn drop(&mut self) {
        shut(self.parent_end);
        #[cfg(test)]
        self.seams.record_parent_end_shut(self.parent_end);
        // An eventfd counter never fills at one write per spawn.
        if let Err(e) = rustix::io::write(self.done, &1u64.to_ne_bytes()) {
            log::warn!(
                "pidfd handshake: the helper could not say it is done: {report}",
                report = crate::error::Report(&e)
            );
            debug_assert!(false, "write to the handshake's eventfd failed: {e}");
        }
    }
}

impl Handshake {
    /// Has a spawn that fails after its fork warn once, naming the child, if a wait of its teardown
    /// for a child it killed passes `after`; the wait goes on. Messaging only: no wait ends on it.
    /// Set from the spawn's [`SpawnPolicy::teardown_warn_after`].
    pub(crate) fn warning_past(mut self, after: Option<std::time::Duration>) -> Handshake {
        self.warn_after = after;
        self
    }

    /// Runs `spawn` (the fork) with the helper thread alive beside it, then answers the pidfd.
    ///
    /// - A failed `pidfd_open` in the child, or any other failure of the helper, fails the spawn
    ///   whatever `spawn` answered: the child aborted, and std collected it by pid (see residuals b
    ///   and c in [`child_exited_before_the_helper_finished`]). A refusal is [`Error::Unsupported`]
    ///   with `spawn`'s error as its cause; any other failure answers the helper's own [`Error::Io`],
    ///   and `spawn`'s, which only echoes it, is logged at warn.
    /// - If the helper thread cannot be started, `spawn` is never called: no child exists.
    /// - A child killed before it reported leaves `spawn` answering `Ok` (std reads the closed
    ///   status pipe as success) and the helper at EOF. It is dead but unreaped, and its number
    ///   cannot be trusted without a pidfd, so it is left unreaped and warned about, as a macOS
    ///   `Drop` leaves a child it cannot verify. The spawn fails.
    /// - A child that sent its pidfd and died before its verdict never ran the program. Which
    ///   answer it gets is a race between the helper's GO and the close of the last copy of its
    ///   end (this thread's goes when `spawn()` returns). If the send meets a closed end, the child
    ///   is reaped through the pidfd and the spawn fails. Otherwise GO is buffered, and the spawn
    ///   succeeds with a child that died. Either way the pidfd names it.
    /// - A spawn that fails after its fork: std collected the child (see residuals b and c in
    ///   [`child_exited_before_the_helper_finished`]), and the pidfd shows it, or ends a child still
    ///   there.
    ///
    /// The child runs the program only once told to go, so every failure proves the program did not
    /// start: std's `spawn` fails only on a report from the child before `exec`, and collects that
    /// child.
    pub(crate) fn run(self, spawn: impl FnOnce() -> io::Result<std::process::Child>) -> Result<Held, SpawnFailure> {
        let Handshake {
            parent_end,
            child_end,
            done,
            shared,
            warn_after,
        } = self;
        #[cfg(test)]
        let seams = fault::take_helper_seams();
        #[cfg(test)]
        let helper_seams = seams.clone();
        #[cfg(test)]
        let mut ends = fault::EndProbes::start(&child_end);
        let done = &done;
        // Borrowed by the helper, so this thread can still force EOF on it.
        let parent_end = &parent_end;

        std::thread::scope(|scope| {
            #[cfg(test)]
            let _unwind_checks = fault::UnwindChecks::new(parent_end, &seams);
            #[cfg(test)]
            let _open_held_verdict = seams.open_on_drop();
            let helper = std::thread::Builder::new()
                .name("cosca-pidfd-handshake".into())
                .spawn_scoped(scope, move || {
                    let outcome = {
                        let _shut = ShutOnDrop {
                            parent_end,
                            done,
                            #[cfg(test)]
                            seams: &helper_seams,
                        };
                        help(
                            parent_end,
                            #[cfg(test)]
                            &helper_seams,
                        )
                    };
                    #[cfg(test)]
                    helper_seams.finish();
                    outcome
                });
            let helper = match helper {
                Ok(helper) => helper,
                Err(e) => {
                    shared.withdraw();
                    return Err(SpawnFailure::NotStarted(helper_start_error(e)));
                }
            };

            // A panic on this thread from here on (a panicking logger) unwinds into a join of the
            // helper, which waits for EOF on the child's end: a forked copy of it would hold the
            // join for as long as the copy lives.
            let _eof_on_unwind = ForceEofOnUnwind(parent_end);
            #[cfg(test)]
            let _wait_over = fault::WaitOverOnDrop;
            #[cfg(test)]
            fault::count_spawn();
            #[cfg(test)]
            fault::fork_holder_if_armed();
            let spawned = spawn();
            shared.withdraw();
            #[cfg(test)]
            fault::spawn_returned(spawned.as_ref().ok().map(std::process::Child::id));
            // This thread's copy goes first: the child, or a hook that failed, closing its own copy
            // then gives the helper EOF, with nothing left to wait for.
            drop(child_end);
            #[cfg(test)]
            ends.check_copies_closed();
            let mut unwatched = None;
            let finished = match &spawned {
                // std collected the child (its by-pid wait, residuals b and c), or never forked.
                Err(_) => true,
                Ok(child) => match child_exited_before_the_helper_finished(Some(child.id()), done) {
                    Watch::Running => false,
                    Watch::Exited => true,
                    // Not knowing is no reason to wait on a copy this process cannot see: with
                    // open stdio the child has execed or died, so nothing is lost by the EOF.
                    Watch::Unwatchable(what, cause) => {
                        unwatched = Some((what, cause));
                        true
                    }
                },
            };
            // Nothing is left to report, but a copy of the child's end made by a fork without
            // `exec` (any thread, in or outside cosca) outlives the child and keeps the helper
            // from EOF: force it.
            if finished {
                force_eof(parent_end);
                #[cfg(test)]
                ends.forced_eof();
            }
            #[cfg(test)]
            fault::wait_over();
            #[cfg(test)]
            ends.finish(parent_end);
            #[cfg(test)]
            seams.release_verdict(spawned.as_ref().ok().map(std::process::Child::id));
            let outcome = join_helper(
                helper,
                #[cfg(test)]
                &seams,
            );
            let outcome = match (outcome, unwatched) {
                (Outcome::NoReport, Some((what, cause))) => Outcome::Unwatched(what, cause),
                (outcome, _) => outcome,
            };
            conclude(spawned, outcome, warn_after)
        })
    }
}

/// What the wait after a successful `spawn()` found.
enum Watch {
    /// The helper finished first, or there is nothing to watch.
    Running,
    /// The child exited while the helper still waited, or its number names no child of this one.
    Exited,
    /// The child could not be watched: what failed, and why.
    Unwatchable(&'static str, io::Error),
}

/// After a successful `spawn()`: blocks until the helper is done or the child has exited, and says
/// whether the child exited while the helper still waited. The wait is the child's own progress
/// to its report, as `spawn()`'s is to `exec`. A child that cannot be watched is
/// [`Watch::Unwatchable`]: the caller forces EOF, as for an exit.
fn child_exited_before_the_helper_finished(pid: Option<u32>, done: &OwnedFd) -> Watch {
    use std::os::fd::AsFd;

    use rustix::event::{PollFd, PollFlags};

    use crate::os_process::child::PeekOutcome;
    use crate::wait::exit_only::{peek, Target};
    use crate::wait::{any_ready_now, poll_ready};

    let unwatchable = |what: &'static str, e: io::Error| {
        log::warn!(
            "{}: the spawned child's exit cannot be watched ({what}: {report}); the wait for its report is ended",
            super::named(pid),
            report = crate::error::Report(&e)
        );
        Watch::Unwatchable(what, e)
    };
    // Normally the child reported and execed: the helper is done, and nothing needs watching.
    let mut fds = [PollFd::new(done, PollFlags::IN)];
    match any_ready_now(&mut fds) {
        Ok(true) if fds[0].revents().contains(PollFlags::IN) => return Watch::Running,
        Ok(_) => {}
        Err(e) => return unwatchable("poll on the helper's completion", e.into()),
    }
    let Some(raw) = pid
        .and_then(|pid| i32::try_from(pid).ok())
        .and_then(rustix::process::Pid::from_raw)
    else {
        debug_assert!(false, "a spawned child without a pid: {pid:?}");
        return Watch::Running;
    };
    // A watch only, opened by number. The number is the child's own while the child is an unreaped
    // child of this process. After a foreign reap, it shows only while the number is free
    // (`ESRCH`, or the peek's `ECHILD`), or names no thread-group leader (`ENOENT` or `EINVAL`,
    // by kernel: a thread of this process took it).
    //
    // The window that remains, until #383 (an atomic pidfd) removes the watch: the number can be
    // reaped by a foreign reaper (a `SIG_IGN` host, another thread's `waitpid(-1)`) and taken by a
    // RUNNING child or tracee of this process, and then the watch opens that process and the peek
    // answers `Running`. Nothing is signalled through the watch, but the poll below then waits
    // until the helper is done or that process exits. It needs ALL of:
    //  1. the child dies before it reports, so the helper is not done when this code looks;
    //  2. a fork without `exec` (any thread) copied the child's end, at any point from
    //     `Pending::open` until the spawning thread closes its own copy after `spawn()`, so the
    //     helper cannot read EOF by itself: without a copy, the helper finishes at the child's
    //     death and ends the poll at once;
    //  3. a foreign reap of the child;
    //  4. the number taken, before the watch opens, by a process that is a RUNNING child or tracee
    //     of this process (`waitid` on its pidfd answers "nothing to report" for both).
    // Closed stdio is NOT needed. A number taken by a thread, a zombie child or a non-child is
    // not in the window, and neither is a watch that cannot be set up (open, move, peek or poll) or a
    // panic on the spawning thread: those force EOF.
    //
    // Separate residuals, owned by std's fork path (std 1.90 to 1.98), until #383 removes the
    // handshake. Without a `pre_exec` hook std takes `posix_spawn` and has none of them; the hook
    // puts every Linux spawn on this path, as an fd mapping already did. No test pins them.
    //  a. std makes its own CLOEXEC status `socketpair` before it forks, drops its write end just
    //     after the fork returns in the parent, and blocks reading the other until every copy of
    //     the write end is closed. A fork without `exec` between that `socketpair` and std's close
    //     of the write end holds a copy, and `spawn()` waits in std for as long as the holder
    //     lives, with a healthy child and no death, reap or reuse needed. The handshake cannot end
    //     that wait. Nothing hooks the parent inside that interval.
    //  b. After a pre-exec failure report (an exec failure, or a handshake abort), std waits for
    //     the child by pid. With `SIGCHLD` set to `SIG_IGN` that wait fails and std panics, where
    //     `posix_spawn` returns the exec error (`PermissionDenied` for a mode-644 file, say).
    //  c. In the same wait, a foreign reap of the child plus reuse of its number lets std wait on,
    //     and reap, an unrelated child, losing its exit status.
    #[cfg(test)]
    let injected = fault::watch_open_errno();
    #[cfg(not(test))]
    let injected = None;
    let opened = match injected {
        Some(errno) => Err(errno),
        None => rustix::process::pidfd_open(raw, rustix::process::PidfdFlags::empty()),
    };
    let watch = match opened {
        Ok(watch) => {
            #[cfg(test)]
            let moved = match fault::watch_move_errno() {
                Some(errno) => Err(io::Error::from(errno)),
                None => crate::above_stdio::above_stdio(watch),
            };
            #[cfg(not(test))]
            let moved = crate::above_stdio::above_stdio(watch);
            match moved {
                Ok(watch) => watch,
                Err(e) => return unwatchable("moving its pidfd above stdio", e),
            }
        }
        // The child was reaped, and the number is free or names no thread-group leader.
        Err(Errno::SRCH | Errno::INVAL | Errno::NOENT) => return Watch::Exited,
        Err(e) => return unwatchable("pidfd_open", e.into()),
    };
    #[cfg(test)]
    let injected = fault::watch_peek_errno();
    #[cfg(test)]
    let peeked = match injected {
        Some(errno) => Err(io::Error::from(errno)),
        None if fault::watch_poll_armed() => Ok(PeekOutcome::Running),
        None => peek(&Target::PidFd(watch.as_fd())),
    };
    #[cfg(test)]
    let injected = injected.is_some();
    #[cfg(not(test))]
    let (peeked, injected) = (peek(&Target::PidFd(watch.as_fd())), false);
    match peeked {
        Ok(PeekOutcome::Foreign(_) | PeekOutcome::Exit(_)) => return Watch::Exited,
        Ok(PeekOutcome::Running) => {}
        Err(e) => {
            debug_assert!(injected, "waitid on a spawned child's pidfd failed: {e}");
            return unwatchable("waitid on its pidfd", e);
        }
    }
    #[cfg(test)]
    fault::before_awaiting_the_child();
    let mut fds = [PollFd::new(done, PollFlags::IN), PollFd::new(&watch, PollFlags::IN)];
    #[cfg(test)]
    let polled = match fault::watch_poll_errno() {
        Some(errno) => Err(errno),
        None => poll_ready(&mut fds),
    };
    #[cfg(not(test))]
    let polled = poll_ready(&mut fds);
    // No contract: a process of the same user can lower `RLIMIT_NOFILE` below the two descriptors
    // polled, and `poll` then fails with `EINVAL`.
    if let Err(e) = polled {
        return unwatchable("poll on its pidfd", e.into());
    }
    if !fds[0].revents().contains(PollFlags::IN) && !fds[1].revents().is_empty() {
        Watch::Exited
    } else {
        Watch::Running
    }
}

/// The helper thread could not be started, so nothing was forked.
fn helper_start_error(e: io::Error) -> Error {
    let context = if e.raw_os_error() == Some(libc::EINVAL) {
        // `clone` refuses `CLONE_THREAD` to a task whose namespace for children is not its own.
        "starting the pidfd handshake thread (Linux refuses new threads to a thread that has \
         unshared or entered a pid or time namespace for its children, and a spawn on Linux needs one)"
    } else {
        "starting the pidfd handshake thread"
    };
    Error::Io(crate::error::io_context(context, e))
}

/// The helper thread's whole job. It sends no verdict but GO: a child not told to go reads EOF
/// once the helper shuts its end, and aborts.
fn help(parent_end: &OwnedFd, #[cfg(test)] seams: &fault::HelperSeams) -> Outcome {
    let report = recv_report(parent_end);
    #[cfg(test)]
    seams.wait_verdict();
    let pidfd = match report {
        Ok(Report::Pidfd(pidfd)) => pidfd,
        Ok(Report::Errno(errno)) => {
            return Outcome::Failed(crate::os_process::linux::open::spawn_open_error(errno), None)
        }
        Ok(Report::Eof) => return Outcome::NoReport,
        Err(e) => return Outcome::Failed(e, None),
    };
    // A pidfd in a stdio slot could be replaced under it, so it is moved above them. If that fails
    // it is still the child's pidfd, and the spawn fails with it in hand: the child is not told to
    // go, and is reaped through it.
    #[cfg(test)]
    let moved = match seams.take_move_errno() {
        Some(errno) => Err((Error::Io(io::Error::from(errno)), pidfd)),
        None => above_stdio_keeping(pidfd),
    };
    #[cfg(not(test))]
    let moved = above_stdio_keeping(pidfd);
    let pidfd = match moved {
        Ok(pidfd) => pidfd,
        Err((e, pidfd)) => return Outcome::Failed(e, Some(pidfd)),
    };
    match send_go(
        parent_end,
        #[cfg(test)]
        seams,
    ) {
        Delivery::Delivered => Outcome::Opened(pidfd),
        Delivery::Gone => Outcome::Gone(pidfd),
        Delivery::Failed(e) => Outcome::Failed(
            Error::Io(crate::error::io_context(
                "pidfd handshake: sending the child its go-ahead",
                e,
            )),
            Some(pidfd),
        ),
    }
}

/// What the child sent first.
#[derive(Debug)]
enum Report {
    Pidfd(OwnedFd),
    /// Its `pidfd_open` on itself failed with this.
    Errno(Errno),
    /// Nothing: every copy of its end closed, or the parent shut it.
    Eof,
}

fn recv_report(parent_end: &OwnedFd) -> Result<Report, Error> {
    use std::mem::MaybeUninit;

    use rustix::net::{recvmsg, RecvAncillaryBuffer, RecvAncillaryMessage};

    let mut message = [0u8; REPORT_LEN];
    // Room for two: a second descriptor is then counted, not lost to a truncation.
    let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(2))];
    let mut control = RecvAncillaryBuffer::new(&mut space);
    let received = loop {
        match recvmsg(
            parent_end,
            &mut [io::IoSliceMut::new(&mut message)],
            &mut control,
            RecvFlags::CMSG_CLOEXEC,
        ) {
            Err(Errno::INTR) => continue,
            other => break other,
        }
    };
    let received = received.map_err(|e| {
        Error::Io(crate::error::io_context(
            "pidfd handshake: receiving the child's report",
            e.into(),
        ))
    })?;
    let mut fds = Vec::new();
    let mut foreign = 0;
    for ancillary in control.drain() {
        match ancillary {
            RecvAncillaryMessage::ScmRights(received) => fds.extend(received),
            _ => foreign += 1,
        }
    }
    parse_report(received.bytes, received.flags, &message, fds, foreign)
}

/// Checks a received report: its size, its tag, and that a pidfd report carries exactly one
/// descriptor. `foreign` counts control messages other than `SCM_RIGHTS`.
fn parse_report(
    bytes: usize,
    flags: ReturnFlags,
    message: &[u8; REPORT_LEN],
    fds: Vec<OwnedFd>,
    foreign: usize,
) -> Result<Report, Error> {
    // The kernel drops a descriptor it cannot install, as when this process's table is full.
    if flags.contains(ReturnFlags::CTRUNC) {
        return Err(Error::Io(io::Error::other(
            "pidfd handshake: the child's pidfd could not be received (its control message was \
             truncated, as when this process has no descriptor free)",
        )));
    }
    if bytes == 0 && fds.is_empty() && foreign == 0 {
        return Ok(Report::Eof);
    }
    let violation = |what: String| {
        debug_assert!(false, "pidfd handshake: {what}");
        Err(Error::Io(io::Error::other(format!("pidfd handshake: {what}"))))
    };
    if bytes != REPORT_LEN || flags.contains(ReturnFlags::TRUNC) || foreign != 0 {
        return violation(format!(
            "malformed report: {bytes} bytes, flags {flags:?}, {foreign} foreign control messages"
        ));
    }
    let tag = i32::from_ne_bytes(message[..4].try_into().expect("four bytes"));
    let value = i32::from_ne_bytes(message[4..].try_into().expect("four bytes"));
    match tag {
        REPORT_PIDFD => match <[OwnedFd; 1]>::try_from(fds) {
            Ok([pidfd]) => Ok(Report::Pidfd(pidfd)),
            Err(fds) => violation(format!("a pidfd report carried {} descriptors, not one", fds.len())),
        },
        REPORT_ERRNO if fds.is_empty() && value > 0 => Ok(Report::Errno(Errno::from_raw_os_error(value))),
        _ => violation(format!(
            "unexpected report: tag {tag}, value {value}, {} descriptors",
            fds.len()
        )),
    }
}

/// What sending GO came to.
#[derive(Debug)]
enum Delivery {
    Delivered,
    /// The child's end is closed or shut: the child is dead, or `spawn()` returned without it
    /// execing.
    Gone,
    Failed(io::Error),
}

fn send_go(parent_end: &OwnedFd, #[cfg(test)] seams: &fault::HelperSeams) -> Delivery {
    loop {
        #[cfg(test)]
        let sent = match seams.take_send_errno() {
            Some(errno) => Err(errno),
            None => rustix::net::send(parent_end, &[GO], SendFlags::NOSIGNAL),
        };
        #[cfg(not(test))]
        let sent = rustix::net::send(parent_end, &[GO], SendFlags::NOSIGNAL);
        if let Some(sent) = classify_send(sent) {
            return sent;
        }
    }
}

/// What a `send` of GO answered; `None` to send again.
fn classify_send(sent: Result<usize, Errno>) -> Option<Delivery> {
    match sent {
        Ok(1) => Some(Delivery::Delivered),
        Ok(n) => {
            debug_assert!(
                false,
                "SOCK_SEQPACKET sends a message whole or not at all; sent {n} of 1"
            );
            Some(Delivery::Failed(io::Error::from_raw_os_error(libc::EMSGSIZE)))
        }
        Err(Errno::INTR) => None,
        // `ECONNRESET` is the same close, with a message still unread in the child's end.
        Err(Errno::PIPE | Errno::CONNRESET) => Some(Delivery::Gone),
        Err(e) => Some(Delivery::Failed(e.into())),
    }
}

/// Joins the helper. A helper that panicked shut the parent's end as it unwound, so the child
/// read EOF and aborted; the panic goes on.
fn join_helper(helper: std::thread::ScopedJoinHandle<'_, Outcome>, #[cfg(test)] seams: &fault::HelperSeams) -> Outcome {
    #[cfg(test)]
    seams.release_probe();
    let outcome = match helper.join() {
        Ok(outcome) => outcome,
        Err(payload) => std::panic::resume_unwind(payload),
    };
    #[cfg(test)]
    seams.publish();
    outcome
}

/// Combines the fork's answer with the helper's. A child that sent its pidfd and then failed its
/// `spawn()` is torn down through that pidfd. A child std already collected never ran the program
/// (its exec failed).
///
/// Only a child the helper told to go can run the program, and std fails its `spawn` only on a
/// report from the child before `exec`, so every failure answers that the program did not start.
/// `warn_after`: see [`Handshake::warning_past`].
fn conclude(
    spawned: io::Result<std::process::Child>,
    outcome: Outcome,
    warn_after: Option<std::time::Duration>,
) -> Result<Held, SpawnFailure> {
    let not_started = |error| -> Result<Held, SpawnFailure> { Err(SpawnFailure::NotStarted(error)) };
    let with_child = |cause, fate| Err(SpawnFailure::NotStartedWithChild { cause, fate });
    match (spawned, outcome) {
        (Ok(child), Outcome::Opened(pidfd)) => Ok(Held { child, pidfd }),
        // Not told to go, so it cannot have execed: it was killed on its way, which std reads as
        // success.
        (Ok(child), Outcome::Gone(pidfd)) => {
            let named = super::named(Some(child.id()));
            let fate = reap_unexecuted(child, pidfd, warn_after);
            with_child(
                Error::Io(io::Error::other(format!(
                    "the spawned child ({named}) died before exec: the program never ran"
                ))),
                fate,
            )
        }
        // Not told to go, as in every arm below but the first with `Opened`.
        (Ok(child), Outcome::Failed(e, Some(pidfd))) => {
            let fate = reap_unexecuted(child, pidfd, warn_after);
            with_child(e, fate)
        }
        // Not told to go either: it dies at its hook, if it has not yet, and is left to its reaper.
        (Ok(child), Outcome::Failed(e, None)) => {
            abandon_unreported(
                child,
                &format!("its pidfd could not be used ({})", crate::error::Report(&e)),
            );
            with_child(e, ChildFate::Killed)
        }
        (Ok(child), Outcome::NoReport) => {
            let named = super::named(Some(child.id()));
            abandon_unreported(child, "it died before it sent its pidfd");
            with_child(
                Error::Io(io::Error::other(format!(
                    "the spawned child ({named}) died before it could send its pidfd"
                ))),
                ChildFate::Killed,
            )
        }
        // The spawn failed after the fork, and std collected the child of a spawn it fails: the
        // program never ran. A child still there is ended through the pidfd.
        (Err(e), Outcome::Opened(pidfd)) => {
            use crate::wait::exit_only::{peek, Target};
            use std::os::fd::AsFd as _;
            // A peek that fails tells nothing, and a look on the pidfd having failed, a wait on it
            // may fail too.
            let past = match peek(&Target::PidFd(pidfd.as_fd())) {
                Ok(_) => Past::Clean,
                Err(e) => {
                    log::debug!(
                        "a failed spawn's child cannot be peeked ({report}); taken to be uncollected",
                        report = crate::error::Report(&e)
                    );
                    Past::WaitMayFail
                }
            };
            end_through_pidfd(None, pidfd, past, warn_after, &mut super::Diagnosis::default());
            not_started(Error::Io(e))
        }
        // Not told to go, so it never ran the program.
        (Err(e), Outcome::Gone(pidfd)) => {
            let fate = end_unexecuted(None, pidfd, warn_after);
            with_child(Error::Io(e), fate)
        }
        // The helper failed too, and its error explains the abort std reports.
        (Err(spawn), Outcome::Failed(helper, pidfd)) => {
            let error = answer_of_failed_spawn_and_helper(spawn, helper);
            match pidfd {
                Some(pidfd) => {
                    let fate = end_unexecuted(None, pidfd, warn_after);
                    with_child(error, fate)
                }
                None => not_started(error),
            }
        }
        // The child reads EOF in place of its verdict, whenever it reaches its hook.
        (Ok(child), Outcome::Unwatched(what, cause)) => {
            let named = super::named(Some(child.id()));
            abandon_unreported(child, "it sent no pidfd, and its exit could not be watched");
            with_child(
                Error::Io(crate::error::io_context(
                    format!("the spawned child ({named}) sent no pidfd, and its exit could not be watched: {what}"),
                    cause,
                )),
                ChildFate::Killed,
            )
        }
        (Err(e), Outcome::Unwatched(what, cause)) => {
            warn_beside_the_answer(
                &format!("the spawn failed, and so did the watch on its child's exit ({what})"),
                &cause,
            );
            not_started(Error::Io(e))
        }
        (Err(e), Outcome::NoReport) => not_started(Error::Io(e)),
    }
}

/// The answer of a spawn that failed while its helper did too. The helper's failure is the cause: the
/// child aborted for it, and std's error only echoes what the child's hook returned. The helper's
/// error is an [`Error::Unsupported`] (the child found `pidfd_open` refused) or an [`Error::Io`].
/// `Unsupported` has a slot for the spawn's error, which goes below it. No variant says "the spawn
/// failed and so did its helper", so `Io` has none: the helper's `Io` is the answer, and the spawn's
/// error is logged. An `Io` answers at every count and its peers are logged at warn; an `Io` goes
/// below a slot variant only where that variant's meaning covers what failed. It is not
/// [`Error::with_peers_or_unassessable`]'s, which turns the answer into an `Unassessable` that says
/// the state could not be determined.
fn answer_of_failed_spawn_and_helper(spawn: io::Error, helper: Error) -> Error {
    match helper {
        Error::Io(_) => {
            warn_beside_the_answer("the spawn failed, and so did its helper; the spawn's error", &spawn);
            helper
        }
        slot => slot.with_peers([Error::io_cause(spawn)]),
    }
}

/// Logs at warn a failure that the answer of a failed spawn has no slot for; `what` says which.
fn warn_beside_the_answer(what: &str, failure: &(dyn std::error::Error + 'static)) {
    log::warn!(
        "pidfd handshake: {what}: {report}",
        report = crate::error::Report(failure)
    );
}

/// [`tear_down_pidfd`] for the child `pidfd` names, whose pid is `pid` if known: a child it could
/// not end is left running and warned of, the warn led by `why`; the fate says so. `past`: see
/// [`Past`]. With `warn_after`, the wait for the killed child warns once it passes that long.
/// Answers what is left of the teardown, whose clause is said. A spawn this module concludes did not
/// start, and its answer has no `cleanup`, so each failure of the teardown that its warn did not
/// hold is logged at warn ([`say_teardown_of_failed_spawn`]).
fn end_through_pidfd(
    pid: Option<u32>,
    pidfd: OwnedFd,
    past: Past,
    warn_after: Option<std::time::Duration>,
    why: &mut super::Diagnosis,
) -> Remains {
    say_teardown_of_failed_spawn(tear_down_pidfd(pid, pidfd, None, past, warn_after), why)
}

/// Says `torn` as the failed spawn's one warn, and logs at warn ([`warn_of_teardown_failures`]) each
/// failure that warn does not hold.
fn say_teardown_of_failed_spawn(torn: HandleTeardown, why: &mut super::Diagnosis) -> Remains {
    let held = torn.outcome.said_in_the_one_warn(why);
    let remains = torn.say_as_failed_spawn(why);
    warn_of_teardown_failures(&remains, held);
    remains
}

/// Logs at warn each failure of a failed spawn's teardown that the event's one warn
/// ([`say_as_failed_spawn`](HandleTeardown::say_as_failed_spawn)) does not hold. That warn holds them
/// all when it was said (`held`: its clause is at warn, or the spawn's diagnosis was owed and folded
/// into it); a clause below warn (a refused kill whose look found the child gone) is said at its
/// level only.
fn warn_of_teardown_failures(remains: &Remains, held: bool) {
    if held {
        return;
    }
    for failure in remains.failures.iter().flat_map(|failures| failures.iter()) {
        warn_beside_the_answer("the failed spawn's teardown of its child failed", failure.as_ref());
    }
}

/// [`end_through_pidfd`] for a child that was never told to go, so it never ran the program
/// ([`Past::Unexecuted`]): nothing has looked at its pidfd, and nothing but its being gone can
/// refuse its kill.
fn end_unexecuted(pid: Option<u32>, pidfd: OwnedFd, warn_after: Option<std::time::Duration>) -> ChildFate {
    end_through_pidfd(
        pid,
        pidfd,
        Past::Unexecuted,
        warn_after,
        &mut super::Diagnosis::default(),
    )
    .fate
}

/// Warns that a child stays unreaped: without its pidfd its number cannot be trusted.
fn leave_unreaped(pid: Option<u32>, why: &str) {
    log::warn!(
        "{}: {why}; it is left unreaped, as cosca never reaps a Linux child by pid",
        super::named(pid)
    );
    #[cfg(test)]
    fault::leaked_pid(pid);
}

/// The child's side. Async-signal-safe: direct syscalls only, no allocation, no lock.
fn hold_child(
    shared: &Shared,
    #[cfg(test)] fault: fault::ChildFault,
    #[cfg(test)] scripted: Option<Errno>,
) -> io::Result<()> {
    let child_end: RawFd = shared.child_end();
    let parent_end: RawFd = shared.parent_end();
    // The parent's end, inherited: it has nothing to do here.
    // SAFETY: a plain `close` of a number this hook was given.
    unsafe { libc::close(parent_end) };
    #[cfg(test)]
    fault.apply()?;
    match open_self(
        #[cfg(test)]
        scripted,
    ) {
        Ok(pidfd) => {
            let sent = send_report(child_end, REPORT_PIDFD, 0, pidfd);
            // SAFETY: the pidfd this hook just opened; the parent has its own copy once sent.
            unsafe { libc::close(pidfd) };
            sent?;
        }
        Err(errno) => {
            // Whether or not the report arrives, this child must not run the program.
            _ = send_report(child_end, REPORT_ERRNO, errno, -1);
            return Err(io::Error::from_raw_os_error(errno));
        }
    }
    #[cfg(test)]
    fault.apply_after_report()?;
    let mut verdict = [0u8];
    if recv_one(child_end, &mut verdict)? == 1 && verdict[0] == GO {
        Ok(())
    } else {
        Err(io::Error::from_raw_os_error(libc::ECANCELED))
    }
}

/// `pidfd_open(getpid(), 0)` through rustix: the `linux_raw` backend issues raw syscalls (no
/// allocation, lock or thread-local), so no libc pid cache can be stale after a fork. The errno on
/// failure.
fn open_self(#[cfg(test)] scripted: Option<Errno>) -> Result<RawFd, i32> {
    #[cfg(test)]
    if let Some(errno) = scripted {
        return Err(errno.raw_os_error());
    }
    match rustix::process::pidfd_open(rustix::process::getpid(), rustix::process::PidfdFlags::empty()) {
        Ok(fd) => Ok(fd.into_raw_fd()),
        Err(e) => Err(e.raw_os_error()),
    }
}

/// Sends one report, with `pidfd` attached as `SCM_RIGHTS` unless it is -1. One `sendmsg` from
/// buffers on this frame.
fn send_report(fd: RawFd, tag: i32, value: i32, pidfd: RawFd) -> io::Result<()> {
    #[repr(C, align(8))]
    struct Control([u8; 64]);

    let mut message = [0u8; REPORT_LEN];
    message[..4].copy_from_slice(&tag.to_ne_bytes());
    message[4..].copy_from_slice(&value.to_ne_bytes());
    let mut iov = libc::iovec {
        iov_base: message.as_mut_ptr().cast(),
        iov_len: message.len(),
    };
    let mut control = Control([0; 64]);
    // SAFETY: plain data; zeroed is a valid empty header.
    let mut header: libc::msghdr = unsafe { std::mem::zeroed() };
    header.msg_iov = &mut iov;
    header.msg_iovlen = 1;
    if pidfd >= 0 {
        let fd_len = std::mem::size_of::<RawFd>() as libc::c_uint;
        header.msg_control = control.0.as_mut_ptr().cast();
        // `as _`: `size_t` on glibc, `socklen_t` on musl.
        // SAFETY: arithmetic on a length.
        header.msg_controllen = unsafe { libc::CMSG_SPACE(fd_len) } as _;
        // SAFETY: `control` is aligned and large enough for one descriptor's header and data.
        unsafe {
            let cmsg = libc::CMSG_FIRSTHDR(&header);
            (*cmsg).cmsg_level = libc::SOL_SOCKET;
            (*cmsg).cmsg_type = libc::SCM_RIGHTS;
            (*cmsg).cmsg_len = libc::CMSG_LEN(fd_len) as _;
            std::ptr::write_unaligned(libc::CMSG_DATA(cmsg).cast::<RawFd>(), pidfd);
        }
    }
    loop {
        // SAFETY: every pointer in `header` is to this frame; `MSG_NOSIGNAL` turns a closed peer
        // into `EPIPE`.
        let sent = unsafe { libc::sendmsg(fd, &header, libc::MSG_NOSIGNAL) };
        if sent == REPORT_LEN as isize {
            return Ok(());
        }
        if sent >= 0 {
            // SOCK_SEQPACKET sends a message whole or not at all.
            return Err(io::Error::from_raw_os_error(libc::EMSGSIZE));
        }
        let err = io::Error::last_os_error();
        if err.kind() != io::ErrorKind::Interrupted {
            return Err(err);
        }
    }
}

fn recv_one(fd: RawFd, buf: &mut [u8; 1]) -> io::Result<usize> {
    loop {
        // SAFETY: `buf` is a live one-byte buffer.
        let n = unsafe { libc::recv(fd, buf.as_mut_ptr().cast(), 1, 0) };
        if n >= 0 {
            return Ok(n as usize);
        }
        let err = io::Error::last_os_error();
        if err.kind() != io::ErrorKind::Interrupted {
            return Err(err);
        }
    }
}

#[cfg(test)]
#[path = "pidfd_handshake/fault.rs"]
pub(crate) mod fault;

#[cfg(test)]
#[path = "pidfd_handshake_tests.rs"]
pub(crate) mod pidfd_handshake_tests;

#[cfg(all(test, feature = "tokio"))]
#[path = "pidfd_handshake/slow_teardown_tests.rs"]
mod slow_teardown_tests;