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
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
//! Test-only child processes shared across the crate's unit tests.
//!
//! On Windows these spawn through [`crate::test_spawn`] or build their `Command` with [`command`],
//! the one place a test builds a `Command`, so a child opens no console window unless the test
//! passes [`Console::Asked`]; a test of the console-group signals takes an `_on_console` helper.

skuld::default_labels!(crate::test_harness::ROOT);

#[cfg(target_os = "linux")]
pub(crate) mod namespaces;

#[cfg(target_os = "linux")]
pub(crate) mod pid_reuse;

#[cfg(windows)]
pub(crate) mod ctrl_break;

/// The handle a spawn's parent end holds, for a test that inspects it.
#[cfg(windows)]
pub(crate) fn parent_handle(end: &crate::pipe::ParentEnd) -> std::os::windows::io::BorrowedHandle<'_> {
    use std::os::windows::io::AsHandle;
    match end {
        crate::pipe::ParentEnd::Reader(r) => r.as_handle(),
        crate::pipe::ParentEnd::Writer(w) => w.as_handle(),
    }
}

#[cfg(windows)]
pub(crate) mod unwaitable;

#[cfg(unix)]
pub(crate) mod blocked_tree_root;

#[cfg(unix)]
pub(crate) mod foreign;

#[cfg(unix)]
pub(crate) mod reaped_elsewhere;

#[cfg(target_os = "linux")]
pub(crate) mod member;

pub(crate) mod over_fake;

#[cfg(target_os = "macos")]
use crate::test_own_process;
#[cfg(target_os = "macos")]
#[path = "../tests/common/kevent_eintr.rs"]
mod kevent_eintr;

pub(crate) use crate::test_spawn::console_flags::Console;

// The Command factory =====

/// The one place a test builds a [`crate::Command`]. On Windows a [`Console::Hidden`] command asks
/// for `no_window()`, so a test run from a process with no console opens no window; a test that
/// signals the child's console group or measures console membership passes [`Console::Asked`].
/// Off Windows both are a plain `Command::new()`.
pub(crate) fn command(console: Console) -> crate::Command {
    let mut cmd = crate::Command::new();
    if console.hides_window() {
        cmd.no_window();
    }
    cmd
}

/// [`command`] for the async `Command`.
#[cfg(feature = "tokio")]
pub(crate) fn tokio_command(console: Console) -> crate::tokio::Command {
    let mut cmd = crate::tokio::Command::new();
    if console.hides_window() {
        cmd.no_window();
    }
    cmd
}

/// The path of the package's `[[bin]]` target `name`. A lib test has no `CARGO_BIN_EXE_*`, so it is
/// read from beside the test binary's own `deps` directory, where cargo puts them (a `--lib`-only
/// build does not make them).
#[cfg(windows)]
pub(crate) fn testbin(name: &str) -> std::path::PathBuf {
    let exe = std::env::current_exe().expect("current_exe");
    let path = exe
        .parent()
        .and_then(std::path::Path::parent)
        .expect("the test binary lives in <target>/<profile>/deps")
        .join(format!("{name}{}", std::env::consts::EXE_SUFFIX));
    assert!(
        path.is_file(),
        "{} is missing: build the package's bin targets (`cargo nextest run` does; `--lib` does not)",
        path.display()
    );
    path
}

// Blocker fixtures =====

/// The argv of a child that does nothing until its stdin reaches EOF or it is killed: `cat`, or
/// `findstr x` on Windows. Every fixture that needs a child "still alive at some later check"
/// uses this instead of a fixed-duration `sleep`/`ping`, whose own timer would end the child on
/// its own and let a mutant that skips the kill under test pass for the wrong reason. Stdin is
/// what decides the child's fate, so the writer's lifetime is the fixture's lifetime:
///
/// - [`leaked_writer_stdin`]: the write end is never closed, so only a kill by the code under
///   test ends the child (teardown tests that own no handle on it).
/// - [`held_std_blocker`], [`held_contained_blocker`] and [`held_contained_blocker_async`]: the
///   caller holds the write end and must keep it for exactly as long as the child must stay
///   alive. Dropping it (or `std::process::Child::wait()`, which closes the piped stdin before
///   it waits) is a deliberate EOF release.
///
/// A `cat` backgrounded inside an `sh -c` script gets `/dev/null` as stdin (POSIX, for a
/// non-interactive shell) unless it is redirected explicitly, and would exit at once. Write it
/// `exec 3<&0; cat <&3 3<&- &`: `<&3` gives it the real pipe and `3<&-` closes the spare copy.
///
/// Neither `cat` nor `findstr` is proof of life by itself: `Existence::Present` is
/// zombie-inclusive, and `SIGKILL`/`TerminateProcess` land asynchronously. A liveness claim needs
/// an echo round trip through a piped stdout, or (Windows, where `findstr` does not echo) a
/// clean exit after a closed stdin.
pub(crate) const BLOCKER_ARGV: &[&str] = if cfg!(windows) { &["findstr", "x"] } else { &["cat"] };

/// A [`Stdio`](crate::stdio::Stdio) reading from a pipe whose write end is leaked (see
/// [`BLOCKER_ARGV`]). For a child the test leaves alone: any test that expects a kill holds the
/// writer instead ([`held_writer_stdin`]) and releases it after the kill.
#[cfg(target_os = "macos")]
pub(crate) fn leaked_writer_stdin() -> crate::stdio::Stdio {
    let (reader, writer) = std::io::pipe().expect("pipe");
    #[cfg(unix)]
    let file = std::fs::File::from(std::os::fd::OwnedFd::from(reader));
    #[cfg(windows)]
    let file = std::fs::File::from(std::os::windows::io::OwnedHandle::from(reader));
    std::mem::forget(writer);
    crate::stdio::Stdio::from_file(file)
}

/// This process's stdio, closed with copies kept at 10 or above, put back when dropped. For a
/// re-exec'd fixture that needs the lowest free numbers to be stdio slots: drop every descriptor
/// created meanwhile first, or the restoring `dup2` replaces it.
#[cfg(unix)]
pub(crate) struct ClosedStdio {
    saved: [std::os::fd::OwnedFd; 3],
}

/// Lowers this process's descriptor limit to its lowest free descriptor, so that no further one can
/// be made, until the guard drops. Process-wide, so it takes the witness that this test runs in a
/// process of its own (`test_own_process::own_process`).
#[cfg(unix)]
pub(crate) fn exhaust_fds(alone: &crate::test_own_process::Completion) -> RestoreNofile {
    // SAFETY: `dup` and `close` on a valid descriptor.
    let lowest_free = unsafe {
        let lowest_free = libc::dup(0);
        assert!(lowest_free >= 0, "dup(0)");
        libc::close(lowest_free);
        lowest_free
    };
    lower_fd_limit(alone, lowest_free as libc::rlim_t)
}

/// Lowers the soft descriptor limit to `soft` until the guard drops. Process-wide, so takes the same
/// witness as [`exhaust_fds`].
#[cfg(unix)]
pub(crate) fn lower_fd_limit(_alone: &crate::test_own_process::Completion, soft: libc::rlim_t) -> RestoreNofile {
    // SAFETY: `getrlimit` and `setrlimit` on valid arguments.
    unsafe {
        let mut limit: libc::rlimit = std::mem::zeroed();
        assert_eq!(libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit), 0);
        let before = limit;
        limit.rlim_cur = soft;
        assert_eq!(libc::setrlimit(libc::RLIMIT_NOFILE, &limit), 0);
        RestoreNofile(before)
    }
}

#[cfg(unix)]
#[must_use = "the limit stays lowered only while this lives"]
pub(crate) struct RestoreNofile(libc::rlimit);

#[cfg(unix)]
impl Drop for RestoreNofile {
    fn drop(&mut self) {
        // SAFETY: `setrlimit` with a limit read from `getrlimit`.
        let restored = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &self.0) };
        debug_assert_eq!(restored, 0, "restoring the descriptor limit");
    }
}

/// Closes fds 0 to 2; see [`ClosedStdio`].
#[cfg(unix)]
pub(crate) fn close_stdio_keeping_a_copy() -> ClosedStdio {
    use std::os::fd::BorrowedFd;
    let copy = |fd: i32| {
        // SAFETY: fds 0 to 2 are open in a running test process.
        let stdio = unsafe { BorrowedFd::borrow_raw(fd) };
        rustix::io::fcntl_dupfd_cloexec(stdio, 10).expect("copy a stdio descriptor")
    };
    let saved = [copy(0), copy(1), copy(2)];
    for fd in 0..3 {
        // SAFETY: closes a descriptor the copies above preserve.
        assert_eq!(unsafe { libc::close(fd) }, 0);
    }
    ClosedStdio { saved }
}

#[cfg(unix)]
impl Drop for ClosedStdio {
    fn drop(&mut self) {
        use std::os::fd::AsRawFd;
        for (fd, saved) in self.saved.iter().enumerate() {
            // SAFETY: `dup2` of a copy this guard owns onto a stdio slot.
            unsafe { libc::dup2(saved.as_raw_fd(), fd as i32) };
        }
    }
}

/// Like [`leaked_writer_stdin`], but the caller keeps the write end: dropping it is the only way
/// to make the [`BLOCKER_ARGV`] child exit by itself (status 0), so a test that must see a kill
/// end it drops the writer only after the kill.
pub(crate) fn held_writer_stdin() -> (crate::stdio::Stdio, crate::PipeWriter) {
    let (reader, writer) = std::io::pipe().expect("pipe");
    #[cfg(unix)]
    let file = std::fs::File::from(std::os::fd::OwnedFd::from(reader));
    #[cfg(windows)]
    let file = std::fs::File::from(std::os::windows::io::OwnedHandle::from(reader));
    (crate::stdio::Stdio::from_file(file), writer.into())
}

/// A [`BLOCKER_ARGV`] `std::process::Command` with piped stdin (held by the spawned `Child`'s
/// own `stdin` field) and the given stdout. The caller spawns it under `spawn_lock()`.
pub(crate) fn held_std_blocker(stdout: std::process::Stdio) -> std::process::Command {
    let mut cmd = std::process::Command::new(BLOCKER_ARGV[0]);
    cmd.args(&BLOCKER_ARGV[1..])
        .stdin(std::process::Stdio::piped())
        .stdout(stdout);
    cmd
}

/// [`held_std_blocker`] with a null stdout, for a test that tells a kill from the child's own exit
/// by its status. On Windows it is `more.com` (see [`windows_more`]): it exits 0 on EOF, where the
/// `findstr x` of [`BLOCKER_ARGV`] exits 1, the code `TerminateProcess(_, 1)` reports too, so a
/// released `findstr` would pass for a killed one.
pub(crate) fn held_std_killable_blocker() -> std::process::Command {
    #[cfg(unix)]
    {
        held_std_blocker(std::process::Stdio::null())
    }
    #[cfg(windows)]
    {
        let mut cmd = std::process::Command::new(windows_more());
        cmd.stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::null());
        cmd
    }
}

/// `.contain()`, except that on Linux it asks for [`ContainMode::Session`](crate::ContainMode::Session)
/// (a process group, torn down with `killpg`), which never looks for a cgroup. `.contain()` tries a
/// cgroup leaf first and logs a warning where none is delegated, so a test that holds a
/// [`warn_watch`](crate::log_capture::warn_watch) would warn on one host and not on another. See
/// principle 9 of `docs/principles.md`. Mirrors `tests/common`'s helper of the same name, which a
/// separate compilation unit cannot share.
#[cfg(unix)]
pub(crate) fn contain_without_cgroup(cmd: &mut crate::Command) -> &mut crate::Command {
    #[cfg(target_os = "linux")]
    return cmd.contain_with(crate::ContainMode::Session);
    #[cfg(not(target_os = "linux"))]
    cmd.contain()
}

