oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
//! Tests of the part of `oscall::process::linux` that is about what a
//! thread may do: capabilities, the identity, system call filters
//! (`seccomp`), and the names of the system.
//!
//! Nothing here restricts the test harness: whatever drops a capability or
//! installs a filter does it in a helper process (this binary, run again
//! with `OSCALL_TEST_HELPER` set) or in a child the helper forks.
//!
//! As in `process_linux.rs`, what the environment does not allow is said
//! (`skipped: ...`) and passes, except in a run that exists to cover it
//! (`OSCALL_REQUIRE_PRIVILEGED`), where it fails.
#![cfg(any(target_os = "linux", target_os = "fullrust"))]

mod common;

/// Says what the environment kept a test from doing: see `common::skip`.
macro_rules! skip {
    ($($arg:tt)*) => {
        crate::common::skip(&format!($($arg)*))
    };
}

use common::{status_capabilities, status_field};
use oscall::ErrorKind;
use oscall::process::linux::seccomp::{self, Action, FilterFlags, Instruction};
use oscall::process::linux::{
    self, Capabilities, Capability, CapabilitySet, FileCapabilities, SecureBits,
};
use oscall::raw::linux::nr;

#[cfg(feature = "alloc")]
const EPERM: i32 = 1;
const EINVAL: i32 = 22;
#[cfg(feature = "alloc")]
const ENOSYS: i32 = 38;
/// Error numbers no system call here returns by itself: what the filters
/// of these tests answer with.
const FIRST: u16 = 77;
#[cfg(feature = "alloc")]
const SECOND: u16 = 78;

#[test]
fn capability_sets() {
    // The numbers are the kernel's.
    assert_eq!(Capability::Chown.number(), 0);
    assert_eq!(Capability::SysAdmin.number(), 21);
    assert_eq!(Capability::Setfcap.number(), 31);
    assert_eq!(Capability::MacOverride.number(), 32);
    assert_eq!(Capability::CheckpointRestore.number(), 40);
    for (number, capability) in Capability::ALL.into_iter().enumerate() {
        assert_eq!(capability.number() as usize, number);
        assert_eq!(Capability::from_number(number as u32), Some(capability));
    }
    assert_eq!(Capability::from_number(41), None);
    assert_eq!(Capability::from_number(u32::MAX), None);

    let set = CapabilitySet::of(&[Capability::NetBindService, Capability::Chown]);
    assert_eq!(set.bits(), 1 << 10 | 1);
    assert!(set.contains(Capability::Chown) && !set.contains(Capability::Kill));
    assert!(!set.is_empty() && CapabilitySet::empty().is_empty());
    assert_eq!(CapabilitySet::default(), CapabilitySet::EMPTY);
    assert_eq!(
        set.with(Capability::Kill).without(Capability::Chown).bits(),
        1 << 10 | 1 << 5
    );
    assert_eq!(set | Capability::Bpf, set.with(Capability::Bpf));
    let other = CapabilitySet::from(Capability::Chown) | CapabilitySet::from(Capability::Kill);
    assert_eq!((set & other).bits(), 1);
    assert_eq!((set - other).bits(), 1 << 10);
    assert_eq!(set.union(other).bits(), 1 << 10 | 1 << 5 | 1);
    assert!(set.is_superset(CapabilitySet::from(Capability::Chown)) && !set.is_superset(other));
    let mut changed = set;
    changed.insert(Capability::SysAdmin);
    changed.remove(Capability::Chown);
    assert_eq!(changed.bits(), 1 << 21 | 1 << 10);
    assert_eq!(
        set.iter().collect::<Vec<_>>(),
        [Capability::Chown, Capability::NetBindService]
    );
    assert_eq!(set.iter().collect::<CapabilitySet>(), set);
    // A capability newer than the list is kept, and shown by its number.
    let newer = CapabilitySet::from_bits(1 << 63 | 1 << 40 | 1 << 1);
    assert_eq!(newer.bits(), 1 << 63 | 1 << 40 | 1 << 1);
    assert_eq!(format!("{newer:?}"), "{DacOverride, CheckpointRestore, 63}");
    assert_eq!(format!("{:?}", CapabilitySet::empty()), "{}");

    let three = Capabilities::all_three(set);
    assert_eq!(
        (three.effective, three.permitted, three.inheritable),
        (set, set, set)
    );
    assert_eq!(Capabilities::default().permitted, CapabilitySet::EMPTY);
}

/// The sets of this thread are what `/proc` says. Nothing is changed.
/// The value of the attribute that holds the capabilities of a file, in
/// the three revisions the kernel has written.
#[test]
fn file_capability_values() {
    let low = CapabilitySet::of(&[Capability::NetBindService, Capability::Chown]);
    let high = CapabilitySet::of(&[Capability::CheckpointRestore, Capability::Setfcap]);
    let none = CapabilitySet::EMPTY;
    assert_eq!(FileCapabilities::MAX_LEN, 24);
    assert_eq!(
        FileCapabilities::default(),
        FileCapabilities::new(none, none, false)
    );

    // Revision 2: the flags, then the low halves and the high halves of
    // the permitted and inheritable sets, little-endian.
    let mut buf = [0xffu8; FileCapabilities::MAX_LEN];
    let capabilities = FileCapabilities::new(low | high, low, true);
    assert_eq!(capabilities.root_id, None);
    let value = capabilities.to_bytes(&mut buf);
    #[rustfmt::skip]
    assert_eq!(value, [
        0x01, 0, 0, 0x02,
        0x01, 0x04, 0, 0x80,  0x01, 0x04, 0, 0,
        0, 0x01, 0, 0,  0, 0, 0, 0,
    ]);
    assert_eq!(FileCapabilities::from_bytes(value), Ok(capabilities));
    // What `setcap cap_net_raw+p` writes.
    #[rustfmt::skip]
    let ping = [
        0, 0, 0, 0x02,
        0, 0x20, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,  0, 0, 0, 0,
    ];
    let parsed = FileCapabilities::from_bytes(&ping).unwrap();
    let raw = CapabilitySet::of(&[Capability::NetRaw]);
    assert_eq!(parsed, FileCapabilities::new(raw, none, false));
    assert_eq!(parsed.to_bytes(&mut buf), ping);

    // Revision 3: the same, and the root of a user namespace.
    let rooted = FileCapabilities::new(high, none, false).with_root_id(0x0102_0304);
    assert_eq!(rooted.root_id, Some(0x0102_0304));
    let value = rooted.to_bytes(&mut buf);
    #[rustfmt::skip]
    assert_eq!(value, [
        0, 0, 0, 0x03,
        0, 0, 0, 0x80,  0, 0, 0, 0,
        0, 0x01, 0, 0,  0, 0, 0, 0,
        0x04, 0x03, 0x02, 0x01,
    ]);
    assert_eq!(FileCapabilities::from_bytes(value), Ok(rooted));
    // The root of the initial namespace is a root like another.
    let zero = FileCapabilities::new(low, low, true).with_root_id(0);
    let value = zero.to_bytes(&mut buf);
    assert_eq!(value.len(), 24);
    assert_eq!(FileCapabilities::from_bytes(value), Ok(zero));

    // Revision 1 had sets of 32 bits.
    #[rustfmt::skip]
    let old = [
        0x01, 0, 0, 0x01,
        0x01, 0x04, 0, 0x80,  0x01, 0, 0, 0,
    ];
    let parsed = FileCapabilities::from_bytes(&old).unwrap();
    let chown = CapabilitySet::of(&[Capability::Chown]);
    assert_eq!(
        parsed,
        FileCapabilities::new(low.with(Capability::Setfcap), chown, true)
    );

    // What is none of them.
    let mut unknown = ping;
    unknown[3] = 0x04;
    let wrong: [&[u8]; 8] = [
        &[],
        &[0, 0, 0],
        &[0, 0, 0, 0x02],
        &ping[..19],
        &old[..8],
        &unknown,
        // The length of another revision.
        &[0u8, 0, 0, 0x02, 0, 0, 0, 0, 0, 0, 0, 0],
        &[0u8; 24],
    ];
    for value in wrong {
        let error = FileCapabilities::from_bytes(value).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{value:?}");
    }
    let mut long = [0u8; 28];
    long[3] = 0x03;
    assert!(FileCapabilities::from_bytes(&long).is_err());
    assert!(FileCapabilities::from_bytes(&long[..24]).is_ok());

    // A file that has none, a filesystem that has no attributes, and
    // what is no file.
    let exe = std::env::current_exe().unwrap();
    match linux::file_capabilities(exe.to_str().unwrap()) {
        Ok(found) => assert_eq!(found, None),
        Err(error) => assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}"),
    }
    let error = linux::file_capabilities("/proc/self/status").unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}");
    let error = linux::file_capabilities("/oscall/no/such/file").unwrap_err();
    assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
    let error = linux::remove_file_capabilities("/oscall/no/such/file").unwrap_err();
    assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
}

#[test]
fn capabilities_of_the_thread() {
    let capabilities = linux::capabilities().unwrap();
    assert_eq!(capabilities.effective.bits(), status_capabilities("CapEff"));
    assert_eq!(capabilities.permitted.bits(), status_capabilities("CapPrm"));
    assert_eq!(
        capabilities.inheritable.bits(),
        status_capabilities("CapInh")
    );
    assert!(capabilities.permitted.is_superset(capabilities.effective));
    assert_eq!(
        linux::bounding_set().unwrap().bits(),
        status_capabilities("CapBnd")
    );
    assert_eq!(
        linux::ambient_set().unwrap().bits(),
        status_capabilities("CapAmb")
    );

    // The setting of the thread, and the secure bit that is the same.
    let keep = linux::keep_capabilities().unwrap();
    let bits = linux::secure_bits().unwrap();
    assert_eq!(bits.contains(SecureBits::KEEP_CAPS), keep);
    assert!(format!("{bits:?}").starts_with("SecureBits("));
}

/// A field of the status of the process with several numbers.
fn status_numbers(name: &str) -> Vec<u32> {
    (0..)
        .map(|index| status_field(name, index))
        .take_while(|field| !field.is_empty())
        .map(|field| field.parse().unwrap())
        .collect()
}

#[test]
fn identity() {
    // Real, effective, saved, filesystem.
    let users = status_numbers("Uid");
    let groups = status_numbers("Gid");
    assert_eq!(linux::user_id(), users[0]);
    assert_eq!(linux::effective_user_id(), users[1]);
    assert_eq!(linux::group_id(), groups[0]);
    assert_eq!(linux::effective_group_id(), groups[1]);

    let mut expected = status_numbers("Groups");
    expected.sort_unstable();
    let count = linux::groups(&mut []).unwrap();
    assert_eq!(count, expected.len());
    let mut buf = vec![u32::MAX; count + 4];
    let written = linux::groups(&mut buf).unwrap();
    assert_eq!(written, count);
    buf.truncate(written);
    buf.sort_unstable();
    assert_eq!(buf, expected);
    if count > 1 {
        let error = linux::groups(&mut buf[..count - 1]).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    }
    #[cfg(feature = "alloc")]
    {
        let mut all = linux::groups_vec().unwrap();
        all.sort_unstable();
        assert_eq!(all, expected);
    }

    // What changes nothing, and what oscall refuses: -1 is no identifier.
    linux::set_user_ids(None, None, None).unwrap();
    linux::set_group_ids(None, None, None).unwrap();
    for ids in [
        [Some(u32::MAX), None, None],
        [None, Some(u32::MAX), None],
        [None, None, Some(u32::MAX)],
    ] {
        let error = linux::set_user_ids(ids[0], ids[1], ids[2]).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        let error = linux::set_group_ids(ids[0], ids[1], ids[2]).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    }
    // Without the capabilities, nobody else's identity. (With them it
    // would work, and this is the test harness.)
    let effective = linux::capabilities().unwrap().effective;
    if !effective.contains(Capability::Setuid) {
        let other = users[0].wrapping_add(1) % 60000;
        if !users.contains(&other) {
            let error = linux::set_user_ids(Some(other), None, None).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        }
    }
    if !effective.contains(Capability::Setgid) {
        let other = groups[0].wrapping_add(1) % 60000;
        if !groups.contains(&other) {
            let error = linux::set_group_ids(None, Some(other), None).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        }
        let error = linux::set_groups(&[]).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
    }
    assert_eq!(status_numbers("Uid"), users);
    assert_eq!(status_numbers("Gid"), groups);
}

