cosca 0.9.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
//! macOS inherited-fd marker: containment membership the child carries.
//!
//! A contained root is handed the write end of a pipe with `FD_CLOEXEC` cleared *in the
//! forked child*, so every descendant inherits it across `fork` and `exec`. Membership
//! becomes "holds this kernel object", which no credential or grouping change can shed — it
//! survives `setsid`, `setpgid` and reparenting to launchd, and it nests arbitrarily.
//!
//! Holders are matched by `pipe_handle` (a `VM_KERNEL_ADDRHASH` of the kernel pipe object)
//! read via `proc_pidfdinfo(…, PROC_PIDFDPIPEINFO, …)`.
//!
//! # Why the supervisor must hold the read end for the mechanism's whole life
//!
//! `pipe_handle` is a true, collision-free identity only while some descriptor on that pipe —
//! either end, in any process — is still open. Once every descriptor on both ends closes, the
//! kernel re-issues the freed address (hence the same handle) almost immediately, to any
//! process on the host, not just this one. A sweep run after the read end was dropped could
//! therefore match an arbitrary unrelated process. `Marker::sweep` takes `&self` and `Marker`
//! owns the read end, so this is structural rather than a rule to remember.
//!
//! # Documented limits
//!
//! This is naive-child containment, not a sandbox: `close(fd)` escapes, and a spawn path that
//! scrubs inherited descriptors — notably Python's `subprocess` (`close_fds=True` by default)
//! and Node's `child_process` — drops the marker for everything below it.
//! `POSIX_SPAWN_CLOEXEC_DEFAULT` drops it unless the fd is passed to
//! `posix_spawn_file_actions_addinherit_np`. Elevation wrappers drop it too: `sudo` closes
//! every descriptor >= 3 by default (`closefrom`), which is why the marker is not installed on
//! an elevation-derived spawn. A concurrent, unrelated `fork()` in THIS process — outside
//! cosca's own spawn path, which serialises itself via `spawn_lock` and drops its
//! supervisor-side copy before releasing that lock, fully excluding every OTHER cosca spawn —
//! can still transiently inherit the marker write end into its own not-yet-`exec`'d child,
//! since `fork()` copies the whole fd table regardless of `FD_CLOEXEC` (that flag only takes
//! effect at THAT child's own `exec`). This residual cannot be closed to zero: no local code
//! change can control a third party's fork timing in the same process.
//!
//! **A tree member that `exec`s a setuid binary, or otherwise changes credentials, becomes
//! unqueryable via `PROC_PIDLISTFDS` (`EPERM`).** If the ppid-walk channel can still place it as
//! a descendant, `sweep` already folds the gap into `incomplete` there, so `holders()`'s own
//! denial for the same pid stays an aggregate `debug!`, not a second `warn!`. But for a pid
//! ppid-walk cannot place — a double-fork-reparented-to-launchd orphan, this module's primary
//! scenario — a denial leaves no channel able to catch it: `holders()` folds it into the same
//! aggregate, never-escalated denial count as ordinary host noise, so `sweep` can return
//! `Ok(())` while that pid is a real, un-swept member. Not escalated to `incomplete`, for the
//! same reason `enumerate::snapshot()`'s ppid-denial count is excluded: folding in bulk
//! per-scan denials (hundreds of unrelated pids on a real host) would make `Ok(())`
//! unreachable in practice.
//!
//! **The marker fd is inherited-only, not an IPC channel — do not write to it.** Every
//! descendant is handed the WRITE end of a pipe whose read end the supervisor holds but never
//! reads. A member that writes to its inherited marker descriptor blocks once the kernel pipe
//! buffer fills (nothing ever drains it), and after `Child::detach()` — which drops the
//! supervisor's read end while a surviving member's write-end copy is what then keeps the
//! marker's `pipe_handle` from being recycled — a subsequent write by that member raises
//! `SIGPIPE` (default action: terminate) instead. Ordinary programs never write to a
//! descriptor they did not open themselves for that purpose, so this is not expected to matter
//! in practice, but it is a real behavior of an fd a tree member's own code could, in
//! principle, stumble onto by number.

use std::os::fd::{AsFd, AsRawFd, BorrowedFd};
use std::time::Instant;

use crate::identity::RawPid;

// FFI: sys/proc_info.h =====
//
// `libc` exposes `proc_pidfdinfo`, `proc_fdinfo`, `vinfo_stat`, `PROC_PIDLISTFDS` and
// `PROX_FDTYPE_PIPE`, but not the five symbols below. They are public SDK API, not private
// layout: the values and offsets are pinned by the static asserts underneath.

/// `proc_pidfdinfo` flavor yielding `struct pipe_fdinfo`.
pub(crate) const PROC_PIDFDPIPEINFO: libc::c_int = 6;
/// `proc_fileinfo::fi_status` bit: this descriptor closes at the holder's next `exec`.
pub(crate) const PROC_FP_CLEXEC: u32 = 2;

/// `struct proc_fileinfo`.
#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct ProcFileInfo {
    fi_openflags: u32,
    fi_status: u32,
    fi_offset: i64,
    fi_type: i32,
    fi_guardflags: u32,
}

/// `struct pipe_fdinfo` — the buffer `PROC_PIDFDPIPEINFO` fills. Using `struct pipe_info`
/// here instead (the shape the folklore recipe uses) makes every call return <= 0 and the
/// sweep find nobody.
#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct PipeFdInfo {
    pfi: ProcFileInfo,
    pipe_stat: libc::vinfo_stat,
    pub(crate) pipe_handle: u64,
    pub(crate) pipe_peerhandle: u64,
    pipe_status: i32,
    rfu_1: i32,
}

const _: () = assert!(std::mem::size_of::<ProcFileInfo>() == 24);
const _: () = assert!(std::mem::size_of::<PipeFdInfo>() == 184);
const _: () = assert!(std::mem::offset_of!(PipeFdInfo, pipe_handle) == 160);

// Reading a pipe's identity =====

/// The `pipe_handle` of `fd` in THIS process, or `None` if `fd` is not a pipe. A self-query, so
/// `FdPipeInfoQuery::Denied` is not expected in practice (a process may always query its own
/// fds) — folded into `None` alongside `Absent` for this convenience wrapper regardless.
pub(crate) fn pipe_handle_of(fd: BorrowedFd<'_>) -> Option<u64> {
    match fd_pipe_info(std::process::id(), fd.as_raw_fd()) {
        FdPipeInfoQuery::Found(info) => Some(info.pipe_handle),
        FdPipeInfoQuery::Absent | FdPipeInfoQuery::Denied => None,
    }
}

/// Same tri-state shape as `PipeQuery`, for the per-fd `PROC_PIDFDPIPEINFO` query — added
/// because `holders()` and `holds_marker_query()` both call this on an fd `pipe_fds_of` JUST
/// reported as a pipe, so a denial here is not the routine "not a pipe" case; it means the
/// query was refused between the two calls (matching the module docs' credential-changing-exec
/// scenario), and each caller needs to react to that specifically — see each call site.
pub(crate) enum FdPipeInfoQuery {
    Found(PipeFdInfo),
    /// Not a pipe, the fd closed, or the pid is gone — indistinguishable at this layer, and
    /// (unlike `PipeQuery`) not worth separating: nothing calls this hoping to count denials
    /// against a NOT-yet-confirmed candidate the way `holders()`'s outer `pipe_fds_of` does.
    Absent,
    /// The OS refused the query (measured: the same `0`-with-`EPERM` shape as `PROC_PIDLISTFDS`).
    Denied,
}

pub(crate) fn fd_pipe_info(pid: RawPid, fd: libc::c_int) -> FdPipeInfoQuery {
    let mut info: PipeFdInfo = unsafe { std::mem::zeroed() };
    let size = std::mem::size_of::<PipeFdInfo>() as libc::c_int;
    // SAFETY: proc_pidfdinfo writes up to `size` bytes into `info`; pointer and size match.
    let n = clear_errno_and_call(|| unsafe {
        libc::proc_pidfdinfo(
            pid as libc::c_int,
            fd,
            PROC_PIDFDPIPEINFO,
            &mut info as *mut _ as *mut libc::c_void,
            size,
        )
    });
    if n == size {
        return FdPipeInfoQuery::Found(info);
    }
    match std::io::Error::last_os_error().raw_os_error() {
        // ESRCH: pid is gone. EBADF: measured directly — the kernel returns this both for "fd
        // was a pipe a moment ago but is now closed" and "fd was never a pipe," i.e. it is
        // `proc_pidfdinfo`'s generic "not found" code for this call, not an access-control
        // signal. Treating it as `Denied` would misreport an ordinary closed-descriptor race
        // (the fd this loop is iterating came from a separate, earlier `PROC_PIDLISTFDS` call)
        // as a permissions problem.
        None | Some(0) | Some(libc::ESRCH) | Some(libc::EBADF) => FdPipeInfoQuery::Absent,
        _ => FdPipeInfoQuery::Denied,
    }
}

// The sweep =====

/// One process found holding the marker.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Holder {
    pub pid: RawPid,
    /// The holder's marker descriptor is `FD_CLOEXEC`: it leaves the containment set at the
    /// holder's next `exec`. An imminent, observable membership loss.
    pub clexec: bool,
}

/// The outcome of trying to read `pid`'s pipe descriptors — a tri-state, not a `Vec` alone,
/// because `holders()` (scanning the WHOLE host) and `holds_marker_query()` (re-checking a
/// KNOWN candidate) need to react to a denial completely differently. See the module docs and
/// each caller for why.
pub(crate) enum PipeQuery {
    /// The fd table was read; these are its pipe descriptors (possibly none).
    Found(Vec<libc::c_int>),
    /// The pid is gone (`ESRCH`) — expected, never worth logging.
    Gone,
    /// The OS refused the query (measured: `EPERM`, returned as `0` — see below). Whether this
    /// is worth logging depends on WHO is asking; `pipe_fds_of` itself stays silent.
    Denied,
}