// What a contained test asks of containment and gets: the integration tests' table, compiled from
// its real source.
#[path = "../tests/common/contain_gives.rs"]
mod contain_gives;
#[cfg(unix)]
pub(crate) use contain_gives::{contain_without_cgroup_gives, session_gives};
pub(crate) use contain_gives::{drainable_gives, tree_walk_gives};

/// [`contain_without_cgroup`] for the async `Command`.
#[cfg(all(unix, feature = "tokio"))]
pub(crate) fn contain_without_cgroup_async(cmd: &mut crate::tokio::Command) -> &mut crate::tokio::Command {
    #[cfg(target_os = "linux")]
    return cmd.contain_with(crate::ContainMode::Session);
    #[cfg(not(target_os = "linux"))]
    cmd.contain()
}

/// The `expect` message of a test that needs a spawned child's identity, which a spawn reads for every
/// child a test makes (only a refused read leaves a child without one).
pub(crate) const IDENTITY_READ: &str = "the spawn read the child's identity";

/// A spawned, contained [`BLOCKER_ARGV`] child and the write end of its stdin. On Windows it has
/// a windowless console of its own, which a `CTRL_BREAK` from this process cannot reach: a test
/// of the graceful signals takes [`held_contained_blocker_on_console`].
pub(crate) fn held_contained_blocker(stdout: crate::Stdio) -> (crate::Child, crate::PipeWriter) {
    held_blocker(stdout, Console::Hidden, |cmd| _ = cmd.contain())
}

/// [`held_contained_blocker`] on this process's console, for a test of the graceful signals.
pub(crate) fn held_contained_blocker_on_console(stdout: crate::Stdio) -> (crate::Child, crate::PipeWriter) {
    held_blocker(stdout, Console::Asked, |cmd| _ = cmd.contain())
}

/// A live [`held_contained_blocker`] with a null stdout and its identity.
#[cfg(windows)]
pub(crate) fn live_blocker() -> (crate::Child, crate::PipeWriter, crate::identity::ProcessId) {
    let (child, stdin) = held_contained_blocker(crate::Stdio::null());
    let id = child.id().expect(IDENTITY_READ);
    (child, stdin, id)
}

/// `cmd /C more`, blocked reading its own piped stdin until EOF: a blocker every Windows host has.
#[cfg(windows)]
fn spawn_more_blocker() -> std::process::Child {
    crate::test_spawn::spawn(
        std::process::Command::new("cmd")
            .args(["/C", "more"])
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null()),
    )
    .expect("spawn cmd /C more")
}

/// A live job with one still-running member: [`spawn_more_blocker`], assigned to a new job.
#[cfg(windows)]
pub(crate) fn spawn_job_member() -> (std::process::Child, crate::containment::windows::JobHandle) {
    use std::os::windows::io::AsRawHandle as _;

    let child = spawn_more_blocker();
    let job = crate::containment::windows::assign_to_kill_on_close_job(child.as_raw_handle()).expect("assign to job");
    (child, job)
}

/// End a [`spawn_job_member`]'s member: EOF on its stdin, and reaped once it has exited.
#[cfg(windows)]
pub(crate) fn let_member_exit(mut child: std::process::Child) {
    drop(child.stdin.take());
    child.wait().expect("wait for cmd /C more to exit");
}

/// [`held_contained_blocker`], contained by [`contain_without_cgroup`].
#[cfg(unix)]
pub(crate) fn held_contained_blocker_without_cgroup(stdout: crate::Stdio) -> (crate::Child, crate::PipeWriter) {
    held_blocker(stdout, Console::Hidden, |cmd| _ = contain_without_cgroup(cmd))
}

/// A spawned [`ContainMode::TreeWalk`](crate::ContainMode::TreeWalk) [`BLOCKER_ARGV`] child with a
/// null stdout, and the write end of its stdin.
#[cfg(target_os = "linux")]
pub(crate) fn held_treewalk_blocker() -> (crate::Child, crate::PipeWriter) {
    held_blocker(crate::Stdio::null(), Console::Hidden, |cmd| {
        cmd.contain_with(crate::ContainMode::TreeWalk);
    })
}

/// [`held_treewalk_blocker`] whose next walk on this thread is forced to leave `left` behind.
#[cfg(target_os = "linux")]
pub(crate) fn held_treewalk_blocker_leaving(
    left: crate::containment::treewalk::fault::LeftBehind,
) -> (crate::Child, crate::PipeWriter) {
    let blocker = held_treewalk_blocker();
    crate::containment::treewalk::fault::force_incomplete_once(left);
    blocker
}

/// A live [`BLOCKER_ARGV`] child with no containment, and the write end of its stdin, which the
/// test holds. `kill_on_drop` is the command's.
pub(crate) fn held_uncontained_blocker(kill_on_drop: bool) -> (crate::Child, crate::PipeWriter) {
    let (stdin, writer) = held_writer_stdin();
    let mut cmd = command(Console::Hidden);
    cmd.args(BLOCKER_ARGV.iter().copied());
    cmd.stdin(stdin).expect("set stdin");
    cmd.kill_on_drop(kill_on_drop);
    (cmd.spawn().expect("spawn"), writer)
}

/// The child a teardown handed back, if it did, and what lets it exit (`release`: the stdin's write
/// end, a thread to resume). `release` drops first, so a failed assertion ends the test instead of
/// hanging in the [`Unreaped`](crate::Unreaped)'s drop. [`tear_down_holding`] builds it from a teardown;
/// [`expect_may_have_started_parts`] and [`expect_handed_back`] from a failure. Only this module
/// builds one, so no row settles an `Unreaped` by hand.
pub(crate) struct HandedBack<R> {
    release: R,
    unreaped: Option<crate::Unreaped>,
}

impl<R> HandedBack<R> {
    fn new(release: R, unreaped: Option<crate::Unreaped>) -> HandedBack<R> {
        HandedBack { release, unreaped }
    }

    pub(crate) fn is_none(&self) -> bool {
        self.unreaped.is_none()
    }

    /// The handed-back child; panics when the teardown handed none back.
    #[track_caller]
    pub(crate) fn unreaped(&self) -> &crate::Unreaped {
        self.unreaped.as_ref().expect("the teardown handed the child back")
    }

    /// Release the child and wait for it to exit.
    #[track_caller]
    pub(crate) fn wait(self) -> std::process::ExitStatus {
        let HandedBack { release, unreaped } = self;
        drop(release);
        unreaped
            .expect("the teardown handed the child back")
            .wait()
            .expect("the handed-back child exits once released")
    }
}

/// [`Child::tear_down_or_hand_back`](crate::Child::tear_down_or_hand_back) with `disposition`, the
/// only way a test calls it: `release` moves into the [`HandedBack`] with the result, so no
/// assertion runs while an [`Unreaped`](crate::Unreaped) is live and its releaser is a separate
/// local that drops after it.
pub(crate) fn tear_down_holding<R>(
    child: crate::Child,
    release: R,
    disposition: crate::child::owned::teardown::Disposition,
) -> (crate::error::ChildFate, HandedBack<R>) {
    let (fate, _, handed_back) = tear_down_holding_failures(child, release, disposition);
    (fate, handed_back)
}

/// [`tear_down_holding`], and the failures of the teardown too (the `cleanup` of a failed run's error).
pub(crate) fn tear_down_holding_failures<R>(
    child: crate::Child,
    release: R,
    disposition: crate::child::owned::teardown::Disposition,
) -> (crate::error::ChildFate, Option<crate::error::Failures>, HandedBack<R>) {
    let crate::child::drop_teardown::Torn {
        fate,
        unreaped,
        cleanup,
    } = child.tear_down_or_hand_back(disposition);
    (fate, cleanup, HandedBack::new(release, unreaped))
}

/// The cause, fate and [`HandedBack`] child (none if the spawn handed none back) inside an error a
/// public spawn returned, which must say the program may have started. `release` is what lets the
/// child exit (`()`: nothing), moved into the result as for [`tear_down_holding`].
#[track_caller]
pub(crate) fn expect_may_have_started_parts<R>(
    error: crate::error::Error,
    release: R,
) -> (crate::error::Error, crate::error::ChildFate, HandedBack<R>) {
    let (cause, fate, unreaped) = crate::child::spawn::failure::error_parts(error);
    (cause, fate, HandedBack::new(release, unreaped))
}

#[cfg(unix)]
#[track_caller]
pub(crate) fn cleanup_of(error: &crate::error::Error) -> crate::error::Failures {
    let crate::error::Error::MayHaveStarted { cleanup, .. } = error else {
        panic!("expected MayHaveStarted, got {error:?}");
    };
    cleanup
        .clone()
        .unwrap_or_else(|| panic!("the teardown's failures are in the cleanup: {error:?}"))
}

/// What the failed spawn did with its child, beyond the fate: the `detail` of the `MayHaveStarted`
/// `error`, which must have one.
#[cfg(unix)]
#[track_caller]
pub(crate) fn detail_of(error: &crate::error::Error) -> String {
    let crate::error::Error::MayHaveStarted { detail, .. } = error else {
        panic!("expected MayHaveStarted, got {error:?}");
    };
    detail
        .clone()
        .unwrap_or_else(|| panic!("the spawn says what it did with its child: {error:?}"))
}

/// [`expect_may_have_started_parts`] for an error that must hand the child back.
#[cfg(unix)]
#[track_caller]
pub(crate) fn expect_handed_back<R>(
    error: crate::error::Error,
    release: R,
) -> (crate::error::Error, crate::error::ChildFate, HandedBack<R>) {
    let (cause, fate, handed_back) = expect_may_have_started_parts(error, release);
    assert!(
        !handed_back.is_none(),
        "the spawn handed no child back ({fate:?}): {cause:?}"
    );
    (cause, fate, handed_back)
}

/// `tear_down_held` (the sync spawn's teardown of the child it holds after the handshake) with the
/// diagnosis `why`, its handed-back child in a [`HandedBack`] with `release`. The child has a pid.
/// The first answer is what the teardown did with a front, the `detail` of the spawn's error.
#[cfg(target_os = "linux")]
pub(crate) fn tear_down_held_holding<R>(
    child: crate::child::owned::OwnedChild,
    front: Option<crate::elevation::front::Front>,
    id: Option<crate::identity::ProcessId>,
    subtree: Option<&crate::containment::cgroup::Subtree>,
    why: &mut crate::child::spawn::Diagnosis,
    release: R,
) -> (Option<String>, crate::error::ChildFate, HandedBack<R>) {
    let how = crate::child::spawn::held_teardown::HeldTeardown {
        front,
        id,
        subtree,
        disposition: crate::child::owned::teardown::Disposition::HandBack,
        policy: crate::child::spawn::policy::SpawnPolicy::SYNC,
    };
    let (detail, torn) = crate::child::spawn::held_teardown::tear_down_held(child, how, why);
    (detail, torn.fate, HandedBack::new(release, torn.unreaped))
}

#[cfg(unix)]
impl crate::child::spawn::SpawnFailure {
    /// [`expect_may_have_started_parts`] for a failure the spawn did not turn into an error yet.
    #[track_caller]
    pub(crate) fn expect_may_have_started_parts<R>(
        self,
        release: R,
    ) -> (crate::error::Error, crate::error::ChildFate, HandedBack<R>) {
        let (cause, fate, unreaped) = self.parts();
        (cause, fate, HandedBack::new(release, unreaped))
    }
}

