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
//! Tests of `oscall::fs::linux`: mounting, unmounting, and the root
//! directory.
//!
//! Nothing is ever mounted where the tests run: what mounts is a helper
//! process (this binary, run again with `OSCALL_TEST_HELPER` set) in a
//! mount namespace of its own, which it leaves no trace of. That takes
//! `CAP_SYS_ADMIN`, or a user namespace to be root of; where the
//! environment has neither, the test says so (`skipped: ...`) and passes,
//! except in a run that exists to cover it (`OSCALL_REQUIRE_PRIVILEGED`).
#![cfg(any(target_os = "linux", target_os = "fullrust"))]

mod common;

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

use oscall::ErrorKind;
use oscall::fs::linux::{
    self as mounts, FsConfig, FsPickFlags, MountAttributes, MountFlags, MountSetAttr,
    MountSetAttrFlags, MoveMountFlags, OpenTreeFlags, Propagation, UnmountFlags,
};
use oscall::process::linux::{self, Capability};

#[test]
fn flags() {
    let all = [
        MountFlags::READ_ONLY,
        MountFlags::NO_SUID,
        MountFlags::NO_DEV,
        MountFlags::NO_EXEC,
        MountFlags::SYNCHRONOUS,
        MountFlags::DIR_SYNC,
        MountFlags::NO_SYMLINK_FOLLOW,
        MountFlags::NO_ATIME,
        MountFlags::NO_DIR_ATIME,
        MountFlags::REL_ATIME,
        MountFlags::STRICT_ATIME,
        MountFlags::LAZY_TIME,
        MountFlags::SILENT,
    ];
    let mut union = MountFlags::empty();
    for flag in all {
        assert!(!flag.is_empty() && !union.intersects(flag));
        union |= flag;
    }
    assert_eq!(
        format!("{:?}", MountFlags::READ_ONLY | MountFlags::NO_EXEC),
        "MountFlags(READ_ONLY | NO_EXEC)"
    );
    let all = [
        UnmountFlags::FORCE,
        UnmountFlags::DETACH,
        UnmountFlags::EXPIRE,
        UnmountFlags::NO_FOLLOW,
    ];
    let mut union = UnmountFlags::empty();
    for flag in all {
        assert!(!flag.is_empty() && !union.intersects(flag));
        union |= flag;
    }
    assert_eq!(UnmountFlags::default(), UnmountFlags::empty());
    // Those of the calls on handles.
    macro_rules! distinct {
        ($type:ident: $($flag:ident),+) => {{
            let mut union = $type::empty();
            for flag in [$($type::$flag),+] {
                assert!(!flag.is_empty() && !union.intersects(flag));
                union |= flag;
            }
        }};
    }
    distinct!(MountAttributes: READ_ONLY, NO_SUID, NO_DEV, NO_EXEC, NO_ATIME, STRICT_ATIME,
        REL_ATIME, NO_DIR_ATIME, NO_SYMLINK_FOLLOW);
    distinct!(FsPickFlags: NO_FOLLOW, NO_AUTOMOUNT, EMPTY_PATH);
    distinct!(OpenTreeFlags: CLONE, RECURSIVE, EMPTY_PATH, NO_FOLLOW, NO_AUTOMOUNT);
    distinct!(MoveMountFlags: FROM_SYMLINKS, FROM_AUTOMOUNTS, FROM_EMPTY_PATH, TO_SYMLINKS,
        TO_AUTOMOUNTS, TO_EMPTY_PATH, SET_GROUP, BENEATH);
    distinct!(MountSetAttrFlags: RECURSIVE, EMPTY_PATH, NO_FOLLOW, NO_AUTOMOUNT);
    assert_eq!(
        format!("{:?}", FsConfig::SetString("size", "1m")),
        r#"SetString("size", "1m")"#
    );
    let change = MountSetAttr::new().set(MountAttributes::READ_ONLY);
    assert!(format!("{change:?}").contains("READ_ONLY"));
    assert_ne!(Propagation::Private, Propagation::Slave);
    assert_eq!(format!("{:?}", Propagation::Unbindable), "Unbindable");
}

/// What oscall refuses, and what the system refuses to who has no
/// privilege. With the privilege these calls would change the system the
/// tests run on: they are not made.
#[test]
fn refused() {
    let dir = common::tmp_dir("fs_linux_refused");
    let dir = dir.to_str().unwrap();
    let none = MountFlags::empty();
    // A type is needed, whoever asks.
    let error = mounts::mount("none", dir, "", none, "").unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    // A NUL is the end of no path.
    let error = mounts::mount("none", "a\0b", "tmpfs", none, "").unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    let error = mounts::chroot("a\0b").unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");

    let effective = linux::capabilities().unwrap().effective;
    if !effective.contains(Capability::SysAdmin) {
        let results = [
            mounts::mount("none", dir, "tmpfs", none, "size=1m"),
            mounts::bind(dir, dir, false),
            mounts::remount(dir, MountFlags::READ_ONLY, ""),
            mounts::remount_bind(dir, MountFlags::READ_ONLY),
            mounts::set_propagation(dir, Propagation::Private, true),
            mounts::move_mount(dir, dir),
            mounts::unmount(dir, UnmountFlags::empty()),
            mounts::unmount(dir, UnmountFlags::DETACH | UnmountFlags::NO_FOLLOW),
            mounts::pivot_root(dir, dir),
        ];
        for (i, result) in results.into_iter().enumerate() {
            let error = result.unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{i}: {error:?}");
        }
    }
    if !effective.contains(Capability::SysChroot) {
        let error = mounts::chroot(dir).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
    }

    // The calls on handles. An emulator of programs has some of them
    // (measured: the qemu-user of the riscv64 job opens a tree and
    // configures nothing, the one of the fullrust image has none), and
    // answers for the others that there is no such call.
    let refused_as = |error: oscall::Error, kind: ErrorKind| {
        let expected = if common::emulated() && error.kind() == ErrorKind::Unsupported {
            ErrorKind::Unsupported
        } else {
            kind
        };
        assert_eq!(error.kind(), expected, "{error:?}");
    };
    let refusal = |error: oscall::Error| refused_as(error, ErrorKind::PermissionDenied);
    let error = mounts::fsopen("a\0b").unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    let error = mounts::open_tree(None, "a\0b", OpenTreeFlags::empty()).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    if !effective.contains(Capability::SysAdmin) {
        let read_only = MountSetAttr::new().set(MountAttributes::READ_ONLY);
        let empty = MoveMountFlags::empty();
        refusal(mounts::fsopen("tmpfs").unwrap_err());
        refusal(mounts::fspick(None, dir, FsPickFlags::empty()).unwrap_err());
        refusal(mounts::open_tree(None, dir, OpenTreeFlags::CLONE).unwrap_err());
        refusal(mounts::move_mount_at(None, dir, None, dir, empty).unwrap_err());
        refusal(
            mounts::mount_setattr(None, "/", MountSetAttrFlags::empty(), &read_only).unwrap_err(),
        );
        // A handle of a place is anyone's to have, where the call may be
        // made at all (the default filter of a container refuses it to
        // who lacks the capability).
        match mounts::open_tree(None, dir, OpenTreeFlags::empty()) {
            Ok(place) => {
                // No configuration (and, like a handle opened for its
                // path alone, nothing a call may act through), and
                // nothing it may move.
                let error = mounts::fsconfig(&place, FsConfig::Create).unwrap_err();
                refused_as(error, ErrorKind::BadHandle);
                let from = Some(oscall::AsHandle::as_handle(&place));
                let flags = MoveMountFlags::FROM_EMPTY_PATH;
                refusal(mounts::move_mount_at(from, "", None, dir, flags).unwrap_err());
                refusal(mounts::fsmount(&place, MountAttributes::empty()).unwrap_err());
            }
            Err(error) => refusal(error),
        }
    }
    // Nothing happened.
    assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0);
}

/// What `/proc/self/mountinfo` says of the mount with the short
/// identifier `id`: the parent, the device, the root, the point, the
/// settings, the type and the source. `None` for a mount that is not
/// there, or whose line has an escape (a space in a path).
fn mountinfo_line(id: u32) -> Option<Vec<String>> {
    let text = std::fs::read_to_string("/proc/self/mountinfo").ok()?;
    text.lines().find_map(|line| {
        let (before, after) = line.split_once(" - ")?;
        let before: Vec<&str> = before.split(' ').collect();
        let after: Vec<&str> = after.split(' ').collect();
        if before[0].parse() != Ok(id) || line.contains('\\') {
            return None;
        }
        let fields = [
            before[1], before[2], before[3], before[4], before[5], after[0], after[1],
        ];
        Some(fields.map(str::to_owned).to_vec())
    })
}