/// Every process in `pids` holding the pipe named by `handle`. Best-effort: a pid we may not
/// query, or one that vanishes mid-sweep, is simply absent — but a denial is COUNTED, not
/// discarded silently, and reported in aggregate (see below).
///
/// A process can hold MULTIPLE descriptors naming the same marker — the inherited one plus any
/// `dup`/`fcntl(F_DUPFD_CLOEXEC)` copy, trivially produced by a shell `exec N>&M` or by any
/// runtime that dups an inherited fd. `Holder.clexec` claims the descriptor "will lose the
/// marker at its next exec"; that is only true if EVERY copy the process holds is CLOEXEC, so
/// the fold below is an AND across every matching fd: a single non-CLOEXEC copy keeps the
/// marker alive past the next exec even if another copy is CLOEXEC.
///
/// **Denials are aggregated, not warned per-pid.** This scans EVERY pid on the host, and most
/// denials here are for processes that have nothing to do with the tree (any other user's
/// processes) — measured on this host: `ps -Ao user=` shows several hundred non-self-owned
/// pids out of roughly a thousand live, every one of which denies `PROC_PIDLISTFDS`. Warning
/// per pid here would bury the genuinely actionable case — a denial on a pid ALREADY confirmed
/// to hold the marker — under hundreds of lines about processes that were never candidates.
/// That actionable case is `kill_holder`'s live re-check via `holds_marker_query`, which DOES
/// `warn!`, because by then the pid is a known member, not an arbitrary host process.
pub(crate) fn holders(handle: u64, pids: &[RawPid]) -> Vec<Holder> {
    let mut out = Vec::new();
    let mut denied = 0usize;
    for &pid in pids {
        let fds = match pipe_fds_of(pid) {
            PipeQuery::Found(fds) => fds,
            PipeQuery::Gone => continue,
            PipeQuery::Denied => {
                denied += 1;
                continue;
            }
        };
        let mut found = false;
        let mut all_clexec = true;
        for fd in fds {
            match fd_pipe_info(pid, fd) {
                FdPipeInfoQuery::Found(info) => {
                    if info.pipe_handle != handle {
                        continue;
                    }
                    found = true;
                    all_clexec &= info.pfi.fi_status & PROC_FP_CLEXEC != 0;
                }
                FdPipeInfoQuery::Absent => {
                    // `pipe_fds_of` just reported this exact fd as a pipe (moments ago), so
                    // this IS the routine "vanished between the two calls" case — `debug!`,
                    // not counted (matches a genuinely gone pid, not a denial).
                    log::debug!(
                        "fd marker {handle:#x}: PROC_PIDFDPIPEINFO for pid {pid} fd {fd} \
                         (already listed as a pipe) came back empty; treating as vanished \
                         between the two calls"
                    );
                }
                FdPipeInfoQuery::Denied => {
                    // Same class of gap as a whole-pid `PROC_PIDLISTFDS` denial (this fd WAS
                    // just listed as a pipe, so this is a real, not routine, miss) — folded
                    // into the SAME aggregate count, not a separate `warn!` per pid, for the
                    // same "most of these are unrelated host noise" reasoning above.
                    denied += 1;
                    log::debug!(
                        "fd marker {handle:#x}: PROC_PIDFDPIPEINFO for pid {pid} fd {fd} \
                         (already listed as a pipe) was denied"
                    );
                }
            }
        }
        if !found {
            continue;
        }
        if all_clexec {
            // The HANDLE is in the message, not just the pid: `log_capture` is one
            // process-global buffer shared by every parallel test, and every unit test
            // shares this pid — only the handle distinguishes one marker from another.
            log::warn!(
                "fd marker {handle:#x}: holder pid {pid} will lose the marker at its next \
                 exec (every copy of its inherited descriptor is FD_CLOEXEC)"
            );
        }
        out.push(Holder {
            pid,
            clexec: all_clexec,
        });
    }
    if denied > 0 {
        log::debug!(
            "fd marker {handle:#x}: {denied} of {} host pids were unqueryable this pass \
             (access denied); none were confirmed holders, but a denied pid already holding \
             the marker would be invisible to this scan",
            pids.len()
        );
    }
    out
}

/// Whether `pid` holds the marker right now — the plain-`bool` convenience most callers
/// (including this file's own tests) want; folds `MarkerQuery::Denied` into `false` alongside
/// `NotHeld`, which is correct for a caller that does not need to distinguish them. `kill_holder`
/// uses `holds_marker_query` directly instead, because IT does need to.
#[cfg_attr(
    not(test),
    allow(
        dead_code,
        reason = "only tests call it; production uses holds_marker_query directly"
    )
)]
pub(crate) fn holds_marker(pid: RawPid, handle: u64) -> bool {
    matches!(holds_marker_query(pid, handle), MarkerQuery::Held)
}

/// The tri-state membership re-check `kill_holder` actually needs: a confirmed non-holder (the
/// documented `close(fd)` escape — safe to leave running, `debug!` only) is a different fact
/// from a KNOWN holder (`holders()` found this pid moments earlier, this pass) that became
/// unqueryable before the kill — almost always the credential-changing `exec` the module docs
/// name, a real teardown gap, not an escape, and worth a `warn!` plus marking the sweep
/// incomplete. Collapsing the two (as a bare `bool` must) would silently reclassify "still a
/// member, now unreachable" as "no longer a member".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MarkerQuery {
    Held,
    NotHeld,
    Denied,
}

pub(crate) fn holds_marker_query(pid: RawPid, handle: u64) -> MarkerQuery {
    let fds = match pipe_fds_of(pid) {
        PipeQuery::Found(fds) => fds,
        PipeQuery::Gone => return MarkerQuery::NotHeld,
        PipeQuery::Denied => return MarkerQuery::Denied,
    };
    for fd in fds {
        match fd_pipe_info(pid, fd) {
            FdPipeInfoQuery::Found(info) if info.pipe_handle == handle => return MarkerQuery::Held,
            FdPipeInfoQuery::Found(_) => continue,
            FdPipeInfoQuery::Absent => {
                // Same shape as `holders()`'s inner loop, same disposition — see there.
                log::debug!(
                    "fd marker {handle:#x}: PROC_PIDFDPIPEINFO for pid {pid} fd {fd} (already \
                     listed as a pipe) came back empty; treating as vanished between the two calls"
                );
                continue;
            }
            FdPipeInfoQuery::Denied => {
                // This pid is a CONFIRMED candidate (`kill_holder` only calls this on an
                // already-discovered holder) — a per-fd denial here is exactly the "known
                // member became unqueryable" gap `MarkerQuery::Denied` exists to report, NOT
                // the same fact as a genuinely absent descriptor. Returning here (rather than
                // continuing to check other fds) is deliberately conservative: one denied fd
                // on a confirmed holder is enough to say "this pid could not be fully
                // re-verified," matching `kill_holder`'s own doc comment.
                return MarkerQuery::Denied;
            }
        }
    }
    MarkerQuery::NotHeld
}

/// `pid`'s pipe descriptors, as a [`PipeQuery`] — see there for what each variant means and
/// why the caller, not this function, decides whether a denial is worth logging.
///
/// **Measured on this host: `PROC_PIDLISTFDS` reports a denial by returning `0` with
/// `errno == EPERM`, NOT a negative value.** `proc_pidinfo(1, PROC_PIDLISTFDS, …)` (pid 1,
/// root-owned, from an unprivileged caller) returns `0`/`EPERM` for both the sizing and fill
/// forms; across the live table, every EPERM-denied pid returned exactly `0`, none returned
/// negative. This matches `identity::macos::pidinfo`'s established handling of the sibling
/// `PROC_PIDTBSDINFO` call: gate on `n <= 0`, then classify by errno. So the failure gate here
/// is `<= 0`, not `< 0` — and because `0` is ALSO the legitimate "successful, empty answer"
/// return (e.g. a zombie with no open fds), `errno` must be cleared immediately before each
/// call (`clear_errno_and_call`) so a `0` return can be told apart from an `EPERM` one: success
/// never touches `errno`, so it reads back as whatever this call just zeroed it to.
///
/// The kernel fills the buffer and reports bytes written with no error on truncation, so a
/// short list is indistinguishable from a complete one unless the buffer was provably larger
/// than the answer. Re-read with a doubled capacity until it is — a truncated fd list means a
/// holder silently missed.
/// The `proc_pidinfo` buffer-size argument for `cap` `proc_fdinfo` entries. Mirrors
/// `size_argument_for` in `enumerate/macos.rs`, guarding the identical hazard: `cap` doubles
/// unbounded in `pipe_fds_of`'s retry loop below, and an unchecked `as libc::c_int` cast wraps
/// once `cap * entry` passes `i32::MAX`, producing an arbitrary size that no longer describes
/// the buffer `fds` actually is — the exact correspondence the caller's `// SAFETY:` comment
/// depends on.
fn fd_list_buf_bytes(cap: usize, entry: usize) -> std::io::Result<libc::c_int> {
    cap.checked_mul(entry)
        .and_then(|bytes| libc::c_int::try_from(bytes).ok())
        .ok_or_else(|| {
            std::io::Error::other(format!(
                "a {cap}-entry proc_fdinfo buffer cannot be described in proc_pidinfo's int \
                 size argument"
            ))
        })
}

pub(crate) fn pipe_fds_of(pid: RawPid) -> PipeQuery {
    let entry = std::mem::size_of::<libc::proc_fdinfo>();
    let needed = clear_errno_and_call(|| unsafe {
        libc::proc_pidinfo(pid as libc::c_int, libc::PROC_PIDLISTFDS, 0, std::ptr::null_mut(), 0)
    });
    if needed <= 0 {
        return classify_pidlistfds_failure();
    }
    let mut cap = needed as usize / entry + 16;
    loop {
        let buf_bytes = match fd_list_buf_bytes(cap, entry) {
            Ok(b) => b,
            Err(e) => {
                // A loud, per-pid denial, not a wrapped cast: matches `collect_pids`'s sibling
                // over-report guard in spirit — a contract this call cannot honor must fail
                // rather than silently truncate. Folded into `Denied` (counted, aggregated by
                // `holders()`) rather than propagated as a hard error: one pid with an
                // unenumerable fd table must not abort a whole-host sweep.
                log::warn!(
                    "fd marker: pid {pid}'s open-fd count cannot be enumerated ({report}); treating \
                     as denied for this pass",
                    report = crate::error::Report(&e)
                );
                return PipeQuery::Denied;
            }
        };
        let mut fds: Vec<libc::proc_fdinfo> = vec![unsafe { std::mem::zeroed() }; cap];
        // SAFETY: `fds` owns `buf_bytes` writable bytes (`fd_list_buf_bytes` computed it from
        // the SAME `cap`/`entry` that sized `fds`, and failed loudly above rather than wrap);
        // proc_pidinfo writes proc_fdinfo records.
        let written = clear_errno_and_call(|| unsafe {
            libc::proc_pidinfo(
                pid as libc::c_int,
                libc::PROC_PIDLISTFDS,
                0,
                fds.as_mut_ptr() as *mut libc::c_void,
                buf_bytes,
            )
        });
        if written <= 0 {
            return classify_pidlistfds_failure();
        }
        let count = written as usize / entry;
        if count > cap {
            // The over-report guard `collect_pids` has too: the kernel cannot legitimately
            // write more entries than the buffer it was handed. Folding this into "ask again
            // with more room" would silently accept an out-of-contract overwrite past `fds`'s
            // own allocation instead of failing loudly on it.
            log::warn!(
                "fd marker: pid {pid}'s proc_pidinfo(PROC_PIDLISTFDS) reported {count} entries \
                 into a {cap}-entry buffer; treating as denied for this pass"
            );
            return PipeQuery::Denied;
        }
        if count == cap {
            cap *= 2;
            continue;
        }
        return PipeQuery::Found(
            fds[..count]
                .iter()
                .filter(|f| f.proc_fdtype == libc::PROX_FDTYPE_PIPE as u32)
                .map(|f| f.proc_fd)
                .collect(),
        );
    }
}