fn held_blocker(
    stdout: crate::Stdio,
    console: Console,
    contain: impl FnOnce(&mut crate::Command),
) -> (crate::Child, crate::PipeWriter) {
    let mut cmd = command(console);
    cmd.args(BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(stdout).expect("set stdout");
    contain(&mut cmd);
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    (child, stdin)
}

/// Async twin of [`held_contained_blocker`].
#[cfg(all(unix, feature = "tokio"))]
pub(crate) async fn held_contained_blocker_async(
    stdout: crate::Stdio,
) -> (crate::tokio::Child, crate::tokio::ChildStdin) {
    held_blocker_async(stdout, Console::Hidden, |cmd| _ = cmd.contain()).await
}

/// Async twin of [`held_contained_blocker_on_console`].
#[cfg(feature = "tokio")]
pub(crate) async fn held_contained_blocker_on_console_async(
    stdout: crate::Stdio,
) -> (crate::tokio::Child, crate::tokio::ChildStdin) {
    held_blocker_async(stdout, Console::Asked, |cmd| _ = cmd.contain()).await
}

/// Async twin of [`held_contained_blocker_without_cgroup`].
#[cfg(all(unix, feature = "tokio"))]
pub(crate) async fn held_contained_blocker_without_cgroup_async(
    stdout: crate::Stdio,
) -> (crate::tokio::Child, crate::tokio::ChildStdin) {
    held_blocker_async(stdout, Console::Hidden, |cmd| _ = contain_without_cgroup_async(cmd)).await
}

#[cfg(feature = "tokio")]
pub(crate) async fn held_blocker_async(
    stdout: crate::Stdio,
    console: Console,
    contain: impl FnOnce(&mut crate::tokio::Command),
) -> (crate::tokio::Child, crate::tokio::ChildStdin) {
    let mut cmd = tokio_command(console);
    cmd.args(BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(stdout).expect("set stdout");
    contain(&mut cmd);
    let mut child = cmd.spawn().await.expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    (child, stdin)
}

/// A process-group member that announces its own pid on a piped stdout and then blocks on a
/// piped stdin. `pgid` is the group to join (`0` mints a new one of the member's own). The
/// caller must take [`await_member_ready`] before using the member's identity: `spawn()`
/// returning establishes neither that the image is running nor that its `setpgid` is visible.
///
/// `std::process::Child::wait()` closes the piped stdin before it waits, so `wait()` itself ends
/// the member by EOF on its `read` (non-zero exit, no signal). An assertion that a real signal
/// was the cause must check the status's `.signal()` and deliver the signal BEFORE `wait()`.
#[cfg(unix)]
pub(crate) fn member_command(pgid: i32) -> std::process::Command {
    use std::os::unix::process::CommandExt;
    let mut cmd = std::process::Command::new("/bin/sh");
    cmd.arg("-c")
        .arg("echo $$; read _ignored")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .process_group(pgid);
    cmd
}

/// Blocks until a [`member_command`] child has announced itself, and checks that the
/// announcement came from that child.
#[cfg(unix)]
pub(crate) fn await_member_ready(child: &mut std::process::Child) {
    use std::io::BufRead;
    let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
    let mut line = String::new();
    out.read_line(&mut line).expect("read the member's announcement");
    let announced: crate::identity::RawPid = line.trim().parse().expect("the announcement carries a pid");
    assert_eq!(
        announced,
        child.id(),
        "the announcement must come from the member itself"
    );
    // Hand the pipe back rather than dropping it: the member outlives this call, and closing
    // the read end under a live child would make any later write to it a `SIGPIPE`.
    child.stdout = Some(out.into_inner());
}

/// A [`member_command`] in its own group that exits `0` at EOF (the plain member's `read` fails
/// there, so the script would exit `1`): an unsignalled member ends by a clean exit, which a
/// signal cannot fake.
#[cfg(unix)]
pub(crate) fn exiting_member_command() -> std::process::Command {
    let mut cmd = std::process::Command::new("/bin/sh");
    cmd.arg("-c")
        .arg("echo $$; read _ignored; exit 0")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped());
    cmd
}

/// An open handle on the live process `id` names. Open it before arming a fault: opening may
/// read what the fault forces.
pub(crate) fn open_live(id: crate::identity::ProcessId) -> crate::Process {
    crate::Process::open(id)
        .expect("open the live process")
        .expect("the live process is not gone")
}

/// A live [`exiting_member_command`] child that has announced itself, and its identity.
#[cfg(unix)]
pub(crate) fn live_exiting_member() -> (std::process::Child, crate::identity::ProcessId) {
    let mut child = crate::test_spawn::spawn(&mut exiting_member_command()).expect("spawn the member");
    await_member_ready(&mut child);
    let id = crate::identity::ProcessId::of(child.id())
        .found()
        .expect("the live member resolves");
    (child, id)
}

/// End a [`live_exiting_member`] by EOF and assert it was never signalled: only a clean exit
/// proves no `SIGKILL`/`SIGTERM` arrived, which a `try_wait` straight after a signal cannot.
#[cfg(unix)]
pub(crate) fn release_unsignalled(mut child: std::process::Child) {
    use std::os::unix::process::ExitStatusExt;
    drop(child.stdin.take());
    let status = child.wait().expect("reap the member");
    assert_eq!(status.signal(), None, "the member must not have been signalled");
    assert_eq!(status.code(), Some(0), "the member must exit by itself");
}

/// `pid`'s `stat` as the kernel gives it now, except for the start time: what the pid's new owner
/// would show.
#[cfg(target_os = "linux")]
pub(crate) fn stat_of_a_new_owner(pid: u32) -> Vec<u8> {
    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).expect("the live pid's stat");
    let (head, tail) = stat.rsplit_once(')').expect("stat names its command in parentheses");
    let mut fields: Vec<String> = tail.split_whitespace().map(str::to_owned).collect();
    // `tail` starts at field 3, the state; the start time is field 22.
    let start: u64 = fields[19].parse().expect("the start time");
    fields[19] = (start + 1).to_string();
    format!("{head}) {}\n", fields.join(" ")).into_bytes()
}

/// A live [`BLOCKER_ARGV`] (`findstr`) child with piped stdin and stdout, and its identity.
#[cfg(windows)]
pub(crate) fn live_findstr_blocker() -> (std::process::Child, crate::identity::ProcessId) {
    let child =
        crate::test_spawn::spawn(&mut held_std_blocker(std::process::Stdio::piped())).expect("spawn the blocker");
    let id = crate::identity::ProcessId::of(child.id())
        .found()
        .expect("the live blocker resolves");
    (child, id)
}

/// Finish a [`live_findstr_blocker`] and assert it was never terminated: fed a matching line and
/// EOF it exits `0` and echoes the match, and `TerminateProcess` gives neither.
#[cfg(windows)]
pub(crate) fn release_findstr_unterminated(mut child: std::process::Child) {
    use std::io::{Read as _, Write as _};
    let mut stdin = child.stdin.take().expect("piped stdin");
    stdin.write_all(b"x\r\n").expect("write to the blocker");
    drop(stdin);
    let mut output = Vec::new();
    child
        .stdout
        .take()
        .expect("piped stdout")
        .read_to_end(&mut output)
        .expect("read stdout to EOF");
    let status = child.wait().expect("reap the blocker");
    assert!(status.success(), "the blocker must exit by itself, got {status:?}");
    assert!(
        output.contains(&b'x'),
        "the blocker must echo its match, got {output:?}"
    );
}

/// Proves a `cat` blocker is alive and responsive: writes a byte to its stdin and reads it back
/// from its stdout. A killed-but-unreaped `cat` cannot echo.
#[cfg(unix)]
pub(crate) fn assert_echoes(stdin: &mut impl std::io::Write, stdout: &mut impl std::io::Read) {
    stdin.write_all(b"x").expect("write to the blocker");
    let mut echo = [0u8; 1];
    stdout
        .read_exact(&mut echo)
        .expect("the blocker must still be alive to echo");
    assert_eq!(&echo, b"x");
}

/// Block until `pid` has exited without reaping it: a zombie, which still pins its group number.
#[cfg(unix)]
pub(crate) fn wait_until_zombie(pid: u32) {
    let _ = zombie_record(pid);
}

/// [`wait_until_zombie`], then assert it was ended by `SIGKILL` and did not exit on its own once
/// its stdin closed. The zombie stays unreaped.
#[cfg(unix)]
pub(crate) fn assert_zombie_sigkilled(who: &str, pid: u32) {
    let info = zombie_record(pid);
    #[cfg(target_os = "linux")]
    // SAFETY: `waitid` returned a `SIGCHLD` record, whose status field is set.
    let status = unsafe { info.si_status() };
    #[cfg(target_os = "macos")]
    let status = info.si_status;
    assert_eq!(
        (info.si_code, status),
        (libc::CLD_KILLED, libc::SIGKILL),
        "{who} must be SIGKILLed, not exit on its own"
    );
}

#[cfg(unix)]
fn zombie_record(pid: u32) -> libc::siginfo_t {
    loop {
        let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
        // SAFETY: `info` is a valid out-parameter. WNOWAIT leaves the child reapable.
        let rc = unsafe { libc::waitid(libc::P_PID, pid as libc::id_t, &mut info, libc::WEXITED | libc::WNOWAIT) };
        if rc == 0 {
            return info;
        }
        // A signal interrupting the wait is a restart, not a failure.
        let e = std::io::Error::last_os_error();
        assert_eq!(e.raw_os_error(), Some(libc::EINTR), "waitid: {e}");
    }
}

/// Whether `pid` is still this process's unreaped child (running, or a zombie nobody collected):
/// `waitid` with `WNOHANG | WNOWAIT` consumes nothing. `false` once something reaped it.
#[cfg(target_os = "macos")]
pub(crate) fn is_unreaped_child(pid: u32) -> bool {
    let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
    // SAFETY: `info` is a valid out-parameter. WNOWAIT leaves the child reapable, WNOHANG never blocks.
    let rc = unsafe {
        libc::waitid(
            libc::P_PID,
            pid as libc::id_t,
            &mut info,
            libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
        )
    };
    if rc == 0 {
        return true;
    }
    let e = std::io::Error::last_os_error();
    assert_eq!(e.raw_os_error(), Some(libc::ECHILD), "waitid: {e}");
    false
}

/// Writes `bytes` to a held blocker stdin whose reader may already be dead: `Ok` and
/// `BrokenPipe` (the kill under test already landed, so the write goes nowhere) are both
/// expected; any other error is a fixture fault and panics.
pub(crate) fn write_to_possibly_dead_stdin(stdin: &mut impl std::io::Write, bytes: &[u8]) {
    match stdin.write_all(bytes) {
        Ok(()) => {}
        Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {}
        Err(e) => panic!("writing to the held stdin failed for a reason other than a dead reader: {e}"),
    }
}

#[cfg(test)]
mod write_to_possibly_dead_stdin_tests {
    use super::write_to_possibly_dead_stdin;

    struct FailsWith(std::io::ErrorKind);
    impl std::io::Write for FailsWith {
        fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
            Err(self.0.into())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    #[skuld::test]
    fn a_dead_reader_is_expected() {
        write_to_possibly_dead_stdin(&mut FailsWith(std::io::ErrorKind::BrokenPipe), b"x");
    }

    #[skuld::test]
    fn a_live_reader_is_expected() {
        write_to_possibly_dead_stdin(&mut Vec::new(), b"x");
    }

