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
//! Memory: page sizes, mappings, protection, reservations.

mod common;

use std::fs::{File, OpenOptions};
use std::path::Path;

use oscall::mem::{self, Advice, MapOptions, Mapping, Protection, Sharing};
use oscall::{BorrowedHandle, ErrorKind};

/// Held for reading by the tests that fail on memory another test locked
/// behind their back, and for writing by the test that locks all the memory
/// of the process.
#[allow(dead_code)]
static ALL_LOCKED: std::sync::RwLock<()> = std::sync::RwLock::new(());

/// WebAssembly cannot map memory: there, every test checks that the
/// functions it is about say so, and stops.
const SUPPORTED: bool = !cfg!(target_family = "wasm");

const RW: Protection = Protection::READ_WRITE;

/// The bytes of a mapping, copied out.
fn bytes(ptr: *const u8, len: usize) -> Vec<u8> {
    // SAFETY: the tests only call this on readable mappings of that length
    // that nothing modifies meanwhile.
    unsafe { std::slice::from_raw_parts(ptr, len) }.to_vec()
}

/// Content that differs from page to page and from zero.
fn pattern(len: usize) -> Vec<u8> {
    (0..len).map(|i| (i % 251) as u8 + 1).collect()
}

/// Creates a file holding `content`, open for reading and writing.
fn file_with(path: &Path, content: &[u8]) -> File {
    std::fs::write(path, content).unwrap();
    OpenOptions::new()
        .read(true)
        .write(true)
        .open(path)
        .unwrap()
}

#[test]
fn sizes() {
    let page = mem::page_size();
    let granularity = mem::allocation_granularity();
    assert!(page.is_power_of_two());
    assert!(page >= 4096);
    assert!(granularity.is_power_of_two());
    assert!(granularity.is_multiple_of(page));
    // Asked twice, the same answer.
    assert_eq!(mem::page_size(), page);
    assert_eq!(mem::allocation_granularity(), granularity);

    if cfg!(any(windows, target_family = "wasm")) {
        assert_eq!(granularity, 65536);
    } else {
        assert_eq!(granularity, page);
    }
    if cfg!(target_family = "wasm") {
        assert_eq!(page, 65536);
    }
    if cfg!(any(target_arch = "x86", target_arch = "x86_64")) {
        assert_eq!(page, 4096);
    }
}

#[test]
fn anonymous() {
    // A null length is refused the same way everywhere.
    let err = mem::map_anonymous(0, RW).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);

    let page = mem::page_size();
    let len = 3 * page;
    if !SUPPORTED {
        let err = mem::map_anonymous(len, RW).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        let ptr = std::ptr::null_mut();
        // SAFETY: nothing is unmapped on this platform.
        let err = unsafe { mem::unmap(ptr, len) }.unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        return;
    }

    let ptr = mem::map_anonymous(len, RW).unwrap();
    assert!(!ptr.is_null());
    assert!(ptr.addr().is_multiple_of(mem::allocation_granularity()));
    assert!(bytes(ptr, len).iter().all(|&b| b == 0));
    let content = pattern(len);
    // SAFETY: the mapping is `len` writable bytes that only this test knows.
    unsafe { ptr.copy_from_nonoverlapping(content.as_ptr(), len) };
    assert_eq!(bytes(ptr, len), content);

    // A second mapping is elsewhere, and its own.
    let other = mem::map_anonymous(len, RW).unwrap();
    assert_ne!(other, ptr);
    assert!(bytes(other, len).iter().all(|&b| b == 0));

    // SAFETY: both are whole mappings made above, not used afterwards.
    unsafe {
        // What is not a range is refused before the system is asked.
        let err = mem::unmap(ptr, 0).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = mem::unmap(ptr.wrapping_add(1), len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        assert_eq!(bytes(ptr, len), content);

        mem::unmap(ptr, len).unwrap();
        mem::unmap(other, len).unwrap();
    }

    // A length that is not a whole number of pages extends to the next one.
    let ptr = mem::map_anonymous(page + 1, RW).unwrap();
    // SAFETY: the mapping is two writable pages.
    unsafe {
        ptr.add(2 * page - 1).write(9);
        assert_eq!(ptr.add(2 * page - 1).read(), 9);
        mem::unmap(ptr, page + 1).unwrap();
    }
}

#[test]
fn protection() {
    let page = mem::page_size();
    let len = 2 * page;
    if !SUPPORTED {
        let ptr = std::ptr::null_mut();
        // SAFETY: nothing is done on this platform.
        let err = unsafe { mem::protect(ptr, len, Protection::READ) }.unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        return;
    }

    let ptr = mem::map_anonymous(len, RW).unwrap();
    let content = pattern(len);
    // SAFETY: the mapping is `len` bytes that only this test knows, and is
    // only accessed in the ways its protection allows at that point.
    unsafe {
        ptr.copy_from_nonoverlapping(content.as_ptr(), len);

        mem::protect(ptr, len, Protection::READ).unwrap();
        assert_eq!(bytes(ptr, len), content);

        // One page of the two, then none: the contents survive.
        mem::protect(ptr.add(page), page, Protection::NONE).unwrap();
        assert_eq!(bytes(ptr, page), content[..page]);
        mem::protect(ptr, len, Protection::NONE).unwrap();

        mem::protect(ptr, len, RW).unwrap();
        assert_eq!(bytes(ptr, len), content);
        ptr.write(0xAA);
        assert_eq!(ptr.read(), 0xAA);

        // Executable pages can be read, when reading is asked for.
        mem::protect(ptr, len, Protection::READ_EXECUTE).unwrap();
        assert_eq!(bytes(ptr.add(1), len - 1), content[1..]);

        // The length is rounded up to the page: one byte is one page.
        mem::protect(ptr, 1, RW).unwrap();
        ptr.add(page - 1).write(0xBB);
        assert_eq!(ptr.add(page - 1).read(), 0xBB);

        let err = mem::protect(ptr, 0, RW).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = mem::protect(ptr.add(1), page, RW).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);

        mem::unmap(ptr, len).unwrap();
    }

    // A mapping can be made with any protection.
    for protection in [
        Protection::NONE,
        Protection::READ,
        Protection::WRITE,
        Protection::READ_EXECUTE,
    ] {
        let ptr = mem::map_anonymous(len, protection).unwrap();
        if protection.contains(Protection::READ) {
            assert!(bytes(ptr, len).iter().all(|&b| b == 0));
        }
        // SAFETY: a whole mapping made above, not used afterwards.
        unsafe { mem::unmap(ptr, len) }.unwrap();
    }
}

#[test]
fn flags() {
    assert!(Protection::NONE.is_empty());
    assert_eq!(Protection::NONE, Protection::empty());
    assert_eq!(Protection::READ | Protection::WRITE, RW);
    assert_eq!(
        Protection::READ | Protection::EXECUTE,
        Protection::READ_EXECUTE
    );
    assert!(RW.contains(Protection::WRITE));
    assert!(!RW.contains(Protection::EXECUTE));
    assert_eq!(format!("{:?}", Protection::READ), "Protection(READ)");
}