/// Clears this thread's `errno` immediately before calling `f`, so a `0` return can be told
/// apart from a same-shaped `0`-meaning-EPERM failure (see `pipe_fds_of`'s doc comment for the
/// measurement). `errno` is thread-local on every platform this crate targets, so this is
/// race-free against other threads.
fn clear_errno_and_call(f: impl FnOnce() -> libc::c_int) -> libc::c_int {
    // SAFETY: `__error()` returns this thread's own errno cell; writing to it is always defined.
    unsafe {
        *libc::__error() = 0;
    }
    f()
}

/// Classifies a `<= 0` `PROC_PIDLISTFDS` return, following a call made through
/// `clear_errno_and_call`. `errno == 0` (never touched) means the call genuinely succeeded with
/// an empty answer; `ESRCH` means gone; anything else (measured: `EPERM` for a cross-user
/// query) is a real denial.
fn classify_pidlistfds_failure() -> PipeQuery {
    let e = std::io::Error::last_os_error();
    match e.raw_os_error() {
        None | Some(0) => PipeQuery::Found(Vec::new()), // genuine empty success, not a failure
        Some(libc::ESRCH) => PipeQuery::Gone,
        _ => PipeQuery::Denied,
    }
}

// Installing the marker on a spawn =====

use std::os::fd::{FromRawFd, OwnedFd, RawFd};

use crate::containment::ContainMode;

/// Whether this spawn installs a marker. Pure, so the policy is directly unit-testable —
/// the same shape as `unix_setup_for` and `windows_contain_setup`.
///
/// Only the outermost root installs one: a nested member inherits the root's marker across
/// `fork`, so a second pipe would add an fd per nesting level and buy nothing. `suppressed`
/// is set for an elevation-derived spawn, whose `sudo`/`doas`/`pkexec` wrapper closes every
/// descriptor >= 3 before exec — installing there would report a guarantee that cannot hold.
pub(crate) fn marker_wanted(mode: Option<ContainMode>, is_root: bool, suppressed: bool) -> bool {
    mode.is_some() && is_root && !suppressed
}

/// A descriptor number clear of everything that could overwrite the marker inside the forked
/// child: `fd_map` `dup2`s each user mapping onto its `child_fd`, std `dup2`s the stdio
/// slots before any `pre_exec` hook runs, AND ordinary, non-adversarial shell scripts and
/// libraries conventionally claim LOW numbers for their own redirections (`exec 3>&1`,
/// `exec 4<file`, a library's own `dup2` bookkeeping) — `dup2` silently closes whatever
/// occupied that number first. A floor of merely "above stdio" (3) still lands the marker at
/// 4-6 in the common case (nothing reserved), squarely inside that conventional range: a
/// script doing `exec 4>log` would then silently drop the marker for itself and everything it
/// spawns afterward — a far likelier ACCIDENTAL escape than the documented deliberate
/// `close(fd)` one, and nothing in this design would log or detect it. `HIGH_FLOOR` puts the
/// marker well clear of that whole range at negligible cost (one descriptor number, unused by
/// convention).
const HIGH_FLOOR: RawFd = 64;

/// `reserved` is caller-supplied (ultimately from `Command::fd()`'s child fd numbers), so
/// `m + 1` must not silently wrap: `saturating_add` keeps a `RawFd::MAX` entry from wrapping to
/// `RawFd::MIN`, which `.max(HIGH_FLOOR)` would otherwise "recover" from into a floor BELOW
/// that reserved fd — silently defeating the entire purpose of this function.
pub(crate) fn safe_marker_fd(candidate: RawFd, reserved: &[RawFd]) -> RawFd {
    let floor = reserved
        .iter()
        .copied()
        .max()
        .map_or(HIGH_FLOOR, |m| m.saturating_add(1))
        .max(HIGH_FLOOR);
    candidate.max(floor)
}

/// A marker pipe created for a spawn: the write end is already owned by the `Command`.
pub(crate) struct PreparedMarker {
    /// The supervisor's read end. See the module docs: holding it is what keeps `handle`
    /// from being re-issued to an unrelated pipe.
    pub read: OwnedFd,
    pub handle: u64,
    /// `read`'s OWN `pipe_handle` (a distinct kernel object from `handle`, the write end's —
    /// see `a_live_pipe_has_a_nonzero_handle_distinct_per_end`), captured while both ends are
    /// provably still open. Unlike `read`'s PEER handle (which reports `0` once every write
    /// end anywhere closes — measured; see `Marker::sweep`'s entry contract for why that
    /// matters), `read`'s OWN handle stays valid for as long as `read` itself stays open,
    /// letting `Marker` re-assert "this really is still my pipe" at sweep time without
    /// depending on the write side's state.
    pub read_handle: u64,
    /// The descriptor number the marker occupies in the child (`fd_map::preserve` does not
    /// renumber, so it is the parent's number too).
    #[cfg_attr(not(test), allow(dead_code, reason = "read only by tests"))]
    pub fd: RawFd,
    /// The kernel the spawn started with: the marker's sweeps read the identity of the root and of
    /// every member they signal through it.
    pub kernel: crate::identity::SpawnKernel,
}

/// Create the marker pipe and hand its write end to `steps`. `reserved` is every child fd
/// number the spawn will `dup2` into (the caller's `fd()` mappings).
///
/// The step clears `FD_CLOEXEC` on the descriptor **in the forked child only**, so the
/// supervisor's copy stays CLOEXEC and is never inherited by a concurrent, unrelated spawn's
/// EXEC'D process image. `steps`, then the `Command` it is registered on, own the write end until
/// that `Command` drops, so the CALLER must drop it promptly after `.spawn()` returns to bound the
/// (documented, non-zero) window where a concurrent `fork()` in this process could see this fd
/// before its own `exec`; see the module docs.
///
/// `Err` on any failure: [`Error::Containment`] naming the step that failed, with the OS error that
/// failed it as its source. Nothing is logged here: [`ContainMode::Strongest`] returns it, and any
/// other mode falls back to the pre-existing mechanism and logs it (see `dispatch::prepare`).
pub(crate) fn install(
    steps: &mut crate::child::spawn::in_child::InChild,
    reserved: &[RawFd],
    kernel: &crate::identity::SpawnKernel,
) -> Result<PreparedMarker, Error> {
    let failed = |detail: &str, source: Option<std::io::Error>| Error::Containment {
        detail: detail.to_owned(),
        source: source.map(Error::io_cause),
    };
    let (read, write) = match create_pipe() {
        Ok(p) => p,
        Err(e) => return Err(failed("fd marker: pipe() failed", Some(e))),
    };

    // A supervisor whose soft RLIMIT_NOFILE sits below `want` (HIGH_FLOOR=64 in the common
    // case, or higher with a large reserved set) makes F_DUPFD_CLOEXEC fail EINVAL here on
    // EVERY contained spawn, not just an occasional one — diagnosable from the error alone,
    // since `nix::errno::Errno`'s `Display` names the symbolic errno (e.g. "EINVAL: Invalid
    // argument"), not just a bare OS error number.
    let want = safe_marker_fd(write.as_fd().as_raw_fd(), reserved);
    let write: OwnedFd = match place_write_end(write, want) {
        Ok(fd) => fd,
        Err(e) => {
            return Err(failed(
                "fd marker: could not place the marker descriptor",
                Some(e.into()),
            ))
        }
    };
    let fd = write.as_raw_fd();
    // CONTRACT: `place_write_end` used `F_DUPFD_CLOEXEC`, which must place the copy WITH
    // FD_CLOEXEC set — the supervisor's own copy staying CLOEXEC (so no concurrent, unrelated
    // fork can inherit it into an exec'd image) is a documented safety property this whole
    // design leans on, not an incidental detail. Asserted, not just documented: a future
    // refactor that swaps in a non-CLOEXEC placement call must fail loudly in a debug/test
    // build, not silently in release.
    // SAFETY: F_GETFD is a plain fcntl read, no allocation.
    debug_assert!(
        unsafe { libc::fcntl(fd, libc::F_GETFD) } & libc::FD_CLOEXEC != 0,
        "the marker's supervisor-side write-end copy must be FD_CLOEXEC"
    );

    let Some(handle) = read_handle(write.as_fd()) else {
        return Err(failed("fd marker: the marker pipe has no readable handle", None));
    };
    // CONTRACT: `handle == 0` must never reach a live `Marker` — 0 is the sentinel this whole
    // mechanism treats as "matches no live pipe" (see `a_dead_handle_finds_no_holders`'s doc
    // comment: 0 is never a valid `pipe_handle` and cannot become one through any amount of
    // churn). If `proc_pidfdinfo` ever DID hand back 0 for a real, live pipe here, installing
    // it anyway would make `Marker.handle == 0` — the one value documented to match NOTHING —
    // instead match the WIDEST possible set: every host pid whose own unrelated pipe fds
    // happen to read back the same sentinel. Rejected as a failed install, exactly like the
    // other two `install()` failure arms, rather than trusted silently.
    if handle == 0 {
        debug_assert!(
            false,
            "fd marker: pipe_handle_of the write end returned 0, the reserved sentinel"
        );
        return Err(failed(
            "fd marker: the marker pipe's write end reported a zero handle",
            None,
        ));
    }
    // CONTRACT, checked HERE specifically because both ends are provably still open (unlike
    // at `Marker::sweep` time, where the write side may already be fully drained — see there):
    // `read` must pin the SAME kernel pipe object `handle` names. The measured invariant
    // (facts C/E) this whole mechanism rests on is exactly "holding a live descriptor on this
    // pipe keeps `handle` from being reissued", and that is only true if `read` really is a
    // descriptor on THIS pipe, not assumed from having called `create_pipe()` moments earlier.
    debug_assert!(
        matches!(
            fd_pipe_info(std::process::id(), read.as_raw_fd()),
            FdPipeInfoQuery::Found(info) if info.pipe_peerhandle == handle
        ),
        "the marker's read end must report the write end's handle as its peer"
    );
    // `read`'s OWN handle (a distinct kernel object from `handle` — see `PreparedMarker::
    // read_handle`'s doc comment for why `Marker` needs this instead of re-deriving a peer
    // check later): captured now, while it is certain to succeed, rather than assumed later.
    let Some(read_handle_value) = pipe_handle_of(read.as_fd()) else {
        return Err(failed(
            "fd marker: the marker pipe's read end has no readable handle",
            None,
        ));
    };
    // Same CONTRACT as the write end's handle above, and for the identical reason:
    // `Marker::sweep`'s entry check compares a LIVE read against this exact value, so a zero
    // here would make that check accept any other pipe descriptor that also happens to report
    // a zero handle, defeating the whole point of the entry contract.
    if read_handle_value == 0 {
        debug_assert!(
            false,
            "fd marker: pipe_handle_of the read end returned 0, the reserved sentinel"
        );
        return Err(failed(
            "fd marker: the marker pipe's read end reported a zero handle",
            None,
        ));
    }

    steps.preserve(write);
    Ok(PreparedMarker {
        read: OwnedFd::from(read),
        handle,
        read_handle: read_handle_value,
        fd,
        kernel: std::sync::Arc::clone(kernel),
    })
}