    #[skuld::test]
    #[should_panic(expected = "other than a dead reader")]
    fn any_other_error_panics() {
        write_to_possibly_dead_stdin(&mut FailsWith(std::io::ErrorKind::PermissionDenied), b"x");
    }
}

// Re-exec fixtures =====

#[cfg(unix)]
#[cfg_attr(
    not(target_os = "macos"),
    allow(dead_code, unused_imports, reason = "only the macOS tracer fixtures use it so far")
)]
mod bounded;
#[cfg(unix)]
#[cfg_attr(
    not(target_os = "macos"),
    allow(unused_imports, reason = "only the macOS tracer fixtures use it so far")
)]
pub(crate) use bounded::{run_fixture_output_within, step, watchdog};
#[cfg(unix)]
mod scratch;
#[cfg(unix)]
pub(crate) use scratch::fixture_scratch_tempdir;
#[cfg(unix)]
mod db_dir;
#[cfg(unix)]
pub(crate) use db_dir::FixtureDirs;

/// The accept handshake shared with `tests/common/accept.rs` and the testbin.
#[path = "../testbin/ack.rs"]
pub(crate) mod ack;

/// The ack, event precedence and drain outcome shared with `tests/common/accept.rs`.
#[path = "../tests/common/accept/shared.rs"]
pub(crate) mod shared;

/// Blocks until either `listener` gets a connection, or `target` exits first, never a bare,
/// hang-forever `accept()`. The `src/` twin of `tests/common/accept.rs`'s `accept_or_die` (a
/// separate compilation unit), built on the crate's own identity-verified exit-watch primitives
/// (`crate::os_process::linux::open::open_verified_with`, and `arm_proc_exit`). The
/// `target` identity is verified when the watch is armed, so a reissued pid is reported as the
/// target being gone, never watched.
///
/// One thread, one wait: each platform's own multiplexer (`poll`, `kqueue`,
/// `WaitForMultipleObjects`) blocks on "the listener is readable" OR "the target exited", and this
/// thread is the only one that ever calls `listener.accept()`.
///
/// A connection is accepted and acked ([`ack`]); the fixture waits for the ack after connecting
/// when [`ack::ACK_ENV`] is set in its environment, so it cannot exit between `connect()` and the
/// accept. An exit before the accept is therefore a failure, decided without consulting the
/// accept queue.
pub(crate) fn accept_or_die(
    listener: &std::net::TcpListener,
    target: crate::identity::ProcessId,
) -> std::net::TcpStream {
    #[cfg(target_os = "linux")]
    let event = watch_linux(listener, target);
    #[cfg(target_os = "macos")]
    let event = watch_macos(listener, target);
    #[cfg(windows)]
    let event = watch_windows(listener, target);
    match event {
        WatchEvent::Connection => shared::accept_and_ack(listener),
        WatchEvent::Died => panic!("the control target (pid {}) died before it connected", target.pid()),
    }
}

/// What ended the wait.
enum WatchEvent {
    Connection,
    Died,
}

/// Wakes [`accept_or_signalled`] when a tree's drain wait ends; see [`shared::DrainOutcome`].
#[cfg(windows)]
pub(crate) struct DrainSignal {
    event: std::os::windows::io::OwnedHandle,
    outcome: shared::DrainOutcome,
}

#[cfg(windows)]
impl DrainSignal {
    pub(crate) fn new() -> Self {
        Self {
            event: crate::os_process::windows::test_event::new_test_event().expect("create the drain event"),
            outcome: shared::DrainOutcome::default(),
        }
    }

    /// Whether the drain has been signalled, by a zero-timeout wait: it never blocks.
    pub(crate) fn is_signalled(&self) -> bool {
        use std::os::windows::io::AsRawHandle as _;

        use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
        use windows::Win32::System::Threading::WaitForSingleObject;
        // SAFETY: the event handle is live and owned by `self`.
        unsafe { WaitForSingleObject(HANDLE(self.event.as_raw_handle()), 0) == WAIT_OBJECT_0 }
    }

    /// Records the result of `wait_tree` and wakes the acceptor.
    pub(crate) fn record<T: std::fmt::Debug, E: std::fmt::Display>(&self, result: Result<T, E>) {
        self.outcome.store(result);
        crate::os_process::windows::test_event::signal_test_event(&self.event);
    }

    /// Runs `wait` (a `wait_tree`) and records its result; a `wait` that panics records an error.
    pub(crate) fn watch<T: std::fmt::Debug, E: std::fmt::Display>(&self, wait: impl FnOnce() -> Result<T, E>) {
        shared::run_watcher(
            &self.outcome,
            || crate::os_process::windows::test_event::signal_test_event(&self.event),
            wait,
        );
    }
}

/// Windows: accepts and acks a connection, or fails once `drained` is signalled. For a target
/// expected to exit at once while a descendant in the job connects, so its pid cannot be watched:
/// the job draining is the death of every possible connector. A watcher thread records
/// `wait_tree`'s result into `drained`; only this thread accepts. The connector waits for the
/// ack, so a drain with nothing accepted is a failure.
#[cfg(windows)]
pub(crate) fn accept_or_signalled(listener: &std::net::TcpListener, drained: &DrainSignal) -> std::net::TcpStream {
    use std::os::windows::io::{AsRawHandle, AsRawSocket};

    use windows::Win32::Foundation::{HANDLE, WAIT_FAILED, WAIT_OBJECT_0};
    use windows::Win32::Networking::WinSock::{WSAEventSelect, FD_ACCEPT, SOCKET, WSAEVENT};
    use windows::Win32::System::Threading::{WaitForMultipleObjects, INFINITE};

    let accept_event = crate::os_process::windows::test_event::new_test_event()
        .expect("create an event for the listener's accept-readiness watch");
    let sock = SOCKET(listener.as_raw_socket() as usize);
    // SAFETY: `sock` is the listener's own live socket; the event is a live, owned handle.
    let rc = unsafe {
        WSAEventSelect(
            sock,
            Some(WSAEVENT(accept_event.as_raw_handle() as _)),
            FD_ACCEPT as i32,
        )
    };
    assert_eq!(
        rc,
        0,
        "WSAEventSelect(FD_ACCEPT) on the control listener: {}",
        std::io::Error::last_os_error()
    );
    // The drain is listed first: the lowest signalled index wins.
    let handles = [
        HANDLE(drained.event.as_raw_handle()),
        HANDLE(accept_event.as_raw_handle()),
    ];
    // SAFETY: both handles are live and owned for the call's duration.
    let woken = unsafe { WaitForMultipleObjects(&handles, false, INFINITE) };
    let wait_error = std::io::Error::last_os_error();
    // SAFETY: `sock` is still the listener's own live socket.
    let cancel_rc = unsafe { WSAEventSelect(sock, None, 0) };
    assert_eq!(
        cancel_rc,
        0,
        "WSAEventSelect(0) to cancel the accept-readiness association: {}",
        std::io::Error::last_os_error()
    );
    // Cancelling alone does not reliably leave the socket blocking.
    listener
        .set_nonblocking(false)
        .expect("restore the control listener to blocking mode");
    assert_ne!(
        woken, WAIT_FAILED,
        "WaitForMultipleObjects while waiting for a control connection: {wait_error}"
    );
    let drain = woken == WAIT_OBJECT_0;
    let connection = woken.0 == WAIT_OBJECT_0.0 + 1;
    assert!(
        drain || connection,
        "WaitForMultipleObjects returned {woken:?} for two handles"
    );
    match shared::first_ready(drain, connection) {
        Some(shared::Ready::Exit) => drained.outcome.fail("tree"),
        Some(shared::Ready::Source) => shared::accept_and_ack(listener),
        None => unreachable!("one of the two handles signalled"),
    }
}

/// Linux: a pidfd (via the crate's own [`crate::os_process::linux::open::open_verified_with`]) polled alongside
/// the listener's fd in ONE `poll()` call.
#[cfg(target_os = "linux")]
fn watch_linux(listener: &std::net::TcpListener, target: crate::identity::ProcessId) -> WatchEvent {
    use std::os::fd::AsFd;

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

    let Some(pidfd) = crate::os_process::linux::open::open_verified_with(&crate::identity::HostKernel, target)
        .expect("open a pidfd to watch the target")
    else {
        return WatchEvent::Died;
    };
    let listener_fd = listener.as_fd();
    let mut fds = [
        PollFd::new(&pidfd, PollFlags::IN),
        PollFd::new(&listener_fd, PollFlags::IN),
    ];
    loop {
        if let Err(e) = crate::wait::poll_ready(&mut fds) {
            panic!(
                "poll while waiting for a control connection: {}",
                std::io::Error::from(e)
            );
        }
        let (pidfd_revents, listener_revents) = (fds[0].revents(), fds[1].revents());
        // POLLNVAL would mean this function handed poll() a bad fd. It returns at once and never
        // clears, so ignoring it spins forever: a violation fails in every build.
        assert!(
            !pidfd_revents.contains(PollFlags::NVAL),
            "the pidfd went invalid mid-wait"
        );
        assert!(
            !listener_revents.contains(PollFlags::NVAL),
            "the control listener's fd went invalid mid-wait"
        );
        if listener_revents.contains(PollFlags::ERR) || listener_revents.contains(PollFlags::HUP) {
            panic!("the control listener reported an error while waiting for a connection: {listener_revents:?}");
        }
        if pidfd_revents.contains(PollFlags::ERR) {
            panic!("pidfd poll returned POLLERR while watching pid {}", target.pid());
        }
        match shared::first_ready(
            pidfd_revents.contains(PollFlags::IN),
            listener_revents.contains(PollFlags::IN),
        ) {
            Some(shared::Ready::Exit) => return WatchEvent::Died,
            Some(shared::Ready::Source) => return WatchEvent::Connection,
            None => {}
        }
    }
}

/// macOS: [`crate::os_process::macos::kqueue::arm_proc_exit`]'s kqueue, with the listener's
/// readability watched on the same queue.
#[cfg(target_os = "macos")]
fn watch_macos(listener: &std::net::TcpListener, target: crate::identity::ProcessId) -> WatchEvent {
    use std::os::fd::AsRawFd;

    use nix::sys::event::{EvFlags, EventFilter, FilterFlag, KEvent};

    use crate::os_process::macos::kqueue::{Event, Subscription};

    let Some(kq) =
        crate::os_process::macos::kqueue::arm_proc_exit(target).expect("arm a kqueue exit-watch for the target")
    else {
        return WatchEvent::Died;
    };
    let listener = Subscription::Readable {
        fd: listener.as_raw_fd(),
        low_water: 1,
    };
    kq.subscribe(listener).expect("watch the control listener");

    let placeholder = KEvent::new(0, EventFilter::EVFILT_PROC, EvFlags::empty(), FilterFlag::empty(), 0, 0);
    let mut events = [placeholder; 2];
    loop {
        // Retries the wait on `EINTR` (see `kevent_eintr`).
        let n = match kq.native().kevent(&[], &mut events, None) {
            Ok(n) => n,
            Err(nix::errno::Errno::EINTR) => {
                kevent_eintr::count_retry();
                continue;
            }
            Err(e) => panic!("kevent while waiting for a control connection: {e}"),
        };
        let read: Vec<Event> = events[..n].iter().filter_map(Event::from_kevent).collect();
        let exited = read.iter().any(|ev| matches!(ev, Event::Process { .. }));
        let connection = read.iter().any(|ev| matches!(ev, Event::Readable { .. }));
        match shared::first_ready(exited, connection) {
            Some(shared::Ready::Exit) => return WatchEvent::Died,
            Some(shared::Ready::Source) => return WatchEvent::Connection,
            None => {}
        }
    }
}