#[test]
fn file_shared() {
    let dir = common::tmp_dir("mem-file-shared");
    let path = dir.join("file");
    let granularity = mem::allocation_granularity();
    // Two units of offset and a partial page.
    let len = 2 * granularity + 100;
    let content = pattern(len);
    let file = file_with(&path, &content);
    let handle = common::handle_of(&file);

    // Refused before the system is asked, on every platform.
    let err = mem::map_file(&handle, 0, 0, RW, Sharing::Shared).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    let err = mem::map_file(&handle, 1, 100, RW, Sharing::Shared).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    if granularity > 4096 {
        let err = mem::map_file(&handle, 4096, 100, RW, Sharing::Shared).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
    }

    if !SUPPORTED {
        let err = mem::map_file(&handle, 0, len, RW, Sharing::Shared).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        let ptr = std::ptr::null();
        let err = mem::flush(ptr, len, &handle).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        return;
    }

    // The mapping is the file.
    let ptr = mem::map_file(&handle, 0, len, RW, Sharing::Shared).unwrap();
    assert!(ptr.addr().is_multiple_of(granularity));
    assert_eq!(bytes(ptr, len), std::fs::read(&path).unwrap());

    // A part of it, from an offset, read-only.
    let tail = len - granularity;
    let part = mem::map_file(
        &handle,
        granularity as u64,
        tail,
        Protection::READ,
        Sharing::Shared,
    )
    .unwrap();
    assert_eq!(bytes(part, tail), content[granularity..]);

    // Writing to the mapping writes to the file, and to its other mappings.
    let mut expected = content.clone();
    for at in [0, granularity + 5, len - 1] {
        expected[at] = 0;
        // SAFETY: inside the writable mapping.
        unsafe { ptr.add(at).write(0) };
    }
    assert_eq!(bytes(part, tail), expected[granularity..]);
    mem::flush(ptr, len, &handle).unwrap();
    assert_eq!(std::fs::read(&path).unwrap(), expected);

    // A range of pages can be flushed, but not what is not a range.
    mem::flush(ptr, 1, &handle).unwrap();
    let err = mem::flush(ptr, 0, &handle).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    let err = mem::flush(ptr.wrapping_add(1), 1, &handle).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);

    // What the file is written with shows in the mapping.
    {
        use std::io::{Seek, SeekFrom, Write};
        let mut writer = &file;
        writer.seek(SeekFrom::Start(3)).unwrap();
        writer.write_all(&[0xEE]).unwrap();
        expected[3] = 0xEE;
    }
    assert_eq!(bytes(ptr, len), expected);

    // The protection can be lowered, and raised back to what it was.
    // SAFETY: the mapping is only this test's, and accessed as allowed.
    unsafe {
        mem::protect(ptr, len, Protection::READ).unwrap();
        assert_eq!(bytes(ptr, len), expected);
        mem::protect(ptr, len, RW).unwrap();
        ptr.write(0x55);
        expected[0] = 0x55;
    }

    // The mappings outlive the handle they were made from.
    drop(file);
    assert_eq!(bytes(ptr, len), expected);
    assert_eq!(bytes(part, tail), expected[granularity..]);

    // SAFETY: whole mappings made above, not used afterwards.
    unsafe {
        mem::unmap(part, tail).unwrap();
        mem::unmap(ptr, len).unwrap();
    }
    assert_eq!(std::fs::read(&path).unwrap(), expected);
}

#[test]
fn file_private() {
    let dir = common::tmp_dir("mem-file-private");
    let path = dir.join("file");
    let len = mem::page_size() + 10;
    let content = pattern(len);
    std::fs::write(&path, &content).unwrap();
    // Reading is all a private mapping needs of the file.
    let file = File::open(&path).unwrap();
    let handle = common::handle_of(&file);

    if !SUPPORTED {
        let err = mem::map_file(&handle, 0, len, RW, Sharing::Private).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        return;
    }

    let private = mem::map_file(&handle, 0, len, RW, Sharing::Private).unwrap();
    let shared = mem::map_file(&handle, 0, len, Protection::READ, Sharing::Shared).unwrap();
    assert_eq!(bytes(private, len), content);
    assert_eq!(bytes(shared, len), content);

    // Changes stay in the private mapping.
    let mut changed = content.clone();
    for at in [0, len - 1] {
        changed[at] = 0;
        // SAFETY: inside the writable mapping.
        unsafe { private.add(at).write(0) };
    }
    assert_eq!(bytes(private, len), changed);
    assert_eq!(bytes(shared, len), content);
    assert_eq!(std::fs::read(&path).unwrap(), content);

    // A private mapping made read-only can be made writable, and is still
    // private then.
    let late = mem::map_file(&handle, 0, len, Protection::READ, Sharing::Private).unwrap();
    assert_eq!(bytes(late, len), content);
    // SAFETY: the mapping is only this test's, and accessed as allowed.
    unsafe {
        mem::protect(late, len, RW).unwrap();
        late.add(1).write(0);
        assert_eq!(late.add(1).read(), 0);
        mem::protect(late, len, Protection::READ).unwrap();
        assert_eq!(late.add(1).read(), 0);
    }
    assert_eq!(bytes(shared, len), content);
    assert_eq!(bytes(private, len), changed);

    // The same goes for pages that are already private copies.
    // SAFETY: as above.
    unsafe {
        mem::protect(private, len, Protection::READ).unwrap();
        assert_eq!(bytes(private, len), changed);
        mem::protect(private, len, RW).unwrap();
        private.add(2).write(0);
        changed[2] = 0;
    }
    assert_eq!(bytes(private, len), changed);
    assert_eq!(bytes(shared, len), content);

    // A shared mapping cannot be given more than the file was opened for.
    let err = mem::map_file(&handle, 0, len, RW, Sharing::Shared).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::PermissionDenied);

    // SAFETY: whole mappings made above, not used afterwards.
    unsafe {
        mem::unmap(late, len).unwrap();
        mem::unmap(private, len).unwrap();
        mem::unmap(shared, len).unwrap();
    }
    assert_eq!(std::fs::read(&path).unwrap(), content);
}

#[test]
fn bad_handle() {
    let len = mem::page_size();
    // SAFETY: the handle is not used: -1 is never an open one.
    let handle = unsafe { BorrowedHandle::borrow_raw(-1isize as oscall::RawHandle) };
    for sharing in [Sharing::Shared, Sharing::Private] {
        let err = mem::map_file(&handle, 0, len, Protection::READ, sharing).unwrap_err();
        if SUPPORTED {
            assert_eq!(err.kind(), ErrorKind::BadHandle);
        } else {
            assert_eq!(err.kind(), ErrorKind::Unsupported);
        }
        let other = Mapping::file(&handle, 0, len, Protection::READ, sharing).unwrap_err();
        assert_eq!(other, err);
    }
}

#[test]
fn reserve_commit() {
    let err = mem::reserve(0).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);

    let page = mem::page_size();
    // Far more than is committed: 64 MiB of address space.
    let len = 64 << 20;
    if !SUPPORTED {
        let err = mem::reserve(len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        let ptr = std::ptr::null_mut();
        // SAFETY: nothing is done on this platform.
        unsafe {
            let err = mem::commit(ptr, page, RW).unwrap_err();
            assert_eq!(err.kind(), ErrorKind::Unsupported);
            let err = mem::decommit(ptr, page).unwrap_err();
            assert_eq!(err.kind(), ErrorKind::Unsupported);
        }
        return;
    }

    let base = mem::reserve(len).unwrap();
    assert!(!base.is_null());
    assert!(base.addr().is_multiple_of(mem::allocation_granularity()));

    // SAFETY: the reservation is only this test's; only committed pages are
    // accessed, as their protection allows.
    unsafe {
        // Three pages in the middle, and the last one.
        let middle = base.add(5 * page);
        mem::commit(middle, 3 * page, RW).unwrap();
        let last = base.add(len - page);
        mem::commit(last, page, RW).unwrap();
        assert!(bytes(middle, 3 * page).iter().all(|&b| b == 0));
        assert!(bytes(last, page).iter().all(|&b| b == 0));
        let content = pattern(3 * page);
        middle.copy_from_nonoverlapping(content.as_ptr(), 3 * page);
        last.write(1);

        // Committing again keeps the contents and sets the protection.
        mem::commit(middle, 3 * page, Protection::READ).unwrap();
        assert_eq!(bytes(middle, 3 * page), content);
        mem::commit(middle, 3 * page, RW).unwrap();
        assert_eq!(bytes(middle, 3 * page), content);

        // A committed page is memory like any other.
        mem::protect(middle, page, Protection::READ).unwrap();
        assert_eq!(bytes(middle, page), content[..page]);
        mem::protect(middle, page, RW).unwrap();

        // Decommitting one page loses that page only.
        mem::decommit(middle.add(page), page).unwrap();
        assert_eq!(bytes(middle, page), content[..page]);
        assert_eq!(bytes(middle.add(2 * page), page), content[2 * page..]);
        mem::commit(middle.add(page), page, RW).unwrap();
        assert!(bytes(middle.add(page), page).iter().all(|&b| b == 0));
        assert_eq!(bytes(middle, page), content[..page]);
        assert_eq!(bytes(middle.add(2 * page), page), content[2 * page..]);

        // Decommitting what is not committed changes nothing.
        mem::decommit(base, 2 * page).unwrap();
        assert_eq!(last.read(), 1);

        let err = mem::commit(middle, 0, RW).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = mem::commit(middle.add(1), page, RW).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = mem::decommit(middle, 0).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = mem::decommit(middle.add(1), page).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);

        // The whole reservation goes at once, committed or not.
        mem::unmap(base, len).unwrap();
    }

    // Anonymous memory can be decommitted and committed too.
    let ptr = mem::map_anonymous(2 * page, RW).unwrap();
    // SAFETY: as above.
    unsafe {
        ptr.write(1);
        ptr.add(page).write(2);
        mem::decommit(ptr, page).unwrap();
        mem::commit(ptr, page, RW).unwrap();
        assert_eq!(ptr.read(), 0);
        assert_eq!(ptr.add(page).read(), 2);
        mem::unmap(ptr, 2 * page).unwrap();
    }
}