// Fault-seam wrappers: each is the ONE place `install`'s corresponding real syscall is called,
// so the `#[cfg(test)]` injection is visibly separated from `install`'s own control flow rather
// than interleaved with it. Each takes the SAME `fault::take_fault()` value implicitly (via its
// own `#[cfg(test)]` check) — see the `fault` module doc for why exactly one of the three fires
// per test, never more.

/// The caller holds `spawn_lock` on macOS: `containment::prepare` runs inside a spawn's lock.
fn create_pipe() -> std::io::Result<(std::io::PipeReader, std::io::PipeWriter)> {
    #[cfg(test)]
    if fault::take_if(fault::Fault::Pipe) {
        return Err(std::io::Error::from_raw_os_error(libc::EMFILE));
    }
    crate::pipe::pair()
}

fn place_write_end(write: std::io::PipeWriter, want: RawFd) -> Result<OwnedFd, nix::errno::Errno> {
    #[cfg(test)]
    if fault::take_if(fault::Fault::Place) {
        return Err(nix::errno::Errno::EMFILE);
    }
    let placed = nix::fcntl::fcntl(write.as_fd(), nix::fcntl::FcntlArg::F_DUPFD_CLOEXEC(want))?;
    // CONTRACT: POSIX guarantees `F_DUPFD_CLOEXEC(want)` returns a descriptor `>= want`, which
    // is the ENTIRE reason `safe_marker_fd` exists (clearing every reserved child fd and the
    // shell-redirection range). Asserted, not just relied on, so a libc/kernel surprise on this
    // platform would fail loudly here rather than resurface as an inexplicable containment
    // escape much later.
    debug_assert!(
        placed >= want,
        "F_DUPFD_CLOEXEC({want}) returned {placed}, below the floor it was given"
    );
    // SAFETY: F_DUPFD_CLOEXEC returned a fresh descriptor we now own.
    Ok(unsafe { OwnedFd::from_raw_fd(placed) })
}

fn read_handle(fd: BorrowedFd<'_>) -> Option<u64> {
    #[cfg(test)]
    if fault::take_if(fault::Fault::Handle) {
        return None;
    }
    pipe_handle_of(fd)
}

/// Test-only: force the NEXT `install` on THIS thread to take one of its real failure arms, by
/// replacing that step's syscall result. `take_if` is what each fault-seam wrapper above
/// actually calls: it consumes the armed fault ONLY if it matches `want`, leaving it untouched
/// (for a DIFFERENT wrapper's own check) otherwise — so exactly one of the three wrappers in
/// one `install` call ever sees a match, matching the single-fault-per-call contract
/// `each_install_failure_arm_fails_and_says_which_step_failed` relies on.
#[cfg(test)]
pub(crate) mod fault {
    use std::cell::Cell;

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) enum Fault {
        Pipe,
        Place,
        Handle,
    }

    thread_local! {
        static FAULT: Cell<Option<Fault>> = const { Cell::new(None) };
    }

    pub(crate) fn set_fault(f: Option<Fault>) {
        FAULT.with(|c| c.set(f));
    }

    /// True and CONSUMED if the armed fault is exactly `want`; false and left untouched
    /// otherwise.
    pub(crate) fn take_if(want: Fault) -> bool {
        FAULT.with(|c| {
            if c.get() == Some(want) {
                c.set(None);
                true
            } else {
                false
            }
        })
    }

    pub(crate) fn take_fault() -> Option<Fault> {
        FAULT.with(|c| c.take())
    }

    // Test-only: force the NEXT `sweep` on THIS thread to skip the root's identity kill
    // (makes the `kill_tree` handle backstop forcible). Take semantics: `sweep` consumes the
    // flag — arm and call on one thread; assert consumption via `armed`. Mirrors
    // `treewalk::fault::set_force_root_kill_noop`/`take_force_root_kill_noop`/`armed`, which
    // this module's `sweep` does NOT go through (it calls `treewalk::kill_by_identity`
    // directly, not `treewalk::hard_kill`), hence a separate seam here.
    thread_local! {
        static FORCE_ROOT_KILL_NOOP: Cell<bool> = const { Cell::new(false) };
    }

    pub(crate) fn set_force_root_kill_noop(on: bool) {
        FORCE_ROOT_KILL_NOOP.with(|f| f.set(on));
    }

    pub(crate) fn take_force_root_kill_noop() -> bool {
        FORCE_ROOT_KILL_NOOP.with(|f| f.replace(false))
    }

    pub(crate) fn armed() -> bool {
        FORCE_ROOT_KILL_NOOP.with(|f| f.get())
    }

    type HolderSignal = (u32, nix::sys::signal::Signal);

    thread_local! {
        static HOLDER_KILLS: std::cell::RefCell<Option<Vec<HolderSignal>>> = const { std::cell::RefCell::new(None) };
    }

    /// From now on `kill_holder` on THIS thread records each marker holder it signals, and the
    /// signal, so a test can tell that the sweep ran without waiting for a process to die.
    pub(crate) fn record_holder_kills() -> HolderKillRecorder {
        HOLDER_KILLS.with(|k| *k.borrow_mut() = Some(Vec::new()));
        HolderKillRecorder(())
    }

    #[must_use = "recording stops as soon as the recorder is dropped"]
    pub(crate) struct HolderKillRecorder(());

    impl HolderKillRecorder {
        pub(crate) fn killed(&self) -> Vec<u32> {
            self.sent().into_iter().map(|(pid, _)| pid).collect()
        }

        /// The signals sent to `pid`, in order.
        pub(crate) fn signals_to(&self, pid: u32) -> Vec<nix::sys::signal::Signal> {
            self.sent()
                .into_iter()
                .filter_map(|(to, signal)| (to == pid).then_some(signal))
                .collect()
        }

        fn sent(&self) -> Vec<HolderSignal> {
            HOLDER_KILLS.with(|k| k.borrow().clone().expect("the recorder is live"))
        }
    }

    impl Drop for HolderKillRecorder {
        fn drop(&mut self) {
            HOLDER_KILLS.with(|k| *k.borrow_mut() = None);
        }
    }

    /// The holders signalled so far under a live [`record_holder_kills`], for a hook that cannot
    /// borrow the recorder.
    pub(crate) fn holder_kills_so_far() -> Vec<u32> {
        HOLDER_KILLS
            .with(|k| k.borrow().clone().expect("a recorder is live"))
            .into_iter()
            .map(|(pid, _)| pid)
            .collect()
    }

    pub(super) fn note_holder_kill(pid: u32, signal: nix::sys::signal::Signal) {
        HOLDER_KILLS.with(|k| {
            if let Some(killed) = k.borrow_mut().as_mut() {
                killed.push((pid, signal));
            }
        });
    }

    /// The fallback line `prepare` logs for a failed `install` (`"fd marker: pipe() failed"`, etc.)
    /// carries no per-call discriminator — there is no handle yet to key on, since `install` hasn't
    /// succeeded. A test asserting on that literal text via `log_capture` (`dispatch_tests.rs`'s
    /// `a_failed_marker_install_leaves_prepare_without_one_unless_strongest`) could otherwise be
    /// satisfied by another test's fallback (`unpinned_public_tests.rs`'s `degraded_blocker`) when
    /// trials overlap, since `log_capture` is one process-global buffer. Trials overlap only under
    /// `--nocapture` with `--test-threads` > 1 (skuld forces one thread while capturing;
    /// nextest runs each test in its own process). `FAULT` itself is thread-local (race-free), but the LOG ASSERTION is not, so both
    /// must hold this for their whole body instead.
    static LOG_SERIALIZE: std::sync::Mutex<()> = std::sync::Mutex::new(());

    pub(crate) fn lock_for_log_assertion() -> std::sync::MutexGuard<'static, ()> {
        LOG_SERIALIZE.lock().unwrap_or_else(|e| e.into_inner())
    }
}

// The attached mechanism =====

use std::io;

use crate::containment::dispatch::{TreeKillOutcome, Unkilled};
use crate::containment::drain_edge::DrainEdge;
use crate::containment::mechanism::{Contains, Release};
use crate::containment::root::NumberLook;
use crate::containment::sweep_passes::run_passes;
use crate::containment::treewalk::{KillOutcome, Listing};
use crate::containment::{Containment, Root, Skip, TerminateOutcome, TreeKill, Why};
use crate::error::Error;
use crate::identity::{ProcessId, Resolved};

/// What a sweep may do.
#[derive(Clone, Copy)]
enum Scope<'r> {
    /// Every channel: the group, the root's number, the ppid walk and the marker holders. The group
    /// is signalled as `root` allows.
    Full(Option<&'r dyn Root>),
    /// The marker holders alone, for a root whose number names no one reliably any more. `except`
    /// is a holder to leave alone: the root, when this process does not pin it.
    HoldersOnly { except: Option<ProcessId> },
}

/// What a sweep carries from one pass to the next ([`Marker::sweep_pass`]).
struct SweepState<'k> {
    /// The identities passes have found and resolved (an `except` holder and an unresolvable one are
    /// looked at again each pass), so no later pass counts or signals one again:
    /// the count that ends the sweep ([`run_passes`]) depends on it.
    seen: std::collections::HashSet<ProcessId>,
    /// The group signals' result across passes: a later pass's success does not erase an earlier
    /// failure, and two failures fold together (`combine_group_errors`).
    group_result: Result<(), Error>,
    /// Whether a cooperative group signal went unsent: its failure is in `group_result`, and the pass went
    /// on through the other channels.
    group_unsent: bool,
    /// Whether any signal reached a member by identity or a marker holder.
    delivered: bool,
    /// Whether any pass was blind, any holder could not be resolved, or any signal was refused: checked
    /// once, by `finish_sweep`, whichever pass it happened on.
    incomplete: bool,
    /// The members a `SIGKILL` reached, for the wait after the kill.
    killed: &'k mut Vec<ProcessId>,
}