/// Windows: the crate's own identity-verified [`crate::os_process::windows::open_verified`] process
/// handle and the listener's `FD_ACCEPT` event (via `WSAEventSelect`) in one explicit
/// `WaitForMultipleObjects`.
#[cfg(windows)]
fn watch_windows(listener: &std::net::TcpListener, target: crate::identity::ProcessId) -> WatchEvent {
    use std::os::windows::io::{AsRawHandle, AsRawSocket, FromRawHandle, OwnedHandle};

    use windows::Win32::Foundation::{HANDLE, WAIT_FAILED, WAIT_OBJECT_0};
    use windows::Win32::Networking::WinSock::{WSAEventSelect, FD_ACCEPT, SOCKET, WSAEVENT};
    use windows::Win32::System::Threading::{WaitForMultipleObjects, INFINITE};

    let Some((process, _granted)) =
        crate::os_process::windows::open_verified(target).expect("open a handle to watch the target")
    else {
        return WatchEvent::Died;
    };
    // SAFETY: `open_verified` returns a handle the caller owns; this wraps it so it is closed.
    let process = unsafe { OwnedHandle::from_raw_handle(process.0 as _) };
    let accept_event = crate::os_process::windows::test_event::new_test_event()
        .expect("create an event for the listener's accept-readiness watch");
    let sock = SOCKET(listener.as_raw_socket() as usize);
    let wsa_event = WSAEVENT(accept_event.as_raw_handle() as _);
    // SAFETY: `sock` is the listener's own live socket; `wsa_event` wraps `accept_event`, a live,
    // owned event handle for the call's duration.
    let rc = unsafe { WSAEventSelect(sock, Some(wsa_event), FD_ACCEPT as i32) };
    assert_eq!(
        rc,
        0,
        "WSAEventSelect(FD_ACCEPT) on the control listener: {}",
        std::io::Error::last_os_error()
    );

    // The process is listed first: the lowest signalled index wins, so an exit beats a connection.
    let handles = [HANDLE(process.as_raw_handle()), HANDLE(accept_event.as_raw_handle())];
    // SAFETY: both handles are live and owned for the call's duration.
    let woken = unsafe { WaitForMultipleObjects(&handles, false, INFINITE) };
    let wait_error = std::io::Error::last_os_error();

    // Cancel the association, then restore blocking mode explicitly: cancelling alone does not
    // reliably leave the socket blocking.
    // SAFETY: `sock` is still the listener's own live socket.
    let cancel_rc = unsafe { WSAEventSelect(sock, None, 0) };
    assert_eq!(
        cancel_rc,
        0,
        "WSAEventSelect(0) to cancel the accept-readiness association: {}",
        std::io::Error::last_os_error()
    );
    listener
        .set_nonblocking(false)
        .expect("restore the control listener to blocking mode");

    assert_ne!(
        woken, WAIT_FAILED,
        "WaitForMultipleObjects while waiting for a control connection: {wait_error}"
    );
    let exited = woken == WAIT_OBJECT_0;
    let connection = woken.0 == WAIT_OBJECT_0.0 + 1;
    assert!(
        exited || connection,
        "WaitForMultipleObjects returned {woken:?} for two handles"
    );
    match shared::first_ready(exited, connection) {
        Some(shared::Ready::Exit) => WatchEvent::Died,
        _ => WatchEvent::Connection,
    }
}

/// Runs the libtest fixture at fully-qualified path `fixture` (e.g.
/// `"resolve::resolve_tests::fixture_foo"`) in a FRESH re-exec of this test binary whose OS-level
/// cwd is `cwd`. This proves what the fixture's body proves about a process's real cwd without
/// mutating this shared, multithreaded binary's own cwd. `Command::current_dir` sets the child's
/// cwd before its `exec`/`CreateProcessW`.
///
/// `marker_env` is set to `cwd` in the child only. The fixture uses it to tell a deliberate
/// re-exec from an ordinary suite run, where it must no-op, and to assert its own
/// `current_dir()` against the value, so a dropped `.current_dir(cwd)` is caught (see
/// [`expected_cwd`]).
///
/// Spawns under `spawn_lock()`, like every raw `std::process::Command` re-exec of this binary (see
/// [`spawn_a_process_that_exits`]).
///
/// Panics with the child's captured output on a non-zero exit, or when its suite events do not
/// show exactly one test ran and passed: `--exact <fixture>` naming no test matches ZERO tests and
/// still exits 0. Build `fixture` with [`fixture_path!`] so a stale name is a compile error; the
/// event check backstops the rest.
pub(crate) fn run_fixture_with_cwd(fixture: &str, cwd: &std::path::Path, marker_env: &str) {
    let mut cmd = fixture_command(fixture);
    cmd.env(marker_env, cwd).current_dir(cwd);
    run_fixture_command(fixture, cmd);
}

/// Runs the libtest fixture at `fixture` in a FRESH re-exec of this binary that starts without
/// DAC bypass (see [`fixture_command_without_dac_bypass`]), for a fixture whose `EACCES`
/// precondition must hold for a root driver too. Credentials are per-process state, so the drop
/// cannot happen in this shared suite process.
///
/// The fixture gets a scratch directory built here, under this driver's ambient `TMPDIR`, that
/// its post-drop identity can use; it reaches it with [`fixture_scratch_tempdir`]. Loosening the
/// ambient `TMPDIR` instead would widen a directory this crate does not own.
///
/// See [`run_fixture_with_cwd`] for the re-exec, the panic conditions and [`fixture_path!`].
#[cfg(unix)]
pub(crate) fn run_fixture(fixture: &str) {
    let scratch = tempfile::tempdir().expect("tempdir for fixture scratch root");
    let (mut cmd, _dirs) = fixture_command_without_dac_bypass(fixture);
    crate::test_reexec::with_json_events(&mut cmd);

    #[cfg(target_os = "linux")]
    {
        use std::os::unix::process::CommandExt as _;
        // `spawn_lock` spans open-to-spawn: `O_CLOEXEC` only acts at `exec`, and a bare `fork`
        // copies the whole fd table, so no other fork that takes the lock may land in between.
        let guard = crate::child::spawn::spawn_lock();
        let fd = scratch::open_scratch_fd(scratch.path());
        let raw = fd.0;
        cmd.env(scratch::FIXTURE_SCRATCH_FD_ENV, raw.to_string());
        // SAFETY: async-signal-safe `fcntl` in the forked child, clearing close-on-exec on the
        // child's own copy only.
        unsafe {
            cmd.pre_exec(move || {
                // `raw` is the scratch fd, open in this forked child.
                let fd = rustix::fd::BorrowedFd::borrow_raw(raw);
                rustix::io::fcntl_setfd(fd, rustix::io::FdFlags::empty()).map_err(std::io::Error::from)
            });
        }
        #[allow(
            clippy::disallowed_methods,
            reason = "spawn_lock is held by `guard`, taken earlier in this fn"
        )]
        let child = cmd.spawn().expect("spawn fixture child");
        drop(fd);
        drop(guard);
        finish_fixture_command(fixture, child);
    }

    #[cfg(not(target_os = "linux"))]
    {
        // The fixture runs as a different uid when this driver is root: hand it the scratch root.
        if unsafe { libc::geteuid() } == 0 {
            use std::os::unix::ffi::OsStrExt as _;
            let path = std::ffi::CString::new(scratch.path().as_os_str().as_bytes())
                .expect("scratch root path has no interior NUL");
            // SAFETY: `path` is a valid C string naming a directory this function just created.
            let rc = unsafe {
                libc::chown(
                    path.as_ptr(),
                    crate::test_privilege::UNPRIVILEGED,
                    crate::test_privilege::UNPRIVILEGED,
                )
            };
            assert!(
                rc == 0,
                "chown scratch root to the fixture's post-drop identity: {}",
                std::io::Error::last_os_error()
            );
        }
        cmd.env(scratch::FIXTURE_SCRATCH_ROOT_ENV, scratch.path());
        let child = crate::test_spawn::spawn(&mut cmd).expect("spawn fixture child");
        finish_fixture_command(fixture, child);
    }
}

/// [`fixture_command`] whose child drops DAC bypass in `pre_exec` (see
/// [`crate::test_privilege::drop_dac_bypass_before_exec`]), so the fixture is unprivileged from its
/// first instruction and so is everything it spawns.
///
/// Where a root driver changes uid (non-Linux), the fixture re-execs a copy of this binary in a
/// directory the new uid can enter, and the ambient `TMPDIR` must be one it can enter too. The
/// returned [`FixtureDirs`] holds that copy and the fixture's coordination-DB directory
/// (`SKULD_DB_DIR`, see [`db_dir`]): keep it until the fixture has exited.
#[cfg(unix)]
pub(crate) fn fixture_command_without_dac_bypass(fixture: &str) -> (std::process::Command, FixtureDirs) {
    #[cfg(target_os = "linux")]
    let (mut cmd, exe_copy) = (fixture_command(fixture), None);
    #[cfg(not(target_os = "linux"))]
    let (mut cmd, exe_copy) = if unsafe { libc::geteuid() } == 0 {
        scratch::assert_dropped_identity_can_traverse_tmpdir();
        let (dir, exe) = scratch::copy_exe_to_traversable_scratch();
        let mut cmd = crate::test_reexec::command(exe);
        configure_fixture_command(&mut cmd, fixture);
        (cmd, Some(dir))
    } else {
        (fixture_command(fixture), None)
    };
    crate::test_privilege::drop_dac_bypass_before_exec(&mut cmd);
    let db_dir = db_dir::fixture_db_dir();
    cmd.env(db_dir::SKULD_DB_DIR_ENV, db_dir.path());
    (cmd, FixtureDirs::new(exe_copy, db_dir))
}

/// Restores a directory's mode on drop, so a test that locked a tempdir down can still remove it,
/// even after a panic. Declare it after the `TempDir` it guards: locals drop in reverse order, so
/// the restore runs first. (`TempDir::drop` swallows its own removal error and would leak the
/// directory.)
#[cfg(unix)]
pub(crate) struct RestoreMode {
    path: std::path::PathBuf,
    mode: u32,
}

#[cfg(unix)]
impl RestoreMode {
    pub(crate) fn new(path: impl Into<std::path::PathBuf>, mode: u32) -> Self {
        Self {
            path: path.into(),
            mode,
        }
    }
}

#[cfg(unix)]
impl Drop for RestoreMode {
    fn drop(&mut self) {
        use std::os::unix::fs::PermissionsExt as _;
        if let Err(e) = std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(self.mode)) {
            log::warn!(
                "could not restore mode {:o} on {:?}: {}",
                self.mode,
                self.path,
                crate::error::Report(&e)
            );
        }
    }
}

/// The `std::process::Command` common to every fixture re-exec: this binary, filtered to exactly
/// one test, single-threaded, uncaptured by skuld (`--nocapture`) with the stdio piped to the
/// driver, [`FIXTURE_PARENT_PID_ENV`] set (see [`is_fixture_reexec`]).
///
/// The ambient `TMPDIR` is inherited untouched; see [`run_fixture`] for writable scratch after a
/// drop.
///
/// No argv-slot-0 placeholder, unlike [`fixture_argv`]: `std::process::Command` supplies argv[0].
///
/// `pub(crate)` so a launcher with its own stdio needs (`exact_posix_tests.rs` pipes stdin) can
/// start here and override only that.
pub(crate) fn fixture_command(fixture: &str) -> std::process::Command {
    // `/proc/self/exe`: the binary's own directory (e.g. nextest's extraction dir under a `0700`
    // TMPDIR) may be unreachable post-drop; the kernel grants a process its own image regardless.
    #[cfg(target_os = "linux")]
    let program = std::path::PathBuf::from("/proc/self/exe");
    #[cfg(not(target_os = "linux"))]
    let program = std::env::current_exe().expect("current_exe");
    let mut cmd = crate::test_reexec::command(program);
    configure_fixture_command(&mut cmd, fixture);
    cmd
}