#[test]
fn advice() {
    let page = mem::page_size();
    let len = 4 * page;
    if !SUPPORTED {
        let ptr = std::ptr::null_mut();
        for advice in [Advice::WillNeed, Advice::Discard] {
            // SAFETY: nothing is done on this platform.
            let err = unsafe { mem::advise(ptr, len, advice) }.unwrap_err();
            assert_eq!(err.kind(), ErrorKind::Unsupported);
        }
        return;
    }

    // Locked memory cannot be discarded.
    let _unlocked = ALL_LOCKED.read().unwrap();
    let ptr = mem::map_anonymous(len, RW).unwrap();
    let content = pattern(len);
    // SAFETY: the mapping is only this test's; after `Discard` its contents
    // are not relied on.
    unsafe {
        ptr.copy_from_nonoverlapping(content.as_ptr(), len);

        mem::advise(ptr, len, Advice::WillNeed).unwrap();
        assert_eq!(bytes(ptr, len), content);

        // Two pages are discarded: each holds what it held or zeroes, and
        // the others are untouched.
        mem::advise(ptr.add(page), page + 1, Advice::Discard).unwrap();
        assert_eq!(bytes(ptr, page), content[..page]);
        assert_eq!(bytes(ptr.add(3 * page), page), content[3 * page..]);
        for index in 1..3 {
            let now = bytes(ptr.add(index * page), page);
            let before = &content[index * page..(index + 1) * page];
            assert!(now == before || now.iter().all(|&b| b == 0));
        }
        // The memory is still there to use.
        ptr.add(page).write_bytes(7, 2 * page);
        assert!(bytes(ptr.add(page), 2 * page).iter().all(|&b| b == 7));

        for advice in [Advice::WillNeed, Advice::Discard] {
            let err = mem::advise(ptr, 0, advice).unwrap_err();
            assert_eq!(err.kind(), ErrorKind::InvalidInput);
            let err = mem::advise(ptr.add(1), page, advice).unwrap_err();
            assert_eq!(err.kind(), ErrorKind::InvalidInput);
        }
        mem::unmap(ptr, len).unwrap();
    }

    // A file mapping can be read ahead.
    let dir = common::tmp_dir("mem-advice");
    let content = pattern(len);
    let file = file_with(&dir.join("file"), &content);
    let handle = common::handle_of(&file);
    let map = Mapping::file(&handle, 0, len, Protection::READ, Sharing::Shared).unwrap();
    // SAFETY: the mapping is this test's.
    unsafe { mem::advise(map.as_ptr(), len, Advice::WillNeed) }.unwrap();
    assert_eq!(bytes(map.as_ptr(), len), content);
}

#[test]
fn locking() {
    let page = mem::page_size();
    if !SUPPORTED {
        let ptr = std::ptr::null();
        let err = mem::lock(ptr, page).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        let err = mem::unlock(ptr, page).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        return;
    }

    // One page: within the little every process is allowed to lock.
    let map = Mapping::anonymous(2 * page, RW).unwrap();
    let ptr = map.as_ptr();
    // SAFETY: inside the writable mapping.
    unsafe { ptr.write(42) };
    mem::lock(ptr, page).unwrap();
    // Locking twice is locking once.
    mem::lock(ptr, 1).unwrap();
    // SAFETY: as above.
    unsafe {
        assert_eq!(ptr.read(), 42);
        ptr.write(43);
    }
    mem::unlock(ptr, page).unwrap();
    // SAFETY: as above.
    assert_eq!(unsafe { ptr.read() }, 43);

    let err = mem::lock(ptr, 0).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    let err = mem::lock(ptr.wrapping_add(1), page).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    let err = mem::unlock(ptr, 0).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    let err = mem::unlock(ptr.wrapping_add(1), page).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
}

#[test]
fn mapping() {
    let page = mem::page_size();
    let len = page + 123;
    for result in [Mapping::anonymous(0, RW), Mapping::reserve(0)] {
        assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidInput);
    }
    if !SUPPORTED {
        let err = Mapping::anonymous(len, RW).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        let err = Mapping::reserve(len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        return;
    }

    let mut map = Mapping::anonymous(len, RW).unwrap();
    assert_eq!(map.len(), len);
    assert!(!map.is_empty());
    assert!(
        map.as_ptr()
            .addr()
            .is_multiple_of(mem::allocation_granularity())
    );
    assert!(format!("{map:?}").starts_with("Mapping {"));
    let content = pattern(len);
    // SAFETY: the mapping is readable, writable and only this test's.
    unsafe {
        assert!(map.as_slice().iter().all(|&b| b == 0));
        map.as_mut_slice().copy_from_slice(&content);
        assert_eq!(map.as_slice(), content);
    }

    // Ownership goes out and comes back.
    let (ptr, raw_len) = map.into_raw();
    assert_eq!(raw_len, len);
    assert_eq!(bytes(ptr, len), content);
    // SAFETY: the pointer and length of a whole mapping, just released.
    let map = unsafe { Mapping::from_raw(ptr, raw_len) };
    assert_eq!(map.as_ptr(), ptr);
    // It can be used from other threads.
    std::thread::scope(|scope| {
        scope.spawn(|| assert_eq!(bytes(map.as_ptr(), map.len()), content));
    });
    drop(map);

    // Dropping unmaps: address space is not leaked. These are 16 GiB of it
    // in total, far more than a 32-bit process has.
    for _ in 0..64 {
        let reserved = Mapping::reserve(256 << 20).unwrap();
        assert_eq!(reserved.len(), 256 << 20);
        // SAFETY: a range of the reservation that only this test knows.
        unsafe {
            mem::commit(reserved.as_ptr(), page, RW).unwrap();
            reserved.as_ptr().write(1);
        }
    }

    // A file, modified through the mapping.
    let dir = common::tmp_dir("mem-mapping");
    let path = dir.join("file");
    let file = file_with(&path, &content);
    let handle = common::handle_of(&file);
    let mut map = Mapping::file(&handle, 0, len, RW, Sharing::Shared).unwrap();
    assert_eq!(map.len(), len);
    // SAFETY: nothing else touches the file or the mapping.
    unsafe {
        assert_eq!(map.as_slice(), content);
        map.as_mut_slice().reverse();
    }
    mem::flush(map.as_ptr(), map.len(), &handle).unwrap();
    drop(map);
    let reversed: Vec<u8> = content.iter().rev().copied().collect();
    assert_eq!(std::fs::read(&path).unwrap(), reversed);
}

/// Maps with `map` at an address that is free: one that a reservation of
/// `len` bytes just had. Another thread of the tests may take the address
/// in between, which `map` must then report as taken; a few tries find one
/// that stays free.
fn at_free_address(len: usize, map: impl Fn(*mut u8) -> oscall::Result<*mut u8>) -> *mut u8 {
    for _ in 0..1000 {
        let free = mem::reserve(len).unwrap();
        // SAFETY: a whole mapping made above, not used afterwards.
        unsafe { mem::unmap(free, len) }.unwrap();
        match map(free) {
            Ok(ptr) => {
                assert_eq!(ptr, free);
                return ptr;
            }
            Err(err) => assert_eq!(err.kind(), ErrorKind::AlreadyExists),
        }
    }
    panic!("no address stays free");
}