/// What is mounted, as `statmount` and `listmount` say it: no privilege
/// is needed to ask about what the caller can reach. Nothing is mounted.
#[test]
fn listing() {
    use mounts::{ListMountFlags, MountInfo, ROOT_MOUNT, StatMountFields};

    const ENOSYS: i32 = 38;
    const EPERM: i32 = 1;
    let all = [
        StatMountFields::FILESYSTEM,
        StatMountFields::MOUNT,
        StatMountFields::PROPAGATE_FROM,
        StatMountFields::ROOT,
        StatMountFields::POINT,
        StatMountFields::FS_TYPE,
        StatMountFields::NAMESPACE_ID,
        StatMountFields::OPTIONS,
        StatMountFields::FS_SUBTYPE,
        StatMountFields::SOURCE,
        StatMountFields::OPTION_LIST,
        StatMountFields::SECURITY_OPTIONS,
        StatMountFields::SUPPORTED,
        StatMountFields::UID_MAP,
        StatMountFields::GID_MAP,
    ];
    let mut union = StatMountFields::empty();
    for field in all {
        assert!(!field.is_empty() && !union.intersects(field));
        union |= field;
    }
    assert_eq!(union, StatMountFields::ALL);
    assert_eq!(MountInfo::MIN_BUFFER, 512);
    assert_eq!(ROOT_MOUNT, u64::MAX);

    // The whole namespace, in one call with room to spare.
    let mut ids = [0u64; 4096];
    let count = match mounts::listmount(ROOT_MOUNT, 0, ListMountFlags::empty(), &mut ids) {
        Ok(count) => count,
        // An emulator of programs, a kernel before 6.8, or the system
        // call filter of a container that is older than the call.
        Err(error) if matches!(error.raw_os_error(), ENOSYS | EPERM) => {
            let mut buf = [0u8; 1024];
            let stat = mounts::statmount(1, StatMountFields::MOUNT, &mut buf).unwrap_err();
            assert_eq!(stat.raw_os_error(), error.raw_os_error(), "{stat:?}");
            let ids: Vec<_> = mounts::mounts(ROOT_MOUNT).collect();
            assert_eq!(ids.len(), 1, "{ids:?}");
            assert_eq!(ids[0].unwrap_err().raw_os_error(), error.raw_os_error());
            common::skip(&format!("no listmount here: {error}"));
            return;
        }
        Err(error) => panic!("listmount: {error:?}"),
    };
    let ids = &ids[..count];
    assert!(count > 0 && count < 4096, "{count}");
    // Unique identifiers, in the order the mounts were made.
    assert!(ids.windows(2).all(|pair| pair[0] < pair[1]), "{ids:?}");
    // They start above the short ones, which are 31 bits.
    assert!(ids.iter().all(|&id| id >= 1 << 31), "{ids:?}");

    // The same list, a few at a time: by the iterator, and one by one.
    // (Other processes mount and unmount meanwhile, on a machine that
    // runs containers: only what was there at first is compared, and
    // only as far as it stayed.)
    let iterated: Vec<u64> = mounts::mounts(ROOT_MOUNT).map(|id| id.unwrap()).collect();
    assert!(iterated.windows(2).all(|pair| pair[0] < pair[1]));
    let stable = ids.iter().filter(|id| iterated.contains(id)).count();
    assert!(
        stable > 0 && stable + 16 > count.min(iterated.len()),
        "{ids:?} {iterated:?}"
    );
    let mut one = [0u64; 1];
    let mut after = 0;
    let mut singly = Vec::new();
    while mounts::listmount(ROOT_MOUNT, after, ListMountFlags::empty(), &mut one).unwrap() == 1 {
        assert!(one[0] > after);
        after = one[0];
        singly.push(after);
    }
    assert!(singly.iter().filter(|id| iterated.contains(id)).count() + 16 > iterated.len());
    // The last first.
    let mut reversed = [0u64; 4096];
    match mounts::listmount(ROOT_MOUNT, 0, ListMountFlags::REVERSE, &mut reversed) {
        Ok(count) => {
            let reversed = &reversed[..count];
            assert!(reversed.windows(2).all(|pair| pair[0] > pair[1]));
        }
        // Linux 6.8 to 6.10.
        Err(error) => assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}"),
    }

    // The mount of the root directory is the first of them, and its own
    // parent's child only in name.
    let root = mounts::mount_id(None, "/", true).unwrap();
    assert!(ids.contains(&root), "{root} {ids:?}");
    let mut buf = [0u8; 8192];
    let mut compared = 0;
    for &id in ids {
        let mount = match mounts::statmount(id, StatMountFields::ALL, &mut buf) {
            Ok(mount) => mount,
            // Gone since it was listed.
            Err(error) if error.kind() == ErrorKind::NotFound => continue,
            Err(error) => panic!("statmount {id}: {error:?}"),
        };
        let basic = StatMountFields::FILESYSTEM
            | StatMountFields::MOUNT
            | StatMountFields::ROOT
            | StatMountFields::POINT
            | StatMountFields::FS_TYPE;
        assert!(mount.fields.contains(basic), "{mount:?}");
        assert_eq!(mount.id, id);
        if mount.fields.contains(StatMountFields::SUPPORTED) {
            assert!(mount.supported.contains(mount.fields), "{mount:?}");
        }
        let times =
            MountAttributes::NO_ATIME | MountAttributes::STRICT_ATIME | MountAttributes::REL_ATIME;
        assert!(mount.attributes.intersects(times), "{mount:?}");
        assert_eq!(
            mount.propagation == Propagation::Shared,
            mount.peer_group != 0,
            "{mount:?}"
        );
        let text = |bytes: Option<&[u8]>| String::from_utf8_lossy(bytes.unwrap()).into_owned();
        // What the file says of the same mount.
        let Some(line) = mountinfo_line(mount.old_id) else {
            continue;
        };
        compared += 1;
        assert_eq!(line[0], mount.old_parent_id.to_string(), "{mount:?}");
        assert_eq!(line[1], format!("{}:{}", mount.device.0, mount.device.1));
        assert_eq!(line[2], text(mount.root), "{mount:?}");
        assert_eq!(line[3], text(mount.point), "{mount:?}");
        // The file joins the type and its kind: `fuse.sshfs`.
        let fs_type = match mount.fs_subtype {
            Some(kind) if !kind.is_empty() => {
                format!("{}.{}", text(mount.fs_type), text(Some(kind)))
            }
            _ => text(mount.fs_type),
        };
        assert_eq!(line[5], fs_type, "{mount:?}");
        let settings: Vec<&str> = line[4].split(',').collect();
        for (name, attribute) in [
            ("ro", MountAttributes::READ_ONLY),
            ("nosuid", MountAttributes::NO_SUID),
            ("nodev", MountAttributes::NO_DEV),
            ("noexec", MountAttributes::NO_EXEC),
            ("noatime", MountAttributes::NO_ATIME),
            ("relatime", MountAttributes::REL_ATIME),
            ("nodiratime", MountAttributes::NO_DIR_ATIME),
        ] {
            let said = settings.contains(&name);
            assert_eq!(
                mount.attributes.contains(attribute),
                said,
                "{name}: {mount:?}"
            );
        }
        if mount.fields.contains(StatMountFields::SOURCE) {
            assert_eq!(line[6], text(mount.source), "{mount:?}");
        }
        if mount.fields.contains(StatMountFields::OPTION_LIST) {
            // One by one, what the text has between commas.
            let listed: Vec<String> = mount
                .option_list
                .map(|option| String::from_utf8_lossy(option).into_owned())
                .collect();
            assert_eq!(listed.len(), mount.option_list.len());
            let options = text(mount.options);
            if !options.contains('\\') {
                for option in &listed {
                    assert!(options.split(',').any(|part| part == option), "{mount:?}");
                }
            }
        }
        if id == root {
            assert_eq!(text(mount.point), "/");
        }
    }
    assert!(compared > 0);

    // Only what was asked for is answered.
    let mount = mounts::statmount(root, StatMountFields::FS_TYPE, &mut buf).unwrap();
    assert_eq!(mount.fields, StatMountFields::FS_TYPE);
    assert!(mount.fs_type.is_some_and(|name| !name.is_empty()));
    assert!(mount.point.is_none() && mount.root.is_none() && mount.source.is_none());
    assert_eq!((mount.id, mount.device, mount.magic), (0, (0, 0), 0));
    assert_eq!(mount.option_list.len(), 0);
    // The numbers fit in the least buffer there is, a string does not.
    let small = &mut buf[..MountInfo::MIN_BUFFER];
    let mount = mounts::statmount(root, StatMountFields::MOUNT, small).unwrap();
    assert_eq!(mount.id, root);
    let error = mounts::statmount(root, StatMountFields::FS_TYPE, small).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{error:?}");
    let error = mounts::statmount(root, StatMountFields::MOUNT, &mut small[1..]).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{error:?}");
    // No such mount.
    let absent = u64::MAX - 1;
    let error = mounts::statmount(absent, StatMountFields::MOUNT, &mut buf).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
    let error = mounts::listmount(absent, 0, ListMountFlags::empty(), &mut one).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
    // The short identifiers are not these, and a kernel that checks
    // (measured: 6.18) says so rather than look for one.
    let wrong = [ErrorKind::InvalidInput, ErrorKind::NotFound];
    let error = mounts::statmount(1, StatMountFields::MOUNT, &mut buf).unwrap_err();
    assert!(wrong.contains(&error.kind()), "{error:?}");
    let error = mounts::listmount(1, 0, ListMountFlags::empty(), &mut one).unwrap_err();
    assert!(wrong.contains(&error.kind()), "{error:?}");
    let error = mounts::listmount(ROOT_MOUNT, 1, ListMountFlags::empty(), &mut one).unwrap_err();
    assert!(wrong.contains(&error.kind()), "{error:?}");

    // A path is on the mount its directory is on, and that mount is
    // attached at the start of the path.
    let dir = common::tmp_dir("fs_linux_listing");
    let dir = dir.canonicalize().unwrap();
    std::fs::write(dir.join("file"), "").unwrap();
    let id_of = |path: std::path::PathBuf, follow| {
        mounts::mount_id(None, path.as_os_str().as_encoded_bytes(), follow)
    };
    let of_dir = id_of(dir.clone(), true).unwrap();
    assert_eq!(id_of(dir.join("file"), false).unwrap(), of_dir);
    let opened = std::fs::File::open(dir.join("file")).unwrap();
    let by_handle = mounts::mount_id(Some(common::handle_of(&opened)), "", true).unwrap();
    assert_eq!(by_handle, of_dir);
    let error = id_of(dir.join("missing"), true).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
    let mount = mounts::statmount(of_dir, StatMountFields::POINT, &mut buf).unwrap();
    let point =
        std::path::PathBuf::from(String::from_utf8_lossy(mount.point.unwrap()).into_owned());
    assert!(dir.starts_with(&point), "{dir:?} {point:?}");
    // What is under a mount is a part of the whole list.
    let under: Vec<u64> = mounts::mounts(root).map(|id| id.unwrap()).collect();
    assert!(!under.contains(&root));
    assert!(under.len() < iterated.len() + 16);
}