/// The argv, env and stdio common to every fixture re-exec, split out for a caller that supplies
/// its own program path.
pub(crate) fn configure_fixture_command(cmd: &mut std::process::Command, fixture: &str) {
    cmd.args(crate::test_reexec::fixture_args(fixture))
        .env(FIXTURE_PARENT_PID_ENV, std::process::id().to_string())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped());
}

/// Set by every fixture re-exec to its parent's pid; see [`is_fixture_reexec`].
const FIXTURE_PARENT_PID_ENV: &str = "COSCA_FIXTURE_PARENT_PID";

/// Whether this process's real parent is the one that re-exec'd it via `run_fixture*`; an
/// inherited marker env var alone does not prove that. On `true`, writes
/// [`FIXTURE_GATE_PASSED_LINE`]; a caller with further checks before its gate is really passed
/// uses [`parent_pid_matches`] and writes the line itself.
#[cfg(unix)]
pub(crate) fn is_fixture_reexec() -> bool {
    let reexec = parent_pid_matches();
    if reexec {
        write_gate_passed();
    }
    reexec
}

/// [`is_fixture_reexec`]'s check, without the write.
#[cfg(unix)]
fn parent_pid_matches() -> bool {
    std::env::var(FIXTURE_PARENT_PID_ENV)
        .ok()
        .and_then(|s| s.parse::<u32>().ok())
        .is_some_and(|pid| pid == std::os::unix::process::parent_id())
}

/// Written to a fixture's stderr once its gate passes; the driver runs the fixture with
/// `--nocapture`, so skuld does not drop it. A gate that returns early exits 0 like a fixture that
/// ran and passed, so [`finish_fixture_command`] requires the line to tell them apart.
pub(crate) const FIXTURE_GATE_PASSED_LINE: &str = "COSCA_FIXTURE_GATE_PASSED";

fn write_gate_passed() {
    use std::io::Write;
    // A failed write is a broken fixture, not a missing line for the driver to guess at.
    writeln!(std::io::stderr(), "{FIXTURE_GATE_PASSED_LINE}").expect("write the gate line to stderr");
}

/// Spawns `cmd` (from [`fixture_command`]) under `spawn_lock()` and waits for it; panics as
/// [`run_fixture_with_cwd`] documents.
pub(crate) fn run_fixture_command(fixture: &str, mut cmd: std::process::Command) {
    crate::test_reexec::with_json_events(&mut cmd);
    let child = crate::test_spawn::spawn(&mut cmd).expect("spawn fixture child");
    finish_fixture_command(fixture, child);
}

/// The post-spawn half of [`run_fixture_command`], for a launcher that spawned under its own lock.
fn finish_fixture_command(fixture: &str, child: std::process::Child) {
    let output = child.wait_with_output().expect("wait for fixture child");
    assert_fixture_passed(fixture, &output);
}

/// Panics unless `output` is that of a fixture that ran and passed exactly one test, and wrote its
/// gate line. For a launcher that waits for the fixture by its own means; the fixture must have run
/// with [`with_json_events`](crate::test_reexec::with_json_events).
pub(crate) fn assert_fixture_passed(fixture: &str, output: &std::process::Output) {
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    if let Err(why) = crate::test_reexec::suite_passed_exactly_one(output) {
        panic!(
            "fixture {fixture} did not run and pass exactly one test: {why}\n--- stdout \
             ---\n{stdout}\n--- stderr ---\n{stderr}"
        );
    }
    assert!(
        stderr.contains(FIXTURE_GATE_PASSED_LINE),
        "fixture {fixture} passed but never wrote {FIXTURE_GATE_PASSED_LINE:?}: its re-exec gate \
         returned early without running its body:\n--- stdout ---\n{stdout}\n--- stderr ---\n{stderr}",
    );
}

/// Whether this process is the fixture re-exec that [`run_fixture_output`] started for `marker_env`:
/// the marker holds the driver's pid, and so does the pid variable every [`fixture_command`] sets.
/// Portable, unlike [`is_fixture_reexec`]; an inherited marker alone proves nothing. On `true`,
/// writes [`FIXTURE_GATE_PASSED_LINE`].
pub(crate) fn is_marked_fixture_reexec(marker_env: &str) -> bool {
    let marker = std::env::var(marker_env).ok();
    let driver = std::env::var(FIXTURE_PARENT_PID_ENV).ok();
    let marked = marker.is_some() && marker == driver;
    if marked {
        write_gate_passed();
    }
    marked
}

/// Runs the libtest fixture at `fixture` in a FRESH re-exec of this binary with `marker_env` set
/// to this process's pid (see [`is_marked_fixture_reexec`]), and returns its output whatever its
/// exit status: for a fixture that is meant to die, unlike [`run_fixture_with_cwd`] which requires
/// it to pass. Spawns under `spawn_lock()`. Build `fixture` with [`fixture_path!`].
pub(crate) fn run_fixture_output(fixture: &str, marker_env: &str) -> std::process::Output {
    let mut cmd = fixture_command(fixture);
    cmd.env(marker_env, std::process::id().to_string());
    let child = crate::test_spawn::spawn(&mut cmd).expect("spawn fixture child");
    child.wait_with_output().expect("wait for fixture child")
}

/// [`run_fixture_output`] for a fixture that must pass, with the case it should run in
/// `case_env`: for a fixture that changes process-wide state (a signal disposition, say) and so
/// runs one case per re-exec. Panics with the fixture's output unless it passes and wrote its gate
/// line. Build `fixture` with [`fixture_path!`].
#[cfg(unix)]
pub(crate) fn run_fixture_case(fixture: &str, marker_env: &str, case_env: &str, case: &str) {
    let mut cmd = fixture_command(fixture);
    cmd.env(marker_env, std::process::id().to_string()).env(case_env, case);
    crate::test_reexec::with_json_events(&mut cmd);
    let child = crate::test_spawn::spawn(&mut cmd).expect("spawn fixture child");
    let output = child.wait_with_output().expect("wait for fixture child");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    if let Err(why) = crate::test_reexec::suite_passed_exactly_one(&output) {
        panic!(
            "fixture {fixture} case {case:?} did not run and pass exactly one test: {why}\n--- stdout \
             ---\n{stdout}\n--- stderr ---\n{stderr}"
        );
    }
    assert!(
        stderr.contains(FIXTURE_GATE_PASSED_LINE),
        "fixture {fixture} case {case:?} never wrote {FIXTURE_GATE_PASSED_LINE:?}:\n{stderr}",
    );
}

/// Set `signo`'s disposition, process-wide: `SIG_IGN` if `ignore`, else `SIG_DFL`. Only a fixture
/// re-exec (see [`run_fixture_case`]) may call it: it changes every thread of the process.
#[cfg(target_os = "macos")]
pub(crate) fn set_signal_ignored(signo: libc::c_int, ignore: bool) {
    let handler = if ignore { libc::SIG_IGN } else { libc::SIG_DFL };
    // SAFETY: `signal` with `SIG_IGN` or `SIG_DFL` installs no handler code.
    let previous = unsafe { libc::signal(signo, handler) };
    assert_ne!(
        previous,
        libc::SIG_ERR,
        "signal({signo}): {}",
        std::io::Error::last_os_error()
    );
}

/// The directory [`run_fixture_with_cwd`]'s caller prepared, read from `marker_env`; `None` when it
/// is unset or (on unix) [`parent_pid_matches`] says this is not a deliberate re-exec. Either way
/// the fixture is also picked up by ordinary suite runs, where it must no-op.
///
/// Also asserts this process's own `current_dir()` IS that directory, so a fixture that reads its
/// cwd through here cannot keep passing after `.current_dir(cwd)` is silently dropped. The gate
/// line is written last, after both checks.
pub(crate) fn expected_cwd(marker_env: &str) -> Option<std::path::PathBuf> {
    #[cfg(unix)]
    if !parent_pid_matches() {
        return None;
    }
    let expected = std::path::PathBuf::from(std::env::var_os(marker_env)?);
    let actual = std::env::current_dir().expect("current_dir");
    assert_eq!(
        actual.canonicalize().expect("canonicalize actual cwd"),
        expected.canonicalize().expect("canonicalize expected cwd"),
        "this fixture's OS-level cwd must be the directory run_fixture_with_cwd's caller prepared",
    );
    write_gate_passed();
    Some(expected)
}

/// Builds the fully-qualified libtest `--exact` path of the `#[test] fn` named `$name`, for
/// [`run_fixture_with_cwd`]'s `fixture` argument. Two things tie the call site to the fixture
/// instead of letting them drift apart as two independently hand-typed strings:
///
/// - `assert_fn_item($name)` forces the compiler to resolve `$name` as a fn in scope — a typo
///   or a stale name after a rename is a compile error here, not a filter that silently matches
///   zero tests at runtime. It accepts any return type, since an `async fn` fixture is not a `fn()` (see [`run_fixture_with_cwd`]'s doc for why that is exactly the bug
///   this macro exists to rule out). A test that takes a group fixture uses
///   `fixture_path!(name, Group)`.
/// - `module_path!()` derives the module portion at compile time, so it can never fall out of
///   sync with a file move or a module rename; libtest's `--exact` filter never includes the
///   crate-name component `module_path!()` always carries as its own first segment, hence the
///   [`strip_crate_prefix`] call.
macro_rules! fixture_path {
    ($name:ident) => {{
        crate::test_child::assert_fn_item($name);
        crate::test_child::strip_crate_prefix(concat!(module_path!(), "::", stringify!($name)))
    }};
    ($name:ident, $group:ty) => {{
        crate::test_child::assert_fn_item_taking::<$group, _>($name);
        crate::test_child::strip_crate_prefix(concat!(module_path!(), "::", stringify!($name)))
    }};
}
pub(crate) use fixture_path;

/// Compiles only for a fn item or closure that takes no arguments, of any return type, `async fn` included: a misspelled name or
/// a non-fn item is a compile error at the [`fixture_path!`] call site.
pub(crate) fn assert_fn_item<R>(_: impl Fn() -> R) {}

/// [`assert_fn_item`] for a fn that takes one fixture, by reference.
#[cfg(target_os = "macos")]
pub(crate) fn assert_fn_item_taking<A: ?Sized, R>(_: impl Fn(&A) -> R) {}