#[test]
fn placement() {
    let granularity = mem::allocation_granularity();
    let page = mem::page_size();
    let len = 2 * granularity;
    assert_eq!(MapOptions::new(), MapOptions::default());
    assert_eq!(MapOptions::new().protection(RW), MapOptions::new());

    let dir = common::tmp_dir("mem-placement");
    let content = pattern(len);
    let file = file_with(&dir.join("file"), &content);
    let handle = common::handle_of(&file);

    // What is not a place for a mapping is refused before the system is
    // asked, on every platform: no address, one that is not on the
    // granularity, a range that wraps around the address space.
    let top = usize::MAX - granularity + 1;
    for addr in [0, granularity + 1, 16 * granularity + page / 2, top] {
        let at = MapOptions::new().at(std::ptr::without_provenance_mut(addr));
        let len = if addr == top { len } else { granularity };
        let err = at.map_anonymous(len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = at.map_file(&handle, 0, len, Sharing::Shared).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = at.reserve(len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = at.reserve_placeholder(len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = Mapping::anonymous_with(len, &at).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
    }
    // The other checks still come first.
    let somewhere = std::ptr::without_provenance_mut(256 * granularity);
    let at = MapOptions::new().at(somewhere);
    assert_eq!(
        at.map_anonymous(0).unwrap_err().kind(),
        ErrorKind::InvalidInput
    );
    assert_eq!(at.reserve(0).unwrap_err().kind(), ErrorKind::InvalidInput);
    let err = at.map_file(&handle, 1, len, Sharing::Shared).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);

    if !SUPPORTED {
        let err = at.map_anonymous(len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        let err = at.map_file(&handle, 0, len, Sharing::Shared).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        let err = at.reserve(len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        let err = Mapping::reserve_with(len, &at).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        return;
    }

    // Memory, exactly where it was asked for.
    let ptr = at_free_address(len, |addr| MapOptions::new().at(addr).map_anonymous(len));
    assert!(bytes(ptr, len).iter().all(|&b| b == 0));
    // SAFETY: the mapping is `len` writable bytes that only this test knows.
    unsafe { ptr.copy_from_nonoverlapping(content.as_ptr(), len) };

    // The address is taken now, and so is every range that reaches into the
    // mapping: nothing is mapped, and what was there is untouched.
    let before = ptr.wrapping_sub(granularity);
    for (addr, len) in [
        (ptr, len),
        (ptr, granularity),
        (ptr.wrapping_add(granularity), granularity),
        (ptr.wrapping_add(granularity), 16 * granularity),
        (before, len),
        (before, 16 * granularity),
    ] {
        let at = MapOptions::new().at(addr);
        let err = at.map_anonymous(len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::AlreadyExists);
        let err = at.protection(Protection::READ).map_anonymous(len);
        assert_eq!(err.unwrap_err().kind(), ErrorKind::AlreadyExists);
        let err = at.reserve(len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::AlreadyExists);
        let err = at.reserve_placeholder(len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::AlreadyExists);
        // A view cannot be longer than the file on Windows.
        if len <= content.len() {
            let err = at.map_file(&handle, 0, len, Sharing::Private).unwrap_err();
            assert_eq!(err.kind(), ErrorKind::AlreadyExists);
        }
        let err = Mapping::anonymous_with(len, &at).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::AlreadyExists);
        let err = Mapping::placeholder_with(len, &at).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::AlreadyExists);
    }
    assert_eq!(bytes(ptr, len), content);
    // SAFETY: a whole mapping made above, not used afterwards.
    unsafe { mem::unmap(ptr, len) }.unwrap();

    // A file, with the protection asked for.
    let view = at_free_address(len, |addr| {
        MapOptions::new()
            .protection(Protection::READ)
            .at(addr)
            .map_file(&handle, 0, len, Sharing::Shared)
    });
    assert_eq!(bytes(view, len), content);
    // A second view of its second half, right after the first if nothing
    // took the place: the two are then one range of memory.
    let next = MapOptions::new().at(view.wrapping_add(len)).map_file(
        &handle,
        granularity as u64,
        granularity,
        Sharing::Shared,
    );
    match next {
        Ok(next) => {
            assert_eq!(next, view.wrapping_add(len));
            assert_eq!(
                bytes(view, len + granularity)[len..],
                content[granularity..]
            );
            // SAFETY: a whole mapping made above, not used afterwards.
            unsafe { mem::unmap(next, granularity) }.unwrap();
        }
        Err(err) => assert_eq!(err.kind(), ErrorKind::AlreadyExists),
    }
    // SAFETY: as above.
    unsafe { mem::unmap(view, len) }.unwrap();

    // A reservation, in which pages are committed as in any other.
    let base = at_free_address(len, |addr| MapOptions::new().at(addr).reserve(len));
    // SAFETY: the reservation is only this test's.
    unsafe {
        mem::commit(base.add(page), page, RW).unwrap();
        base.add(page).write(7);
        assert_eq!(base.add(page).read(), 7);
        mem::unmap(base, len).unwrap();
    }

    // The owning forms.
    let owned = at_free_address(len, |addr| {
        let at = MapOptions::new().at(addr);
        let map = Mapping::anonymous_with(len, &at)?;
        assert_eq!(map.len(), len);
        let again = Mapping::reserve_with(len, &at).unwrap_err();
        assert_eq!(again.kind(), ErrorKind::AlreadyExists);
        Ok(map.into_raw().0)
    });
    // SAFETY: a whole mapping, whose ownership `into_raw` gave up.
    drop(unsafe { Mapping::from_raw(owned, len) });
    let map = Mapping::file_with(&handle, 0, len, Sharing::Private, &MapOptions::new()).unwrap();
    // SAFETY: the mapping is readable and nothing modifies it.
    assert_eq!(unsafe { map.as_slice() }, content);
}

#[test]
fn placeholders() {
    let granularity = mem::allocation_granularity();
    let page = mem::page_size();
    let len = 5 * granularity;

    let dir = common::tmp_dir("mem-placeholders");
    // Two units and a partial page.
    let content = pattern(2 * granularity + 100);
    let file = file_with(&dir.join("file"), &content);
    let handle = common::handle_of(&file);

    let err = mem::reserve_placeholder(0).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    // Inside a placeholder, the unit is the page; there is no reserving.
    let inside = std::ptr::without_provenance_mut::<u8>(256 * granularity);
    // SAFETY: nothing is mapped: every call is refused.
    unsafe {
        for addr in [
            0,
            page + 1,
            256 * granularity + page / 2,
            usize::MAX - page + 1,
        ] {
            let options = MapOptions::new().in_placeholder(std::ptr::without_provenance_mut(addr));
            let len = if addr > usize::MAX - page {
                2 * page
            } else {
                page
            };
            let err = options.map_anonymous(len).unwrap_err();
            assert_eq!(err.kind(), ErrorKind::InvalidInput);
            let err = options.map_file(&handle, 0, len, Sharing::Shared);
            assert_eq!(err.unwrap_err().kind(), ErrorKind::InvalidInput);
        }
        let options = MapOptions::new().in_placeholder(inside);
        let err = options.map_anonymous(0).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = options.map_file(&handle, 1, page, Sharing::Shared);
        assert_eq!(err.unwrap_err().kind(), ErrorKind::InvalidInput);
        let err = options.reserve(page).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = options.reserve_placeholder(page).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
    }

    if !SUPPORTED {
        let err = mem::reserve_placeholder(len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        let err = Mapping::placeholder_with(len, &MapOptions::new()).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        // SAFETY: nothing is mapped on this platform.
        let options = unsafe { MapOptions::new().in_placeholder(inside) };
        let err = options.map_anonymous(page).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        let err = options.map_file(&handle, 0, page, Sharing::Shared);
        assert_eq!(err.unwrap_err().kind(), ErrorKind::Unsupported);
        return;
    }

    let base = mem::reserve_placeholder(len).unwrap();
    assert!(!base.is_null());
    assert!(base.addr().is_multiple_of(granularity));
    // It holds its address against everything else.
    let err = MapOptions::new().at(base).map_anonymous(granularity);
    assert_eq!(err.unwrap_err().kind(), ErrorKind::AlreadyExists);

    // SAFETY: the placeholder is only this test's; each range mapped lies
    // in a part of it that is still a placeholder, and each mapping is used
    // as its protection allows, then released by itself.
    unsafe {
        let unit = granularity;
        // The first unit of the file, in the second unit of the
        // placeholder: three mappings where there was one.
        let first = MapOptions::new()
            .protection(Protection::READ)
            .in_placeholder(base.add(unit))
            .map_file(&handle, 0, unit, Sharing::Shared)
            .unwrap();
        assert_eq!(first, base.add(unit));
        assert_eq!(bytes(first, unit), content[..unit]);

        // Memory in the part before it, all of which it takes.
        let memory = MapOptions::new()
            .in_placeholder(base)
            .map_anonymous(unit)
            .unwrap();
        assert_eq!(memory, base);
        assert!(bytes(memory, unit).iter().all(|&b| b == 0));
        memory.write_bytes(0xAB, unit);
        // The two are one range of memory.
        assert_eq!(
            bytes(base, 2 * unit)[unit - 1..unit + 1],
            [0xAB, content[0]]
        );

        // The rest of the file, to its last partial page, at the start of
        // the part after: it follows the first unit, as it does in the file.
        let tail = content.len() - unit;
        let rest = MapOptions::new()
            .in_placeholder(base.add(2 * unit))
            .map_file(&handle, unit as u64, tail, Sharing::Private)
            .unwrap();
        assert_eq!(rest, base.add(2 * unit));
        assert_eq!(bytes(first, content.len()), content);
        // A private mapping: writing it changes neither the file nor the
        // other mappings.
        rest.write(0);
        assert_eq!(rest.read(), 0);
        mem::protect(rest, tail, Protection::READ).unwrap();
        assert_eq!(bytes(rest, tail)[1..], content[unit + 1..]);

        // What remains of the placeholder starts on the next page.
        let used = 2 * unit + tail.next_multiple_of(page);
        let remains = base.add(used);
        // A range that leaves it is refused or, where a placeholder is
        // only a mapping like the others, takes what follows: not tried.
        // What cannot be mapped leaves it as it was.
        let bad = BorrowedHandle::borrow_raw(-1isize as oscall::RawHandle);
        let err = MapOptions::new()
            .in_placeholder(remains)
            .map_file(&bad, 0, page, Sharing::Shared)
            .unwrap_err();
        assert_eq!(err.kind(), ErrorKind::BadHandle);
        // On Windows a view cannot start past the end of its file: the
        // placeholder was cut by then, and is put together again. (Linux
        // and macOS map the range, which faults when touched.)
        #[cfg(windows)]
        {
            let err = MapOptions::new()
                .in_placeholder(remains)
                .map_file(&handle, 16 * unit as u64, page, Sharing::Shared)
                .unwrap_err();
            assert_ne!(err.kind(), ErrorKind::InvalidInput);
        }
        // All that remains can still be taken at once.
        let last = MapOptions::new()
            .protection(Protection::READ)
            .in_placeholder(remains)
            .map_anonymous(len - used)
            .unwrap();
        assert_eq!(last, remains);
        assert!(bytes(last, len - used).iter().all(|&b| b == 0));

        // Each mapping is released by itself, in any order, and the others
        // stay.
        mem::unmap(first, unit).unwrap();
        assert!(bytes(memory, unit).iter().all(|&b| b == 0xAB));
        assert_eq!(bytes(rest, tail)[1..], content[unit + 1..]);
        mem::unmap(last, len - used).unwrap();
        mem::unmap(memory, unit).unwrap();
        mem::unmap(rest, tail).unwrap();
    }
    // The file was only read.
    assert_eq!(std::fs::read(dir.join("file")).unwrap(), content);

    // The same page of a file twice in a row: what is written through one
    // mapping is read through the other, and a range that runs over the end
    // of the first continues at the start of the second. What remains of
    // the placeholder is released like any mapping.
    let ring = file_with(&dir.join("ring"), &vec![0; granularity]);
    let ring_handle = common::handle_of(&ring);
    let unit = granularity;
    let base = mem::reserve_placeholder(3 * unit).unwrap();
    // SAFETY: as above.
    unsafe {
        for index in 0..2 {
            let view = MapOptions::new()
                .in_placeholder(base.add(index * unit))
                .map_file(&ring_handle, 0, unit, Sharing::Shared)
                .unwrap();
            assert_eq!(view, base.add(index * unit));
        }
        let message = b"around the end";
        let start = unit - 6;
        base.add(start)
            .copy_from_nonoverlapping(message.as_ptr(), message.len());
        assert_eq!(bytes(base.add(start), message.len()), message);
        assert_eq!(bytes(base.add(unit + start), 6), message[..6]);
        assert_eq!(bytes(base, message.len() - 6), message[6..]);

        mem::unmap(base.add(2 * unit), unit).unwrap();
        mem::unmap(base.add(unit), unit).unwrap();
        mem::unmap(base, unit).unwrap();
    }

    // A placeholder nothing was mapped in is released whole, and owned.
    let whole = Mapping::placeholder_with(len, &MapOptions::new()).unwrap();
    assert_eq!(whole.len(), len);
    drop(whole);
    let base = mem::reserve_placeholder(page + 1).unwrap();
    // SAFETY: a whole mapping made above, not used afterwards.
    unsafe { mem::unmap(base, page + 1) }.unwrap();
}

/// The machine code of an `extern "C" fn() -> i32` that returns `value`, for
/// the processor the tests are built for.
fn code_returning(value: u8) -> Vec<u8> {
    let words: [u32; 2] = if cfg!(any(target_arch = "x86", target_arch = "x86_64")) {
        // mov eax, value; ret
        return vec![0xB8, value, 0, 0, 0, 0xC3];
    } else if cfg!(target_arch = "aarch64") {
        // mov w0, #value; ret
        [0x5280_0000 | (value as u32) << 5, 0xD65F_03C0]
    } else if cfg!(target_arch = "arm") {
        // mov r0, #value; bx lr, as ARM (not Thumb) instructions: the call
        // changes mode as the address, which is even, says.
        [0xE3A0_0000 | value as u32, 0xE12F_FF1E]
    } else if cfg!(any(target_arch = "riscv32", target_arch = "riscv64")) {
        // li a0, value; ret
        [(value as u32) << 20 | 0x0000_0513, 0x0000_8067]
    } else {
        panic!("no code for this architecture");
    };
    words.iter().flat_map(|word| word.to_le_bytes()).collect()
}

/// Calls the code at `ptr`.
///
/// # Safety
///
/// `ptr` must be the address of executable memory that holds what
/// [`code_returning`] made, flushed from the instruction cache.
unsafe fn call(ptr: *const u8) -> i32 {
    // SAFETY: the caller's contract.
    let function: extern "C" fn() -> i32 = unsafe { std::mem::transmute(ptr) };
    function()
}

#[test]
fn executable() {
    let page = mem::page_size();
    let len = 3 * page;

    // What is not a range is refused before the system is asked.
    let nowhere = std::ptr::without_provenance::<u8>(page);
    // SAFETY: nothing is flushed: every call is refused.
    unsafe {
        let err = mem::flush_instruction_cache(nowhere, 0).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let top = std::ptr::without_provenance::<u8>(usize::MAX - 7);
        let err = mem::flush_instruction_cache(top, 8).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
    }
    if !SUPPORTED {
        // SAFETY: nothing is done on this platform.
        let err = unsafe { mem::flush_instruction_cache(nowhere, 8) }.unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        return;
    }

    // Write, make executable, flush, call: the steps that work everywhere,
    // and again each time the code changes. Without the flush, a processor
    // other than x86 may run what the memory held before.
    let ptr = mem::map_anonymous(len, RW).unwrap();
    for value in [42, 43, 7, 200] {
        let code = code_returning(value);
        // SAFETY: the mapping is only this test's; it is written while
        // writable, and called while executable and flushed.
        unsafe {
            mem::protect(ptr, len, RW).unwrap();
            // In the second page too, across the boundary.
            let other = ptr.add(2 * page - 4);
            ptr.copy_from_nonoverlapping(code.as_ptr(), code.len());
            other.copy_from_nonoverlapping(code.as_ptr(), code.len());
            mem::protect(ptr, len, Protection::READ_EXECUTE).unwrap();
            mem::flush_instruction_cache(ptr, code.len()).unwrap();
            mem::flush_instruction_cache(other, code.len()).unwrap();
            assert_eq!(call(ptr), value as i32);
            assert_eq!(call(other), value as i32);
            // The code can still be read.
            assert_eq!(bytes(ptr, code.len()), code);
        }
    }
    // SAFETY: the mapping is readable memory, whatever part of it is given;
    // it is not used after it is unmapped.
    unsafe {
        mem::flush_instruction_cache(ptr, len).unwrap();
        mem::flush_instruction_cache(ptr.add(1), 1).unwrap();
        mem::flush_instruction_cache(ptr.add(len - 1), 1).unwrap();
        assert_eq!(call(ptr), 200);
        mem::unmap(ptr, len).unwrap();
    }

    // The same in a reservation, where committing sets the protection.
    let base = mem::reserve(64 * page).unwrap();
    let code = code_returning(42);
    // SAFETY: the reservation is only this test's; only committed pages are
    // accessed, as their protection allows.
    unsafe {
        let ptr = base.add(5 * page);
        mem::commit(ptr, page, RW).unwrap();
        ptr.copy_from_nonoverlapping(code.as_ptr(), code.len());
        mem::commit(ptr, page, Protection::READ_EXECUTE).unwrap();
        mem::flush_instruction_cache(ptr, code.len()).unwrap();
        assert_eq!(call(ptr), 42);
        mem::unmap(base, 64 * page).unwrap();
    }
}

#[cfg(target_os = "macos")]
#[test]
fn macos_jit() {
    use oscall::mem::macos::{self, MapOptionsExt};

    let len = mem::page_size();
    // Per-thread protection is a feature of Apple silicon, that a virtual
    // machine may lack: the arm64 runners of GitHub say they have none.
    // Intel processors never have it. The steps are the same either way.
    if cfg!(target_arch = "x86_64") {
        assert!(!macos::jit_write_protect_supported());
    }

    let all = Protection::READ | Protection::WRITE | Protection::EXECUTE;
    let options = MapOptions::new().protection(all).jit(true);
    assert_ne!(options, MapOptions::new().protection(all));
    assert_eq!(options.jit(false), MapOptions::new().protection(all));

    let ptr = options.map_anonymous(len).unwrap();
    for value in [42, 43] {
        let code = code_returning(value);
        // SAFETY: the mapping is only this test's; this thread writes it
        // with the protection off and calls it with the protection on.
        unsafe {
            macos::jit_write_protect(false);
            ptr.copy_from_nonoverlapping(code.as_ptr(), code.len());
            macos::jit_write_protect(true);
            mem::flush_instruction_cache(ptr, code.len()).unwrap();
            assert_eq!(call(ptr), value as i32);
            assert_eq!(bytes(ptr, code.len()), code);
        }
    }
    // A thread starts with the protection on: the mapping is code to it.
    let addr = ptr.addr();
    std::thread::scope(|scope| {
        scope.spawn(move || {
            // SAFETY: the mapping holds flushed code, executable for this
            // thread.
            assert_eq!(unsafe { call(std::ptr::with_exposed_provenance(addr)) }, 43);
        });
    });
    let _ = ptr.expose_provenance();

    // The mapping is placed like any other.
    let err = options.at(ptr).map_anonymous(len).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::AlreadyExists);
    // SAFETY: a whole mapping made above, not used afterwards.
    unsafe { mem::unmap(ptr, len) }.unwrap();

    // Only anonymous memory can be mapped so.
    let dir = common::tmp_dir("mem-macos-jit");
    let file = file_with(&dir.join("file"), &pattern(len));
    let handle = common::handle_of(&file);
    let err = MapOptions::new()
        .protection(Protection::READ)
        .jit(true)
        .map_file(&handle, 0, len, Sharing::Private)
        .unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);

    // Without it, memory that is writable and executable at once is refused
    // on Apple silicon, to a program that is not hardened as to any other,
    // and granted on Intel processors.
    let plain = mem::map_anonymous(len, all).map_err(|err| err.kind());
    if cfg!(target_arch = "aarch64") {
        assert_eq!(plain, Err(ErrorKind::PermissionDenied));
    } else {
        // SAFETY: a whole mapping made above, not used afterwards.
        unsafe { mem::unmap(plain.unwrap(), len) }.unwrap();
    }
}

#[test]
fn shared() {
    let err = mem::create_shared(0).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);

    let granularity = mem::allocation_granularity();
    let len = 2 * granularity;
    if !SUPPORTED {
        let err = mem::create_shared(len).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Unsupported);
        return;
    }

    let memory = mem::create_shared(len).unwrap();
    // Two mappings of it are the same memory, at two addresses.
    let one = mem::map_file(&memory, 0, len, RW, Sharing::Shared).unwrap();
    let two = mem::map_file(&memory, 0, len, RW, Sharing::Shared).unwrap();
    assert_ne!(one, two);
    assert!(bytes(one, len).iter().all(|&b| b == 0));
    assert!(bytes(two, len).iter().all(|&b| b == 0));
    let mut content = pattern(len);
    // SAFETY: both mappings are `len` writable bytes that only this test
    // knows.
    unsafe {
        one.copy_from_nonoverlapping(content.as_ptr(), len);
        assert_eq!(bytes(two, len), content);
        two.add(len - 1).write(0);
        content[len - 1] = 0;
        assert_eq!(one.add(len - 1).read(), 0);
    }

    // A part of it, from an offset, read-only.
    let part = mem::map_file(
        &memory,
        granularity as u64,
        granularity,
        Protection::READ,
        Sharing::Shared,
    )
    .unwrap();
    assert_eq!(bytes(part, granularity), content[granularity..]);
    // The offset follows the rule of every mapping.
    let err = mem::map_file(&memory, 1, granularity, RW, Sharing::Shared).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);

    // A copy-on-write view of it starts with its contents and keeps its
    // changes to itself; macOS has no such view of shared memory.
    let private = mem::map_file(&memory, 0, len, RW, Sharing::Private);
    #[cfg(target_os = "macos")]
    assert_eq!(private.unwrap_err().kind(), ErrorKind::InvalidInput);
    #[cfg(not(target_os = "macos"))]
    {
        let private = private.unwrap();
        assert_eq!(bytes(private, len), content);
        // SAFETY: inside the writable mapping, which is then unmapped.
        unsafe {
            private.write(0xEE);
            assert_eq!(one.read(), content[0]);
            mem::unmap(private, len).unwrap();
        }
    }

    // Another handle to it is the same memory, and it outlives the first.
    let other = oscall::io::duplicate(&memory).unwrap();
    drop(memory);
    let three = Mapping::file(&other, 0, len, Protection::READ, Sharing::Shared).unwrap();
    // SAFETY: nothing writes the memory while the slice is alive.
    assert_eq!(unsafe { three.as_slice() }, content);
    drop(three);
    // The mappings outlive every handle.
    drop(other);
    // SAFETY: inside the writable mappings.
    unsafe {
        two.write(0x77);
        assert_eq!(one.read(), 0x77);
        assert_eq!(bytes(part, granularity), content[granularity..]);
    }
    // SAFETY: whole mappings made above, not used afterwards.
    unsafe {
        mem::unmap(part, granularity).unwrap();
        mem::unmap(two, len).unwrap();
        mem::unmap(one, len).unwrap();
    }

    // Memory made apart is apart.
    let first = mem::create_shared(len).unwrap();
    let second = mem::create_shared(len).unwrap();
    let first = Mapping::file(&first, 0, len, RW, Sharing::Shared).unwrap();
    let second = Mapping::file(&second, 0, len, RW, Sharing::Shared).unwrap();
    // SAFETY: inside the writable mappings.
    unsafe {
        first.as_ptr().write(1);
        assert_eq!(second.as_ptr().read(), 0);
    }

    // A ring buffer: the same memory twice in a row, so that what runs over
    // its end continues at its start, with no file behind it.
    let unit = granularity;
    let ring = mem::create_shared(unit).unwrap();
    let base = mem::reserve_placeholder(2 * unit).unwrap();
    // SAFETY: the placeholder is only this test's, and each half of it is
    // replaced once; the mappings are used as their protection allows, then
    // released each by itself.
    unsafe {
        for index in 0..2 {
            let view = MapOptions::new()
                .in_placeholder(base.add(index * unit))
                .map_file(&ring, 0, unit, Sharing::Shared)
                .unwrap();
            assert_eq!(view, base.add(index * unit));
        }
        drop(ring);
        let message = b"around the end";
        let start = unit - 6;
        base.add(start)
            .copy_from_nonoverlapping(message.as_ptr(), message.len());
        assert_eq!(bytes(base.add(start), message.len()), message);
        assert_eq!(bytes(base.add(unit + start), 6), message[..6]);
        assert_eq!(bytes(base, message.len() - 6), message[6..]);
        mem::unmap(base, unit).unwrap();
        mem::unmap(base.add(unit), unit).unwrap();
    }
}