/// 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")]
    if let Some(root) = mode.strip_prefix("root:") {
        container::helper_root(std::path::Path::new(root));
        oscall::process::exit(0);
    } else if let Some(root) = mode.strip_prefix("api:") {
        container::helper_api(std::path::Path::new(root));
        oscall::process::exit(0);
    }
    if mode == "wait" {
        // Until the other end of its input is closed.
        let mut line = String::new();
        let _ = std::io::stdin().read_line(&mut line);
        oscall::process::exit(0);
    }
    panic!("unknown helper mode {mode}");
}

#[cfg(feature = "alloc")]
mod container {
    use std::path::Path;
    use std::time::{Duration, Instant};

    use oscall::process::linux::{self, Capability, CommandExt as _, IdMap, Namespaces};
    use oscall::process::{Command, Stdio};
    use oscall::{ErrorKind, fs};

    use super::common;
    use super::{MountFlags, Propagation, UnmountFlags, mounts};

    const ENOEXEC: i32 = 8;
    const ENODEV: i32 = 19;

    /// What `/proc/self/mountinfo` says of the mount point `path`.
    struct MountInfo {
        /// The flags of the mount point: `rw`, `nosuid`...
        options: Vec<String>,
        /// How it propagates: `shared:N`, `master:N`, `unbindable`.
        tags: Vec<String>,
        fstype: String,
        source: String,
        /// The options of the filesystem.
        super_options: Vec<String>,
    }

    fn mount_info(path: &Path) -> Option<MountInfo> {
        let text = std::fs::read_to_string("/proc/self/mountinfo").unwrap();
        let list = |text: &str| text.split(',').map(str::to_owned).collect();
        // The last one is on top.
        text.lines().rev().find_map(|line| {
            let (before, after) = line.split_once(" - ")?;
            let before: Vec<&str> = before.split(' ').collect();
            let after: Vec<&str> = after.split(' ').collect();
            (Path::new(before[4]) == path).then(|| MountInfo {
                options: list(before[5]),
                tags: before[6..].iter().map(|&tag| tag.to_owned()).collect(),
                fstype: after[0].to_owned(),
                source: after[1].to_owned(),
                super_options: list(after.get(2).copied().unwrap_or_default()),
            })
        })
    }

    fn has(list: &[String], option: &str) -> bool {
        list.iter().any(|item| item == option)
    }

    /// The names in a directory, sorted.
    fn names(dir: &str) -> Vec<String> {
        let mut names: Vec<String> = std::fs::read_dir(dir)
            .unwrap()
            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
            .collect();
        names.sort();
        names
    }