/// Strips the crate-name segment `module_path!()` always carries as its own first component
/// (e.g. `"cosca::resolve::resolve_tests"`), since libtest's `--exact` filter never includes it
/// (e.g. `"resolve::resolve_tests"`). Panics if `path` does not start with that segment, which
/// would mean `module_path!()`'s documented contract no longer holds.
pub(crate) fn strip_crate_prefix(path: &'static str) -> &'static str {
    let prefix = concat!(env!("CARGO_PKG_NAME"), "::");
    path.strip_prefix(prefix)
        .unwrap_or_else(|| panic!("{path:?} does not start with {prefix:?} — module_path!()'s contract changed"))
}

/// A child that exits promptly and needs no external binary: this same test binary, run
/// with a filter that matches nothing, so libtest runs zero tests and exits 0.
///
/// The libtest filter is mandatory, and is why this lives in exactly one place: re-execing
/// the test binary with NO arguments runs the whole suite — including whichever test called
/// this — which then re-execs again, unboundedly.
///
/// Spawns under `spawn_lock()`: on macOS, a fork here that lands while another test's fd
/// marker write end happens to be open would transiently inherit it, and a concurrently
/// running sweep could then find and signal this bystander child. `spawn_lock()` is the same
/// lock every cosca-originated spawn in this test binary already takes.
pub(crate) fn spawn_a_process_that_exits() -> std::process::Child {
    crate::test_spawn::spawn(
        crate::test_reexec::command(std::env::current_exe().expect("current_exe"))
            .args(["--exact", "__cosca_no_such_test__"])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null()),
    )
    .expect("spawn")
}

/// `name` by its `System32` path (no `PATH` lookup).
#[cfg(windows)]
pub(crate) fn system32(name: &str) -> std::path::PathBuf {
    std::path::Path::new(&std::env::var_os("SystemRoot").expect("SystemRoot is set on Windows"))
        .join("System32")
        .join(name)
}

/// `more.com` by its `System32` path: blocks reading stdin and exits 0 on EOF,
/// unlike `findstr x`, whose exit 1 is indistinguishable from a kill.
#[cfg(windows)]
pub(crate) fn windows_more() -> std::path::PathBuf {
    system32("more.com")
}

/// A contained [`windows_more`] child blocked on a piped stdin the caller holds. It ends only by a
/// real kill or the caller closing the pipe (exit 0). Stdout is nulled because `more` echoes.
#[cfg(windows)]
pub(crate) fn windows_blocker() -> (crate::Child, crate::PipeWriter) {
    windows_blocker_with(Console::Hidden)
}

/// [`windows_blocker`] on this process's console, for a test of the graceful signals.
#[cfg(windows)]
pub(crate) fn windows_blocker_on_console() -> (crate::Child, crate::PipeWriter) {
    windows_blocker_with(Console::Asked)
}

#[cfg(windows)]
fn windows_blocker_with(console: Console) -> (crate::Child, crate::PipeWriter) {
    let mut cmd = command(console);
    cmd.args([windows_more()]);
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::null()).expect("set stdout null");
    cmd.contain();
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    (child, stdin)
}

/// Async twin of [`windows_blocker`]; `configure` selects the containment under test.
#[cfg(all(windows, feature = "tokio"))]
pub(crate) async fn windows_blocker_async(
    configure: impl FnOnce(&mut crate::tokio::Command),
) -> (crate::tokio::Child, crate::tokio::ChildStdin) {
    windows_blocker_async_with(Console::Hidden, configure).await
}

/// [`windows_blocker_async`] on this process's console, for a test of the graceful signals.
#[cfg(all(windows, feature = "tokio"))]
pub(crate) async fn windows_blocker_on_console_async(
    configure: impl FnOnce(&mut crate::tokio::Command),
) -> (crate::tokio::Child, crate::tokio::ChildStdin) {
    windows_blocker_async_with(Console::Asked, configure).await
}

#[cfg(all(windows, feature = "tokio"))]
async fn windows_blocker_async_with(
    console: Console,
    configure: impl FnOnce(&mut crate::tokio::Command),
) -> (crate::tokio::Child, crate::tokio::ChildStdin) {
    let mut cmd = tokio_command(console);
    cmd.args([windows_more()]);
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::null()).expect("set stdout null");
    configure(&mut cmd);
    let mut child = cmd.spawn().await.expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    (child, stdin)
}

/// The argv of a child that ignores `SIGTERM` (an ignored disposition survives the `exec`), tells
/// its stdout it is ready, then blocks on stdin as `cat`. Only `SIGKILL` or stdin EOF ends it.
#[cfg(unix)]
pub(crate) const TERM_IGNORING_BLOCKER_ARGV: &[&str] = &["sh", "-c", "trap '' TERM; echo r; exec cat"];

/// A root and a grandchild on one stdin pipe, in one process group. The root prints `r` once the
/// grandchild is forked. The grandchild prints `eof` if its `cat` ends of its own accord, so a test
/// that closes the stdin only after the kill finds `eof` on the stdout when the kill missed it.
#[cfg(unix)]
pub(crate) const CAT_TREE_ARGV: &[&str] = &[
    "sh",
    "-c",
    "exec 3<&0; { cat <&3 3<&- && echo eof; } & echo r; exec cat",
];

/// Three processes that ignore `SIGTERM` (an ignored disposition survives `exec`) and block on one
/// stdin pipe: the root (`cat`), a subshell, and the subshell's child `sh`. The child prints `r`
/// once it runs, so all three exist when a test reads it. Each of the last two then prints its own
/// marker once the stdin ends, if it is still alive: the child `leaf`, the subshell `eof`.
#[cfg(unix)]
pub(crate) const TERM_IGNORING_TREE_ARGV: &[&str] = &[
    "sh",
    "-c",
    "trap '' TERM; exec 3<&0; { sh -c 'echo r; read -r _; echo leaf' <&3 3<&- && echo eof; } & exec cat",
];

/// A root and a grandchild on one stdin pipe, in one process group. Only the grandchild ignores
/// `SIGTERM`: the root, `cat` again after the `exec`, has the default disposition back, so the
/// group's soft signal ends it and leaves a survivor that only a `SIGKILL` sweep reaches. The
/// ignored disposition is the grandchild's from its fork, so the readiness line (`r`, once the
/// grandchild is forked) says it already holds. The grandchild prints `eof` if its `cat` ends of its
/// own accord.
#[cfg(unix)]
pub(crate) const TERM_SURVIVOR_TREE_ARGV: &[&str] = &[
    "sh",
    "-c",
    "trap '' TERM; exec 3<&0; { cat <&3 3<&- && echo eof; } & trap - TERM; echo r; exec cat",
];

/// A spawned, contained `SIGTERM`-ignoring [`TERM_IGNORING_BLOCKER_ARGV`] child and the write end of
/// its stdin, returned once its readiness byte proves the trap is installed. A test whose only end
/// for it is a sweep or escalation holds the stdin and releases it after the kill.
#[cfg(unix)]
pub(crate) fn term_ignoring_blocker() -> (crate::Child, crate::PipeWriter) {
    use std::io::Read as _;

    let mut cmd = command(Console::Hidden);
    cmd.args(TERM_IGNORING_BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
    cmd.contain();
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    let mut readiness = [0u8; 1];
    child
        .stdout()
        .expect("piped stdout")
        .read_exact(&mut readiness)
        .expect("readiness byte");
    (child, stdin)
}

/// Async twin of [`term_ignoring_blocker`].
#[cfg(all(unix, feature = "tokio"))]
pub(crate) async fn term_ignoring_blocker_async() -> (crate::tokio::Child, crate::tokio::ChildStdin) {
    use ::tokio::io::AsyncReadExt as _;

    let mut cmd = tokio_command(Console::Hidden);
    cmd.args(TERM_IGNORING_BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
    cmd.contain();
    let mut child = cmd.spawn().await.expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    let mut readiness = [0u8; 1];
    child
        .stdout()
        .expect("piped stdout")
        .read_exact(&mut readiness)
        .await
        .expect("readiness byte");
    (child, stdin)
}

/// A blocker died to a kill, not by exiting on its own once its stdin closed: `SIGKILL` on Unix, the
/// kill's exit code `1` on Windows (`more.com` exits 0 on EOF), so a crash on the release fails too.
/// Separate compilation units cannot share it: `tests/common` keeps its own copy.
pub(crate) fn assert_killed(who: &str, status: std::process::ExitStatus) {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt as _;
        assert_eq!(
            status.signal(),
            Some(libc::SIGKILL),
            "{who} must be SIGKILLed, not exit on its own: {status:?}"
        );
    }
    #[cfg(windows)]
    assert_eq!(
        status.code(),
        Some(1),
        "{who} must be killed (exit code 1), not exit on its own: {status:?}"
    );
}

/// The argv for re-executing this test binary against one fixture through `cosca::Command`,
/// whose `args` is the **full** argv — libtest drops slot 0 as the binary name, so a filter or
/// option placed there is silently eaten and `--exact` degrades to substring matching.
/// `--test-threads=1` keeps a future filter that matches more than one test from running them
/// concurrently inside a process the caller is about to signal.
#[cfg(any(windows, target_os = "macos", feature = "tokio"))]
pub(crate) fn fixture_argv(test: &str) -> [&str; 5] {
    let [threads, exact, test, nocapture] = crate::test_reexec::fixture_args(test);
    ["cosca_unit_tests", threads, exact, test, nocapture]
}

/// The fully-qualified libtest path of [`fixture_survives_group_signal`], for callers that
/// re-exec this binary against it directly (`current_exe() --exact <this>`) rather than through
/// [`spawn_a_process_that_exits`]'s own filter.
#[cfg(windows)]
pub(crate) const FIXTURE_SURVIVES_GROUP_SIGNAL_TEST: &str = "test_child::fixture_survives_group_signal";

/// The env var carrying the `127.0.0.1:<port>` address the grandchild (a re-exec'd
/// [`fixture_registers_then_blocks`]) connects back to; [`fixture_survives_group_signal`] only
/// forwards it. Its presence also tells that fixture it was re-exec'd deliberately rather than
/// picked up by an ordinary, unfiltered suite run.
#[cfg(windows)]
pub(crate) const FIXTURE_SURVIVES_GROUP_SIGNAL_ADDR_ENV: &str = "COSCA_FIXTURE_SURVIVES_GROUP_SIGNAL_ADDR";

/// Windows-only fixture for the `root_exited`-on-`MembersRemain` regression (sync and async
/// twins): a no-op when picked up by an ordinary, unfiltered suite run —
/// [`FIXTURE_SURVIVES_GROUP_SIGNAL_ADDR_ENV`] is unset there. Re-executed via `current_exe()
/// --exact` [`FIXTURE_SURVIVES_GROUP_SIGNAL_TEST`] with that var set, it spawns a grandchild a
/// group `CTRL_BREAK` can never reach — `CREATE_NEW_PROCESS_GROUP` puts it in its own process
/// group, the same isolation `graceful_shutdown_tree`'s own doc describes for a nested
/// contained descendant — then returns immediately, letting this intermediate process exit.
///
/// The grandchild is itself a re-exec'd [`fixture_registers_then_blocks`], given THIS fixture's
/// OWN `addr` (forwarded via [`FIXTURE_REGISTERS_THEN_BLOCKS_ADDR_ENV`]) so it connects and
/// blocks DIRECTLY against the caller's listener — never against a socket this short-lived
/// intermediate process would itself own and then close on its own exit, which a
/// caller-chosen `grace` can easily outlive. The grandchild's own connect-and-tag is thus the
/// happens-before edge the caller blocks on: it cannot tag until its own code is running, in
/// its own group. The tag goes out over a real TCP socket, not `print!`/`io::stdout()`: the
/// grandchild's stdout is null, so a stdout-based readiness byte never reaches the caller. The job object still tracks the grandchild as a
/// tree member despite its own process group (job membership and process group are independent
/// Win32 concepts), so it shows up as a `MembersRemain` survivor even though the signal itself
/// never reaches it, and it stays that way for as long as the caller holds its control socket
/// open. Mirrors [`spawn_a_process_that_exits`]'s
/// filtered-re-exec idiom (see its own doc for why the filter is mandatory) put to a second use.
#[cfg(windows)]
#[skuld::test]
fn fixture_survives_group_signal() {
    let Some(addr) = std::env::var_os(FIXTURE_SURVIVES_GROUP_SIGNAL_ADDR_ENV) else {
        return; // picked up by an ordinary suite run — deliberately inert
    };
    // CREATE_NEW_PROCESS_GROUP (winbase.h). A scalar flag, so a raw constant needs no
    // `windows`-crate import: the creation word is a plain `u32`.
    const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
    // `Asked`: the grandchild stays on this process's console, in a group of its own, which is the
    // isolation the fixture exists for.
    #[allow(
        clippy::zombie_processes,
        reason = "the grandchild must outlive us; containment kills it"
    )]
    let _survivor = crate::test_spawn::spawn_with(
        crate::test_reexec::command(std::env::current_exe().expect("current_exe"))
            // `[1..]`: skip `fixture_argv`'s slot-0 placeholder; `std::process::Command` supplies argv[0].
            .args(&fixture_argv(FIXTURE_REGISTERS_THEN_BLOCKS_TEST)[1..])
            .env(FIXTURE_REGISTERS_THEN_BLOCKS_ADDR_ENV, &addr)
            .stdout(std::process::Stdio::null()),
        CREATE_NEW_PROCESS_GROUP,
        Console::Asked,
    )
    .expect("spawn a grandchild the group signal cannot reach");
}