#[test]
fn file_executable() {
    if !SUPPORTED {
        // No code to map, and `file_shared` covers the refusal.
        return;
    }
    let dir = common::tmp_dir("mem-file-executable");
    let path = dir.join("code");
    let code = code_returning(42);
    std::fs::write(&path, &code).unwrap();
    // Windows wants the right to execute asked for when the file is opened.
    #[cfg(windows)]
    let handle = {
        use oscall::fs::windows::OpenOptionsExt;
        let options = oscall::fs::OpenOptions::new().read(true).execute(true);
        // The option taken back is no option.
        assert_eq!(
            options.execute(false),
            oscall::fs::OpenOptions::new().read(true)
        );
        oscall::fs::open(path.to_str().unwrap(), &options).unwrap()
    };
    #[cfg(not(windows))]
    let file = File::open(&path).unwrap();
    #[cfg(not(windows))]
    let handle = common::handle_of(&file);

    for sharing in [Sharing::Private, Sharing::Shared] {
        let ptr = mem::map_file(&handle, 0, code.len(), Protection::READ_EXECUTE, sharing).unwrap();
        assert_eq!(bytes(ptr, code.len()), code);
        // SAFETY: the mapping is readable memory that holds the code of a
        // function, and is not used after it is unmapped.
        unsafe {
            mem::flush_instruction_cache(ptr, code.len()).unwrap();
            // On Apple silicon too, where the file carries no signature:
            // the tests are not built with the hardened runtime.
            assert_eq!(call(ptr), 42);
            mem::unmap(ptr, code.len()).unwrap();
        }
    }

    // A file opened for reading alone cannot be mapped as code on Windows;
    // elsewhere reading is all it takes, which is what was just done.
    #[cfg(windows)]
    {
        let file = File::open(&path).unwrap();
        let handle = common::handle_of(&file);
        for sharing in [Sharing::Private, Sharing::Shared] {
            let err = mem::map_file(&handle, 0, code.len(), Protection::READ_EXECUTE, sharing)
                .unwrap_err();
            assert_eq!(err.kind(), ErrorKind::PermissionDenied);
        }
        // The right is asked for relative to a directory too, and with
        // the right to write: a shared mapping that is written and run.
        use oscall::fs::windows::OpenOptionsExt;
        let options = oscall::fs::OpenOptions::new().read(true).execute(true);
        let directory = oscall::fs::open(
            dir.to_str().unwrap(),
            &oscall::fs::OpenOptions::new().read(true).directory(true),
        )
        .unwrap();
        let relative = oscall::fs::open_at(&directory, "code", &options).unwrap();
        let ptr = mem::map_file(
            &relative,
            0,
            code.len(),
            Protection::READ_EXECUTE,
            Sharing::Shared,
        )
        .unwrap();
        // SAFETY: as above.
        unsafe {
            mem::flush_instruction_cache(ptr, code.len()).unwrap();
            assert_eq!(call(ptr), 42);
            mem::unmap(ptr, code.len()).unwrap();
        }
        let writable = oscall::fs::open(path.to_str().unwrap(), &options.write(true)).unwrap();
        let all = Protection::READ_WRITE | Protection::EXECUTE;
        match mem::map_file(&writable, 0, code.len(), all, Sharing::Shared) {
            // SAFETY: the mapping is this test's.
            Ok(ptr) => unsafe { mem::unmap(ptr, code.len()).unwrap() },
            Err(error) => panic!("a file open to write and to execute is not mapped: {error:?}"),
        }
    }
}