impl<'k> SweepState<'k> {
    fn new(killed: &'k mut Vec<ProcessId>) -> SweepState<'k> {
        SweepState {
            seen: std::collections::HashSet::new(),
            group_result: Ok(()),
            group_unsent: false,
            delivered: false,
            incomplete: false,
            killed,
        }
    }

    /// Folds the outcome of a kill of `id` by identity into the sweep, for a walk member and a marker
    /// holder alike. [`KillOutcome::NotAttempted`] means the OS refused to query or signal an identity
    /// that was resolved: a known member left running, not a gap in discovery, so the sweep is
    /// `incomplete`, and it is not retried (see [`Marker::sweep_pass`]). Any delivered signal is
    /// `delivered`; only a delivered `SIGKILL` adds `id` to `killed` (the members the kill's wait waits
    /// for), and only when `waited_for` (the root's owner waits for the root).
    fn record(&mut self, id: ProcessId, signal: nix::sys::signal::Signal, outcome: &KillOutcome, waited_for: bool) {
        match outcome {
            KillOutcome::Terminated => {
                self.delivered = true;
                if waited_for && signal == nix::sys::signal::Signal::SIGKILL {
                    self.killed.push(id);
                }
            }
            KillOutcome::NotAttempted(_) => self.incomplete = true,
            KillOutcome::AlreadyGone => {}
        }
    }
}

/// The live marker for one contained tree.
pub(crate) struct Marker {
    /// Held for the mechanism's whole life. See the module docs: this is what stops `handle`
    /// from being re-issued to an unrelated pipe once the tree drains.
    read: OwnedFd,
    /// See `PreparedMarker::kernel`.
    kernel: crate::identity::SpawnKernel,
    handle: u64,
    /// `read`'s OWN handle, captured at `install()` time — see `PreparedMarker::read_handle`'s
    /// doc comment. What `sweep`'s entry contract re-checks against `read` at signal time.
    read_handle: u64,
    /// The root's identity, for the ppid-walk channel: the one the spawn verified against the
    /// child's handle, never a read by pid at attach. `None` only for a marker made by
    /// [`without_root`](Marker::without_root), which sweeps its holders alone.
    root: Option<ProcessId>,
    /// The root's process group, when the requested mode created one. `None` for TreeWalk.
    pgid: Option<i32>,
    /// The descriptor number the marker occupies in the child, copied from
    /// `PreparedMarker::fd`. Exposed to this crate's OWN integration tests (`tests/*.rs`) via
    /// `Child::test_fdmarker_fd`, so a test can be TOLD the exact fd rather than inferring it
    /// from ambient process state (see `tests/macos_fdmarker.rs`'s
    /// `holders_and_folds_cloexec_across_a_holder_with_a_mixed_copy`, and the CI failure that
    /// motivated it, #59).
    own_fd: RawFd,
}

impl std::fmt::Debug for Marker {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Marker")
            .field("handle", &format_args!("{:#x}", self.handle))
            .field("pgid", &self.pgid)
            .finish_non_exhaustive()
    }
}

impl Contains for Marker {
    /// No drain edge is named: the marker pipe's EOF waits for holders the kill never reached, so the
    /// wait is for the identities the sweep killed.
    fn kill(&self, root: Option<&dyn Root>) -> TreeKill<'_> {
        self.kill_tree(root)
    }

    fn send_terminate(&self, _pid: u32, root: Option<&dyn Root>) -> (TerminateOutcome, Option<Listing>) {
        (self.terminate_tree(root), None)
    }

    /// The marker pipe's EOF, advisory: see [`TreeDrain`](crate::containment::TreeDrain).
    fn drain_edge(&self) -> Option<DrainEdge<'_>> {
        Some(DrainEdge::Marker(self))
    }

    fn kind(&self) -> Containment {
        Containment::FdMarker
    }

    /// Dropping the read end kills nothing.
    fn disarm(&self) -> io::Result<()> {
        Ok(())
    }

    fn subject(&self) -> String {
        format!("FdMarker({self:?})")
    }

    /// A signal to a marker's holders is subject to the kernel's permission check, as the child's own
    /// kill is.
    fn would_reach(&self, _pid: u32, _pidfd: Option<BorrowedFd<'_>>) -> Result<bool, crate::error::Error> {
        Ok(false)
    }

    fn reached(&self, _child: &crate::child::owned::OwnedChild) -> Result<bool, crate::error::Error> {
        Ok(false)
    }

    /// The marker's read end closes with the release.
    fn release(self) -> (Release, Option<Marker>) {
        (Release::nothing(), None)
    }
}

/// Whether a swept pid may be signalled at all. The supervisor is excluded because signalling
/// itself would tear down the caller; pid 0 and pid 1 because neither is ever a tree member
/// and `kill(0, …)` signals the caller's whole process group.
pub(crate) fn is_signalable(pid: RawPid) -> bool {
    pid > 1 && pid != std::process::id()
}

/// Whether `pid`, right now, is a live member of process group `pgid` — the group-signal
/// re-fire gate's anchor (see `Marker::sweep_pass`'s doc for the full argument for why this,
/// and not the root's own identity, is what a later pass checks). `getpgid` fails (`ESRCH`) for
/// a pid that no longer exists, so a successful, matching call is itself the liveness proof; no
/// separate `is_alive()` check is needed or wanted.
fn pid_is_live_group_member(pid: RawPid, pgid: i32) -> bool {
    debug_assert!(
        pid <= i32::MAX as u32,
        "pid {pid} exceeds i32::MAX; pgid comparison would truncate"
    );
    nix::unistd::getpgid(Some(nix::unistd::Pid::from_raw(pid as i32)))
        .map(|g| g.as_raw() == pgid)
        .unwrap_or(false)
}

/// Fold two `Error`s (the `incomplete` summary and a group signal's failure) into one: both are kept
/// whole as an [`Error::Several`], the `source` of the merged error. [`Error::Containment`] when
/// either side is one (the mechanism could not tear the tree down, as its doc says), else
/// [`Error::Unassessable`].
fn combine_group_errors(first: Error, latest: Error) -> Error {
    let containment = matches!(first, Error::Containment { .. }) || matches!(latest, Error::Containment { .. });
    let detail = "the teardown failed in more than one way".to_owned();
    let source =
        Some(crate::error::Failures::new(std::sync::Arc::new(first), [std::sync::Arc::new(latest)]).into_cause());
    if containment {
        Error::Containment { detail, source }
    } else {
        Error::Unassessable { detail, source }
    }
}

impl Marker {
    pub(crate) fn new(prepared: PreparedMarker, root: ProcessId, pgid: Option<i32>) -> Marker {
        Marker {
            read: prepared.read,
            kernel: prepared.kernel,
            handle: prepared.handle,
            read_handle: prepared.read_handle,
            root: Some(root),
            pgid,
            own_fd: prepared.fd,
        }
    }

    /// The marker of a root that is not shown to be this process's child: no channel that names the
    /// tree by the root's number may run, so its kill sweeps its holders alone
    /// ([`kill_tree`](Self::kill_tree)).
    pub(crate) fn without_root(prepared: PreparedMarker) -> Marker {
        Marker {
            read: prepared.read,
            kernel: prepared.kernel,
            handle: prepared.handle,
            read_handle: prepared.read_handle,
            root: None,
            pgid: None,
            own_fd: prepared.fd,
        }
    }