#[test]
fn system_name() {
    let read = |name: &str| {
        let text = std::fs::read_to_string(format!("/proc/sys/kernel/{name}")).unwrap();
        text.trim_end_matches('\n').to_owned()
    };
    let name = linux::system_name().unwrap();
    assert_eq!(name.system(), b"Linux");
    assert_eq!(name.host_name(), read("hostname").as_bytes());
    assert_eq!(name.domain_name(), read("domainname").as_bytes());
    assert!(!name.machine().is_empty() && !name.version().is_empty());
    // An emulator answers for the system it emulates.
    if !common::emulated() {
        assert_eq!(name.release(), read("osrelease").as_bytes());
        assert_eq!(name.version(), read("version").as_bytes());
        // 32-bit programs of a 64-bit kernel are told of the kernel's
        // architecture, unless their personality says otherwise.
        let machine = String::from_utf8(name.machine().to_vec()).unwrap();
        let family: &[&str] = match std::env::consts::ARCH {
            "x86_64" => &["x86_64"],
            "x86" => &["x86_64", "i686", "i586", "i486", "i386"],
            "aarch64" => &["aarch64"],
            "arm" => &["aarch64", "armv8l", "armv7l", "armv6l"],
            "riscv64" => &["riscv64"],
            "riscv32" => &["riscv32"],
            other => panic!("unknown architecture {other}"),
        };
        assert!(family.contains(&machine.as_str()), "{machine}");
    }
    let debug = format!("{name:?}");
    assert!(
        debug.starts_with("SystemName { system: \"Linux\", host_name: \""),
        "{debug}"
    );
    assert_eq!(name, linux::system_name().unwrap());
}

/// The programs `seccomp` writes, without installing anything.
#[test]
fn seccomp_programs() {
    assert_eq!(Action::Allow.value(), 0x7fff_0000);
    assert_eq!(Action::Log.value(), 0x7ffc_0000);
    assert_eq!(Action::Errno(38).value(), 0x0005_0026);
    assert_eq!(Action::Trap.value(), 0x0003_0000);
    assert_eq!(Action::KillThread.value(), 0);
    assert_eq!(Action::KillProcess.value(), 0x8000_0000);

    assert_eq!(seccomp::AUDIT_ARCH_X86_64, 0xc000_003e);
    assert_eq!(seccomp::AUDIT_ARCH_X86, 0x4000_0003);
    assert_eq!(seccomp::AUDIT_ARCH_AARCH64, 0xc000_00b7);
    assert_eq!(seccomp::AUDIT_ARCH_ARM, 0x4000_0028);
    assert_eq!(seccomp::AUDIT_ARCH_RISCV64, 0xc000_00f3);
    assert_eq!(seccomp::AUDIT_ARCH_RISCV32, 0x4000_00f3);
    let own = match std::env::consts::ARCH {
        "x86_64" => seccomp::AUDIT_ARCH_X86_64,
        "x86" => seccomp::AUDIT_ARCH_X86,
        "aarch64" => seccomp::AUDIT_ARCH_AARCH64,
        "arm" => seccomp::AUDIT_ARCH_ARM,
        "riscv64" => seccomp::AUDIT_ARCH_RISCV64,
        "riscv32" => seccomp::AUDIT_ARCH_RISCV32,
        other => panic!("unknown architecture {other}"),
    };
    assert_eq!(seccomp::AUDIT_ARCH, own);

    // `struct sock_filter`, and the instructions by their kernel codes.
    assert_eq!(size_of::<Instruction>(), 8);
    assert_eq!(Instruction::load(4), Instruction::new(0x20, 0, 0, 4));
    assert_eq!(
        Instruction::jump_if_equal(9, 1, 2),
        Instruction::new(0x15, 1, 2, 9)
    );
    assert_eq!(
        Instruction::jump_if_at_least(9, 1, 2),
        Instruction::new(0x35, 1, 2, 9)
    );
    assert_eq!(
        Instruction::ret(Action::Errno(5)),
        Instruction::new(0x06, 0, 0, 0x0005_0005)
    );
    assert_eq!(
        (
            seccomp::DATA_NUMBER,
            seccomp::DATA_ARCH,
            seccomp::DATA_INSTRUCTION_POINTER,
            seccomp::DATA_ARGS
        ),
        (0, 4, 8, 16)
    );

    let x32 = cfg!(target_arch = "x86_64");
    let preamble = if x32 { 6 } else { 4 };
    assert_eq!(seccomp::len_for(0), preamble + 1);
    assert_eq!(seccomp::len_for(3), preamble + 7);
    let mut buf = [Instruction::default(); 64];
    let rules = [
        (nr::GETPPID, Action::Errno(FIRST)),
        (nr::GETSID, Action::KillProcess),
    ];
    let program = seccomp::build(&mut buf, &rules, Action::Allow).unwrap();
    assert_eq!(program.len(), seccomp::len_for(2));
    let kill = Instruction::ret(Action::KillProcess);
    assert_eq!(program[0], Instruction::load(seccomp::DATA_ARCH));
    assert_eq!(program[1], Instruction::jump_if_equal(own, 1, 0));
    assert_eq!(program[2], kill);
    assert_eq!(program[3], Instruction::load(seccomp::DATA_NUMBER));
    if x32 {
        assert_eq!(program[4], Instruction::jump_if_at_least(0x4000_0000, 0, 1));
        assert_eq!(program[5], kill);
    }
    let rest = &program[preamble..];
    assert_eq!(
        rest,
        [
            Instruction::jump_if_equal(nr::GETPPID as u32, 0, 1),
            Instruction::ret(Action::Errno(FIRST)),
            Instruction::jump_if_equal(nr::GETSID as u32, 0, 1),
            kill,
            Instruction::ret(Action::Allow),
        ]
    );
    // The two lists are that, with one action.
    let mut other = [Instruction::default(); 64];
    let allow = seccomp::allow_list(&mut other, &[nr::READ, nr::WRITE], Action::Trap).unwrap();
    let mut expected = [Instruction::default(); 64];
    let rules = [(nr::READ, Action::Allow), (nr::WRITE, Action::Allow)];
    assert_eq!(
        allow,
        seccomp::build(&mut expected, &rules, Action::Trap).unwrap()
    );
    let deny = seccomp::deny_list(&mut other, &[nr::READ], Action::Errno(1)).unwrap();
    let rules = [(nr::READ, Action::Errno(1))];
    assert_eq!(
        deny,
        seccomp::build(&mut expected, &rules, Action::Allow).unwrap()
    );

    // A buffer of exactly the size, and one too small.
    let mut exact = [Instruction::default(); seccomp::len_for(1)];
    assert_eq!(
        seccomp::deny_list(&mut exact, &[nr::READ], Action::Trap)
            .unwrap()
            .len(),
        exact.len()
    );
    let error = seccomp::deny_list(&mut exact, &[nr::READ, nr::WRITE], Action::Trap).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{error:?}");
    let error = seccomp::build(&mut [], &[], Action::Allow).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{error:?}");
    // More than a filter holds, and a number that is none.
    let mut large = vec![Instruction::default(); 5000];
    let many = vec![nr::READ; (4096 - preamble - 1) / 2];
    assert_eq!(
        seccomp::allow_list(&mut large, &many, Action::Trap)
            .unwrap()
            .len(),
        seccomp::len_for(many.len())
    );
    assert!(seccomp::len_for(many.len()) <= 4096);
    let many = vec![nr::READ; many.len() + 1];
    let error = seccomp::allow_list(&mut large, &many, Action::Trap).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    #[cfg(target_pointer_width = "64")]
    {
        let error = seccomp::deny_list(&mut large, &[1 << 32], Action::Trap).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    }

    // What `install` refuses by itself: nothing is installed.
    let error = seccomp::install(&[], FilterFlags::empty()).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    let error = seccomp::install(&large[..4097], FilterFlags::ALL_THREADS).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    assert_eq!(
        format!("{:?}", FilterFlags::ALL_THREADS | FilterFlags::LOG),
        "FilterFlags(ALL_THREADS | LOG)"
    );
}

/// The mode of this thread, which the tests leave alone, is what `/proc`
/// says: no filter, or the one of a container.
/// The values a supervisor exchanges with the kernel.
#[test]
fn seccomp_notification_values() {
    use seccomp::{Notification, Response, SyscallData};
    assert_eq!(Action::UserNotify.value(), 0x7fc0_0000);
    assert_eq!(size_of::<SyscallData>(), 64);
    assert_eq!(size_of::<Notification>(), 80);
    assert_eq!(size_of::<Response>(), 24);
    let empty = Notification::default();
    assert_eq!((empty.id, empty.pid, empty.flags), (0, 0, 0));
    assert_eq!(empty.data, SyscallData::default());
    assert_eq!(empty.data.args, [0; 6]);
    // The offsets a filter reads at are those of the structure.
    assert_eq!(
        std::mem::offset_of!(SyscallData, number),
        seccomp::DATA_NUMBER as usize
    );
    assert_eq!(
        std::mem::offset_of!(SyscallData, arch),
        seccomp::DATA_ARCH as usize
    );
    assert_eq!(
        std::mem::offset_of!(SyscallData, instruction_pointer),
        seccomp::DATA_INSTRUCTION_POINTER as usize
    );
    assert_eq!(
        std::mem::offset_of!(SyscallData, args),
        seccomp::DATA_ARGS as usize
    );
    // An answer is one of three things.
    let debug = |response: Response| format!("{response:?}");
    assert_eq!(
        debug(Response::success(7, -3)),
        "Response { id: 7, val: -3, error: 0, flags: 0 }"
    );
    assert_eq!(
        debug(Response::error(7, 13)),
        "Response { id: 7, val: 0, error: -13, flags: 0 }"
    );
    assert_eq!(
        debug(Response::continue_syscall(9)),
        "Response { id: 9, val: 0, error: 0, flags: 1 }"
    );
    assert_ne!(Response::success(1, 0), Response::continue_syscall(1));
    assert!(!seccomp::AddHandleFlags::CLOSE_ON_EXEC.intersects(seccomp::AddHandleFlags::RESPOND));
    assert!(
        !FilterFlags::WAIT_KILLABLE.intersects(
            FilterFlags::ALL_THREADS | FilterFlags::LOG | FilterFlags::ALLOW_SPECULATION
        )
    );

    // What the running kernel has for them.
    match seccomp::notification_sizes() {
        Ok(sizes) => {
            assert_eq!(
                (sizes.notification, sizes.response, sizes.data),
                (80, 24, 64),
                "{sizes:?}"
            );
        }
        Err(error) if common::emulated() && error.raw_os_error() == 38 => {
            skip!("qemu-user has no seccomp: {error}");
        }
        // The filter of a container may refuse the question.
        Err(error) => assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}"),
    }
    // A handle that is no listener.
    let file = std::fs::File::open("/proc/self/status").unwrap();
    let file = common::handle_of(&file);
    match seccomp::receive(&file) {
        Err(error) if error.raw_os_error() == 25 => {}
        Err(error) if common::emulated() => {
            assert!(
                matches!(error.raw_os_error(), 38 | 25 | EINVAL),
                "{error:?}"
            );
        }
        other => panic!("receive: {other:?}"),
    }
    let error = seccomp::respond(&file, &Response::success(1, 0)).unwrap_err();
    assert_eq!(error.raw_os_error(), 25, "{error:?}");
    let error = seccomp::is_valid(&file, 1).unwrap_err();
    assert_eq!(error.raw_os_error(), 25, "{error:?}");
}