#[cfg(windows)]
#[test]
fn windows_query() {
    use oscall::mem::windows::{self, RegionState};

    let page = mem::page_size();
    let granularity = mem::allocation_granularity();
    let len = 4 * granularity;

    // A reservation is one region until pages of it differ.
    let base = mem::reserve(len).unwrap();
    let region = windows::query(base).unwrap();
    assert_eq!(region.base, base);
    assert_eq!(region.len, len);
    assert_eq!(region.state, RegionState::Reserved);
    assert_eq!(region.protection, Protection::NONE);
    assert_eq!(region.allocation_base, base);
    assert_eq!(windows::query(base).unwrap(), region);

    // SAFETY: the reservation is only this test's.
    unsafe {
        let second = base.add(page);
        mem::commit(second, page, RW).unwrap();
        let region = windows::query(base).unwrap();
        assert_eq!((region.len, region.state), (page, RegionState::Reserved));
        // An address inside a page is asked about as the page.
        let region = windows::query(second.add(1)).unwrap();
        assert_eq!(region.base, second);
        assert_eq!(region.len, page);
        assert_eq!(region.state, RegionState::Committed);
        assert_eq!(region.protection, RW);
        assert_eq!(region.allocation_base, base);
        let region = windows::query(second.add(page)).unwrap();
        assert_eq!(region.len, len - 2 * page);
        assert_eq!(region.state, RegionState::Reserved);

        for protection in [
            Protection::READ,
            Protection::READ_EXECUTE,
            Protection::NONE,
            RW,
        ] {
            mem::protect(second, page, protection).unwrap();
            let region = windows::query(second).unwrap();
            assert_eq!(region.protection, protection);
            assert_eq!(region.state, RegionState::Committed);
        }
        mem::unmap(base, len).unwrap();
    }

    // Memory is committed from the start, to the end of its last page.
    let map = Mapping::anonymous(page + 1, Protection::READ).unwrap();
    let region = windows::query(map.as_ptr()).unwrap();
    assert_eq!(region.len, 2 * page);
    assert_eq!(region.state, RegionState::Committed);
    assert_eq!(region.protection, Protection::READ);

    // A placeholder is reserved; a copy-on-write view is writable.
    let placeholder = Mapping::placeholder_with(len, &MapOptions::new()).unwrap();
    let region = windows::query(placeholder.as_ptr()).unwrap();
    assert_eq!((region.len, region.state), (len, RegionState::Reserved));
    let dir = common::tmp_dir("mem-windows-query");
    let file = file_with(&dir.join("file"), &pattern(page));
    let handle = common::handle_of(&file);
    let view = Mapping::file(&handle, 0, page, RW, Sharing::Private).unwrap();
    let region = windows::query(view.as_ptr()).unwrap();
    assert_eq!(region.state, RegionState::Committed);
    assert_eq!(region.protection, RW);
    assert_eq!(region.allocation_base, view.as_ptr());

    // The first pages of the address space are never anyone's.
    let region = windows::query(std::ptr::null()).unwrap();
    assert_eq!(region.state, RegionState::Free);
    assert!(region.allocation_base.is_null());
    assert_eq!(region.protection, Protection::NONE);
    // The system's own addresses are no one's to ask about.
    let top = std::ptr::without_provenance::<u8>(usize::MAX - page + 1);
    let err = windows::query(top).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
}