    #[cfg_attr(
        not(test),
        allow(dead_code, reason = "consumed by Child::test_marker_handle (test-only)")
    )]
    pub(crate) fn handle(&self) -> u64 {
        self.handle
    }

    /// The descriptor number the marker occupies in the child. Consumed by
    /// `Child::test_fdmarker_fd`, this crate's own `#[doc(hidden)]` test-only accessor for
    /// `tests/*.rs` (see `own_fd`'s doc comment for why this exists).
    pub(crate) fn own_fd(&self) -> RawFd {
        self.own_fd
    }

    /// The root the ppid walk starts from; `None` for a marker made [`without_root`](Self::without_root).
    #[cfg(test)]
    pub(crate) fn root(&self) -> Option<ProcessId> {
        self.root
    }

    /// The group `killpg` targets, if this mode created one.
    #[cfg(test)]
    pub(crate) fn pgid(&self) -> Option<i32> {
        self.pgid
    }

    /// Test-only: force the group channel's pgid, to drive `unix::signal_group`'s real
    /// `pgid <= 0` guard — a real, privilege-free `Error::Unassessable { source: None, .. }`
    /// path — deterministically through the REAL public `Child::kill_tree`/`Drop` path.
    /// Consumed by `Child::test_force_fdmarker_pgid` (`src/child.rs`), which is what a test
    /// outside this module actually calls; see its doc for why this exists.
    #[cfg(test)]
    pub(crate) fn force_pgid_for_test(&mut self, pgid: i32) {
        self.pgid = Some(pgid);
    }

    /// The supervisor's read end. `read()` on it returns EOF exactly when the last holder of
    /// the write end is gone.
    pub(crate) fn read_end(&self) -> BorrowedFd<'_> {
        self.read.as_fd()
    }

    /// Block until every holder of the marker's write end has EXITED (not reaped), or until
    /// `deadline` — see `marker_eof::block_until_drained`'s own doc for what `deadline` means
    /// and what it guarantees.
    ///
    /// Calls [`check_read_end_still_valid`](Self::check_read_end_still_valid) FIRST, exactly
    /// like `hard_kill`/`terminate` do: `marker_eof::block_until_drained` takes a bare
    /// `BorrowedFd` and has no way to know it is still the SAME kernel object `self` was built
    /// around, only that the number is still open. Skipping this check here would let a
    /// reissued fd (an unrelated pipe with no open write end) deliver `EV_EOF` immediately and
    /// report `AllMembersExited` for a fully live tree — the same false-edge risk `hard_kill`
    /// refuses on, not merely a discrepancy between two code paths.
    pub(crate) fn wait_drained(&self, deadline: Option<Instant>) -> Result<crate::containment::TreeDrain, Error> {
        self.check_read_end_still_valid()?;
        // This process is the supervisor: it must have closed its own copy of the write end at
        // spawn time (`install`'s contract), or the edge could never fire. A deliberately
        // constructed `HeldByUs` condition still needs a real `Err`, not a panic, so the
        // enforcement lives in `refuse_if_write_end_held`'s `Err` return, not here; this assert
        // instead catches a violation of that contract reaching THIS, the crate's own call
        // site, in debug builds — the crate's own code path, not a test deliberately
        // constructing the condition.
        debug_assert_ne!(
            crate::containment::marker_eof::write_end_check(self.read_end()),
            crate::containment::marker_eof::WriteEndCheck::HeldByUs,
            "the supervisor still holds a copy of the marker write end - the tree-drain edge can never fire"
        );
        crate::containment::marker_eof::block_until_drained(self.read_end(), deadline)
    }

    /// `Err` is [`Error::Containment`] when a live member refused the signal, and
    /// [`Error::Unassessable`] when a member could not be fully assessed or reached. Same distinction as
    /// `ProcessGroup`/`Session` `verify`.
    fn hard_kill(&self, root: Option<&dyn Root>, killed: &mut Vec<ProcessId>) -> Result<(), Error> {
        self.hard_kill_impl(Scope::Full(root), killed)
    }

    /// What `look` at `root` (`None` for a marker made [`without_root`](Self::without_root), whose
    /// tree is its holders alone) lets this marker send by the root's number. The `killpg` on
    /// `self.pgid`, the root's identity kill and the ppid walk from the root's pid all name their
    /// target by that number, which may belong to an unrelated process once the root is reaped or
    /// not pinned, so then none runs: only the marker holders, which the kernel names by the pipe
    /// they hold, are signalled. `except` is a holder to leave alone: the root, when this process
    /// does not pin it (launchd holds it), because signalling a process by a pid this process does
    /// not pin can hit whoever reuses the pid.
    fn look_at(&self, root: Option<&dyn Root>) -> Option<(NumberLook, Option<ProcessId>)> {
        let (Some(_), Some(root)) = (self.root, root) else {
            return None;
        };
        let look = crate::containment::root::look(root);
        #[cfg(test)]
        crate::graceful_hooks::run_hook(crate::graceful_hooks::HookPoint::AfterRootLook);
        let except = match &look {
            NumberLook::Untrusted(crate::signal::RootState::Unpinned) => self.root,
            _ => None,
        };
        Some((look, except))
    }

    /// What this marker's channels by the root's number are, as an action for a message.
    fn number_named(&self, verb: &str, root_pid: u32) -> String {
        let walk = format!("walk the process table from the root's pid (root pid {root_pid})");
        match self.pgid {
            Some(pgid) => format!("{verb} its process group (pgid {pgid}) or {walk}"),
            None => walk,
        }
    }

    /// What this marker skipped, and why, for `look`: its holders' own signal, `holders`, was sent.
    fn skip(&self, verb: &str, root_pid: u32, look: NumberLook, holders: Result<(), Error>) -> Skip {
        let why = match look {
            NumberLook::Untrusted(state) => Why::untrusted(&state),
            NumberLook::MayNameAnother { refusal, probe, .. } => Why::MayNameAnother(refusal, probe),
            NumberLook::Trusted | NumberLook::GroupGone => {
                unreachable!("a send that is not skipped has no skip to say")
            }
        };
        Skip {
            action: self.number_named(verb, root_pid),
            why,
            root_alone: false,
            holders: Some(holders),
        }
    }

    /// The marker's kill, decided on one look at `root` (see [`look_at`](Self::look_at)): every channel
    /// while the root's number names the root; the holders alone, with the rest skipped
    /// ([`TreeKillOutcome::Skipped`]), when the number may name another process or the root is
    /// `Unpinned` or `Unknown`.
    pub(crate) fn kill_tree<'a>(&self, root: Option<&dyn Root>) -> TreeKill<'a> {
        let ran = |sent: Result<(), Error>| sent.map_err(Unkilled::from);
        let mut killed = Vec::new();
        let outcome = match self.look_at(root) {
            // No look to take: without its root only the holders are the tree.
            None => match self.root {
                None => TreeKillOutcome::Ran(ran(
                    self.hard_kill_impl(Scope::HoldersOnly { except: None }, &mut killed)
                )),
                Some(_) => {
                    debug_assert!(false, "a marker with a root was given no root to look at");
                    TreeKillOutcome::Ran(ran(self.hard_kill(root, &mut killed)))
                }
            },
            Some((look, except)) => {
                let root_pid = root.map_or(0, Root::pid);
                match look {
                    NumberLook::Trusted => TreeKillOutcome::Ran(ran(self.hard_kill(root, &mut killed))),
                    look => TreeKillOutcome::Skipped(self.skip(
                        "kill",
                        root_pid,
                        look,
                        self.hard_kill_impl(Scope::HoldersOnly { except }, &mut killed),
                    )),
                }
            }
        };
        TreeKill::of(outcome).reaching(killed)
    }

    fn hard_kill_impl(&self, scope: Scope<'_>, killed: &mut Vec<ProcessId>) -> Result<(), Error> {
        self.check_read_end_still_valid()?;
        // Carries across every pass: an earlier pass's group failure is kept, and `incomplete`
        // stays set whichever pass set it.
        let mut state = SweepState::new(killed);
        // Re-snapshots and re-computes after every pass, repeating while `run_passes` says another
        // pass is needed — no numeric cap (forbidden by this crate's no-arbitrary-loop-limit
        // rule).
        let still_forking =
            run_passes(|pass| self.sweep_pass(nix::sys::signal::Signal::SIGKILL, &mut state, pass == 1, scope));
        Self::finish_sweep(self.handle, state.group_result, state.incomplete, still_forking)
    }

    /// See [`hard_kill`](Self::hard_kill)'s doc for what `Err` does and does not mean here, and
    /// `sweep_pass`'s doc for the shared per-pass mechanics. Unlike `hard_kill`, this never
    /// loops: SIGTERM is catchable and ignorable, so a re-snapshot loop could spin forever
    /// against a member that traps it and keeps forking on every delivery, hanging
    /// `terminate_tree()` — a blocking API with no timeout — forever. One pass, matching
    /// `term_group`'s own cooperative, best-effort contract; `hard_kill` (`kill_tree`) is the
    /// guaranteed sweep.
    fn terminate(&self, root: Option<&dyn Root>) -> Result<Result<(), Error>, Error> {
        self.terminate_impl(Scope::Full(root))
    }

    /// The marker's cooperative signal as a tree call decides it, on one look at `root`
    /// ([`kill_tree`](Self::kill_tree)): the holders alone get it when the root's number names no
    /// one, and then, once the number may name another process, the caller waits the grace and
    /// kills any left ([`TerminateOutcome::HoldersOnly`]). A signal never sent is
    /// [`TerminateOutcome::NotSent`].
    pub(crate) fn terminate_tree(&self, root: Option<&dyn Root>) -> TerminateOutcome {
        let holders_only = |except| self.terminate_impl(Scope::HoldersOnly { except });
        let earlier = Some("the SIGTERM");
        let Some((look, except)) = self.look_at(root) else {
            let result = match self.root {
                None => holders_only(None),
                Some(_) => {
                    debug_assert!(false, "a marker with a root was given no root to look at");
                    self.terminate(root)
                }
            };
            return TerminateOutcome::of(result, earlier);
        };
        let root_pid = root.map_or(0, Root::pid);
        match look {
            NumberLook::Trusted => TerminateOutcome::of(self.terminate(root), earlier),
            NumberLook::Untrusted(_) => TerminateOutcome::of(holders_only(except), earlier),
            look => match holders_only(None) {
                Ok(result) => TerminateOutcome::HoldersOnly(self.skip("signal", root_pid, look, result)),
                Err(not_sent) => TerminateOutcome::NotSent(not_sent),
            },
        }
    }

    /// One `SIGTERM` pass of `scope`: `Err` is a signal never sent (a read end that no longer names
    /// its pipe, or a group that cannot be signalled while no other channel sent anything), `Ok` what
    /// the pass found. A group that cannot be signalled is one failed channel: when another channel
    /// sent, its failure is among what the pass found.
    fn terminate_impl(&self, scope: Scope<'_>) -> Result<Result<(), Error>, Error> {
        self.check_read_end_still_valid()?;
        // A `SIGTERM` is not a kill: nothing it reaches is waited for.
        let mut reached = Vec::new();
        let mut state = SweepState::new(&mut reached);
        self.sweep_pass(nix::sys::signal::Signal::SIGTERM, &mut state, true, scope);
        let swept = Self::finish_sweep(self.handle, state.group_result, state.incomplete, false);
        match swept {
            // Nothing was sent: the group's failure and the members that refused or could not be assessed
            // are all `finish_sweep` found.
            Err(unsent) if state.group_unsent && !state.delivered => Err(unsent),
            swept => Ok(swept),
        }
    }

    /// CONTRACT, re-checked on every `hard_kill`/`terminate` call, not just at `Marker::new`
    /// time: `self.read` must STILL be a pipe descriptor naming its OWN recorded handle. Rust
    /// ownership already makes "a sweep cannot run after `self.read` is dropped" a compile error
    /// (both callers borrow `&self`), but that only proves the FD IS STILL OPEN, not that it
    /// still names the SAME kernel object.
    ///
    /// This checks `read`'s OWN handle (`self.read_handle`), NOT its peer's — a peer check
    /// is wrong here and was measured to be wrong: once the LAST write end anywhere closes
    /// (the ordinary, ROUTINE case — the tree drained before `Child::drop` swept it, which
    /// is exactly what `hard_kill_never_reaches_a_pid_that_closed_the_marker_before_the_
    /// sweep` exercises), the read end's PEER handle reports `0` while the read end's OWN
    /// handle stays valid for as long as `read` itself stays open. A peer check here would
    /// fire on that ordinary path; `install()`'s peer check (both ends provably open then)
    /// is where that check belongs, not here.
    ///
    /// **This is not an ordinary internal-consistency assertion, so it is not `debug_assert!`
    /// -only.** Its documented failure mode is the worst outcome this whole design exists to
    /// prevent: a stale `read_handle` means `self.handle`/`self.read_handle` could now name
    /// ANY unrelated live pipe the OS has reissued the identity onto, and `holders()`
    /// matching by raw handle equality would then confirm-and-SIGKILL a stranger with no
    /// indication anything was wrong. A single debug-only line is not enough defense for that
    /// severity; it is checked in EVERY build, and a violation refuses to sweep at all rather
    /// than proceeding on a handle that may no longer mean what `self` claims.
    ///
    /// `pub(crate)`: also called from `DrainEdge::wait_async` (`containment/drain_edge.rs`) before
    /// it reads `self.read`'s raw fd directly, for the same reason — a reissued fd there would
    /// falsely report `EV_EOF` just as readily as it would here.
    pub(crate) fn check_read_end_still_valid(&self) -> Result<(), Error> {
        let read_still_valid = matches!(
            fd_pipe_info(std::process::id(), self.read.as_raw_fd()),
            FdPipeInfoQuery::Found(info) if info.pipe_handle == self.read_handle
        );
        debug_assert!(
            read_still_valid,
            "fd marker {:#x}: the read end must still be the same pipe object at sweep time",
            self.handle
        );
        if !read_still_valid {
            let msg = format!(
                "fd marker {:#x}: the read end no longer names its recorded pipe object at \
                 sweep entry — refusing to sweep rather than signal against a handle that may \
                 now name an unrelated live pipe",
                self.handle
            );
            log::error!("{msg}");
            // This process's own bookkeeping is stale, not a member's refusal.
            return Err(Error::Containment {
                detail: msg,
                source: None,
            });
        }
        Ok(())
    }

    /// One pass of `hard_kill`/`terminate`: snapshot, compute, signal. Three membership
    /// channels, deduplicated across the whole sweep (via `seen`, carried by the caller across
    /// passes) by IDENTITY, not raw pid — a pid signalled and reaped on one pass can be
    /// recycled by the OS onto a genuinely new fork of a still-live tree member before the next
    /// pass's snapshot, and deduping on the raw pid would then skip that new, never-signalled
    /// process, reintroducing the exact pid-reuse ambiguity `kill_by_identity` exists to close,
    /// one layer up. Resolving identity for a marker-channel candidate happens HERE, at
    /// discovery, not deferred to `kill_holder` — `kill_holder` still re-verifies at signal time
    /// (the window between discovery and signal, not between passes).
    ///
    /// Returns how many identities this pass found that no earlier pass of the sweep had seen
    /// (`new_walk` and `new_holders`; on pass 1 that includes the root and the members still
    /// visible). `hard_kill` loops on it through
    /// [`run_passes`](crate::containment::sweep_passes::run_passes), which is pure.
    ///
    /// **Termination.** The sweep stops on a count that does not fall; the rule and why are in
    /// [`after_pass`](crate::containment::sweep_passes::after_pass). Processes forked during the
    /// last pass may be left running, and `finish_sweep` says so.
    ///
    /// **A single snapshot-compute-signal pass has a check-then-act gap a real tree can hit.**
    /// Between the snapshot and the signal, any live member can `fork` a child that inherits the
    /// marker; that child is in no channel of THIS pass (its ppid edge postdates `parents`, it
    /// isn't in `pids`, and if its parent already left the group it isn't reachable by `killpg`
    /// either). If the parent is then killed, the child reparents to launchd and is lost for
    /// good — precisely the escapee class this mechanism exists to close. `hard_kill`'s
    /// re-snapshot loop is what closes it, over repeated passes; a single `terminate` pass
    /// accepts this gap, matching `term_group`'s own cooperative, non-chasing contract.
    ///
    /// **A blind pass, an unresolvable holder, and a refused signal are all real teardown gaps
    /// — none of them is convergence, and NONE of them may be reported as `Ok(())`.**
    /// `enumerate::snapshot()` returns an empty pid list on its own internal failure (logged
    /// there) — never on a genuinely converged pass (there is always at least launchd and this
    /// process on a real host). Neither the root (`self.root`, already a resolved `ProcessId`)
    /// nor the process group (`self.pgid`, a plain integer) needs a snapshot, so a blind FIRST
    /// pass still attempts both: the root is not yet in `seen`, and pass 1's group signal fires
    /// unconditionally. A blind LATER pass attempts NEITHER: the root is already in `seen` (see
    /// below), and the group signal's re-fire gate needs THIS pass's own holder scan to confirm
    /// a live member — a scan a blind pass never ran. "Not observed" is not "observed absent",
    /// and this function's log messages say so explicitly rather than crediting a channel with
    /// running when it could not have; `*incomplete = true` is what keeps `finish_sweep` from
    /// reporting `Ok(())` regardless. A marker-holder pid that resolves `Resolved::Unknown`
    /// (access denied), a `MarkerQuery::Denied` re-check, and a `kill_by_identity`/`kill_holder`
    /// outcome of `KillOutcome::NotAttempted` (the OS refused to query or signal an identity
    /// that WAS resolved), are each a known member this pass could not verify or reach; the
    /// caller folds every one of them into the same `incomplete` flag, checked exactly once by
    /// `finish_sweep`.
    ///
    /// A `NotAttempted` identity is NOT retried on a later pass — retrying would hit the same OS
    /// refusal again — but it IS already in `seen`, so it does not re-enter `new_walk`/
    /// `new_holders` either; it is simply left running, logged, and folded into `incomplete`,
    /// the same disposition `treewalk::hard_kill`'s single pass already gives it. The same
    /// `seen` membership is why the root itself is never retried on any later pass, blind or
    /// not: pass 1 already inserted it.
    ///
    /// **Deliberately NOT in `incomplete`: `snapshot()`'s bulk denied-ppid-read count.**
    /// `PROC_PIDTBSDINFO` denies for every process this caller does not own — measured on this
    /// host, 327 of 1022 live pids, from an ordinary unprivileged shell, right now. Escalating
    /// that bulk count would make `Ok(())` unreachable on any real multi-user host;
    /// `snapshot()` logs it in aggregate for visibility (matching `holders()`'s own aggregate
    /// `debug!` for the identical class of mostly-irrelevant host-wide denials), and this
    /// function escalates a ppid-read denial only insofar as it prevents a SPECIFIC candidate
    /// from being resolved — which the `Resolved::Unknown`/`Denied`/`NotAttempted` arms above
    /// already cover at the granularity where a denial is actually diagnostic.
    ///
    /// Each channel covers a gap the others have: a member that lost the marker but kept its
    /// ppid chain is caught by the walk; a member that left the group and was reparented is
    /// caught only by the marker; a member that lost the marker AND was reparented but stayed in
    /// the group is caught only by `killpg`.
    ///
    /// **The group signal's re-fire gate.** Pass 1 fires unconditionally, carrying exactly
    /// today's baseline `killpg`/`ProcessGroup` pgid-reuse risk (`src/containment/unix.rs`) — a
    /// resolve-then-signal window this design does not try to close further. A LATER pass
    /// re-fires only when THIS pass's own marker-holder scan (`this_pass_holders`, computed
    /// above, before this block runs) contains a pid that is BOTH signalable and, queried via
    /// `getpgid` right here, reports membership in `self.pgid`. `getpgid` on a gone pid fails
    /// (`ESRCH`), so a successful, matching call is itself live-membership proof — no separate
    /// liveness check is needed, and no zombie can satisfy it: `holders()` only reports pids the
    /// fd-table scan found with an OPEN descriptor, which a zombie cannot hold (every fd closes
    /// before a process becomes a zombie), so this candidate set is narrower than `self.root`'s
    /// own `is_alive()` in exactly the way that matters — this design tried `self.root`'s
    /// identity as the anchor first, and it does not work: pass 1's `killpg` signals the WHOLE
    /// group, including the root itself (the root is always a member of its own `self.pgid`, by
    /// this crate's process-group convention), so `self.root` is already a SIGKILL target the
    /// instant pass 1's group signal is sent — deferring only the walk channel's OWN
    /// `kill_by_identity(root)` call changes nothing, because the root dies from the group
    /// signal regardless of what the walk channel does. And once signalled, a root that has not
    /// yet been reaped reads `Liveness::Dead` (`identity/macos.rs` reports `Dead` for a zombie),
    /// not merely "eventually recycled" — so `root.is_alive()` is false on every later pass of
    /// an ORDINARY teardown, not just an unlucky one, and the group signal would never re-fire
    /// at all. A live, marker-confirmed member has no such flaw: it is not the process pass 1's
    /// own signal necessarily kills, so when the scan finds one, it is real, current evidence,
    /// not a proxy this design's own prior action already invalidated.
    ///
    /// **What this gate proves, and what it does not — stated precisely, not overclaimed.** A
    /// successful, matching `getpgid` call is a real, positive fact: AT THAT INSTANT, a live
    /// process was a confirmed member of `self.pgid`'s group, which — because a process group's
    /// numeric id cannot be freed for reuse while any process remains a member of it — proves
    /// `self.pgid` had not yet been recycled onto an unrelated group at that instant. It does
    /// NOT prove `self.pgid` is still valid microseconds later when `killpg` actually runs: the
    /// `getpgid` check and the `killpg` call are two separate syscalls, and the checked member
    /// could exit (releasing the last hold on `self.pgid`) in the gap between them. This is the
    /// same class of check-then-act window `src/containment/unix.rs` already documents for
    /// `ProcessGroup`'s own one-shot `killpg` — narrowed here to "immediately after a live
    /// member was freshly confirmed," not eliminated, and this module makes no claim beyond
    /// that. Each pass's `killpg` is preceded by its own root check
    /// ([`check_number`](crate::containment::check_number)).
    fn sweep_pass(
        &self,
        signal: nix::sys::signal::Signal,
        state: &mut SweepState<'_>,
        first_pass: bool,
        scope: Scope<'_>,
    ) -> usize {
        let SweepState {
            seen,
            group_result,
            group_unsent,
            incomplete,
            killed,
            ..
        } = state;
        let walk = matches!(scope, Scope::Full(_));
        let group_root = match scope {
            Scope::Full(root) => root,
            Scope::HoldersOnly { .. } => None,
        };
        let except = match scope {
            Scope::HoldersOnly { except } => except,
            Scope::Full(_) => None,
        };
        // Snapshot FIRST, always — the group-signal-ordering invariant below depends on this
        // pass's snapshot (when one is obtained) predating any signal sent this pass.
        // `_ppid_denied` is intentionally NOT folded into `incomplete` — see this fn's doc.
        let (pids, parents, _ppid_denied) = crate::containment::enumerate::snapshot();
        let blind = pids.is_empty();
        if blind {
            *incomplete = true;
            if first_pass {
                let still = match scope {
                    Scope::Full(_) => {
                        "the group signal and root kill below still run, since neither needs the process table"
                    }
                    Scope::HoldersOnly { .. } => "nothing else runs, so nothing is signalled this pass",
                };
                log::warn!(
                    "fd marker {:#x}: the host process table could not be read on the first \
                     pass; the ppid-walk and marker channels are blind ({still})",
                    self.handle
                );
            } else {
                log::warn!(
                    "fd marker {:#x}: the host process table could not be read this pass; \
                     every channel is blind this pass — the root was already handled on an \
                     earlier pass and is not retried, and the group signal does not re-fire \
                     without a live member freshly confirmed THIS pass (not observed this \
                     pass is not the same as observed absent). This pass performs no teardown \
                     on any channel",
                    self.handle
                );
            }
        }

        // Channel 1+2: the root (needs no snapshot — already a resolved `ProcessId`) plus its
        // ppid-walk descendants NOT already signalled this sweep (need THIS pass's snapshot;
        // skipped when blind, since there is nothing to walk). The walk keeps a process whose
        // ppid, read after the root was proved, names it.
        //
        // Outside `Scope::Full` the root's pid is not trusted.
        let mut new_walk: Vec<ProcessId> = Vec::new();
        debug_assert!(
            !walk || self.root.is_some(),
            "a full sweep of a marker made without its root"
        );
        if let Some(root) = self.root.filter(|_| walk) {
            if seen.insert(root) {
                new_walk.push(root);
            }
            if !blind {
                match crate::containment::treewalk::walk_from(&*self.kernel, root, &parents, crate::Recursive::Yes) {
                    Ok(Some(walk)) => {
                        // A walk ran: the root held its pid, as `hard_kill` and `terminate` record.
                        #[cfg(test)]
                        crate::containment::treewalk::fault::note_walk(root.pid());
                        for id in walk.members {
                            if seen.insert(id) {
                                new_walk.push(id);
                            }
                        }
                        // A candidate that could not be read is warned of and not signalled: not
                        // observed is not observed absent, so the sweep is incomplete.
                        if !walk.unassessed.is_empty() {
                            crate::containment::treewalk::warn_unassessed(&walk.unassessed);
                            *incomplete = true;
                        }
                    }
                    // Gone: nothing to walk.
                    Ok(None) => {}
                    // Not observed is not observed absent: like a blind pass, the walk channel
                    // is skipped and the sweep reports `incomplete`.
                    Err(e) => {
                        log::warn!(
                            "fd marker {:#x}: the root's descendants could not be walked ({report}) \
                             - the ppid-walk channel is blind this pass",
                            self.handle,
                            report = crate::error::Report(&e)
                        );
                        *incomplete = true;
                    }
                }
            }
        }

        // Channel 3: every marker holder found THIS pass, captured once in full (not just
        // newly-discovered ones) — the group-signal gate below needs to check EVERY confirmed
        // holder this pass, not only the ones this sweep has not already dealt with.
        let this_pass_holders: Vec<Holder> = if blind { Vec::new() } else { holders(self.handle, &pids) };
        let mut new_holders: Vec<ProcessId> = Vec::new();
        for h in &this_pass_holders {
            if !is_signalable(h.pid) {
                // Reaching this branch at all means `h.pid` is the supervisor, pid 0, or pid 1
                // — every one of which is a defect in this process's own marker plumbing (the
                // write end must never reach any of them), not a routine miss. Both the log and
                // the debug-build contract check cover all three, not just the supervisor case.
                log::warn!(
                    "fd marker {:#x}: self-exclusion guard fired for pid {} found in the \
                     holder set (the supervisor or pid 0/1 must never hold its own marker)",
                    self.handle,
                    h.pid
                );
                debug_assert!(
                    false,
                    "fd marker sweep found pid {} in its own holder set (supervisor, pid 0, or \
                     pid 1) — the write-end hand-off must never reach any of them",
                    h.pid
                );
                continue;
            }
            let id = match ProcessId::of_with(&*self.kernel, h.pid).0 {
                Resolved::Found(id) => id,
                Resolved::Gone => continue,
                Resolved::Unknown => {
                    log::warn!(
                        "fd marker {:#x}: holder pid {} could not be queried (access denied?) \
                         - not signaled, left running",
                        self.handle,
                        h.pid
                    );
                    *incomplete = true;
                    continue;
                }
            };
            if Some(id) == except {
                log::debug!(
                    "fd marker {:#x}: holder pid {} is not pinned by this process - not signaled",
                    self.handle,
                    h.pid
                );
                continue;
            }
            if seen.insert(id) {
                new_holders.push(id);
            }
        }

        // Group signal: pass 1 unconditionally; a later pass only when this pass's own holder
        // scan just confirmed a live member of `self.pgid` — see this fn's doc for what that
        // does and does not prove. Always after THIS pass's other channels are computed:
        // signalling the process group before a pass's own channels are computed would destroy
        // the channel that pass reads (an intermediate in the group whose child lost the marker
        // below a scrubbing spawn path but still chains by ppid would be killed, reparenting
        // that child to launchd before the snapshot sees it — reachable by no channel at all).
        // `group_result` folds together across passes (a later pass's success does not erase an
        // earlier failure, and vice versa) so a transient failure on one pass is not silently
        // dropped by the next pass's success.
        {
            // `!blind &&`, not merely an empty `this_pass_holders`: a blind pass never ran the
            // scan at all ("not observed"), which must not read the same as a genuine scan that
            // found nobody ("observed absent") — both happen to produce an empty `Vec`, but only
            // the second is evidence the pgid was not confirmed live this pass.
            let live_holder_confirms_pgid = !blind
                && self.pgid.is_some_and(|pgid| {
                    this_pass_holders
                        .iter()
                        .any(|h| is_signalable(h.pid) && pid_is_live_group_member(h.pid, pgid))
                });
            let should_fire = first_pass || live_holder_confirms_pgid;
            if !walk {
            } else if should_fire {
                // `kill_group`/`term_group` already return `crate::error::Error`, carrying
                // #61's own `Error::Containment`/`Error::Unassessable` distinction for an
                // ordinary refusal — preserved as-is here, NOT collapsed into a stringified
                // `io::Error` (see this fn's doc, and `combine_group_errors`).
                let this_pass_group_result: Result<(), Error> = match (self.pgid, signal) {
                    (Some(pgid), nix::sys::signal::Signal::SIGKILL) => {
                        crate::containment::unix::kill_group(pgid, group_root, killed)
                    }
                    (Some(pgid), _) => match crate::containment::unix::term_group_sent(pgid, group_root) {
                        Ok(checked) => checked,
                        Err(unsent) => {
                            *group_unsent = true;
                            Err(unsent)
                        }
                    },
                    (None, _) => Ok(()),
                };
                *group_result = match (std::mem::replace(group_result, Ok(())), this_pass_group_result) {
                    (Ok(()), r) => r,
                    (e @ Err(_), Ok(())) => e,
                    (Err(first), Err(latest)) => Err(combine_group_errors(first, latest)),
                };
            } else if self.pgid.is_some() {
                if blind {
                    log::debug!(
                        "fd marker {:#x}: skipping this pass's group signal — the process \
                         table could not be read this pass, so no live member of this pass's \
                         pgid was observed (not: none was found)",
                        self.handle
                    );
                } else {
                    log::debug!(
                        "fd marker {:#x}: skipping this pass's group signal — no live member \
                         confirmed this pass's pgid, so it may have been recycled",
                        self.handle
                    );
                }
            }
        }

        let found = new_walk.len() + new_holders.len();
        if found == 0 {
            return 0;
        }
        for id in new_walk {
            // Test-only fault seam: skip the root's identity kill (take semantics — see
            // `fault`), mirroring `treewalk::hard_kill`'s own seam so a test can force the
            // `kill_tree` handle backstop to be the sole killer regardless of which mechanism a
            // given platform actually attaches for a request.
            #[cfg(test)]
            if Some(id) == self.root && fault::take_force_root_kill_noop() {
                continue;
            }
            let outcome = crate::containment::treewalk::kill_by_identity(&*self.kernel, id, signal);
            crate::containment::treewalk::warn_if_not_attempted(id, signal, &outcome);
            // The root's owner waits for the root.
            state.record(id, signal, &outcome, Some(id) != self.root);
        }
        for id in new_holders {
            if let Some(outcome) = self.kill_holder(id, signal) {
                state.record(id, signal, &outcome, true);
            }
        }
        found
    }

    /// Fold `incomplete` and `still_forking` (the sweep ended on a count that did not fall) into
    /// the final `Result` — see `sweep_pass`'s doc for why a blind pass or an unresolved member is
    /// a real gap, never silently `Ok(())`. A failed `group_result` stays the error, with the
    /// incomplete summary as its peer, so the group's OS code is the first one found.
    fn finish_sweep(
        handle: u64,
        group_result: Result<(), Error>,
        incomplete: bool,
        still_forking: bool,
    ) -> Result<(), Error> {
        if incomplete || still_forking {
            let mut causes = Vec::new();
            if incomplete {
                causes.push(
                    "the host process table was unreadable on at least one pass, or at least one \
                     known/suspected member could not be assessed or signalled",
                );
            }
            if still_forking {
                causes.push(
                    "the tree was still forking when the sweep stopped, so a process it forked \
                     during the last pass may be left running, unnamed",
                );
            }
            let msg = format!(
                "fd marker {handle:#x}: teardown may be incomplete — {}",
                causes.join("; ")
            );
            // `incomplete` is a summary bool with no cause to attach; `snapshot()` logs a blind pass itself.
            let incomplete_err = Error::Unassessable {
                detail: msg,
                source: None,
            };
            return match group_result {
                Ok(()) => Err(incomplete_err),
                Err(group_err) => Err(group_err.with_peers([std::sync::Arc::new(incomplete_err)])),
            };
        }
        group_result
    }

    /// Kill one marker holder (already identity-resolved by the caller for dedup), closing the
    /// discovery-to-signal window this one pass opens.
    ///
    /// `id` was resolved at discovery time; between then and now it could have exited (its pid
    /// recycled onto a stranger) or genuinely stopped holding the marker (the `close(fd)`
    /// escape). `holds_marker` re-verifies membership against the SAME pid; `kill_by_identity`
    /// then re-verifies the identity once more immediately before signalling, closing the
    /// remaining window exactly as the tree walk does.
    ///
    /// No separate ancestry check: unlike the ppid-walk channel (where a stale ppid can
    /// point at a recycled root pid, which is what `treewalk`'s parent proof defends against),
    /// membership re-checked HERE, at signal time, is already a complete proof — `Marker.handle`
    /// names a kernel object that cannot be reissued while `self.read` is held (the module's
    /// central invariant), so a pid that currently holds an fd naming it can only be a real
    /// inheritor of this marker's write end.
    ///
    /// Uses `holds_marker_query` (the tri-state), not the plain-`bool` `holds_marker`: a
    /// confirmed non-holder and a DENIED re-check are different facts here specifically. The
    /// pid reaching this function was found by `holders()` moments earlier, this same pass —
    /// so a `Denied` result now means a KNOWN member became unqueryable between discovery and
    /// signal (almost always the credential-changing `exec` the module docs name), not the
    /// documented `close(fd)` escape. `holders()`'s own aggregate-only denial logging does not
    /// apply here for exactly that reason: this pid is not an arbitrary host process, it is a
    /// confirmed candidate, so a denial here is a [`KillOutcome::NotAttempted`], warned of here.
    ///
    /// Returns the outcome of the kill for the caller to fold ([`SweepState::record`]), or `None` for a
    /// confirmed non-holder (nothing to fold: not incomplete, just resolved).
    fn kill_holder(&self, id: ProcessId, signal: nix::sys::signal::Signal) -> Option<KillOutcome> {
        match holds_marker_query(id.pid(), self.handle) {
            MarkerQuery::NotHeld => {
                log::debug!(
                    "fd marker {:#x}: pid {} no longer holds the marker - not signaled",
                    self.handle,
                    id.pid()
                );
                None
            }
            MarkerQuery::Denied => {
                let detail = format!(
                    "fd marker {:#x}: pid {} (a confirmed holder this pass) could not be re-queried before \
                     signalling (access denied?)",
                    self.handle,
                    id.pid()
                );
                log::warn!("{detail} - not signalled, left running");
                Some(KillOutcome::NotAttempted(Error::Unassessable { detail, source: None }))
            }
            MarkerQuery::Held => {
                let outcome = crate::containment::treewalk::kill_by_identity(&*self.kernel, id, signal);
                crate::containment::treewalk::warn_if_not_attempted(id, signal, &outcome);
                // From the outcome, after the call: a kill that re-verified a different process, or
                // sent nothing, leaves no record of a holder killed.
                #[cfg(test)]
                if matches!(outcome, KillOutcome::Terminated) {
                    fault::note_holder_kill(id.pid(), signal);
                }
                Some(outcome)
            }
        }
    }
}

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