#[test]
fn seccomp_mode() {
    let mode = match linux::seccomp::mode() {
        Ok(mode) => mode,
        Err(error) if common::emulated() && error.raw_os_error() == EINVAL => {
            skip!("qemu-user has no seccomp: {error}");
            return;
        }
        Err(error) => panic!("mode: {error:?}"),
    };
    let expected = match status_field("Seccomp", 0).as_str() {
        "0" => seccomp::Mode::Disabled,
        "2" => seccomp::Mode::Filter,
        other => panic!("Seccomp: {other}"),
    };
    assert_eq!(mode, expected);
}

/// The child half of the tests that run this binary again: does what the
/// `OSCALL_TEST_HELPER` variable says, and nothing in an ordinary run.
#[test]
fn helper_child_process() {
    let Some(mode) = std::env::var_os("OSCALL_TEST_HELPER") else {
        return;
    };
    let mode = mode.into_string().unwrap();
    #[cfg(feature = "alloc")]
    children::helper_main(&mode);
    panic!("unknown helper mode {mode}");
}

#[cfg(feature = "alloc")]
mod children {
    use std::collections::HashMap;
    use std::time::{Duration, Instant};

    use oscall::process::linux::seccomp::{self, Action, FilterFlags, Instruction, Mode};
    use oscall::process::linux::{
        self, Capabilities, Capability, CapabilitySet, CommandExt as _, ConfineExt as _,
        FileCapabilities, IdMap, Namespaces, SecureBits,
    };
    use oscall::process::unix::{self, CommandExt as _, ExitStatusExt as _, Fork, SIGKILL};
    use oscall::process::{self, Child, Command, ExitStatus, Stdio};
    use oscall::raw::linux::{nr, syscall};
    use oscall::{Error, ErrorKind, io};

    use super::common::{self, status_capabilities, status_field, tmp_dir};
    use super::{EINVAL, ENOSYS, EPERM, FIRST, SECOND};

    const ENOEXEC: i32 = 8;
    const EACCES: i32 = 13;
    const SIGILL: i32 = 4;
    const SIGSYS: i32 = 31;

    /// Waits for the child, for a limited time.
    fn wait(child: &mut Child) -> ExitStatus {
        let start = Instant::now();
        loop {
            if let Some(status) = child.try_wait().unwrap() {
                return status;
            }
            if start.elapsed() > Duration::from_secs(60) {
                child.kill().unwrap();
                panic!("the child did not exit");
            }
            std::thread::sleep(Duration::from_millis(2));
        }
    }

    /// Everything a pipe holds until its last writer is gone.
    fn read_all(pipe: &oscall::OwnedHandle) -> Vec<u8> {
        let mut data = Vec::new();
        let mut buf = [0u8; 64];
        loop {
            match io::read(pipe, &mut buf).unwrap() {
                0 => return data,
                n => data.extend_from_slice(&buf[..n]),
            }
        }
    }

    /// Whether the error is the answer of an emulator that has no
    /// `seccomp`.
    fn no_seccomp(error: &Error) -> bool {
        common::emulated() && matches!(error.raw_os_error(), ENOSYS | EINVAL)
    }

    /// The maps that make the caller root of a namespace.
    fn root_maps() -> ([IdMap; 1], [IdMap; 1]) {
        let map = |outside| {
            [IdMap {
                inside: 0,
                outside,
                count: 1,
            }]
        };
        (
            map(linux::effective_user_id()),
            map(linux::effective_group_id()),
        )
    }

    /// The environment of this process, and what tells the helper its
    /// mode.
    fn helper_env(mode: &str) -> Vec<Vec<u8>> {
        let mut env: Vec<Vec<u8>> = std::env::vars_os()
            .filter(|(name, _)| name != "OSCALL_TEST_HELPER")
            .map(|(name, value)| [name.as_encoded_bytes(), b"=", value.as_encoded_bytes()].concat())
            .collect();
        env.push(format!("OSCALL_TEST_HELPER={mode}").into_bytes());
        env
    }

    /// How a helper is run.
    #[derive(Clone, Copy, PartialEq)]
    enum Place {
        /// As the caller.
        Here,
        /// As root of a new user namespace.
        UserNamespace,
    }

    /// This test binary, to run again as the helper of a mode.
    struct Helper {
        mode: String,
        exe: std::path::PathBuf,
        env: Vec<Vec<u8>>,
        ids: ([IdMap; 1], [IdMap; 1]),
    }

    impl Helper {
        fn new(mode: &str) -> Self {
            Self {
                mode: mode.to_owned(),
                exe: std::env::current_exe().unwrap(),
                env: helper_env(mode),
                ids: root_maps(),
            }
        }

        /// Runs the helper, set up by `configure`. `Err` with the error
        /// of `spawn`; `None`, having said why, where the system cannot
        /// run it at all.
        fn run<'a>(
            &'a self,
            place: Place,
            configure: impl FnOnce(Command<'a>) -> Command<'a>,
        ) -> Option<Result<ExitStatus, Error>> {
            const ARGS: &[&str] = &["--exact", "--nocapture", "helper_child_process"];
            let mut command = Command::new(self.exe.as_os_str().as_encoded_bytes())
                .args(ARGS)
                .env(&self.env)
                .stdin(Stdio::Null)
                .stdout(Stdio::Null);
            if place == Place::UserNamespace {
                command = command
                    .namespaces(Namespaces::USER)
                    .uid_map(&self.ids.0)
                    .gid_map(&self.ids.1)
                    .deny_setgroups();
            }
            match configure(command).spawn() {
                Ok(mut child) => Some(Ok(wait(&mut child))),
                // The binary is for another architecture, and runs here
                // under an emulator the kernel knows nothing about.
                Err(error) if error.raw_os_error() == ENOEXEC => {
                    skip!("the system cannot execute {}", self.exe.display());
                    None
                }
                Err(error) => match common::namespace_refusal(&error) {
                    Some(reason) if place == Place::UserNamespace => {
                        skip!("({}) {reason}: {error}", self.mode);
                        None
                    }
                    _ => Some(Err(error)),
                },
            }
        }

        /// The error of a `spawn` that must fail.
        fn refused<'a>(
            &'a self,
            configure: impl FnOnce(Command<'a>) -> Command<'a>,
        ) -> Option<Error> {
            Some(self.run(Place::Here, configure)?.unwrap_err())
        }
    }

    /// Runs the helper `mode` as the caller, and wants it to succeed.
    fn helper(mode: &str) {
        if let Some(result) = Helper::new(mode).run(Place::Here, |command| command) {
            let status = result.unwrap();
            assert!(status.success(), "{mode}: {status}");
        }
    }

    /// The helper that says what it is.
    struct Report {
        helper: Helper,
        file: std::path::PathBuf,
    }

    impl Report {
        /// `name` is that of a directory for the report.
        fn new(name: &str) -> Self {
            let dir = tmp_dir(name);
            // The helper may be run as another user.
            std::fs::set_permissions(&dir, std::os::unix::fs::PermissionsExt::from_mode(0o777))
                .unwrap();
            let file = std::path::absolute(dir.join("report")).unwrap();
            Self {
                helper: Helper::new(&format!("report:{}", file.display())),
                file,
            }
        }

        /// Runs the helper, and returns what it said.
        fn run<'a>(
            &'a self,
            place: Place,
            configure: impl FnOnce(Command<'a>) -> Command<'a>,
        ) -> Option<Result<HashMap<String, String>, Error>> {
            let status = match self.helper.run(place, configure)? {
                Ok(status) => status,
                Err(error) => return Some(Err(error)),
            };
            assert!(status.success(), "{status}");
            let text = std::fs::read_to_string(&self.file).unwrap();
            Some(Ok(text
                .lines()
                .map(|line| {
                    let (name, value) = line.split_once('=').unwrap();
                    (name.to_owned(), value.to_owned())
                })
                .collect()))
        }
    }

    /// A helper whose `spawn` is to fail: its report goes nowhere.
    fn unwanted() -> Helper {
        Helper::new("report:/dev/null")
    }

    /// A set of the report.
    fn set_of(report: &HashMap<String, String>, name: &str) -> CapabilitySet {
        CapabilitySet::from_bits(u64::from_str_radix(&report[name], 16).unwrap())
    }

    pub(super) fn helper_main(mode: &str) {
        if let Some(file) = mode.strip_prefix("report:") {
            let mut report = String::new();
            for name in ["CapEff", "CapPrm", "CapInh", "CapBnd", "CapAmb"] {
                report += &format!("{name}={:x}\n", status_capabilities(name));
            }
            report += &format!(
                "uid={}\ngid={}\nnnp={}\nseccomp={}\nkeep={}\n",
                linux::effective_user_id(),
                linux::effective_group_id(),
                linux::no_new_privileges().unwrap(),
                status_field("Seccomp", 0),
                linux::keep_capabilities().unwrap(),
            );
            std::fs::write(file, report).unwrap();
            process::exit(0);
        }
        match mode {
            "capabilities" => helper_capabilities(),
            mode if mode.starts_with("filecaps:") => {
                helper_file_capabilities(std::path::Path::new(&mode["filecaps:".len()..]));
            }
            "identity" => helper_identity(),
            "filtered" => helper_filtered(),
            "killed" => {
                // The filter of the parent ends the process here.
                let _ = unix::session(process::id());
                process::exit(1)
            }
            "inherited" => {
                let error = unix::session(process::id()).unwrap_err();
                assert_eq!(error.raw_os_error(), i32::from(FIRST), "{error:?}");
            }
            "unanswered" => {
                // No one listens: the kernel answers that there is no
                // such call. Until the parent has closed the listener,
                // the call waits.
                let error = unix::session(process::id()).unwrap_err();
                assert_eq!(error.raw_os_error(), ENOSYS, "{error:?}");
            }
            "threads" => helper_threads(),
            "strict" => helper_strict(),
            "allow" => helper_allow(),
            "notify" => helper_notify(),
            mode if mode.starts_with("notified:") => helper_notified(&mode["notified:".len()..]),
            _ => return,
        }
        process::exit(0);
    }

    /// Something another thread is asked to do, and its answer.
    struct Worker<T> {
        ask: std::sync::mpsc::Sender<()>,
        answer: std::sync::mpsc::Receiver<T>,
    }

    impl<T: Send + 'static> Worker<T> {
        /// A thread that exists from now on, and runs `f` each time it is
        /// asked.
        fn new(f: impl Fn() -> T + Send + 'static) -> Self {
            let (ask, asked) = std::sync::mpsc::channel::<()>();
            let (reply, answer) = std::sync::mpsc::channel();
            std::thread::spawn(move || {
                // Here before the caller goes on.
                reply.send(f()).unwrap();
                while asked.recv().is_ok() {
                    reply.send(f()).unwrap();
                }
            });
            let worker = Self { ask, answer };
            worker.answer.recv().unwrap();
            worker
        }