#[cfg(target_os = "macos")]
#[test]
fn macos_query() {
    use oscall::mem::macos;

    let page = mem::page_size();
    let len = 4 * page;
    let ptr = mem::map_anonymous(len, RW).unwrap();
    // The region that holds the mapping may hold its neighbours too, when
    // they are alike.
    let region = macos::query(ptr.wrapping_add(page + 1)).unwrap().unwrap();
    assert!(region.base <= ptr);
    assert!(region.base.addr() + region.len >= ptr.addr() + len);
    assert_eq!(region.protection, RW);
    assert!(region.max_protection.contains(RW));

    // SAFETY: the mapping is only this test's.
    unsafe {
        // A page that differs is a region of its own.
        let second = ptr.add(page);
        for protection in [Protection::READ, Protection::NONE] {
            mem::protect(second, page, protection).unwrap();
            let region = macos::query(second).unwrap().unwrap();
            assert_eq!(region.base, second);
            assert_eq!(region.len, page);
            assert_eq!(region.protection, protection);
            assert!(region.max_protection.contains(RW));
        }
        mem::unmap(ptr, len).unwrap();
    }

    // A reservation is a region with no access.
    let reserved = Mapping::reserve(len).unwrap();
    let region = macos::query(reserved.as_ptr()).unwrap().unwrap();
    assert_eq!(region.protection, Protection::NONE);

    // Nothing is mapped at the top of the address space.
    let top = std::ptr::without_provenance::<u8>(usize::MAX - page + 1);
    assert_eq!(macos::query(top).unwrap(), None);
}

#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
#[test]
fn unix_access_pattern() {
    use oscall::mem::unix::{self, AccessPattern};

    let page = mem::page_size();
    let len = 4 * page;
    let dir = common::tmp_dir("mem-unix-access");
    let content = pattern(len);
    let file = file_with(&dir.join("file"), &content);
    let handle = common::handle_of(&file);
    let view = Mapping::file(&handle, 0, len, Protection::READ, Sharing::Shared).unwrap();
    let memory = Mapping::anonymous(len, RW).unwrap();

    for pattern in [
        AccessPattern::Sequential,
        AccessPattern::Random,
        AccessPattern::Normal,
    ] {
        unix::advise_access(view.as_ptr(), len, pattern).unwrap();
        // A hint changes nothing that can be seen.
        assert_eq!(bytes(view.as_ptr(), len), content);
        unix::advise_access(memory.as_ptr(), len, pattern).unwrap();
        unix::advise_access(memory.as_ptr().wrapping_add(page), 1, pattern).unwrap();

        let err = unix::advise_access(view.as_ptr(), 0, pattern).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = unix::advise_access(view.as_ptr().wrapping_add(1), page, pattern).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
    }
}