/// The fully-qualified libtest path of [`fixture_registers_then_blocks`], for callers that
/// re-exec this binary against it directly (`current_exe() --exact <this>`).
// Gated with its consumers, which are Windows' `CTRL_BREAK` tests: a Unix build has none and
// `-D warnings` rejects it.
#[cfg(windows)]
pub(crate) const FIXTURE_REGISTERS_THEN_BLOCKS_TEST: &str = "test_child::fixture_registers_then_blocks";

/// The env var carrying the `127.0.0.1:<port>` address [`fixture_registers_then_blocks`] tags.
/// Its mere presence also tells the fixture it was re-exec'd deliberately rather than picked up
/// by an ordinary, unfiltered suite run.
pub(crate) const FIXTURE_REGISTERS_THEN_BLOCKS_ADDR_ENV: &str = "COSCA_FIXTURE_REGISTERS_THEN_BLOCKS_ADDR";

/// Bind a rendezvous listener for [`fixture_registers_then_blocks`]; returns it and its
/// `127.0.0.1:<port>` address.
#[cfg(windows)]
pub(crate) fn registration_rendezvous() -> (std::net::TcpListener, String) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind rendezvous listener");
    let addr = listener.local_addr().expect("local_addr").to_string();
    (listener, addr)
}

/// Fixture supplying a happens-before edge on a live child: a no-op when picked up by an
/// ordinary, unfiltered suite run ([`FIXTURE_REGISTERS_THEN_BLOCKS_ADDR_ENV`] is unset there).
/// Re-executed via `current_exe() --exact` [`FIXTURE_REGISTERS_THEN_BLOCKS_TEST`] with that var
/// set, it connects to the caller's listener, writes one tag byte, then blocks on a 1-byte read
/// of that same socket. The caller unblocks it by writing a byte back, and it then exits 0 of
/// its own accord — an exit code no forced kill can produce.
///
/// The tag is the edge: the fixture cannot write it until it is executing its own code. On
/// Windows that is also after the console has registered it — a child signalled before that
/// point dies during loader init instead of to the console event, which is a different exit code
/// and a different thing under test.
///
/// It installs no console-control handler, so `CTRL_BREAK`'s default disposition terminates it.
/// Blocking on the socket rather than parking means a panicking or aborted caller closes the
/// socket and the fixture exits on EOF instead of orphaning.
#[skuld::test]
fn fixture_registers_then_blocks() {
    let Some(addr) = std::env::var_os(FIXTURE_REGISTERS_THEN_BLOCKS_ADDR_ENV) else {
        return; // picked up by an ordinary suite run — deliberately inert
    };
    use std::io::{Read, Write};

    let mut sock = ack::connect_control(addr.to_str().expect("utf8 addr")).expect("connect rendezvous socket");
    sock.write_all(b"R").expect("write registration tag");
    sock.flush().expect("flush registration tag");
    let mut sink = [0u8; 1];
    _ = sock.read(&mut sink);
}

/// The fully-qualified libtest path of [`fixture_connects_and_exits`].
const FIXTURE_CONNECTS_AND_EXITS_TEST: &str = "test_child::fixture_connects_and_exits";

/// The env var carrying the `127.0.0.1:<port>` address [`fixture_connects_and_exits`] tags.
const FIXTURE_CONNECTS_AND_EXITS_ADDR_ENV: &str = "COSCA_FIXTURE_CONNECTS_AND_EXITS_ADDR";

/// A child that connects, tags, and exits 0 immediately, with no blocking read. Whether it waits
/// for the accept ack after connecting is up to its environment ([`ack::ACK_ENV`]).
#[skuld::test]
fn fixture_connects_and_exits() {
    let Some(addr) = std::env::var_os(FIXTURE_CONNECTS_AND_EXITS_ADDR_ENV) else {
        return; // picked up by an ordinary suite run — deliberately inert
    };
    use std::io::Write;

    let mut sock = ack::connect_control(addr.to_str().expect("utf8 addr")).expect("connect rendezvous socket");
    sock.write_all(b"R").expect("write registration tag");
    sock.flush().expect("flush registration tag");
}

/// Spawns [`fixture_connects_and_exits`], with the ack handshake when `acked`. Returns the child
/// and the target identity to watch.
fn spawn_connects_and_exits(
    listener: &std::net::TcpListener,
    acked: bool,
) -> (std::process::Child, crate::identity::ProcessId) {
    let addr = listener.local_addr().expect("local_addr").to_string();
    let mut cmd = std::process::Command::new(std::env::current_exe().expect("current_exe"));
    cmd.args(["--test-threads=1", "--exact", FIXTURE_CONNECTS_AND_EXITS_TEST])
        .env(FIXTURE_CONNECTS_AND_EXITS_ADDR_ENV, &addr)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    if acked {
        cmd.env(ack::ACK_ENV, "1");
    }
    let child = crate::test_spawn::spawn(&mut cmd).expect("spawn the connects-and-exits fixture");
    let target = crate::identity::ProcessId::of(child.id())
        .found()
        .expect("resolve the freshly spawned fixture's pid");
    (child, target)
}

/// Waits for the zombie edge WITHOUT reaping, so the pid keeps naming the target.
#[cfg(unix)]
fn wait_unreaped(pid: u32) {
    loop {
        let mut si: libc::siginfo_t = unsafe { std::mem::zeroed() };
        // SAFETY: `si` is a valid out-param; `pid` is our own unreaped child.
        let rc = unsafe { libc::waitid(libc::P_PID, pid as libc::id_t, &mut si, libc::WEXITED | libc::WNOWAIT) };
        if rc == 0 {
            return;
        }
        let e = std::io::Error::last_os_error();
        assert_eq!(e.raw_os_error(), Some(libc::EINTR), "waitid: {e}");
    }
}

/// A fixture that connects and exits without waiting for the ack (not opted in) is dead whether
/// or not its connection reached the accept queue: the exit alone decides. The target has exited,
/// unreaped, before `accept_or_die` starts.
#[skuld::test]
fn death_watch_accept_or_die_reports_a_target_that_connected_and_exited_without_the_ack_as_dead() {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind rendezvous listener");
    let (mut child, target) = spawn_connects_and_exits(&listener, false);
    #[cfg(unix)]
    wait_unreaped(child.id());
    #[cfg(windows)]
    child.wait().expect("wait for the fixture to exit");

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| accept_or_die(&listener, target)));
    let payload = result.expect_err("accept_or_die must panic for an exited target");
    let message = payload
        .downcast_ref::<String>()
        .cloned()
        .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
        .expect("string panic payload");
    assert_eq!(
        message,
        format!("the control target (pid {}) died before it connected", target.pid())
    );
    child.wait().expect("reap the fixture");
}

/// The ack protects an opted-in fixture that connects, tags and exits at once: it cannot exit
/// before `accept_or_die` accepted and acked, so the connection is always returned.
#[skuld::test]
fn death_watch_accept_or_die_returns_the_connection_of_an_acked_target_that_exits_at_once() {
    use std::io::Read;

    let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind rendezvous listener");
    let (mut child, target) = spawn_connects_and_exits(&listener, true);
    let mut sock = accept_or_die(&listener, target);
    let mut tag = [0u8; 1];
    sock.read_exact(&mut tag).expect("read the fixture's tag");
    assert_eq!(&tag, b"R");
    child.wait().expect("reap the fixture");
}

/// Exit code of the `tool` in [`cwd_and_path_tools`]'s first directory.
#[cfg(unix)]
pub(crate) const CWD_TOOL_EXIT: i32 = 11;
/// Exit code of the `tool` in [`cwd_and_path_tools`]'s second directory.
#[cfg(unix)]
pub(crate) const PATH_TOOL_EXIT: i32 = 22;

/// Two directories, each holding an executable script named `tool` that exits with its own code
/// ([`CWD_TOOL_EXIT`], [`PATH_TOOL_EXIT`]), so a child's exit status says which one was loaded.
/// Meant as the child's working directory and its `PATH`, respectively.
///
/// Each write is serialized against every other spawn's `fork` and the guard dropped before the
/// caller's spawn: a `fork` while a script's writable descriptor is open leaves the forked child
/// holding it until it execs, and `execve` of that script then fails with `ETXTBSY`. The lock is
/// not reentrant, so holding it across a `spawn()` would deadlock.
#[cfg(unix)]
pub(crate) fn cwd_and_path_tools() -> (tempfile::TempDir, tempfile::TempDir) {
    use std::os::unix::fs::PermissionsExt;
    let dirs = (
        tempfile::tempdir().expect("tempdir"),
        tempfile::tempdir().expect("tempdir"),
    );
    for (dir, code) in [(&dirs.0, CWD_TOOL_EXIT), (&dirs.1, PATH_TOOL_EXIT)] {
        let tool = dir.path().join("tool");
        let _guard = crate::child::spawn::spawn_lock();
        std::fs::write(&tool, format!("#!/bin/sh\nexit {code}\n")).expect("write tool");
        std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).expect("chmod tool");
    }
    dirs
}

#[cfg(test)]
#[path = "test_child_tests.rs"]
mod test_child_tests;

/// Whether the process `id` names has exited by `timeout` (`None`: for ever), found through a fresh
/// open; a gone id has exited. Reaps nothing.
#[cfg(any(target_os = "linux", windows))]
pub(crate) fn exited_through_open(
    id: crate::identity::ProcessId,
    timeout: Option<std::time::Duration>,
) -> Result<bool, crate::error::Error> {
    match crate::Process::open(id)? {
        None => Ok(true),
        Some(process) => match timeout {
            None => process.wait().map(|()| true),
            Some(timeout) => process.wait_timeout(timeout),
        },
    }
}

/// The first Toolhelp snapshot that no longer lists `pid`, an exited process whose handle is held.
/// Toolhelp can still list such a process for a moment after its exit; poll until it drops the row.
#[cfg(windows)]
pub(crate) fn parents_once_unlisted(
    pid: crate::identity::RawPid,
) -> Vec<(crate::identity::RawPid, crate::identity::RawPid)> {
    loop {
        let parents =
            crate::containment::enumerate::process_parents(&crate::identity::HostKernel).expect("the process snapshot");
        if !parents.iter().any(|&(listed, _)| listed == pid) {
            return parents;
        }
        std::thread::yield_now();
    }
}