        fn ask(&self) -> T {
            self.ask.send(()).unwrap();
            self.answer.recv().unwrap()
        }
    }

    /// The sets of a thread, changed: this process is the helper, and its
    /// threads are the test's.
    fn helper_capabilities() {
        let before = linux::capabilities().unwrap();
        let bounding = linux::bounding_set().unwrap();
        // A security module may deny a process the capabilities its
        // credentials hold, and then also hides them from `capget`, which
        // `/proc` does not go through: what Ubuntu's AppArmor restriction
        // of user namespaces does to their root. The kernel's own checks
        // are then no longer of one mind (the bounding set asks the
        // module, the secure bits look at the credentials), and nothing
        // here can be told from anything else.
        let held = status_capabilities("CapEff");
        if before.effective.bits() != held {
            skip!(
                "(capabilities) capget says {:x} where the credentials hold {held:x}: no use of \
                 capabilities in the user namespace ({})",
                before.effective.bits(),
                common::confinement()
            );
            return;
        }
        // A thread that exists before anything changes.
        let earlier = Worker::new(|| {
            (
                linux::capabilities().unwrap(),
                linux::bounding_set().unwrap(),
                linux::keep_capabilities().unwrap(),
            )
        });
        assert_eq!(earlier.ask(), (before, bounding, false));

        // The setting that keeps capabilities across a change of user.
        assert!(!linux::keep_capabilities().unwrap());
        linux::set_keep_capabilities(true).unwrap();
        assert!(linux::keep_capabilities().unwrap());
        assert!(
            linux::secure_bits()
                .unwrap()
                .contains(SecureBits::KEEP_CAPS)
        );
        // Of this thread alone.
        assert!(!earlier.ask().2);
        linux::set_keep_capabilities(false).unwrap();
        assert!(
            !linux::secure_bits()
                .unwrap()
                .contains(SecureBits::KEEP_CAPS)
        );

        // The ambient set takes what is permitted and inheritable.
        assert_eq!(linux::ambient_set().unwrap(), CapabilitySet::EMPTY);
        linux::lower_ambient(Capability::Chown).unwrap();
        linux::clear_ambient().unwrap();
        if !before.inheritable.contains(Capability::Chown) {
            let error = linux::raise_ambient(Capability::Chown).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        }

        let privileged = before.effective.contains(Capability::Setpcap)
            && before.permitted.contains(Capability::Chown)
            && bounding.contains(Capability::AuditWrite);
        if privileged {
            // A capability may be given, and yet not be the process's to
            // use: what Ubuntu's AppArmor restriction of user namespaces
            // does to their root.
            if let Err(error) = linux::drop_bounding(Capability::AuditWrite) {
                assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
                skip!(
                    "(capabilities) no use of capabilities in the user namespace ({})",
                    common::confinement()
                );
                return;
            }
            // Gone from the bounding set of this thread, for good, and
            // still in its other sets.
            let now = linux::bounding_set().unwrap();
            assert_eq!(now, bounding.without(Capability::AuditWrite));
            assert_eq!(now.bits(), status_capabilities("CapBnd"));
            assert_eq!(linux::capabilities().unwrap(), before);
            assert_eq!(earlier.ask().1, bounding);
            // Again is no error.
            linux::drop_bounding(Capability::AuditWrite).unwrap();

            // Inheritable, then ambient.
            let chown = CapabilitySet::from(Capability::Chown);
            let mut wanted = before;
            wanted.inheritable = before.inheritable | chown | Capability::Kill;
            linux::set_capabilities(&wanted).unwrap();
            assert_eq!(linux::capabilities().unwrap(), wanted);
            linux::raise_ambient(Capability::Chown).unwrap();
            linux::raise_ambient(Capability::Kill).unwrap();
            assert_eq!(linux::ambient_set().unwrap(), chown | Capability::Kill);
            assert_eq!(status_capabilities("CapAmb"), 1 << 5 | 1);
            linux::lower_ambient(Capability::Kill).unwrap();
            assert_eq!(linux::ambient_set().unwrap(), chown);
            // What leaves the inheritable set leaves the ambient one.
            wanted.inheritable = before.inheritable;
            linux::set_capabilities(&wanted).unwrap();
            assert_eq!(linux::ambient_set().unwrap(), CapabilitySet::EMPTY);
            wanted.inheritable = before.inheritable | chown;
            linux::set_capabilities(&wanted).unwrap();
            linux::raise_ambient(Capability::Chown).unwrap();
            linux::clear_ambient().unwrap();
            assert_eq!(linux::ambient_set().unwrap(), CapabilitySet::EMPTY);

            // The secure bits: nothing more in the ambient set, and that
            // for good.
            let bits = linux::secure_bits().unwrap();
            let locked = SecureBits::NO_CAP_AMBIENT_RAISE | SecureBits::NO_CAP_AMBIENT_RAISE_LOCKED;
            linux::set_secure_bits(bits | locked).unwrap();
            assert_eq!(linux::secure_bits().unwrap(), bits | locked);
            let error = linux::raise_ambient(Capability::Chown).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
            let error = linux::set_secure_bits(bits).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        } else {
            if !before.effective.contains(Capability::Setpcap) {
                let error = linux::drop_bounding(Capability::AuditWrite).unwrap_err();
                assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
                let bits = linux::secure_bits().unwrap();
                let error = linux::set_secure_bits(bits | SecureBits::NO_ROOT).unwrap_err();
                assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
            }
            skip!("(capabilities) this process has no capability to drop or pass on");
        }

        // Everything given up, which anyone may do: nothing is permitted
        // any more, to this thread.
        let mut less = linux::capabilities().unwrap();
        less.effective = CapabilitySet::EMPTY;
        linux::set_capabilities(&less).unwrap();
        assert_eq!(linux::capabilities().unwrap(), less);
        // The effective set comes back from the permitted one.
        less.effective = less.permitted;
        linux::set_capabilities(&less).unwrap();
        let none = Capabilities::default();
        linux::set_capabilities(&none).unwrap();
        assert_eq!(linux::capabilities().unwrap(), none);
        assert_eq!(status_capabilities("CapEff"), 0);
        assert_eq!(status_capabilities("CapPrm"), 0);
        if !before.permitted.is_empty() {
            let error = linux::set_capabilities(&before).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        }
        let error = linux::set_capabilities(&Capabilities::all_three(
            CapabilitySet::EMPTY.with(Capability::SysAdmin),
        ))
        .unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        // The thread that existed has what it had, and one created now
        // has what its creator has left.
        assert_eq!(earlier.ask().0, before);
        let later = std::thread::spawn(|| linux::capabilities().unwrap());
        assert_eq!(later.join().unwrap(), none);
    }

    #[test]
    fn capabilities() {
        helper("capabilities");
        // The same as root of a user namespace, which has every
        // capability there: what a process without privilege can try.
        if linux::capabilities().unwrap().effective.is_empty()
            && let Some(result) =
                Helper::new("capabilities").run(Place::UserNamespace, |command| command)
        {
            let status = result.unwrap();
            assert!(status.success(), "{status}");
        }
    }

    /// Whether this process is root of the system, with what it takes to
    /// give files capabilities and to become someone else.
    fn real_root() -> bool {
        let effective = linux::capabilities().unwrap().effective;
        linux::effective_user_id() == 0
            && std::fs::read_to_string("/proc/self/uid_map")
                .is_ok_and(|map| map.split_whitespace().eq(["0", "0", "4294967295"]))
            && effective.is_superset(CapabilitySet::of(&[
                Capability::Setfcap,
                Capability::Setuid,
                Capability::Setgid,
            ]))
    }

    /// The capabilities of files, written and read back by who has
    /// `CAP_SETFCAP`: root, or root of a user namespace. `dir` is a
    /// directory of the test, where a file named `kept` is left with
    /// capabilities for the parent to read, or `skipped` with the reason
    /// there are none.
    fn helper_file_capabilities(dir: &std::path::Path) {
        let path = |name: &str| dir.join(name).into_os_string().into_string().unwrap();
        let skipped = |reason: String| {
            std::fs::write(dir.join("skipped"), &reason).unwrap();
            skip!("(filecaps) {reason}");
        };
        let file = path("program");
        std::fs::write(&file, b"#!/bin/true\n").unwrap();
        assert_eq!(linux::file_capabilities(&file), Ok(None));

        let wide = CapabilitySet::of(&[Capability::NetBindService, Capability::CheckpointRestore]);
        let chown = CapabilitySet::of(&[Capability::Chown]);
        let first = FileCapabilities::new(wide, chown, true);
        match linux::set_file_capabilities(&file, &first) {
            Ok(()) => {}
            Err(error) if error.kind() == ErrorKind::Unsupported => {
                return skipped(format!(
                    "the filesystem of the tests has no such attribute: {error}"
                ));
            }
            // Root of its namespace on paper: see `helper_capabilities`.
            Err(error) if error.raw_os_error() == EPERM && !real_root() => {
                return skipped(format!(
                    "no use of capabilities in the user namespace ({})",
                    common::confinement()
                ));
            }
            Err(error) => panic!("set_file_capabilities: {error:?}"),
        }
        // Read from the namespace they are for, they have no root.
        assert_eq!(linux::file_capabilities(&file), Ok(Some(first)));
        // A file that has none has none to remove.
        let bare = path("bare");
        std::fs::write(&bare, b"").unwrap();
        assert_eq!(linux::remove_file_capabilities(&bare), Ok(false));
        // The attribute itself, as the kernel gives it to this process.
        let mut raw = [0u8; 64];
        let len = oscall::fs::unix::get_xattr(&file, "security.capability", &mut raw)
            .unwrap()
            .unwrap();
        assert_eq!(FileCapabilities::from_bytes(&raw[..len]), Ok(first));
        let mut buf = [0u8; FileCapabilities::MAX_LEN];
        assert_eq!(&raw[..len], first.to_bytes(&mut buf));

        // By handle, and replaced.
        let handle = std::fs::File::open(&file).unwrap();
        let handle = common::handle_of(&handle);
        assert_eq!(linux::handle_file_capabilities(handle), Ok(Some(first)));
        let second = FileCapabilities::new(chown, CapabilitySet::EMPTY, false);
        linux::set_handle_file_capabilities(handle, &second).unwrap();
        assert_eq!(linux::file_capabilities(&file), Ok(Some(second)));
        assert_eq!(linux::remove_handle_file_capabilities(handle), Ok(true));
        assert_eq!(linux::remove_handle_file_capabilities(handle), Ok(false));
        assert_eq!(linux::handle_file_capabilities(handle), Ok(None));
        linux::set_file_capabilities(&file, &first).unwrap();
        // Through a link, the file's.
        std::os::unix::fs::symlink("program", dir.join("link")).unwrap();
        assert_eq!(linux::file_capabilities(&path("link")), Ok(Some(first)));
        assert_eq!(linux::remove_file_capabilities(&path("link")), Ok(true));
        assert_eq!(linux::file_capabilities(&file), Ok(None));

        // Writing to the file takes them away.
        linux::set_file_capabilities(&file, &first).unwrap();
        std::fs::OpenOptions::new()
            .append(true)
            .open(&file)
            .unwrap()
            .set_len(4)
            .unwrap();
        std::fs::write(&file, b"changed").unwrap();
        assert_eq!(linux::file_capabilities(&file), Ok(None));

        // A root that is someone else: for who prepares the files of a
        // namespace from the initial one.
        if real_root() {
            let other = first.with_root_id(100_000);
            linux::set_file_capabilities(&file, &other).unwrap();
            assert_eq!(linux::file_capabilities(&file), Ok(Some(other)));
            // The root of the initial namespace is no root to record.
            linux::set_file_capabilities(&file, &first.with_root_id(0)).unwrap();
            assert_eq!(linux::file_capabilities(&file), Ok(Some(first)));
        }

        let kept = path("kept");
        std::fs::write(&kept, b"").unwrap();
        linux::set_file_capabilities(&kept, &first).unwrap();
    }

    /// The capabilities of a file, from within the namespace they are
    /// for and from above.
    #[test]
    fn file_capabilities() {
        let dir = tmp_dir("process_linux_filecaps");
        let dir = std::path::absolute(dir).unwrap();
        let place = if real_root() {
            Place::Here
        } else {
            Place::UserNamespace
        };
        // Without the capability, nothing is written.
        if !linux::capabilities()
            .unwrap()
            .effective
            .contains(Capability::Setfcap)
        {
            let file = dir.join("refused");
            std::fs::write(&file, b"").unwrap();
            let file = file.to_str().unwrap();
            let capabilities = FileCapabilities::new(
                CapabilitySet::of(&Capability::ALL),
                CapabilitySet::EMPTY,
                true,
            );
            match linux::set_file_capabilities(file, &capabilities) {
                Err(error) if error.kind() == ErrorKind::Unsupported => {}
                result => {
                    let error = result.unwrap_err();
                    assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
                    assert_eq!(linux::file_capabilities(file), Ok(None));
                    // Asked before the kernel looks for anything to
                    // remove.
                    let error = linux::remove_file_capabilities(file).unwrap_err();
                    assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
                }
            }
        }
        let helper = Helper::new(&format!("filecaps:{}", dir.display()));
        let Some(result) = helper.run(place, |command| command) else {
            return;
        };
        let status = result.unwrap();
        assert!(status.success(), "{status}");
        if dir.join("skipped").exists() {
            return;
        }
        let kept = dir.join("kept");
        let read = linux::file_capabilities(kept.to_str().unwrap())
            .unwrap()
            .unwrap();
        let wide = CapabilitySet::of(&[Capability::NetBindService, Capability::CheckpointRestore]);
        let chown = CapabilitySet::of(&[Capability::Chown]);
        let written = FileCapabilities::new(wide, chown, true);
        if place == Place::Here {
            assert_eq!(read, written);
        } else {
            // Written by the root of a user namespace, they are for that
            // namespace: from here they have a root, who is this user.
            assert_eq!(read, written.with_root_id(linux::effective_user_id()));
        }
    }

    /// The options of the mount point `path` is under.
    fn mount_options(path: &std::path::Path) -> Vec<String> {
        let text = std::fs::read_to_string("/proc/self/mountinfo").unwrap();
        let mut best: Option<(usize, &str)> = None;
        for line in text.lines() {
            let fields: Vec<&str> = line.split(' ').collect();
            let point = std::path::Path::new(fields[4]);
            // The last of the longest is on top.
            if path.starts_with(point) && best.is_none_or(|(len, _)| fields[4].len() >= len) {
                best = Some((fields[4].len(), fields[5]));
            }
        }
        best.unwrap().1.split(',').map(str::to_owned).collect()
    }

    /// What a program gets from the capabilities of its file, when it is
    /// run by someone who has none.
    #[test]
    fn file_capabilities_of_a_program() {
        if !real_root() {
            // A matter of who runs the tests, not of what they may do:
            // the root of a user namespace of one user has no one else to
            // run a program as.
            common::note("skipped: only root can run a program as a user without capabilities");
            return;
        }
        let mut report = Report::new("process_linux_filecaps_run");
        let dir = report.file.parent().unwrap().to_owned();
        if mount_options(&dir).iter().any(|option| option == "nosuid") {
            skip!(
                "the tests are on a filesystem mounted nosuid, where file capabilities are ignored"
            );
            return;
        }
        let program = dir.join("program");
        std::fs::copy(&report.helper.exe, &program).unwrap();
        std::fs::set_permissions(
            &program,
            std::os::unix::fs::PermissionsExt::from_mode(0o755),
        )
        .unwrap();
        report.helper.exe = program.clone();
        let program = program.to_str().unwrap();
        // A file that is open for writing is not run (`ETXTBSY`), and
        // the copy was: by this process, which closed it, and by every
        // child another test created meanwhile, which has the descriptor
        // until it runs its own program. They are given the time.
        let start = Instant::now();
        loop {
            let probe = Command::new(program)
                .args(&["--exact", "--list", "no-such-test"])
                .stdin(Stdio::Null)
                .stdout(Stdio::Null)
                .spawn();
            match probe {
                Ok(mut child) => {
                    wait(&mut child);
                    break;
                }
                Err(error) if error.kind() == ErrorKind::ExecutableFileBusy => {
                    assert!(start.elapsed() < Duration::from_secs(30), "{error:?}");
                    std::thread::sleep(Duration::from_millis(5));
                }
                Err(error) if error.raw_os_error() == ENOEXEC => break,
                Err(error) => panic!("spawn: {error:?}"),
            }
        }
        // Run as someone else, the program has nothing.
        let Some(inside) = report.run(Place::Here, |command| command.uid(54321).gid(54321)) else {
            return;
        };
        let inside = inside.unwrap();
        assert_eq!(inside["uid"], "54321");
        assert_eq!(set_of(&inside, "CapPrm"), CapabilitySet::EMPTY);

        // With capabilities on its file, it has them: in effect when the
        // file says so.
        let bind = CapabilitySet::of(&[Capability::NetBindService]);
        let both = bind.with(Capability::Chown);
        let capabilities = FileCapabilities::new(both, CapabilitySet::EMPTY, true);
        match linux::set_file_capabilities(program, &capabilities) {
            Ok(()) => {}
            Err(error) if error.kind() == ErrorKind::Unsupported => {
                skip!("the filesystem of the tests has no such attribute: {error}");
                return;
            }
            Err(error) => panic!("set_file_capabilities: {error:?}"),
        }
        let run = |report: &Report| {
            report
                .run(Place::Here, |command| command.uid(54321).gid(54321))
                .unwrap()
                .unwrap()
        };
        let inside = run(&report);
        assert_eq!(inside["uid"], "54321");
        assert_eq!(set_of(&inside, "CapPrm"), both);
        assert_eq!(set_of(&inside, "CapEff"), both);
        assert_eq!(set_of(&inside, "CapInh"), CapabilitySet::EMPTY);
        let capabilities = FileCapabilities::new(bind, CapabilitySet::EMPTY, false);
        linux::set_file_capabilities(program, &capabilities).unwrap();
        let inside = run(&report);
        assert_eq!(set_of(&inside, "CapPrm"), bind);
        assert_eq!(set_of(&inside, "CapEff"), CapabilitySet::EMPTY);

        // Not past the bounding set: a file that wants in effect what the
        // process may not have is not run.
        let capabilities = FileCapabilities::new(both, CapabilitySet::EMPTY, true);
        linux::set_file_capabilities(program, &capabilities).unwrap();
        let keep = CapabilitySet::of(&[Capability::Setuid, Capability::Setgid, Capability::Chown]);
        let error = report
            .run(Place::Here, |command| {
                command.uid(54321).gid(54321).bounding_set(keep)
            })
            .unwrap()
            .unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        // And not for a process that may gain nothing.
        let inside = report
            .run(Place::Here, |command| {
                command.uid(54321).gid(54321).no_new_privileges()
            })
            .unwrap()
            .unwrap();
        assert_eq!(set_of(&inside, "CapPrm"), CapabilitySet::EMPTY);

        // For another namespace than the one of who runs it, nothing.
        linux::set_file_capabilities(program, &capabilities.with_root_id(100_000)).unwrap();
        let inside = run(&report);
        assert_eq!(set_of(&inside, "CapPrm"), CapabilitySet::EMPTY);
        assert_eq!(linux::remove_file_capabilities(program), Ok(true));
    }

    /// The identity of a thread, changed by who may: root, in a process of
    /// its own.
    fn helper_identity() {
        let ids = || {
            (
                linux::user_id(),
                linux::effective_user_id(),
                linux::group_id(),
                linux::effective_group_id(),
            )
        };
        assert_eq!(ids(), (0, 0, 0, 0));
        let earlier = Worker::new(move || (ids(), linux::groups_vec().unwrap()));
        let before = earlier.ask();

        // The groups, then the group, then the user: each needs what the
        // next gives up.
        linux::set_groups(&[7, 5]).unwrap();
        let mut groups = linux::groups_vec().unwrap();
        groups.sort_unstable();
        assert_eq!(groups, [5, 7]);
        linux::set_groups(&[]).unwrap();
        assert_eq!(linux::groups(&mut []).unwrap(), 0);
        assert_eq!(linux::groups_vec().unwrap(), []);

        // The effective identity alone, and back, which the saved one
        // allows.
        linux::set_group_ids(None, Some(12), None).unwrap();
        assert_eq!((linux::group_id(), linux::effective_group_id()), (0, 12));
        linux::set_user_ids(None, Some(11), None).unwrap();
        assert_eq!((linux::user_id(), linux::effective_user_id()), (0, 11));
        // No longer root, as far as rights go.
        assert_eq!(status_capabilities("CapEff"), 0);
        let error = linux::set_groups(&[1]).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        let error = linux::set_user_ids(Some(13), None, None).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        linux::set_user_ids(None, Some(0), None).unwrap();
        linux::set_group_ids(None, Some(0), None).unwrap();
        assert_eq!(ids(), (0, 0, 0, 0));

        // All three, for good: the capabilities go with them.
        linux::set_group_ids(Some(22), Some(22), Some(22)).unwrap();
        linux::set_user_ids(Some(21), Some(21), Some(21)).unwrap();
        assert_eq!(ids(), (21, 21, 22, 22));
        assert_eq!(linux::capabilities().unwrap(), Capabilities::default());
        let error = linux::set_user_ids(None, Some(0), None).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        // To the values it has is always allowed.
        linux::set_user_ids(Some(21), None, Some(21)).unwrap();

        // The thread that existed is who it was: this is the kernel's
        // call, which a C library would have told every thread of.
        assert_eq!(earlier.ask(), before);
        let later = std::thread::spawn(ids);
        assert_eq!(later.join().unwrap(), (21, 21, 22, 22));
    }

    #[test]
    fn identity_of_a_thread() {
        if linux::effective_user_id() != 0
            || linux::user_id() != 0
            || !linux::capabilities()
                .unwrap()
                .effective
                .is_superset(CapabilitySet::of(&[Capability::Setuid, Capability::Setgid]))
        {
            skip!("only root may change its identity");
            return;
        }
        helper("identity");
    }

    /// What a child is left with: the bounding set.
    #[test]
    fn child_bounding_set() {
        let here = linux::capabilities().unwrap().effective;
        let keep = CapabilitySet::of(&[Capability::Chown, Capability::Kill, Capability::Setuid]);
        if !here.contains(Capability::Setpcap) {
            // Refused to a child without the capability, before its
            // program runs.
            if let Some(error) = unwanted().refused(|command| command.bounding_set(keep)) {
                assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
            }
        }
        // Root, of the system or of a namespace of its own, has it.
        let place = if here.contains(Capability::Setpcap) && linux::effective_user_id() == 0 {
            Place::Here
        } else {
            Place::UserNamespace
        };
        let dumpable = linux::is_dumpable().unwrap();
        let report = Report::new("process_linux_bounding");
        let inside = match report.run(place, |command| command.bounding_set(keep)) {
            None => return,
            Some(Ok(inside)) => inside,
            // Root of its namespace on paper: see `helper_capabilities`.
            Some(Err(error)) if error.raw_os_error() == EPERM && place == Place::UserNamespace => {
                skip!(
                    "no use of capabilities in the user namespace ({})",
                    common::confinement()
                );
                return;
            }
            Some(Err(error)) => panic!("spawn: {error:?}"),
        };
        assert_eq!(inside["uid"], "0");
        assert_eq!(set_of(&inside, "CapBnd"), keep);
        // A program run by root gets what the bounding set leaves, and
        // no more.
        assert_eq!(set_of(&inside, "CapPrm"), keep);
        assert_eq!(set_of(&inside, "CapEff"), keep);
        // The caller is as it was: its sets, and its memory, which the
        // child shared (the kernel marks the memory of a process that
        // gains capabilities, not of one that loses some).
        assert_eq!(linux::capabilities().unwrap().effective, here);
        assert_eq!(linux::is_dumpable().unwrap(), dumpable);

        // Nothing at all.
        let inside = Report::new("process_linux_bounding_none")
            .run(place, |command| command.bounding_set(CapabilitySet::EMPTY))
            .unwrap()
            .unwrap();
        assert_eq!(set_of(&inside, "CapBnd"), CapabilitySet::EMPTY);
        assert_eq!(set_of(&inside, "CapEff"), CapabilitySet::EMPTY);
    }

    /// The sets a child gives itself before its program runs.
    #[test]
    fn child_capabilities() {
        let here = linux::capabilities().unwrap();
        // Giving up everything is anyone's right.
        let inside = Report::new("process_linux_caps_none").run(Place::Here, |command| {
            command.capabilities(Capabilities::default())
        });
        let Some(inside) = inside else { return };
        let inside = inside.unwrap();
        assert_eq!(set_of(&inside, "CapInh"), CapabilitySet::EMPTY);
        if linux::effective_user_id() != 0 {
            assert_eq!(set_of(&inside, "CapEff"), CapabilitySet::EMPTY);
        }
        // Taking what one has not is nobody's.
        if !here.permitted.contains(Capability::SysAdmin) {
            let error = unwanted()
                .refused(|command| {
                    command.capabilities(Capabilities::all_three(Capability::SysAdmin.into()))
                })
                .unwrap();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
            let error = unwanted()
                .refused(|command| command.ambient_capabilities(Capability::SysAdmin.into()))
                .unwrap();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        }
        assert_eq!(linux::capabilities().unwrap(), here);

        // The inheritable set passes to the program as it is; the others
        // are computed again, and root gets its bounding set back.
        let place = if here.effective.contains(Capability::Setpcap) {
            Place::Here
        } else {
            Place::UserNamespace
        };
        let set = CapabilitySet::of(&[Capability::Chown, Capability::NetBindService]);
        let Some(inside) = Report::new("process_linux_caps").run(place, |command| {
            command.capabilities(Capabilities::all_three(set))
        }) else {
            return;
        };
        let inside = inside.unwrap();
        assert_eq!(set_of(&inside, "CapInh"), set);
        if inside["uid"] == "0" {
            assert_eq!(set_of(&inside, "CapEff"), set_of(&inside, "CapBnd"));
        }
    }

    /// A child of root that becomes someone else, and keeps a capability.
    #[test]
    fn child_ambient_capabilities() {
        let here = linux::capabilities().unwrap().effective;
        let needed =
            CapabilitySet::of(&[Capability::Setuid, Capability::Setgid, Capability::Setpcap]);
        if linux::effective_user_id() != 0 || !here.is_superset(needed) {
            skip!("only root may start a child as another user");
            return;
        }
        let set = CapabilitySet::of(&[Capability::NetBindService, Capability::Kill])
            .intersection(linux::capabilities().unwrap().permitted);
        assert!(!set.is_empty());
        fn someone(command: Command<'_>) -> Command<'_> {
            command.uid(4321).gid(1234).groups(&[])
        }
        // Nothing when the helper cannot be executed (root in a container
        // under qemu-user): it said so.
        let Some(inside) = Report::new("process_linux_ambient").run(Place::Here, |command| {
            someone(command)
                .capabilities(Capabilities::all_three(set))
                .ambient_capabilities(set)
        }) else {
            return;
        };
        let inside = inside.unwrap();
        assert_eq!(
            (inside["uid"].as_str(), inside["gid"].as_str()),
            ("4321", "1234")
        );
        for name in ["CapEff", "CapPrm", "CapInh", "CapAmb"] {
            assert_eq!(set_of(&inside, name), set, "{name}");
        }
        // The setting that kept them across the change of user does not
        // outlive `execve`.
        assert_eq!(inside["keep"], "false");

        // Without the ambient set the program has nothing: it is not
        // root, and its file has no capabilities.
        let inside = Report::new("process_linux_ambient_none")
            .run(Place::Here, |command| {
                someone(command).capabilities(Capabilities::all_three(set))
            })
            .unwrap()
            .unwrap();
        assert_eq!(set_of(&inside, "CapInh"), set);
        assert_eq!(set_of(&inside, "CapEff"), CapabilitySet::EMPTY);
        assert_eq!(set_of(&inside, "CapPrm"), CapabilitySet::EMPTY);
        // And without anything asked, a change of user gives up all.
        let inside = Report::new("process_linux_ambient_plain")
            .run(Place::Here, someone)
            .unwrap()
            .unwrap();
        assert_eq!(set_of(&inside, "CapEff"), CapabilitySet::EMPTY);
        assert_eq!(set_of(&inside, "CapAmb"), CapabilitySet::EMPTY);
        // What is not inheritable cannot be ambient.
        let error = unwanted()
            .refused(|command| someone(command).ambient_capabilities(set))
            .unwrap();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
    }

    /// Run under a filter: two calls fail with errors of the filter's
    /// choosing, and the rest works.
    fn helper_filtered() {
        let me = process::id();
        let error = unix::session(me).unwrap_err();
        assert_eq!(error.raw_os_error(), i32::from(FIRST), "{error:?}");
        let error = unix::process_group(me).unwrap_err();
        assert_eq!(error.raw_os_error(), i32::from(SECOND), "{error:?}");
        assert_ne!(process::parent_id(), 0);
        assert_eq!(linux::seccomp::mode().unwrap(), Mode::Filter);
        assert_eq!(status_field("Seccomp", 0), "2");
        assert!(linux::no_new_privileges().unwrap());
        // What the program starts is under the filter too.
        helper("inherited");
    }

    /// A filter for a child, installed before its program starts.
    #[test]
    fn child_filter() {
        let mut buf = [Instruction::default(); seccomp::len_for(2)];
        let rules = [
            (nr::GETSID, Action::Errno(FIRST)),
            (nr::GETPGID, Action::Errno(SECOND)),
        ];
        let errors = seccomp::build(&mut buf, &rules, Action::Allow).unwrap();
        let flags = FilterFlags::empty();

        let filtered = Helper::new("filtered");
        let Some(result) = filtered.run(Place::Here, |command| {
            command.no_new_privileges().seccomp(errors, flags)
        }) else {
            return;
        };
        let status = match result {
            Ok(status) => status,
            Err(error) if no_seccomp(&error) => {
                skip!("qemu-user has no seccomp: {error}");
                return;
            }
            Err(error) => panic!("spawn: {error:?}"),
        };
        assert!(status.success(), "{status}");
        // The caller has no filter for that.
        unix::session(process::id()).unwrap();

        // Who may gain privileges may not be filtered, unless it has the
        // capability.
        if !linux::capabilities()
            .unwrap()
            .effective
            .contains(Capability::SysAdmin)
            && !linux::no_new_privileges().unwrap()
        {
            let error = filtered
                .refused(|command| command.seccomp(errors, flags))
                .unwrap();
            assert_eq!(error.raw_os_error(), EACCES, "{error:?}");
            assert_eq!(error.kind(), ErrorKind::PermissionDenied);
        }

        // A filter that ends the process.
        let mut buf = [Instruction::default(); seccomp::len_for(1)];
        let kills = seccomp::deny_list(&mut buf, &[nr::GETSID], Action::KillProcess).unwrap();
        let status = Helper::new("killed")
            .run(Place::Here, |command| {
                command
                    .no_new_privileges()
                    .seccomp(kills, FilterFlags::LOG)
                    .stderr(Stdio::Null)
            })
            .unwrap()
            .unwrap();
        assert_eq!(status.signal(), Some(SIGSYS), "{status}");

        // A filter that forbids `execve` leaves no program to run, and
        // `spawn` says what the filter said.
        let mut buf = [Instruction::default(); seccomp::len_for(1)];
        let no_exec = seccomp::deny_list(&mut buf, &[nr::EXECVE], Action::Errno(FIRST)).unwrap();
        let error = filtered
            .refused(|command| command.no_new_privileges().seccomp(no_exec, flags))
            .unwrap();
        assert_eq!(error.raw_os_error(), i32::from(FIRST), "{error:?}");

        // A filter that allows next to nothing, and answers the rest with
        // an error: the child can neither run its program, nor say so,
        // nor exit. It ends all the same, and the caller is not left
        // waiting for it.
        let mut buf = [Instruction::default(); seccomp::len_for(1)];
        let nothing = seccomp::allow_list(&mut buf, &[nr::READ], Action::Errno(FIRST)).unwrap();
        // No core dump for that.
        let no_core = [(
            unix::Resource::CoreSize,
            unix::Limit {
                soft: Some(0),
                hard: Some(0),
            },
        )];
        let status = filtered
            .run(Place::Here, |command| {
                command
                    .limits(&no_core)
                    .no_new_privileges()
                    .seccomp(nothing, flags)
            })
            .unwrap()
            .unwrap();
        assert_eq!(status.signal(), Some(SIGILL), "{status}");

        // What is no program is refused before anything is created.
        let error = filtered
            .refused(|command| command.seccomp(&[], flags))
            .unwrap();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    }

    /// Filters are a thread's, unless every thread is asked for.
    fn helper_threads() {
        let me = process::id();
        let probe = move || {
            let code = |result: oscall::Result<u32>| result.err().map(|error| error.raw_os_error());
            (code(unix::session(me)), code(unix::process_group(me)))
        };
        let earlier = Worker::new(probe);
        assert_eq!(earlier.ask(), (None, None));
        let before = match linux::seccomp::mode() {
            Ok(mode) => mode,
            Err(error) if no_seccomp(&error) => {
                skip!("(threads) qemu-user has no seccomp: {error}");
                return;
            }
            Err(error) => panic!("mode: {error:?}"),
        };

        let mut buf = [Instruction::default(); seccomp::len_for(1)];
        let first = seccomp::deny_list(&mut buf, &[nr::GETSID], Action::Errno(FIRST)).unwrap();
        let privileged = linux::capabilities()
            .unwrap()
            .effective
            .contains(Capability::SysAdmin);
        if !privileged && !linux::no_new_privileges().unwrap() {
            let error = seccomp::install(first, FilterFlags::empty()).unwrap_err();
            assert_eq!(error.raw_os_error(), EACCES, "{error:?}");
            assert_eq!(linux::seccomp::mode().unwrap(), before);
        }
        linux::set_no_new_privileges().unwrap();
        if let Err(error) = seccomp::install(first, FilterFlags::empty()) {
            assert!(no_seccomp(&error), "install: {error:?}");
            skip!("(threads) qemu-user has no seccomp: {error}");
            return;
        }
        assert_eq!(linux::seccomp::mode().unwrap(), Mode::Filter);
        let first = Some(i32::from(FIRST));
        let second = Some(i32::from(SECOND));
        assert_eq!(probe(), (first, None));
        // The thread that existed has no filter; one created now has its
        // creator's.
        assert_eq!(earlier.ask(), (None, None));
        assert_eq!(std::thread::spawn(probe).join().unwrap(), (first, None));

        // Strict mode is not for a thread that has a filter.
        let error = seccomp::set_strict().unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");

        // A second filter, for every thread: it adds to the first where
        // there is one. The thread that had none gets both, since it is
        // given the filters of the caller.
        let mut buf = [Instruction::default(); seccomp::len_for(1)];
        let more = seccomp::deny_list(&mut buf, &[nr::GETPGID], Action::Errno(SECOND)).unwrap();
        seccomp::install(more, FilterFlags::ALL_THREADS).unwrap();
        assert_eq!(probe(), (first, second));
        assert_eq!(earlier.ask(), (first, second));
        // Of two filters, the one that is harder on a call decides.
        let mut buf = [Instruction::default(); seccomp::len_for(1)];
        let softer = seccomp::deny_list(&mut buf, &[nr::GETSID], Action::Log).unwrap();
        seccomp::install(softer, FilterFlags::empty()).unwrap();
        assert_eq!(probe(), (first, second));
    }

    #[test]
    fn filter_of_a_thread() {
        helper("threads");
    }

    /// Forks a child that runs `f`, which must only make system calls and
    /// not return, and gives it the write end of a pipe: what it wrote,
    /// and how it ended.
    fn forked(f: impl FnOnce(&oscall::OwnedHandle)) -> (Vec<u8>, ExitStatus) {
        let (read, write) = io::pipe().unwrap();
        // SAFETY: the child makes system calls only, and exits.
        match unsafe { unix::fork() }.unwrap() {
            Fork::Child => {
                f(&write);
                process::exit(100)
            }
            Fork::Parent(mut child) => {
                drop(write);
                let said = read_all(&read);
                (said, wait(&mut child))
            }
        }
    }

    /// Ends the calling thread, which `exit_group` is not allowed to do in
    /// strict mode.
    fn exit_thread(code: i32) -> ! {
        loop {
            // SAFETY: the call does not return.
            let _ = unsafe { syscall!(EXIT, code) };
        }
    }

    /// Says an error to the parent, in a child that may do nothing else.
    fn say_error(pipe: &oscall::OwnedHandle, error: Error) -> ! {
        let _ = io::write(pipe, &error.raw_os_error().to_ne_bytes());
        process::exit(101)
    }

    /// Strict mode, in children that have one thread and nothing to lose.
    fn helper_strict() {
        let filtered = match linux::seccomp::mode() {
            Ok(mode) => mode == Mode::Filter,
            Err(error) if no_seccomp(&error) => {
                skip!("(strict) qemu-user has no seccomp: {error}");
                return;
            }
            Err(error) => panic!("mode: {error:?}"),
        };
        // `read`, `write` and the `exit` of the thread are what is left.
        let (said, status) = forked(|pipe| {
            if let Err(error) = seccomp::set_strict() {
                say_error(pipe, error);
            }
            let _ = io::write(pipe, b"strict");
            exit_thread(7)
        });
        if status.code() == Some(101) {
            let error = Error::from_raw_os_error(i32::from_ne_bytes(said[..4].try_into().unwrap()));
            // A process that has a filter already, as in a container,
            // cannot change to this mode.
            if filtered && error.kind() == ErrorKind::InvalidInput {
                skip!("(strict) the process has a filter already, as in a container: {error}");
                return;
            }
            assert!(no_seccomp(&error), "set_strict: {error:?}");
            skip!("(strict) qemu-user has no seccomp: {error}");
            return;
        }
        assert_eq!(said, b"strict");
        assert_eq!(status.code(), Some(7), "{status}");
        // Anything else is the end, by a signal nothing catches.
        let (said, status) = forked(|pipe| {
            if let Err(error) = seccomp::set_strict() {
                say_error(pipe, error);
            }
            let _ = io::write(pipe, b"strict");
            let _ = process::parent_id();
            let _ = io::write(pipe, b"alive");
            exit_thread(8)
        });
        assert_eq!(said, b"strict");
        assert_eq!(status.signal(), Some(SIGKILL), "{status}");
        // `exit_group`, which is how a process usually ends, included.
        let (_, status) = forked(|pipe| {
            if let Err(error) = seccomp::set_strict() {
                say_error(pipe, error);
            }
            process::exit(9)
        });
        assert_eq!(status.signal(), Some(SIGKILL), "{status}");
    }

    #[test]
    fn strict_mode() {
        helper("strict");
    }

    /// An allow-list, in a child that makes four system calls.
    fn helper_allow() {
        let mut buf = [Instruction::default(); seccomp::len_for(3)];
        let allowed = [nr::WRITE, nr::EXIT_GROUP, nr::GETPPID];
        let program = seccomp::allow_list(&mut buf, &allowed, Action::Errno(FIRST)).unwrap();
        let me = process::id();
        let (said, status) = forked(|pipe| {
            if let Err(error) = linux::set_no_new_privileges() {
                say_error(pipe, error);
            }
            if let Err(error) = seccomp::install(program, FilterFlags::empty()) {
                say_error(pipe, error);
            }
            // Allowed, and not: the error is the filter's.
            let parent = process::parent_id();
            let refused = match unix::session(me) {
                Err(error) => error.raw_os_error(),
                Ok(_) => 0,
            };
            let _ = io::write(pipe, &parent.to_ne_bytes());
            let _ = io::write(pipe, &refused.to_ne_bytes());
            process::exit(9)
        });
        if status.code() == Some(101) {
            let error = Error::from_raw_os_error(i32::from_ne_bytes(said[..4].try_into().unwrap()));
            assert!(no_seccomp(&error), "install: {error:?}");
            skip!("(allow) qemu-user has no seccomp: {error}");
            return;
        }
        assert_eq!(status.code(), Some(9), "{status}");
        assert_eq!(said[..4], me.to_ne_bytes());
        assert_eq!(said[4..], i32::from(FIRST).to_ne_bytes());
    }

    #[test]
    fn allow_list() {
        helper("allow");
    }

    /// Waits for the listener to be readable, and receives the call.
    fn next_call(
        poller: &oscall::event::Poller,
        listener: &oscall::OwnedHandle,
    ) -> seccomp::Notification {
        let mut events = [oscall::event::Event::EMPTY; 4];
        let long = Some(Duration::from_secs(60));
        assert_eq!(poller.wait(&mut events, long).unwrap(), 1, "no call came");
        assert_eq!(events[0].token(), 7);
        assert!(events[0].readiness().is_readable(), "{:?}", events[0]);
        seccomp::receive(listener).unwrap()
    }

    /// A poller that waits for the calls of a listener.
    fn listener_poller(listener: &oscall::OwnedHandle) -> oscall::event::Poller {
        use oscall::event::{self, Interest, Mode, Poller};
        let poller = Poller::new().unwrap();
        event::unix::register(&poller, listener, 7, Interest::READABLE, Mode::LEVEL).unwrap();
        poller
    }

    /// Whether `tid` is a thread of the process `pid`.
    fn is_thread_of(tid: u32, pid: u32) -> bool {
        std::path::Path::new(&format!("/proc/{pid}/task/{tid}")).exists()
    }

    /// The filter of the tests of a supervisor: two calls are handed
    /// over, the rest is allowed.
    fn notifying() -> Vec<Instruction> {
        let mut buf = [Instruction::default(); seccomp::len_for(2)];
        let rules = [
            (nr::GETSID, Action::UserNotify),
            (nr::GETPGID, Action::UserNotify),
        ];
        seccomp::build(&mut buf, &rules, Action::Allow)
            .unwrap()
            .to_vec()
    }

    /// Gives the caller of `call` the write end of a new pipe as the
    /// result of its call, and returns the read end.
    fn answer_with_pipe(
        listener: &oscall::OwnedHandle,
        call: &seccomp::Notification,
    ) -> oscall::OwnedHandle {
        use seccomp::{AddHandleFlags, Response};
        let (read, write) = io::pipe().unwrap();
        // A place of the supervisor's choosing first, which is not an
        // answer.
        let at = seccomp::add_handle(
            listener,
            call.id,
            &write,
            Some(700),
            AddHandleFlags::empty(),
        );
        assert_eq!(at, Ok(700));
        assert!(seccomp::is_valid(listener, call.id).unwrap());
        // What is not there to give, and whom there is no one to give to.
        // SAFETY: the number is used for one call, which finds nothing.
        let closed = unsafe { oscall::BorrowedHandle::borrow_raw(999_999) };
        let flags = AddHandleFlags::CLOSE_ON_EXEC;
        let error = seccomp::add_handle(listener, call.id, &closed, None, flags).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");
        let error = seccomp::add_handle(listener, !call.id, &write, None, flags).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        // Then the answer and the handle in one step.
        let flags = AddHandleFlags::CLOSE_ON_EXEC | AddHandleFlags::RESPOND;
        match seccomp::add_handle(listener, call.id, &write, None, flags) {
            Ok(number) => assert!(number > 2 && number != 700, "{number}"),
            // Before Linux 5.14: in two.
            Err(error) if error.kind() == ErrorKind::InvalidInput => {
                common::note(&format!(
                    "no answer with a handle in one step here: {error}"
                ));
                let number =
                    seccomp::add_handle(listener, call.id, &write, None, AddHandleFlags::empty())
                        .unwrap();
                let response = Response::success(call.id, i64::from(number));
                seccomp::respond(listener, &response).unwrap();
            }
            Err(error) => panic!("add_handle: {error:?}"),
        }
        assert!(!seccomp::is_valid(listener, call.id).unwrap());
        read
    }

    /// A thread whose calls another thread of the process answers.
    fn helper_notify() {
        use seccomp::Response;
        use std::sync::mpsc;

        let me = process::id();
        let program = notifying();
        let (send, installed) = mpsc::channel();
        let (said, results) = mpsc::channel();
        let filtered = std::thread::spawn(move || {
            let tid = oscall::thread::id();
            if let Err(error) = linux::set_no_new_privileges() {
                send.send(Err(error)).unwrap();
                return;
            }
            // Waiting until killed is for a filter that has a listener.
            let plain = seccomp::install(&program, FilterFlags::WAIT_KILLABLE).unwrap_err();
            let listener = match seccomp::install_listener(&program, FilterFlags::empty()) {
                Ok(listener) => listener,
                Err(error) => {
                    send.send(Err(error)).unwrap();
                    return;
                }
            };
            // One listener for the filters of a thread.
            let second = seccomp::install_listener(&program, FilterFlags::empty()).unwrap_err();
            send.send(Ok((listener, tid, plain, second))).unwrap();
            // From here on these calls are another thread's to answer.
            let code = |result: oscall::Result<u32>| match result {
                Ok(value) => i64::from(value),
                Err(error) => -i64::from(error.raw_os_error()),
            };
            for _ in 0..3 {
                said.send(code(unix::session(me))).unwrap();
            }
            let pipe = code(unix::process_group(me));
            // What the supervisor gave: two numbers for one pipe.
            for (fd, text) in [(pipe, b"via"), (700, b"700")] {
                // SAFETY: the bytes written are readable.
                let _ = unsafe { syscall!(WRITE, fd as usize, text.as_ptr(), 3usize) };
            }
            said.send(pipe).unwrap();
        });
        let (listener, tid, plain, second) = match installed.recv().unwrap() {
            Ok(installed) => installed,
            Err(error) => {
                assert!(no_seccomp(&error), "install_listener: {error:?}");
                skip!("(notify) qemu-user has no seccomp: {error}");
                filtered.join().unwrap();
                return;
            }
        };
        assert_eq!(plain.kind(), ErrorKind::InvalidInput, "{plain:?}");
        assert_eq!(second.kind(), ErrorKind::ResourceBusy, "{second:?}");
        // Close-on-exec, like every handle.
        assert!(!io::is_inheritable(&listener).unwrap());
        let poller = listener_poller(&listener);

        // A call, and what is known of it.
        let call = next_call(&poller, &listener);
        assert_eq!(u64::from(call.pid), tid);
        assert_eq!(call.data.number as usize, nr::GETSID);
        assert_eq!(call.data.arch, seccomp::AUDIT_ARCH);
        assert_eq!(call.data.args[0], u64::from(me));
        assert_ne!(call.data.instruction_pointer, 0);
        assert_eq!(call.flags, 0);
        assert!(seccomp::is_valid(&listener, call.id).unwrap());
        assert!(!seccomp::is_valid(&listener, !call.id).unwrap());
        // It waits: nothing was said.
        assert!(results.try_recv().is_err());
        // An answer for a call there is not, then for this one, once.
        let error = seccomp::respond(&listener, &Response::success(!call.id, 1)).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        seccomp::respond(&listener, &Response::success(call.id, 4242)).unwrap();
        assert_eq!(results.recv().unwrap(), 4242);
        assert!(!seccomp::is_valid(&listener, call.id).unwrap());
        let error = seccomp::respond(&listener, &Response::success(call.id, 1)).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");

        // An error of the supervisor's choosing.
        let second = next_call(&poller, &listener);
        assert_ne!(second.id, call.id);
        seccomp::respond(&listener, &Response::error(second.id, i32::from(FIRST))).unwrap();
        assert_eq!(results.recv().unwrap(), -i64::from(FIRST));

        // The call made after all, by the kernel.
        let third = next_call(&poller, &listener);
        seccomp::respond(&listener, &Response::continue_syscall(third.id)).unwrap();
        let session = results.recv().unwrap();
        assert_eq!(session, i64::from(unix::session(me).unwrap()));

        // A handle for the caller, as the result of its call.
        let fourth = next_call(&poller, &listener);
        assert_eq!(fourth.data.number as usize, nr::GETPGID);
        let pipe = answer_with_pipe(&listener, &fourth);
        let number = results.recv().unwrap();
        assert!(number > 2, "{number}");
        let mut text = [0u8; 6];
        let mut len = 0;
        while len < text.len() {
            len += io::read(&pipe, &mut text[len..]).unwrap();
        }
        assert_eq!(&text, b"via700");

        // The settings of a listener, where the kernel has any.
        match seccomp::set_listener_flags(&listener, seccomp::ListenerFlags::SYNC_WAKE_UP) {
            Ok(()) => {
                seccomp::set_listener_flags(&listener, seccomp::ListenerFlags::empty()).unwrap()
            }
            // Before Linux 6.7.
            Err(error) => assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}"),
        }

        // When nothing is left that the filter applies to, the listener
        // says so.
        filtered.join().unwrap();
        let mut events = [oscall::event::Event::EMPTY; 4];
        let long = Some(Duration::from_secs(60));
        assert_eq!(poller.wait(&mut events, long).unwrap(), 1);
        let readiness = events[0].readiness();
        assert!(
            readiness.contains(oscall::event::Readiness::HANGUP),
            "{readiness:?}"
        );
        // This thread never had the filter.
        assert_eq!(unix::session(me).map(i64::from), Ok(session));
    }

    #[test]
    fn notifications_of_a_thread() {
        helper("notify");
    }

    /// Run under a filter whose listener the parent holds: says what its
    /// two calls returned.
    fn helper_notified(file: &str) {
        let me = process::id();
        let session = unix::session(me).unwrap();
        // The answer to this one is a handle to write to.
        let pipe = unix::process_group(me).unwrap();
        // SAFETY: the bytes written are readable.
        let written = unsafe { syscall!(WRITE, pipe as usize, b"through".as_ptr(), 7usize) };
        assert_eq!(written, Ok(7));
        // A third call, which the supervisor refuses.
        let other = unix::session(me).unwrap_err();
        std::fs::write(
            file,
            format!(
                "session={session}\nother={}\npid={me}\n",
                other.raw_os_error()
            ),
        )
        .unwrap();
    }

    /// A child whose calls its parent answers.
    #[test]
    fn child_listener() {
        use linux::ChildExt as _;
        use seccomp::Response;

        let program = notifying();
        let flags = FilterFlags::empty();
        let report = Report::new("process_linux_notified");
        let helper = Helper::new(&format!("notified:{}", report.file.display()));
        fn command(helper: &Helper) -> Command<'_> {
            Command::new(helper.exe.as_os_str().as_encoded_bytes())
                .args(&["--exact", "--nocapture", "helper_child_process"])
                .env(&helper.env)
                .stdin(Stdio::Null)
                .stdout(Stdio::Null)
        }
        let spawned = command(&helper)
            .no_new_privileges()
            .seccomp_listener(&program, flags)
            .spawn();
        let mut child = match spawned {
            Ok(child) => child,
            Err(error) if error.raw_os_error() == ENOEXEC => {
                skip!("the system cannot execute {}", helper.exe.display());
                return;
            }
            Err(error) if no_seccomp(&error) => {
                skip!("qemu-user has no seccomp: {error}");
                return;
            }
            Err(error) => panic!("spawn: {error:?}"),
        };
        // The listener is here before the program has asked anything.
        let listener = child.take_seccomp_listener().unwrap();
        assert!(child.take_seccomp_listener().is_none());
        assert!(!io::is_inheritable(&listener).unwrap());
        let poller = listener_poller(&listener);

        let call = next_call(&poller, &listener);
        // The thread that asked: one of the child (its test runs on a
        // thread of the harness).
        assert!(is_thread_of(call.pid, child.id()), "{call:?}");
        assert_eq!(call.data.number as usize, nr::GETSID);
        assert_eq!(call.data.args[0], u64::from(child.id()));
        seccomp::respond(&listener, &Response::success(call.id, 777)).unwrap();
        let call = next_call(&poller, &listener);
        assert_eq!(call.data.number as usize, nr::GETPGID);
        let pipe = answer_with_pipe(&listener, &call);
        let mut text = [0u8; 7];
        let mut len = 0;
        while len < text.len() {
            match io::read(&pipe, &mut text[len..]).unwrap() {
                0 => panic!("the child wrote {:?}", &text[..len]),
                n => len += n,
            }
        }
        assert_eq!(&text, b"through");
        let call = next_call(&poller, &listener);
        seccomp::respond(&listener, &Response::error(call.id, i32::from(SECOND))).unwrap();
        let status = wait(&mut child);
        assert!(status.success(), "{status}");
        let said = std::fs::read_to_string(&report.file).unwrap();
        assert_eq!(
            said,
            format!("session=777\nother={SECOND}\npid={}\n", child.id())
        );
        // No process is left under the filter.
        let mut events = [oscall::event::Event::EMPTY; 4];
        let long = Some(Duration::from_secs(60));
        assert_eq!(poller.wait(&mut events, long).unwrap(), 1);
        assert!(
            events[0]
                .readiness()
                .contains(oscall::event::Readiness::HANGUP)
        );
        // The caller has no filter for that, and no child it did not
        // create.
        unix::session(process::id()).unwrap();

        // A child that has none has no listener.
        let mut plain = command(&Helper::new("report:/dev/null")).spawn().unwrap();
        assert!(plain.take_seccomp_listener().is_none());
        assert!(wait(&mut plain).success());
        let mut buf = [Instruction::default(); seccomp::len_for(1)];
        let errors = seccomp::deny_list(&mut buf, &[nr::GETSID], Action::Errno(FIRST)).unwrap();
        let mut filtered = command(&Helper::new("inherited"))
            .no_new_privileges()
            .seccomp(errors, flags)
            .spawn()
            .unwrap();
        assert!(filtered.take_seccomp_listener().is_none());
        assert!(wait(&mut filtered).success());

        // A listener closed: the calls it was to answer fail.
        let report = Report::new("process_linux_notified_closed");
        let helper = Helper::new(&format!("report:{}", report.file.display()));
        let mut child = command(&helper)
            .no_new_privileges()
            .seccomp_listener(&program, FilterFlags::LOG)
            .spawn()
            .unwrap();
        // With the `Child`, which holds it.
        assert!(wait(&mut child).success());
        drop(child);
        let mut child = command(&Helper::new("unanswered"))
            .no_new_privileges()
            .seccomp_listener(&program, flags)
            .stdin(Stdio::Null)
            .spawn()
            .unwrap();
        drop(child.take_seccomp_listener());
        let status = wait(&mut child);
        assert!(status.success(), "{status}");

        // What `spawn` refuses, and what the child cannot do: the caller
        // is told, and waits for nothing.
        let error = command(&helper)
            .no_new_privileges()
            .seccomp_listener(&[], flags)
            .spawn()
            .unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        if !linux::capabilities()
            .unwrap()
            .effective
            .contains(Capability::SysAdmin)
            && !linux::no_new_privileges().unwrap()
        {
            let error = command(&helper)
                .seccomp_listener(&program, flags)
                .spawn()
                .unwrap_err();
            assert_eq!(error.raw_os_error(), EACCES, "{error:?}");
        }
        let mut buf = [Instruction::default(); seccomp::len_for(2)];
        let rules = [
            (nr::EXECVE, Action::Errno(FIRST)),
            (nr::GETSID, Action::UserNotify),
        ];
        let no_exec = seccomp::build(&mut buf, &rules, Action::Allow).unwrap();
        let error = command(&helper)
            .no_new_privileges()
            .seccomp_listener(no_exec, flags)
            .spawn()
            .unwrap_err();
        assert_eq!(error.raw_os_error(), i32::from(FIRST), "{error:?}");

        // With everything else a child may be given: namespaces whose
        // maps the caller writes while the child waits, in which it is
        // the first process.
        let ids = root_maps();
        let report = Report::new("process_linux_notified_namespaces");
        let helper = Helper::new(&format!("notified:{}", report.file.display()));
        let spawned = command(&helper)
            .namespaces(Namespaces::USER | Namespaces::PID)
            .uid_map(&ids.0)
            .gid_map(&ids.1)
            .deny_setgroups()
            .no_new_privileges()
            .seccomp_listener(&program, flags)
            .spawn();
        let mut child = match spawned {
            Ok(child) => child,
            Err(error) => match common::namespace_refusal(&error) {
                Some(reason) => {
                    skip!("(notified) {reason}: {error}");
                    return;
                }
                None => panic!("spawn: {error:?}"),
            },
        };
        let listener = child.take_seccomp_listener().unwrap();
        let poller = listener_poller(&listener);
        let call = next_call(&poller, &listener);
        // The process is the first of its namespace, and one like
        // another in this one.
        assert!(is_thread_of(call.pid, child.id()), "{call:?}");
        assert_eq!(call.data.args[0], 1);
        seccomp::respond(&listener, &Response::success(call.id, 778)).unwrap();
        let call = next_call(&poller, &listener);
        let pipe = answer_with_pipe(&listener, &call);
        let call = next_call(&poller, &listener);
        // What the child wrote before it asked again.
        let mut text = [0u8; 7];
        assert_eq!(io::read(&pipe, &mut text), Ok(7));
        assert_eq!(&text, b"through");
        seccomp::respond(&listener, &Response::error(call.id, i32::from(SECOND))).unwrap();
        let status = wait(&mut child);
        assert!(status.success(), "{status}");
        let said = std::fs::read_to_string(&report.file).unwrap();
        assert_eq!(said, format!("session=778\nother={SECOND}\npid=1\n"));
    }
}