#[cfg(any(target_os = "linux", target_os = "fullrust"))]
#[test]
fn linux_map_options() {
    use oscall::mem::linux::MapOptionsExt;

    let page = mem::page_size();
    let len = 4 * page;
    let options = MapOptions::new();
    for set in [
        options.populate(true),
        options.huge_tlb(true),
        options.no_reserve(true),
    ] {
        assert_ne!(set, options);
        let cleared = set.populate(false).huge_tlb(false).no_reserve(false);
        assert_eq!(cleared, options);
    }

    // Memory that is there before it is touched, and memory that is not
    // accounted for: both are memory like any other.
    for options in [
        options.populate(true),
        options.no_reserve(true),
        options.populate(true).no_reserve(true),
    ] {
        let map = Mapping::anonymous_with(len, &options).unwrap();
        assert!(bytes(map.as_ptr(), len).iter().all(|&b| b == 0));
        // SAFETY: inside the writable mapping.
        unsafe { map.as_ptr().add(len - 1).write(1) };
        let reserved = Mapping::reserve_with(len, &options).unwrap();
        // SAFETY: a page of the reservation, that only this test knows.
        unsafe {
            mem::commit(reserved.as_ptr(), page, RW).unwrap();
            reserved.as_ptr().write(1);
        }
    }
    // A file, read in advance; and placed, like any mapping.
    let dir = common::tmp_dir("mem-linux-map-options");
    let content = pattern(len);
    let file = file_with(&dir.join("file"), &content);
    let handle = common::handle_of(&file);
    let populated = options.populate(true).protection(Protection::READ);
    let map = Mapping::file_with(&handle, 0, len, Sharing::Shared, &populated).unwrap();
    assert_eq!(bytes(map.as_ptr(), len), content);
    let err = populated.at(map.as_ptr()).map_anonymous(len).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::AlreadyExists);

    // Huge pages are there when the administrator set some aside, of a
    // size that depends on the machine: 2 MiB on most. A system without
    // any free has no memory for the mapping, one whose huge pages are of
    // another size refuses the length, and a kernel built without them
    // does not know the request.
    let huge = 2 << 20;
    match options.huge_tlb(true).map_anonymous(huge) {
        Ok(ptr) => {
            assert!(ptr.addr().is_multiple_of(huge));
            // SAFETY: the mapping is `huge` writable bytes, unmapped whole.
            unsafe {
                ptr.add(huge - 1).write(1);
                assert_eq!(ptr.add(huge - 1).read(), 1);
                mem::unmap(ptr, huge).unwrap();
            }
        }
        Err(err) => assert!(
            matches!(
                err.kind(),
                ErrorKind::OutOfMemory | ErrorKind::InvalidInput | ErrorKind::Unsupported
            ),
            "{err:?}"
        ),
    }
}

#[cfg(any(target_os = "linux", target_os = "fullrust"))]
#[test]
fn linux_advice() {
    use oscall::mem::linux::{self, Advice};

    let page = mem::page_size();
    let len = 4 * page;
    let map = Mapping::anonymous(len, RW).unwrap();
    let ptr = map.as_ptr();
    let content = pattern(len);
    // SAFETY: the mapping is `len` writable bytes that only this test knows.
    unsafe { ptr.copy_from_nonoverlapping(content.as_ptr(), len) };

    for advice in [
        Advice::DontDump,
        Advice::DoDump,
        Advice::DontFork,
        Advice::DoFork,
    ] {
        linux::advise(ptr, len, advice).unwrap();
        linux::advise(ptr.wrapping_add(page), 1, advice).unwrap();
        assert_eq!(bytes(ptr, len), content);
    }
    // Populating came with Linux 5.14: before, the kernel does not know the
    // advice. The contents are the same either way.
    for advice in [Advice::PopulateRead, Advice::PopulateWrite] {
        match linux::advise(ptr, len, advice) {
            Ok(()) => {}
            Err(err) => assert_eq!(err.kind(), ErrorKind::InvalidInput),
        }
        assert_eq!(bytes(ptr, len), content);
    }
    // Fresh memory, populated for writing, is zeroes that can be written.
    let fresh = Mapping::anonymous(len, RW).unwrap();
    let _ = linux::advise(fresh.as_ptr(), len, Advice::PopulateWrite);
    assert!(bytes(fresh.as_ptr(), len).iter().all(|&b| b == 0));

    for advice in [Advice::DontDump, Advice::PopulateRead] {
        let err = linux::advise(ptr, 0, advice).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = linux::advise(ptr.wrapping_add(1), page, advice).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
    }
}

#[cfg(any(target_os = "linux", target_os = "fullrust"))]
#[test]
fn linux_locking() {
    use oscall::mem::linux::{self, LockAll};

    let page = mem::page_size();
    // One page: within the little every process is allowed to lock.
    let map = Mapping::anonymous(2 * page, RW).unwrap();
    let ptr = map.as_ptr();
    match linux::lock_on_fault(ptr, page) {
        Ok(()) => {
            // SAFETY: inside the writable mapping.
            unsafe {
                ptr.write(42);
                assert_eq!(ptr.read(), 42);
            }
            mem::unlock(ptr, page).unwrap();
        }
        // Every kernel supported has the call, but not every emulator
        // passes it on: the qemu-user that runs the tests of the fullrust
        // image for other architectures answers that there is no `mlock2`.
        Err(err) => assert_eq!(err.kind(), ErrorKind::Unsupported),
    }
    let err = linux::lock_on_fault(ptr, 0).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    let err = linux::lock_on_fault(ptr.wrapping_add(1), page).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);

    assert_eq!(
        LockAll::CURRENT | LockAll::FUTURE | LockAll::ON_FAULT,
        LockAll::CURRENT | LockAll::FUTURE | LockAll::ON_FAULT | LockAll::CURRENT
    );
    // Neither mappings that are nor mappings to come: nothing to lock.
    for what in [LockAll::empty(), LockAll::ON_FAULT] {
        let err = linux::lock_all(what).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
    }

    // All that is mapped now, page by page as it is used. The tests that
    // cannot do with locked memory wait; mappings to come are left alone,
    // so that those of the other tests cannot fail for it.
    let _locked = ALL_LOCKED.write().unwrap();
    match linux::lock_all(LockAll::CURRENT | LockAll::ON_FAULT) {
        Ok(()) => {
            // SAFETY: inside the writable mapping.
            unsafe {
                ptr.add(page).write(1);
                assert_eq!(ptr.add(page).read(), 1);
            }
        }
        // More than the process may lock (`RLIMIT_MEMLOCK`), or nothing at
        // all if the limit is zero.
        Err(err) => assert!(
            matches!(
                err.kind(),
                ErrorKind::OutOfMemory | ErrorKind::PermissionDenied
            ),
            "{err:?}"
        ),
    }
    // Unlocking is always possible, locked or not.
    linux::unlock_all().unwrap();
    linux::unlock_all().unwrap();
}

#[cfg(any(target_os = "linux", target_os = "fullrust"))]
#[test]
fn linux_remap() {
    let page = mem::page_size();
    let content = pattern(2 * page);
    let ptr = mem::map_anonymous(2 * page, RW).unwrap();
    // SAFETY: the mapping is only this test's, and is used at the address
    // and with the length `remap` last gave it.
    unsafe {
        ptr.copy_from_nonoverlapping(content.as_ptr(), 2 * page);

        // Growing, wherever that has to be: the contents follow.
        let grown = mem::linux::remap(ptr, 2 * page, 64 * page, true).unwrap();
        assert!(grown.addr().is_multiple_of(page));
        assert_eq!(bytes(grown, 2 * page), content);
        assert!(
            bytes(grown.add(2 * page), 62 * page)
                .iter()
                .all(|&b| b == 0)
        );
        grown.add(64 * page - 1).write(1);

        // Shrinking happens in place.
        let shrunk = mem::linux::remap(grown, 64 * page, page, false).unwrap();
        assert_eq!(shrunk, grown);
        assert_eq!(bytes(shrunk, page), content[..page]);

        let err = mem::linux::remap(shrunk, page, 0, true).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = mem::linux::remap(shrunk, 0, page, true).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        let err = mem::linux::remap(shrunk.add(1), page, page, true).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);

        // Growing in place is impossible when something is in the way:
        // here, the second page of the mapping itself.
        let pair = mem::map_anonymous(2 * page, RW).unwrap();
        let err = mem::linux::remap(pair, page, 4 * page, false).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::OutOfMemory);
        mem::unmap(pair, 2 * page).unwrap();

        mem::unmap(shrunk, page).unwrap();
    }
}

#[cfg(any(target_os = "linux", target_os = "fullrust"))]
#[test]
fn linux_huge_pages() {
    let page = mem::page_size();
    let len = 4 << 20;
    let map = Mapping::anonymous(len, RW).unwrap();
    for enable in [true, false] {
        match mem::linux::huge_pages(map.as_ptr(), len, enable) {
            Ok(()) => {}
            // A kernel built without transparent huge pages.
            Err(err) => assert_eq!(err.kind(), ErrorKind::InvalidInput),
        }
        let err = mem::linux::huge_pages(map.as_ptr(), 0, enable).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
    }
    // The memory works the same either way.
    // SAFETY: inside the writable mapping.
    unsafe {
        map.as_ptr().add(len - page).write(5);
        assert_eq!(map.as_ptr().add(len - page).read(), 5);
    }
}