    /// Run in a new mount namespace, with `CAP_SYS_ADMIN` there: mounts
    /// under `root`, an empty directory, by the calls that work on
    /// handles, and checks each step.
    pub(super) fn helper_api(root: &Path) {
        use oscall::fs::{OpenOptions, linux::*};
        use oscall::{AsHandle as _, BorrowedHandle, io};

        const ENODATA: i32 = 61;
        let at = |name: &str| root.join(name);
        let path = |name: &str| at(name).into_os_string().into_string().unwrap();
        let read = |name: &str| std::fs::read_to_string(at(name)).unwrap();
        let options = |name: &str| mount_info(&at(name)).unwrap().options;
        let read_only = |result: std::io::Result<()>| {
            let error = result.unwrap_err();
            assert_eq!(
                error.kind(),
                std::io::ErrorKind::ReadOnlyFilesystem,
                "{error:?}"
            );
        };
        let from_handle = MoveMountFlags::FROM_EMPTY_PATH;
        let no_flags = MountSetAttrFlags::empty();

        // Nothing of what follows leaves this namespace.
        if let Err(error) = mounts::set_propagation("/", Propagation::Private, true) {
            // Root of its namespace on paper, and denied the use of it:
            // what Ubuntu's AppArmor restriction of user namespaces does.
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
            skip!(
                "(api) no use of capabilities in the user namespace ({})",
                common::confinement()
            );
            return;
        }
        for name in ["new", "copy", "single", "moved", "mapped", "mapped-root"] {
            std::fs::create_dir(at(name)).unwrap();
        }

        // A filesystem configured one option at a time.
        let error = fsopen("oscall-no-such-type").unwrap_err();
        assert_eq!(error.raw_os_error(), ENODEV, "{error:?}");
        let fs = fsopen("tmpfs").unwrap();
        fsconfig(&fs, FsConfig::SetString("source", "oscall-new")).unwrap();
        fsconfig(&fs, FsConfig::SetString("size", "1m")).unwrap();
        fsconfig(&fs, FsConfig::SetString("mode", "755")).unwrap();
        // What the filesystem refuses, and what it says about it.
        let mut message = [0u8; 256];
        let error = io::read(&fs, &mut message).unwrap_err();
        assert_eq!(error.raw_os_error(), ENODATA, "{error:?}");
        let error = fsconfig(&fs, FsConfig::SetString("oscall-no-option", "1")).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        let n = io::read(&fs, &mut message).unwrap();
        let said = String::from_utf8_lossy(&message[..n]).into_owned();
        assert!(
            said.starts_with("e ") && said.contains("oscall-no-option"),
            "{said:?}"
        );
        let refused = [
            FsConfig::SetString("size", "oscall"),
            // An option that wants a value, and of another kind.
            FsConfig::SetFlag("size"),
            FsConfig::SetBinary("size", &[1, 2, 3]),
            FsConfig::SetHandle("size", fs.as_handle()),
            FsConfig::SetFlag("oscall-no-flag"),
        ];
        for step in refused {
            let error = fsconfig(&fs, step).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{step:?}: {error:?}");
        }
        // A handle that is not open is looked for, which shows where the
        // call takes it.
        // SAFETY: the number is used for one call, which finds nothing.
        let closed = unsafe { BorrowedHandle::borrow_raw(999_999) };
        let error = fsconfig(&fs, FsConfig::SetHandle("source", closed)).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");
        // Nothing to mount yet, and then one filesystem, once.
        let attributes =
            MountAttributes::NO_SUID | MountAttributes::NO_DEV | MountAttributes::NO_DIR_ATIME;
        let error = fsmount(&fs, attributes).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        fsconfig(&fs, FsConfig::Create).unwrap();
        for step in [FsConfig::Create, FsConfig::SetString("size", "2m")] {
            let error = fsconfig(&fs, step).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::ResourceBusy, "{step:?}: {error:?}");
        }
        let mount = fsmount(&fs, attributes).unwrap();
        let error = fsmount(&fs, attributes).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::ResourceBusy, "{error:?}");
        // A mount is no configuration, nor is a file.
        let error = fsconfig(&mount, FsConfig::Create).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");
        let file = std::fs::File::open("/proc/self/status").unwrap();
        let error = fsconfig(&common::handle_of(&file), FsConfig::Create).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        let error = fsmount(&common::handle_of(&file), attributes).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");

        // Attached nowhere, it is used through its handle.
        fs::create_dir_at(&mount, "data").unwrap();
        let create = OpenOptions::new().write(true).create_new(true);
        let file = fs::open_at(&mount, "data/file", &create).unwrap();
        assert_eq!(io::write(&file, b"one"), Ok(3));
        drop(file);
        assert!(mount_info(&at("new")).is_none());
        assert!(names(&path("new")).is_empty());
        // An empty path is a path unless said otherwise.
        let from = Some(mount.as_handle());
        let error =
            move_mount_at(from, "", None, &path("new"), MoveMountFlags::empty()).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        move_mount_at(from, "", None, &path("new"), from_handle).unwrap();
        drop((mount, fs));
        let info = mount_info(&at("new")).unwrap();
        assert_eq!(
            (info.fstype.as_str(), info.source.as_str()),
            ("tmpfs", "oscall-new")
        );
        for option in ["rw", "nosuid", "nodev", "nodiratime", "relatime"] {
            assert!(has(&info.options, option), "{option}: {:?}", info.options);
        }
        assert!(!has(&info.options, "noexec"), "{:?}", info.options);
        for option in ["size=1024k", "mode=755"] {
            assert!(
                has(&info.super_options, option),
                "{option}: {:?}",
                info.super_options
            );
        }
        assert_eq!(read("new/data/file"), "one");

        // The filesystem, picked up where it is mounted and changed.
        let error = fspick(None, &path("missing"), FsPickFlags::empty()).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        // By its mount point, and nothing under it.
        let error = fspick(None, &path("new/data"), FsPickFlags::empty()).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        let picked = fspick(None, &path("new"), FsPickFlags::NO_FOLLOW).unwrap();
        fsconfig(&picked, FsConfig::SetString("size", "2m")).unwrap();
        fsconfig(&picked, FsConfig::SetFlag("ro")).unwrap();
        // It exists already.
        let error = fsconfig(&picked, FsConfig::Create).unwrap_err();
        assert!(
            matches!(
                error.kind(),
                ErrorKind::InvalidInput | ErrorKind::ResourceBusy
            ),
            "{error:?}"
        );
        assert!(has(&mount_info(&at("new")).unwrap().super_options, "rw"));
        fsconfig(&picked, FsConfig::Reconfigure).unwrap();
        let info = mount_info(&at("new")).unwrap();
        assert!(
            has(&info.super_options, "size=2048k"),
            "{:?}",
            info.super_options
        );
        assert!(has(&info.super_options, "ro"), "{:?}", info.super_options);
        read_only(std::fs::write(at("new/data/file"), "no"));
        // By a handle of the mount point, and an empty path.
        let new_dir = std::fs::File::open(at("new")).unwrap();
        let inside = common::handle_of(&new_dir);
        let error = fspick(Some(inside), "", FsPickFlags::empty()).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        let picked = fspick(Some(inside), "", FsPickFlags::EMPTY_PATH).unwrap();
        fsconfig(&picked, FsConfig::SetFlag("rw")).unwrap();
        fsconfig(&picked, FsConfig::Reconfigure).unwrap();
        assert!(has(&mount_info(&at("new")).unwrap().super_options, "rw"));
        std::fs::write(at("new/data/file"), "two").unwrap();
        drop(picked);
        drop(new_dir);

        // A tree as a handle: where it is, or a copy that is nowhere.
        std::fs::create_dir(at("new/sub")).unwrap();
        let settings = MountFlags::NO_SUID | MountFlags::NO_DEV;
        mounts::mount("oscall-sub", &path("new/sub"), "tmpfs", settings, "").unwrap();
        std::fs::write(at("new/sub/inner"), "inner").unwrap();
        let place = open_tree(None, &path("new"), OpenTreeFlags::empty()).unwrap();
        assert!(fs::metadata_at(&place, "data/file").unwrap().is_file());
        let error = open_tree(None, &path("new"), OpenTreeFlags::RECURSIVE).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        let error = open_tree(None, &path("missing"), OpenTreeFlags::CLONE).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        let tree = open_tree(
            None,
            &path("new"),
            OpenTreeFlags::CLONE | OpenTreeFlags::RECURSIVE,
        )
        .unwrap();
        // The copy has what was mounted under the original.
        assert!(fs::metadata_at(&tree, "sub/inner").unwrap().is_file());
        assert!(mount_info(&at("copy")).is_none());
        move_mount_at(Some(tree.as_handle()), "", None, &path("copy"), from_handle).unwrap();
        drop(tree);
        assert_eq!(mount_info(&at("copy")).unwrap().source, "oscall-new");
        assert_eq!(mount_info(&at("copy/sub")).unwrap().source, "oscall-sub");
        assert_eq!(read("copy/data/file"), "two");
        assert_eq!(read("copy/sub/inner"), "inner");
        // One mount alone, from the handle of the place.
        let flags = OpenTreeFlags::CLONE | OpenTreeFlags::EMPTY_PATH;
        let single = open_tree(Some(place.as_handle()), "", flags).unwrap();
        move_mount_at(
            Some(single.as_handle()),
            "",
            None,
            &path("single"),
            from_handle,
        )
        .unwrap();
        drop(single);
        assert!(mount_info(&at("single")).is_some());
        assert!(mount_info(&at("single/sub")).is_none());
        assert!(names(&path("single/sub")).is_empty());
        assert_eq!(read("single/data/file"), "two");

        // A mount moved: by two paths, and by a handle of where it is.
        let empty = MoveMountFlags::empty();
        move_mount_at(None, &path("single"), None, &path("moved"), empty).unwrap();
        assert!(mount_info(&at("single")).is_none());
        assert_eq!(read("moved/data/file"), "two");
        let there = open_tree(None, &path("moved"), OpenTreeFlags::empty()).unwrap();
        let root_dir = std::fs::File::open(root).unwrap();
        let root_dir = Some(common::handle_of(&root_dir));
        move_mount_at(Some(there.as_handle()), "", root_dir, "single", from_handle).unwrap();
        drop(there);
        assert!(mount_info(&at("moved")).is_none());
        assert_eq!(read("single/data/file"), "two");
        // What is no mount point does not move.
        let error =
            move_mount_at(None, &path("new/data"), None, &path("moved"), empty).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");

        // The settings of a whole tree, in one call.
        let lock = MountSetAttr::new().set(MountAttributes::READ_ONLY | MountAttributes::NO_EXEC);
        mount_setattr(None, &path("copy"), MountSetAttrFlags::RECURSIVE, &lock).unwrap();
        for name in ["copy", "copy/sub"] {
            let options = options(name);
            assert!(
                has(&options, "ro") && has(&options, "noexec"),
                "{name}: {options:?}"
            );
            // What was there stays.
            assert!(
                has(&options, "nosuid") && has(&options, "nodev"),
                "{name}: {options:?}"
            );
        }
        read_only(std::fs::write(at("copy/data/file"), "no"));
        read_only(std::fs::write(at("copy/sub/inner"), "no"));
        // The filesystems are as they were, through their other mounts.
        assert!(has(&options("new"), "rw") && has(&options("new/sub"), "rw"));
        std::fs::write(at("new/sub/inner"), "written").unwrap();
        assert_eq!(read("copy/sub/inner"), "written");
        // One mount point alone, and one setting of it.
        let unlock = MountSetAttr::new().clear(MountAttributes::READ_ONLY);
        mount_setattr(None, &path("copy"), no_flags, &unlock).unwrap();
        let top = options("copy");
        assert!(has(&top, "rw") && has(&top, "noexec"), "{top:?}");
        assert!(has(&options("copy/sub"), "ro"));
        std::fs::write(at("copy/data/file"), "three").unwrap();
        read_only(std::fs::write(at("copy/sub/inner"), "no"));
        // A change of nothing changes nothing.
        mount_setattr(None, &path("copy"), no_flags, &MountSetAttr::new()).unwrap();
        assert_eq!(options("copy"), top);

        // How access times are kept is one setting.
        let times = |attributes| MountSetAttr::new().set(attributes);
        assert!(has(&top, "relatime") && has(&top, "nodiratime"), "{top:?}");
        mount_setattr(
            None,
            &path("copy"),
            no_flags,
            &times(MountAttributes::NO_ATIME),
        )
        .unwrap();
        let now = options("copy");
        assert!(has(&now, "noatime") && !has(&now, "relatime"), "{now:?}");
        mount_setattr(
            None,
            &path("copy"),
            no_flags,
            &times(MountAttributes::STRICT_ATIME),
        )
        .unwrap();
        let now = options("copy");
        assert!(!has(&now, "noatime") && !has(&now, "relatime"), "{now:?}");
        let both = MountAttributes::NO_ATIME | MountAttributes::STRICT_ATIME;
        let error = mount_setattr(None, &path("copy"), no_flags, &times(both)).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        let relative = MountSetAttr::new()
            .clear(MountAttributes::STRICT_ATIME | MountAttributes::NO_DIR_ATIME);
        mount_setattr(None, &path("copy"), no_flags, &relative).unwrap();
        let now = options("copy");
        assert!(has(&now, "relatime") && !has(&now, "nodiratime"), "{now:?}");
        mount_setattr(
            None,
            &path("copy"),
            no_flags,
            &times(MountAttributes::NO_ATIME),
        )
        .unwrap();
        mount_setattr(
            None,
            &path("copy"),
            no_flags,
            &times(MountAttributes::REL_ATIME),
        )
        .unwrap();
        assert!(has(&options("copy"), "relatime"));

        // How it propagates, with the rest or alone.
        let shared = MountSetAttr::new()
            .set(MountAttributes::NO_EXEC)
            .propagation(Propagation::Shared);
        mount_setattr(None, &path("copy"), MountSetAttrFlags::RECURSIVE, &shared).unwrap();
        for name in ["copy", "copy/sub"] {
            let tags = mount_info(&at(name)).unwrap().tags;
            assert!(
                tags.iter().any(|tag| tag.starts_with("shared:")),
                "{name}: {tags:?}"
            );
        }
        let private = MountSetAttr::new().propagation(Propagation::Private);
        mount_setattr(None, &path("copy"), MountSetAttrFlags::RECURSIVE, &private).unwrap();
        assert!(mount_info(&at("copy/sub")).unwrap().tags.is_empty());
        // Only a mount point has settings.
        let error = mount_setattr(None, &path("copy/data"), no_flags, &lock).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        let error = mount_setattr(None, &path("missing"), no_flags, &lock).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");

        // A copy that is read-only before it shows anywhere.
        let tree = open_tree(None, &path("new"), OpenTreeFlags::CLONE).unwrap();
        let by_handle = MountSetAttrFlags::EMPTY_PATH;
        let error = mount_setattr(Some(tree.as_handle()), "", no_flags, &lock).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        mount_setattr(Some(tree.as_handle()), "", by_handle, &lock).unwrap();
        move_mount_at(
            Some(tree.as_handle()),
            "",
            None,
            &path("moved"),
            from_handle,
        )
        .unwrap();
        drop(tree);
        assert!(has(&options("moved"), "ro"));
        read_only(std::fs::write(at("moved/data/file"), "no"));

        more_handles(root);
        id_mapped(root);
        for name in ["moved", "single", "copy/sub", "copy", "new/sub"] {
            mounts::unmount(&path(name), UnmountFlags::empty())
                .unwrap_or_else(|error| panic!("{name}: {error:?}"));
        }
        // A handle of a place is a use of its mount.
        let error = mounts::unmount(&path("new"), UnmountFlags::empty()).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::ResourceBusy, "{error:?}");
        drop(place);
        mounts::unmount(&path("new"), UnmountFlags::empty()).unwrap();
    }

    /// The rest of the calls on handles, on what `helper_api` mounted
    /// under `root`: the options that are paths, a filesystem that must
    /// be new, a copy that has its settings from the start, and what the
    /// kernel says is mounted.
    fn more_handles(root: &Path) {
        use oscall::fs::{OpenOptions, linux::*};
        use oscall::{AsHandle as _, io};

        let at = |name: &str| root.join(name);
        let path = |name: &str| at(name).into_os_string().into_string().unwrap();
        let options = |name: &str| mount_info(&at(name)).unwrap().options;
        let from_handle = MoveMountFlags::FROM_EMPTY_PATH;

        // An option given as a path. The kernel takes the command; none
        // of the filesystems at hand has an option that is one, `source`
        // included, and each says so.
        let fs = fsopen("tmpfs").unwrap();
        let dir = fs::open(root, &OpenOptions::new().read(true).directory(true)).unwrap();
        let new = path("new");
        let steps = [
            (
                FsConfig::SetPath("source", None, new.as_bytes()),
                "Non-string source",
            ),
            (
                FsConfig::SetPath("size", None, new.as_bytes()),
                "Bad value for 'size'",
            ),
            (
                FsConfig::SetPath("oscall-none", Some(dir.as_handle()), b"new"),
                "Unknown parameter 'oscall-none'",
            ),
            (
                FsConfig::SetPathEmpty("source", dir.as_handle()),
                "Non-string source",
            ),
            (
                FsConfig::SetPathEmpty("oscall-none", dir.as_handle()),
                "Unknown parameter 'oscall-none'",
            ),
        ];
        for (step, reason) in steps {
            let error = fsconfig(&fs, step).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{step:?}: {error:?}");
            let mut message = [0u8; 256];
            let n = io::read(&fs, &mut message).unwrap();
            let said = String::from_utf8_lossy(&message[..n]).into_owned();
            assert!(
                said.starts_with("e ") && said.contains(reason),
                "{step:?}: {said:?}"
            );
        }
        let error = fsconfig(&fs, FsConfig::SetPath("source", None, b"a\0b")).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");

        // A filesystem that must be a new one: `tmpfs` always is.
        match fsconfig(&fs, FsConfig::CreateExclusive) {
            Ok(()) => {
                for step in [FsConfig::CreateExclusive, FsConfig::Create] {
                    let error = fsconfig(&fs, step).unwrap_err();
                    assert_eq!(error.kind(), ErrorKind::ResourceBusy, "{step:?}: {error:?}");
                }
                let mount = fsmount(&fs, MountAttributes::empty()).unwrap();
                fs::create_dir_at(&mount, "made").unwrap();
            }
            Err(error) if kernel_before(6, 6) => {
                assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}");
                common::note("skipped: no FSCONFIG_CMD_CREATE_EXCL before Linux 6.6");
            }
            Err(error) => panic!("an exclusive creation: {error:?}"),
        }
        // And one that never is: there is one cgroup hierarchy, mounted
        // already. (Its type may only be mounted by who has the cgroup
        // namespace, which the root of a user namespace made for the
        // occasion has not.)
        if let Ok(fs) = fsopen("cgroup2") {
            match fsconfig(&fs, FsConfig::CreateExclusive) {
                Err(error) if error.kind() == ErrorKind::PermissionDenied => {}
                Err(error) if kernel_before(6, 6) => {
                    assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}");
                }
                result => {
                    let error = result.unwrap_err();
                    assert_eq!(error.kind(), ErrorKind::ResourceBusy, "{error:?}");
                    // A configuration that failed to create is over
                    // (measured: Linux 6.18).
                    let error = fsconfig(&fs, FsConfig::Create).unwrap_err();
                    assert_eq!(error.kind(), ErrorKind::ResourceBusy, "{error:?}");
                    // Shared, it is there for the asking.
                    let fs = fsopen("cgroup2").unwrap();
                    fsconfig(&fs, FsConfig::Create).unwrap();
                    common::note("fs: an exclusive creation of cgroup2 was refused");
                }
            }
        }

        // A copy that is read-only from the moment it exists.
        std::fs::create_dir(at("attr")).unwrap();
        let read_only = MountSetAttr::new().set(MountAttributes::READ_ONLY);
        match open_tree_attr(None, &path("single"), OpenTreeFlags::CLONE, &read_only) {
            Ok(tree) => {
                assert!(has(&options("single"), "rw"));
                move_mount_at(Some(tree.as_handle()), "", None, &path("attr"), from_handle)
                    .unwrap();
                drop(tree);
                assert!(has(&options("attr"), "ro"));
                let error = std::fs::write(at("attr/no"), "no").unwrap_err();
                assert_eq!(error.kind(), std::io::ErrorKind::ReadOnlyFilesystem);
                // Without a copy, the change is made to the mount that is
                // there, and the handle is of the place (measured: Linux
                // 6.18).
                let no_exec = MountSetAttr::new().set(MountAttributes::NO_EXEC);
                let place =
                    open_tree_attr(None, &path("attr"), OpenTreeFlags::empty(), &no_exec).unwrap();
                let now = options("attr");
                assert!(has(&now, "noexec") && has(&now, "ro"), "{now:?}");
                let error = fsmount(&place, MountAttributes::empty()).unwrap_err();
                assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");
                drop(place);
                // A change of nothing is `open_tree`.
                let nothing = MountSetAttr::new();
                open_tree_attr(None, &path("attr"), OpenTreeFlags::empty(), &nothing).unwrap();
                assert_eq!(options("attr"), now);
                // Only a mount has settings, and two values of one
                // setting are none.
                let inside = path("new/data");
                let error =
                    open_tree_attr(None, &inside, OpenTreeFlags::empty(), &no_exec).unwrap_err();
                assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
                let both = MountSetAttr::new()
                    .set(MountAttributes::NO_ATIME | MountAttributes::STRICT_ATIME);
                let error =
                    open_tree_attr(None, &path("single"), OpenTreeFlags::CLONE, &both).unwrap_err();
                assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
                let error = open_tree_attr(None, &path("missing"), OpenTreeFlags::CLONE, &nothing)
                    .unwrap_err();
                assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
                mounts::unmount(&path("attr"), UnmountFlags::empty()).unwrap();
            }
            Err(error) if kernel_before(6, 15) => {
                assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}");
                common::note("skipped: no open_tree_attr before Linux 6.15");
            }
            Err(error) => panic!("open_tree_attr: {error:?}"),
        }

        // What the kernel says of these mounts, without the file.
        let mut buf = [0u8; 4096];
        let id = match mount_id(None, &new, true) {
            Ok(id) => id,
            Err(error) if kernel_before(6, 8) => {
                assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}");
                common::note("skipped: no statmount before Linux 6.8");
                return;
            }
            Err(error) => panic!("mount_id: {error:?}"),
        };
        let parent = mount_id(None, root, true).unwrap();
        assert_ne!(id, parent);
        let mount = statmount(id, StatMountFields::ALL, &mut buf).unwrap();
        assert_eq!((mount.id, mount.parent_id), (id, parent), "{mount:?}");
        assert_eq!(mount.fs_type, Some(&b"tmpfs"[..]), "{mount:?}");
        assert_eq!(mount.magic, 0x0102_1994, "{mount:?}");
        assert_eq!(mount.root, Some(&b"/"[..]), "{mount:?}");
        assert_eq!(mount.point, Some(new.as_bytes()), "{mount:?}");
        let set = MountAttributes::NO_SUID | MountAttributes::NO_DEV | MountAttributes::REL_ATIME;
        assert!(mount.attributes.contains(set), "{mount:?}");
        let unset = MountAttributes::READ_ONLY | MountAttributes::NO_EXEC;
        assert!(!mount.attributes.intersects(unset), "{mount:?}");
        assert!(!mount.id_mapped, "{mount:?}");
        assert_eq!(
            (mount.propagation, mount.peer_group, mount.master),
            (Propagation::Private, 0, 0),
            "{mount:?}"
        );
        assert!(mount.filesystem_flags.is_empty(), "{mount:?}");
        if mount.fields.contains(StatMountFields::SOURCE) {
            assert_eq!(mount.source, Some(&b"oscall-new"[..]), "{mount:?}");
        }
        if mount.fields.contains(StatMountFields::OPTIONS) {
            let text = String::from_utf8_lossy(mount.options.unwrap()).into_owned();
            assert!(
                text.split(',').any(|option| option == "size=2048k"),
                "{text}"
            );
        }
        if mount.fields.contains(StatMountFields::OPTION_LIST) {
            let listed: Vec<&[u8]> = mount.option_list.collect();
            assert!(listed.contains(&&b"size=2048k"[..]), "{mount:?}");
            assert!(listed.contains(&&b"mode=755"[..]), "{mount:?}");
        }
        // What is mounted under it, and nothing else.
        let sub = mount_id(None, &path("new/sub"), true).unwrap();
        let under: Vec<u64> = mounts(id).map(|id| id.unwrap()).collect();
        assert_eq!(under, [sub]);
        let whole: Vec<u64> = mounts(ROOT_MOUNT).map(|id| id.unwrap()).collect();
        assert!(whole.contains(&id) && whole.contains(&sub) && whole.contains(&parent));
        // The read-only copy of it: the same filesystem, another mount.
        let moved = mount_id(None, &path("moved"), true).unwrap();
        assert_ne!(moved, id);
        let copy = statmount(moved, StatMountFields::ALL, &mut buf).unwrap();
        assert!(
            copy.attributes.contains(MountAttributes::READ_ONLY),
            "{copy:?}"
        );
        assert_eq!(copy.fs_type, Some(&b"tmpfs"[..]), "{copy:?}");
        let device = copy.device;
        let mount = statmount(id, StatMountFields::FILESYSTEM, &mut buf).unwrap();
        assert_eq!(mount.device, device);
        // Shared, it has a peer group.
        let shared = MountSetAttr::new().propagation(Propagation::Shared);
        mount_setattr(None, &path("moved"), MountSetAttrFlags::empty(), &shared).unwrap();
        let copy = statmount(moved, StatMountFields::MOUNT, &mut buf).unwrap();
        assert_eq!(copy.propagation, Propagation::Shared, "{copy:?}");
        assert_ne!(copy.peer_group, 0, "{copy:?}");
        let private = MountSetAttr::new().propagation(Propagation::Private);
        mount_setattr(None, &path("moved"), MountSetAttrFlags::empty(), &private).unwrap();
        // A mount that is attached nowhere has an identifier, and is in
        // no namespace to be found in.
        let tree = open_tree(None, &new, OpenTreeFlags::CLONE).unwrap();
        let detached = mount_id(Some(tree.as_handle()), "", true).unwrap();
        assert!(detached != id && !whole.contains(&detached));
        let error = statmount(detached, StatMountFields::MOUNT, &mut buf).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
    }

    /// A process that waits, in a user namespace whose maps are `uid` and
    /// `gid`, and what keeps it waiting.
    fn in_user_namespace(maps: &[IdMap; 1]) -> (oscall::process::Child, oscall::OwnedHandle) {
        use oscall::AsHandle as _;
        let exe = std::env::current_exe().unwrap();
        let env = helper_env("wait");
        let (input, hold) = oscall::io::pipe().unwrap();
        let child = Command::new(exe.as_os_str().as_encoded_bytes())
            .args(&["--exact", "--nocapture", "helper_child_process"])
            .env(&env)
            .stdin(Stdio::Handle(input.as_handle()))
            .stdout(Stdio::Null)
            .namespaces(Namespaces::USER)
            .uid_map(maps)
            .gid_map(maps)
            .spawn()
            .unwrap();
        (child, hold)
    }

    /// The owners of files, mapped by a mount: `root/new` is a `tmpfs`
    /// this process mounted, with a file of its own in `data/file`.
    fn id_mapped(root: &Path) {
        use oscall::AsHandle as _;
        use oscall::fs::linux::*;
        use oscall::fs::unix::MetadataExt as _;

        let at = |name: &str| root.join(name);
        let path = |name: &str| at(name).into_os_string().into_string().unwrap();
        let owner = |name: &str| {
            let metadata = fs::metadata(&path(name)).unwrap();
            (metadata.uid(), metadata.gid())
        };
        let sysctl = |name: &str| -> u32 {
            let text = std::fs::read_to_string(format!("/proc/sys/kernel/{name}")).unwrap();
            text.trim().parse().unwrap()
        };
        let nobody = (sysctl("overflowuid"), sysctl("overflowgid"));
        let by_handle = MountSetAttrFlags::EMPTY_PATH;
        let from_handle = MoveMountFlags::FROM_EMPTY_PATH;
        assert_eq!(owner("new/data/file"), (0, 0));

        // A map that has no place for the owner of the file: user 1
        // there is the root of here, and nobody is its user 0.
        let (mut child, hold) = in_user_namespace(&[IdMap {
            inside: 1,
            outside: 0,
            count: 1,
        }]);
        let namespace = std::fs::File::open(format!("/proc/{}/ns/user", child.id())).unwrap();
        let map = MountSetAttr::new().id_map(common::handle_of(&namespace));
        let tree = open_tree(None, &path("new"), OpenTreeFlags::CLONE).unwrap();
        match mount_setattr(Some(tree.as_handle()), "", by_handle, &map) {
            Ok(()) => {}
            // `tmpfs` has had them since Linux 6.3.
            Err(error) if error.kind() == ErrorKind::InvalidInput && kernel_before(6, 3) => {
                common::note(&format!(
                    "skipped: no mapped mounts of tmpfs before Linux 6.3: {error}"
                ));
                drop(hold);
                child.wait().unwrap();
                return;
            }
            Err(error) => panic!("mount_setattr: {error:?}"),
        }
        move_mount_at(
            Some(tree.as_handle()),
            "",
            None,
            &path("mapped"),
            from_handle,
        )
        .unwrap();
        let info = mount_info(&at("mapped")).unwrap();
        assert!(has(&info.options, "idmapped"), "{:?}", info.options);
        assert_eq!(owner("mapped/data/file"), nobody);
        assert_eq!(owner("new/data/file"), (0, 0));
        // Who the map does not know creates nothing through it
        // (`EOVERFLOW`). Root of the system is known to it, as the user
        // 1 of the filesystem: a user like another, to whom the
        // directory of someone the map does not know is closed.
        let real_root = std::fs::read_to_string("/proc/self/uid_map")
            .is_ok_and(|map| map.split_whitespace().eq(["0", "0", "4294967295"]));
        let error = std::fs::write(at("mapped/data/other"), "").unwrap_err();
        let expected = if real_root { 13 } else { 75 };
        assert_eq!(error.raw_os_error(), Some(expected), "{error:?}");
        std::fs::write(at("new/data/other"), "").unwrap();

        // Mapped once, and never where it shows already.
        let error = mount_setattr(Some(tree.as_handle()), "", by_handle, &map).unwrap_err();
        assert!(
            matches!(
                error.kind(),
                ErrorKind::InvalidInput | ErrorKind::PermissionDenied
            ),
            "{error:?}"
        );
        let flags = MountSetAttrFlags::empty();
        let error = mount_setattr(None, &path("copy"), flags, &map).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        // The namespace must be one, and another than the filesystem's.
        drop(tree);
        let tree = open_tree(None, &path("new"), OpenTreeFlags::CLONE).unwrap();
        let file = std::fs::File::open(at("new/data/file")).unwrap();
        let not_one = MountSetAttr::new().id_map(common::handle_of(&file));
        let error = mount_setattr(Some(tree.as_handle()), "", by_handle, &not_one).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        let own = std::fs::File::open("/proc/self/ns/user").unwrap();
        let own = MountSetAttr::new().id_map(common::handle_of(&own));
        let error = mount_setattr(Some(tree.as_handle()), "", by_handle, &own).unwrap_err();
        assert!(
            matches!(
                error.kind(),
                ErrorKind::InvalidInput | ErrorKind::PermissionDenied
            ),
            "{error:?}"
        );
        // SAFETY: the number is used for one call, which finds nothing.
        let closed = unsafe { oscall::BorrowedHandle::borrow_raw(999_999) };
        let closed = MountSetAttr::new().id_map(closed);
        let error = mount_setattr(Some(tree.as_handle()), "", by_handle, &closed).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");
        drop(hold);
        assert!(child.wait().unwrap().success());
        // The map is the mount's: the namespace it was read from is gone.
        assert_eq!(owner("mapped/data/file"), nobody);

        // Root of the system maps whom it pleases: the files of root, as
        // those of the first user of a container.
        if real_root {
            let (mut child, hold) = in_user_namespace(&[IdMap {
                inside: 0,
                outside: 100_000,
                count: 65_536,
            }]);
            let namespace = std::fs::File::open(format!("/proc/{}/ns/user", child.id())).unwrap();
            let map = MountSetAttr::new()
                .set(MountAttributes::NO_SUID)
                .id_map(common::handle_of(&namespace));
            mount_setattr(Some(tree.as_handle()), "", by_handle, &map).unwrap();
            drop(hold);
            assert!(child.wait().unwrap().success());
            let to = path("mapped-root");
            move_mount_at(Some(tree.as_handle()), "", None, &to, from_handle).unwrap();
            assert_eq!(owner("mapped-root/data/file"), (100_000, 100_000));
            drop(tree);
            mounts::unmount(&to, UnmountFlags::empty()).unwrap();
        } else {
            common::note("skipped: only root may map identifiers that are not its own");
        }
        mounts::unmount(&path("mapped"), UnmountFlags::empty()).unwrap();
    }

    /// Whether the kernel is older than the release `major.minor`.
    fn kernel_before(major: u32, minor: u32) -> bool {
        let name = linux::system_name().unwrap();
        let release = String::from_utf8_lossy(name.release()).into_owned();
        let mut parts = release
            .split(|c: char| !c.is_ascii_digit())
            .map(|part| part.parse::<u32>().unwrap_or(0));
        let found = (parts.next().unwrap_or(0), parts.next().unwrap_or(0));
        found < (major, minor)
    }

    /// Run in new mount and process namespaces, with `CAP_SYS_ADMIN`
    /// there: builds a root under `root`, moves into it, and checks each
    /// step. `root` is an empty directory, next to a file named
    /// `outside`.
    pub(super) fn helper_root(root: &Path) {
        let at = |name: &str| root.join(name);
        let path = |name: &str| at(name).into_os_string().into_string().unwrap();
        let outside = root.parent().unwrap().join("outside");
        assert!(outside.exists());
        let settings = MountFlags::NO_SUID | MountFlags::NO_DEV;
        let none = UnmountFlags::empty();

        // Nothing of what follows leaves this namespace.
        if let Err(error) = mounts::set_propagation("/", Propagation::Private, true) {
            // Root of its namespace on paper, and denied the use of it:
            // what Ubuntu's AppArmor restriction of user namespaces does.
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
            skip!(
                "(root) no use of capabilities in the user namespace ({})",
                common::confinement()
            );
            return;
        }

        // The root is to be a mount point.
        assert!(mount_info(root).is_none());
        let here = root.to_str().unwrap();
        mounts::bind(here, here, true).unwrap();
        assert!(mount_info(root).is_some());
        for name in ["proc", "tmp", "dev", "ro", "moved"] {
            std::fs::create_dir(at(name)).unwrap();
        }

        // A filesystem by its type, with its options.
        let tmp = path("tmp");
        mounts::mount("oscall-tmp", &tmp, "tmpfs", settings, "size=1m,mode=750").unwrap();
        let info = mount_info(&at("tmp")).unwrap();
        assert_eq!(
            (info.fstype.as_str(), info.source.as_str()),
            ("tmpfs", "oscall-tmp")
        );
        assert!(has(&info.options, "rw") && has(&info.options, "nosuid"));
        assert!(has(&info.options, "nodev") && !has(&info.options, "noexec"));
        assert!(
            has(&info.super_options, "size=1024k"),
            "{:?}",
            info.super_options
        );
        assert!(
            has(&info.super_options, "mode=750"),
            "{:?}",
            info.super_options
        );
        // What the system refuses.
        let dev = path("dev");
        let error = mounts::mount("none", &dev, "oscall-no-such-type", settings, "").unwrap_err();
        assert_eq!(error.raw_os_error(), ENODEV, "{error:?}");
        let error = mounts::mount("none", &dev, "tmpfs", settings, "oscall-no-option").unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        let error = mounts::mount("none", &path("missing"), "tmpfs", settings, "").unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        let error = mounts::mount("none", &outside, "tmpfs", settings, "").unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotADirectory, "{error:?}");
        assert!(mount_info(&at("dev")).is_none());

        // The processes of this namespace, of which this one is the
        // first.
        let flags = settings | MountFlags::NO_EXEC;
        let proc = match mounts::mount("proc", &path("proc"), "proc", flags, "") {
            Ok(()) => {
                let me = std::fs::read_link(at("proc/self")).unwrap();
                assert_eq!(me, Path::new("1"));
                assert_eq!(oscall::process::id(), 1);
                let info = mount_info(&at("proc")).unwrap();
                assert!(has(&info.options, "noexec"), "{:?}", info.options);
                true
            }
            // A user namespace may mount it only if it could see all of
            // the one it has, which a container hides parts of.
            Err(error) if error.kind() == ErrorKind::PermissionDenied => {
                skip!("(root) proc may not be mounted here: {error}");
                false
            }
            Err(error) => panic!("proc: {error:?}"),
        };
        // Terminals of its own.
        std::fs::create_dir(at("dev/pts")).unwrap();
        let options = "newinstance,ptmxmode=0666,mode=0620";
        match mounts::mount(
            "devpts",
            &path("dev/pts"),
            "devpts",
            MountFlags::NO_SUID,
            options,
        ) {
            Ok(()) => assert!(at("dev/pts/ptmx").exists()),
            Err(error) if error.raw_os_error() == ENODEV => {
                skip!("(root) the kernel has no devpts: {error}");
            }
            Err(error) => panic!("devpts: {error:?}"),
        }

        // A tree shown at a second place, where it cannot be written.
        std::fs::create_dir(at("tmp/data")).unwrap();
        std::fs::write(at("tmp/data/file"), "one").unwrap();
        let (data, ro) = (path("tmp/data"), path("ro"));
        mounts::bind(&data, &ro, false).unwrap();
        assert_eq!(std::fs::read_to_string(at("ro/file")).unwrap(), "one");
        std::fs::write(at("ro/file"), "two").unwrap();
        mounts::remount_bind(&ro, settings | MountFlags::READ_ONLY).unwrap();
        let error = std::fs::write(at("ro/file"), "three").unwrap_err();
        assert_eq!(
            error.kind(),
            std::io::ErrorKind::ReadOnlyFilesystem,
            "{error:?}"
        );
        let error = fs::create_dir(&path("ro/new")).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::ReadOnlyFilesystem, "{error:?}");
        // The filesystem is as it was, through its other mount point.
        std::fs::write(at("tmp/data/file"), "four").unwrap();
        assert_eq!(std::fs::read_to_string(at("ro/file")).unwrap(), "four");
        assert!(has(&mount_info(&at("ro")).unwrap().options, "ro"));
        assert!(has(&mount_info(&at("tmp")).unwrap().options, "rw"));

        // The filesystem itself, read-only and larger, then as before.
        mounts::remount(&tmp, settings | MountFlags::READ_ONLY, "size=2m").unwrap();
        let error = std::fs::write(at("tmp/data/file"), "five").unwrap_err();
        assert_eq!(
            error.kind(),
            std::io::ErrorKind::ReadOnlyFilesystem,
            "{error:?}"
        );
        let info = mount_info(&at("tmp")).unwrap();
        assert!(
            has(&info.super_options, "size=2048k"),
            "{:?}",
            info.super_options
        );
        mounts::remount(&tmp, settings | MountFlags::NO_ATIME, "").unwrap();
        std::fs::write(at("tmp/data/file"), "six").unwrap();
        let info = mount_info(&at("tmp")).unwrap();
        assert!(has(&info.options, "noatime") && has(&info.options, "rw"));

        // How it propagates.
        let shared = |info: &MountInfo| info.tags.iter().any(|tag| tag.starts_with("shared:"));
        assert!(mount_info(&at("tmp")).unwrap().tags.is_empty());
        mounts::set_propagation(&tmp, Propagation::Shared, false).unwrap();
        assert!(shared(&mount_info(&at("tmp")).unwrap()));
        // A copy made now is a peer, and what is mounted in one shows in
        // the other.
        mounts::bind(&tmp, &path("moved"), false).unwrap();
        assert!(shared(&mount_info(&at("moved")).unwrap()));
        std::fs::create_dir(at("tmp/sub")).unwrap();
        mounts::mount("oscall-sub", &path("moved/sub"), "tmpfs", settings, "").unwrap();
        assert_eq!(mount_info(&at("tmp/sub")).unwrap().source, "oscall-sub");
        // A slave receives and does not send.
        mounts::set_propagation(&path("moved"), Propagation::Slave, false).unwrap();
        let info = mount_info(&at("moved")).unwrap();
        assert!(
            info.tags.iter().any(|tag| tag.starts_with("master:")),
            "{:?}",
            info.tags
        );
        mounts::unmount(&path("tmp/sub"), none).unwrap();
        assert!(mount_info(&at("moved/sub")).is_none());
        mounts::mount("oscall-sub", &path("moved/sub"), "tmpfs", settings, "").unwrap();
        assert!(mount_info(&at("tmp/sub")).is_none());
        mounts::unmount(&path("moved/sub"), none).unwrap();
        mounts::unmount(&path("moved"), none).unwrap();
        // Private again, then not even a source.
        mounts::set_propagation(&tmp, Propagation::Private, false).unwrap();
        assert!(mount_info(&at("tmp")).unwrap().tags.is_empty());
        mounts::set_propagation(&tmp, Propagation::Unbindable, false).unwrap();
        assert!(has(&mount_info(&at("tmp")).unwrap().tags, "unbindable"));
        let error = mounts::bind(&tmp, &path("moved"), false).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        mounts::set_propagation(&tmp, Propagation::Private, false).unwrap();
        // Only a mount point has any.
        let error =
            mounts::set_propagation(&path("moved"), Propagation::Private, false).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");

        // A mount point moved.
        mounts::move_mount(&ro, &path("moved")).unwrap();
        assert!(mount_info(&at("ro")).is_none());
        assert!(has(&mount_info(&at("moved")).unwrap().options, "ro"));
        assert_eq!(std::fs::read_to_string(at("moved/file")).unwrap(), "six");
        let error = mounts::move_mount(&ro, &path("moved")).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");

        // Unmounting: not while in use, unless it is only detached.
        let held = std::fs::File::open(at("moved/file")).unwrap();
        let error = mounts::unmount(&path("moved"), none).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::ResourceBusy, "{error:?}");
        mounts::unmount(
            &path("moved"),
            UnmountFlags::DETACH | UnmountFlags::NO_FOLLOW,
        )
        .unwrap();
        assert!(mount_info(&at("moved")).is_none());
        assert!(names(&path("moved")).is_empty());
        // What was open stays so.
        let mut text = String::new();
        std::io::Read::read_to_string(&mut &held, &mut text).unwrap();
        assert_eq!(text, "six");
        drop(held);
        let error = mounts::unmount(&path("moved"), none).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        // Expiry takes two calls with no use in between.
        mounts::bind(&data, &ro, false).unwrap();
        let error = mounts::unmount(&ro, UnmountFlags::EXPIRE).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::WouldBlock, "{error:?}");
        mounts::unmount(&ro, UnmountFlags::EXPIRE).unwrap();
        assert!(mount_info(&at("ro")).is_none());
        // Not through a symbolic link, when told so.
        std::os::unix::fs::symlink("tmp", at("link")).unwrap();
        let error = mounts::unmount(&path("link"), UnmountFlags::NO_FOLLOW).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        std::fs::remove_file(at("link")).unwrap();

        // Into the new root, and the old one let go.
        let error = mounts::pivot_root(&path("ro"), &path("ro")).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        fs::set_current_dir(here).unwrap();
        mounts::pivot_root(".", ".").unwrap();
        mounts::unmount(".", UnmountFlags::DETACH).unwrap();
        fs::set_current_dir("/").unwrap();
        assert_eq!(names("/"), ["dev", "moved", "proc", "ro", "tmp"]);
        assert_eq!(std::env::current_dir().unwrap(), Path::new("/"));
        assert!(!outside.exists() && !root.exists());
        assert_eq!(std::fs::read_to_string("/tmp/data/file").unwrap(), "six");
        if proc {
            assert_eq!(std::fs::read_link("/proc/self").unwrap(), Path::new("1"));
            // All that is mounted is what was built.
            let mounted = std::fs::read_to_string("/proc/self/mountinfo").unwrap();
            let mut points: Vec<&str> = mounted
                .lines()
                .map(|line| line.split(' ').nth(4).unwrap())
                .collect();
            points.sort_unstable();
            points.retain(|&point| point != "/dev/pts");
            assert_eq!(points, ["/", "/proc", "/tmp"], "{mounted}");
        }

        // A root that is only a directory.
        std::fs::create_dir("/tmp/jail").unwrap();
        std::fs::write("/tmp/jail/inside", "").unwrap();
        let error = mounts::chroot("/tmp/missing").unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        mounts::chroot("/tmp/jail").unwrap();
        fs::set_current_dir("/").unwrap();
        assert_eq!(names("/"), ["inside"]);
        assert!(!Path::new("/tmp").exists());
        // From a root that is no mount point there is no pivoting.
        let error = mounts::pivot_root("/", "/").unwrap_err();
        assert!(
            matches!(
                error.kind(),
                ErrorKind::InvalidInput | ErrorKind::ResourceBusy
            ),
            "{error:?}"
        );
    }

    /// 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
    }

    /// A root built and entered, by a child with the capability for it.
    #[test]
    fn container_root() {
        mounting("fs_linux_root", "root", Namespaces::PID);
    }

    /// The calls that mount by handles, by a child with the capability
    /// for them. Its process namespace is the caller's: it writes the
    /// maps of a child of its own, through a `/proc` that must show it.
    #[test]
    fn mount_handles() {
        mounting("fs_linux_api", "api", Namespaces::empty());
    }

    /// Runs the helper `mode` on the directory `root` of a new directory
    /// `name`, in a mount namespace of its own and in `namespaces`, with
    /// `CAP_SYS_ADMIN` there, and checks that nothing it mounted shows
    /// here.
    fn mounting(name: &str, mode: &str, namespaces: Namespaces) {
        let dir = std::path::absolute(common::tmp_dir(name)).unwrap();
        let dir = dir.canonicalize().unwrap();
        let root = dir.join("root");
        std::fs::create_dir(&root).unwrap();
        std::fs::write(dir.join("outside"), "").unwrap();
        let before = std::fs::read_to_string("/proc/self/mountinfo").unwrap_or_default();

        let exe = std::env::current_exe().unwrap();
        let env = helper_env(&format!("{mode}:{}", root.display()));
        let map = |outside| {
            [IdMap {
                inside: 0,
                outside,
                count: 1,
            }]
        };
        let ids = (
            map(linux::effective_user_id()),
            map(linux::effective_group_id()),
        );
        let mut command = Command::new(exe.as_os_str().as_encoded_bytes())
            .args(&["--exact", "--nocapture", "helper_child_process"])
            .env(&env)
            .stdin(Stdio::Null)
            .stdout(Stdio::Null);
        // Root of the system has the capability; anyone else is root of a
        // user namespace made for the occasion.
        let privileged = linux::effective_user_id() == 0
            && linux::capabilities()
                .unwrap()
                .effective
                .contains(Capability::SysAdmin);
        command = if privileged {
            command.namespaces(Namespaces::MOUNT | namespaces)
        } else {
            command
                .namespaces(Namespaces::USER | Namespaces::MOUNT | namespaces)
                .uid_map(&ids.0)
                .gid_map(&ids.1)
                .deny_setgroups()
        };
        let mut child = match command.spawn() {
            Ok(child) => child,
            Err(error) if error.raw_os_error() == ENOEXEC => {
                skip!("the system cannot execute {}", exe.display());
                return;
            }
            Err(error) => match common::namespace_refusal(&error) {
                Some(reason) => {
                    skip!("{reason}: {error}");
                    return;
                }
                None => panic!("spawn: {error:?}"),
            },
        };
        let start = Instant::now();
        let status = loop {
            if let Some(status) = child.try_wait().unwrap() {
                break status;
            }
            if start.elapsed() > Duration::from_secs(60) {
                child.kill().unwrap();
                panic!("the helper did not exit");
            }
            std::thread::sleep(Duration::from_millis(2));
        };
        assert!(status.success(), "{status}");

        // Nothing of it shows here: the mounts were the namespace's, and
        // went with it.
        let after = std::fs::read_to_string("/proc/self/mountinfo").unwrap_or_default();
        let under = |text: &str| text.lines().filter(|line| line.contains(name)).count();
        assert_eq!(under(&after), under(&before), "{after}");
        assert!(dir.join("outside").exists());
    }
}