oscall 0.1.0

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
//! Memory: pages, mappings and their protection.
//!
//! The module works on *mappings*: ranges of pages of the address space,
//! obtained from the system and given back to it whole.
//!
//! - [`map_anonymous`] maps zero-filled memory, [`map_file`] the contents of
//!   a file (shared with the file, or copy-on-write), and [`reserve`] address
//!   space with nothing behind it, of which [`commit`] and [`decommit`] then
//!   turn ranges into memory and back: what allocators and JIT compilers are
//!   built from.
//! - [`protect`], [`advise`], [`lock`], [`unlock`] and [`flush`] act on any
//!   range of pages inside one mapping.
//! - [`create_shared`] makes memory with a handle, that can be mapped more
//!   than once, and by more than one process.
//! - [`unmap`] releases a mapping.
//! - [`MapOptions`] makes the same mappings with a say in where they go:
//!   [at an address](MapOptions::at) that must be free, or
//!   [inside a placeholder](MapOptions::in_placeholder), a reservation made
//!   by [`reserve_placeholder`] to be filled with mappings side by side.
//!
//! These functions take and return raw pointers. [`Mapping`] owns a mapping
//! and unmaps it when dropped.
//!
//! # Ranges
//!
//! A range is a pointer and a length in bytes. Wherever a function takes a
//! range inside a mapping, the pointer must be a multiple of [`page_size`]
//! and the length is rounded up to the next page; a null length, or a
//! pointer that is not on a page boundary, is refused with
//! [`ErrorKind::InvalidInput`] before the system is asked anything. A range
//! must lie within a single mapping: Windows cannot operate across two.
//!
//! # Executable memory
//!
//! A program that generates code at run time maps memory, writes the code
//! and runs it. Memory that is writable and executable at once is refused
//! by some systems (macOS on Apple silicon, hardened Linux), and processors
//! other than x86 keep instructions in a cache that knows nothing of what
//! was just written. What works everywhere is:
//!
//! 1. map the memory with [`Protection::READ_WRITE`] ([`map_anonymous`], or
//!    [`commit`] in a reservation), and write the code;
//! 2. [`protect`] it as [`Protection::READ_EXECUTE`];
//! 3. [`flush_instruction_cache`] over the code;
//! 4. call it.
//!
//! To change the code, make the pages writable again and go through the
//! same steps; nothing may be executing them meanwhile.
//!
//! ```
//! use oscall::mem::{self, Protection};
//!
//! # fn main() -> oscall::Result<()> {
//! # if cfg!(target_family = "wasm") { return Ok(()); }
//! // A function that returns 42, for the processor at hand.
//! let code: &[u8] = if cfg!(any(target_arch = "x86", target_arch = "x86_64")) {
//!     &[0xB8, 42, 0, 0, 0, 0xC3] // mov eax, 42; ret
//! } else if cfg!(target_arch = "aarch64") {
//!     &[0x40, 0x05, 0x80, 0x52, 0xC0, 0x03, 0x5F, 0xD6] // mov w0, #42; ret
//! } else if cfg!(target_arch = "arm") {
//!     &[0x2A, 0x00, 0xA0, 0xE3, 0x1E, 0xFF, 0x2F, 0xE1] // mov r0, #42; bx lr
//! } else if cfg!(any(target_arch = "riscv32", target_arch = "riscv64")) {
//!     &[0x13, 0x05, 0xA0, 0x02, 0x67, 0x80, 0x00, 0x00] // li a0, 42; ret
//! } else {
//!     return Ok(());
//! };
//!
//! let len = mem::page_size();
//! let ptr = mem::map_anonymous(len, Protection::READ_WRITE)?;
//! // SAFETY: the mapping is this function's own: the code fits in it, no
//! // reference to it exists when its protection changes, and once
//! // executable and flushed it holds a function of the type it is called
//! // as.
//! let answer = unsafe {
//!     ptr.copy_from_nonoverlapping(code.as_ptr(), code.len());
//!     mem::protect(ptr, len, Protection::READ_EXECUTE)?;
//!     mem::flush_instruction_cache(ptr, code.len())?;
//!     let function: extern "C" fn() -> i32 = core::mem::transmute(ptr);
//!     let answer = function();
//!     mem::unmap(ptr, len)?;
//!     answer
//! };
//! assert_eq!(answer, 42);
//! # Ok(())
//! # }
//! ```
//!
//! On macOS a program built with the *hardened runtime* (which notarisation
//! requires) may not make anonymous memory executable this way: it needs an
//! entitlement and the `MAP_JIT` mappings of `oscall::mem::macos`.
//!
//! # WebAssembly
//!
//! WebAssembly has a single linear memory and no control over its pages:
//! [`page_size`] and [`allocation_granularity`] work (64 KiB), and every
//! other function fails with [`ErrorKind::Unsupported`].
//!
//! # Example
//!
//! ```
//! use oscall::mem::{self, Mapping, Protection};
//!
//! # fn main() -> oscall::Result<()> {
//! # if cfg!(target_family = "wasm") { return Ok(()); }
//! let mut map = Mapping::anonymous(mem::page_size(), Protection::READ_WRITE)?;
//! // SAFETY: the mapping is readable, writable and not shared.
//! let bytes = unsafe { map.as_mut_slice() };
//! assert_eq!(bytes[0], 0);
//! bytes[0] = 1;
//! # Ok(())
//! # }
//! ```

use core::fmt;
use core::mem::ManuallyDrop;
use core::ptr::NonNull;

use crate::macros::flags;
use crate::{AsHandle, ErrorKind, OwnedHandle, Result, sys};

/// The size in bytes of a page of memory, the unit of protection and of
/// every range in this module. It is a power of two.
///
/// It is a property of the running system, not of the target: 4 KiB on x86,
/// but 4, 16 or 64 KiB on aarch64 depending on the kernel (16 KiB on Apple
/// silicon). On WebAssembly it is the 64 KiB page of linear memory.
///
/// On Linux it is read once from the auxiliary vector
/// (`/proc/self/auxv`), or, where `/proc` is not available, found by
/// probing how the kernel aligns a mapping; on macOS it is `getpagesize`,
/// on Windows `GetSystemInfo`.
#[inline]
pub fn page_size() -> usize {
    sys::mem::page_size()
}

/// The alignment of the addresses at which mappings are placed, and of the
/// offsets at which a file can be mapped: [`map_file`] takes offsets that
/// are multiples of it.
///
/// It is 64 KiB on Windows and on WebAssembly, and [`page_size`] everywhere
/// else. It is a power of two, and a multiple of the page size.
#[inline]
pub fn allocation_granularity() -> usize {
    sys::mem::allocation_granularity()
}

flags! {
    /// How the pages of a mapping may be accessed. No flag at all
    /// ([`Protection::NONE`]) makes them inaccessible: any access faults.
    ///
    /// Hardware cannot express every combination, and the system grants at
    /// least what is asked: write access comes with read access nearly
    /// everywhere, and execute access often does too.
    ///
    /// Asking for [`WRITE`](Self::WRITE) and [`EXECUTE`](Self::EXECUTE)
    /// together can be refused with [`ErrorKind::PermissionDenied`]: macOS
    /// on Apple silicon does not allow it, nor do hardened Linux systems.
    /// Code generators that must run everywhere write the code with
    /// [`READ_WRITE`](Self::READ_WRITE), then [`protect`] it as
    /// [`READ_EXECUTE`](Self::READ_EXECUTE).
    pub struct Protection: u32 {
        /// No access.
        const NONE = 0;
        /// The pages can be read.
        const READ = 1;
        /// The pages can be written.
        const WRITE = 2;
        /// The pages can be executed.
        const EXECUTE = 4;
        /// [`READ`](Self::READ) and [`WRITE`](Self::WRITE).
        const READ_WRITE = 3;
        /// [`READ`](Self::READ) and [`EXECUTE`](Self::EXECUTE).
        const READ_EXECUTE = 5;
    }
}

/// What becomes of the changes made to a file mapping.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Sharing {
    /// Changes are made to the file itself: they are visible to every other
    /// mapping of the file and to those who read it, and reach the storage
    /// eventually (see [`flush`]). A writable shared mapping needs a file
    /// opened for reading and writing.
    Shared,
    /// Copy-on-write: a page that is written is first copied, and the copy
    /// belongs to this mapping alone. The file is never modified, and only
    /// needs to be opened for reading. Whether changes made to the file by
    /// others after the mapping was made show in the pages not yet written
    /// is unspecified.
    Private,
}

/// What a program expects of a range of memory: see [`advise`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Advice {
    /// The range is about to be used: the system may read it ahead from the
    /// file or from swap (`MADV_WILLNEED`, `PrefetchVirtualMemory`).
    WillNeed,
    /// The contents of the range are no longer needed, though the range
    /// will be used again: the system may take the memory back whenever it
    /// is short of it, without writing it to swap (`MADV_FREE`,
    /// `MEM_RESET`). The range stays accessible, with **unspecified
    /// contents**: each page holds either what it held or zeroes, until it
    /// is next written. Only for anonymous memory ([`map_anonymous`],
    /// [`commit`]).
    ///
    /// To give the memory back at once and be sure to read zeroes
    /// afterwards, use [`decommit`] then [`commit`].
    Discard,
}

/// Refuses the ranges no system call would take the same way everywhere.
fn check_range(ptr: *const u8, len: usize) -> Result<()> {
    if len == 0 || !ptr.addr().is_multiple_of(page_size()) {
        return Err(ErrorKind::InvalidInput.into());
    }
    Ok(())
}

/// Where a mapping goes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Place {
    /// Wherever the system likes.
    Anywhere,
    /// At this address, which must be free.
    At(usize),
    /// At this address, inside a placeholder.
    In(usize),
}

/// How a mapping is made, and where: what [`map_anonymous`], [`map_file`],
/// [`reserve`] and [`reserve_placeholder`] do, with a choice of address.
///
/// ```
/// use oscall::mem::{self, MapOptions, Protection};
///
/// # fn main() -> oscall::Result<()> {
/// # if cfg!(target_family = "wasm") { return Ok(()); }
/// let len = mem::allocation_granularity();
/// let ptr = MapOptions::new()
///     .protection(Protection::READ_WRITE)
///     .map_anonymous(len)?;
/// // The address is taken: a second mapping there is refused.
/// let err = MapOptions::new().at(ptr).map_anonymous(len).unwrap_err();
/// assert_eq!(err.kind(), oscall::ErrorKind::AlreadyExists);
/// // SAFETY: a whole mapping made above, not used afterwards.
/// unsafe { mem::unmap(ptr, len)? };
/// # Ok(())
/// # }
/// ```
///
/// # Hints
///
/// There is no way to ask for a mapping *near* an address, to be placed
/// elsewhere if that address is taken: Linux and macOS take such hints,
/// Windows has none. What does the same everywhere is to try
/// [`at`](Self::at) an address, then anywhere if that fails.
///
/// # Replacing a mapping
///
/// Nor is there a way to map over whatever an address holds (`MAP_FIXED`),
/// which Windows cannot do. Mapping
/// [inside a placeholder](Self::in_placeholder) is the form of it every
/// system has.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MapOptions {
    pub(crate) protection: Protection,
    pub(crate) place: Place,
    /// Flags private to the backend, set by the extension traits.
    #[allow(dead_code)]
    pub(crate) extra: u32,
}

impl Default for MapOptions {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl MapOptions {
    /// A readable and writable mapping, wherever the system likes.
    #[inline]
    pub const fn new() -> Self {
        Self {
            protection: Protection::READ_WRITE,
            place: Place::Anywhere,
            extra: 0,
        }
    }

    /// Sets how the pages may be accessed ([`Protection::READ_WRITE`]
    /// unless set). A reservation has no use for it.
    #[inline]
    pub const fn protection(mut self, protection: Protection) -> Self {
        self.protection = protection;
        self
    }

    /// Asks for the mapping to start at `addr`, **exactly there or not at
    /// all**: when any page of the range is already mapped or reserved, the
    /// call fails with [`ErrorKind::AlreadyExists`] and what is there is
    /// left alone. Nothing is ever replaced, which is why this is safe.
    ///
    /// `addr` must not be null and must be a multiple of
    /// [`allocation_granularity`], and the range must not wrap around the
    /// address space, or the call fails with [`ErrorKind::InvalidInput`]. An
    /// address the system keeps for itself fails with the system's own
    /// error.
    ///
    /// Whether an address is free is only known by trying, or by owning it:
    /// to place memory at chosen addresses of a range of one's own, make
    /// the range with [`reserve`] and [`commit`] its pages, or make it with
    /// [`reserve_placeholder`] and map
    /// [inside it](Self::in_placeholder).
    ///
    /// This is `MAP_FIXED_NOREPLACE` on Linux, and the address given to
    /// `VirtualAlloc` or `MapViewOfFileEx` on Windows. macOS has no such
    /// request, only a hint, which it follows when the range is free: a
    /// mapping that the system placed elsewhere is unmapped again, and the
    /// call fails as above. Linux does the same should the kernel take the
    /// address for a hint.
    #[inline]
    pub fn at(mut self, addr: *mut u8) -> Self {
        self.place = Place::At(addr.addr());
        self
    }

    /// Asks for the mapping to take the place of the range that starts at
    /// `ptr` inside a placeholder: a reservation made by
    /// [`reserve_placeholder`].
    ///
    /// This is how several mappings are laid side by side at addresses
    /// chosen in advance, with no moment at which something else could
    /// take the address: a file loaded in segments, or a ring buffer whose
    /// memory ([`create_shared`]) is mapped twice in a row.
    ///
    /// `ptr` must be a multiple of [`page_size`], or the call fails with
    /// [`ErrorKind::InvalidInput`]; the length is rounded up to the next
    /// page, as everywhere. For a file, the offset must still be a multiple
    /// of [`allocation_granularity`].
    ///
    /// The mapping made is cut out of the placeholder, which leaves **up to
    /// three mappings** where there was one: what remains of the placeholder
    /// before the range, the new mapping, and what remains after it. Each is
    /// a mapping of its own from then on, to be released by itself with
    /// [`unmap`] and its own address and length; what remains of the
    /// placeholder can be mapped into in turn. A mapping cannot be turned
    /// back into a placeholder. When the call fails, the placeholder is as
    /// it was.
    ///
    /// On Linux and macOS this is `MAP_FIXED`; on Windows the placeholder
    /// is split (`VirtualFree` with `MEM_PRESERVE_PLACEHOLDER`) and the
    /// part replaced (`MapViewOfFile3` or `VirtualAlloc2` with
    /// `MEM_REPLACE_PLACEHOLDER`).
    ///
    /// # Safety
    ///
    /// The whole range, from `ptr` to the end of the last page of the
    /// mapping that is then made, must lie within one placeholder (or what
    /// remains of one) that the caller owns, and nothing else may map into
    /// that placeholder or release it meanwhile. Linux and macOS replace
    /// whatever the range holds, without a word: memory that the rest of
    /// the program uses, if the range is wrong.
    #[inline]
    pub unsafe fn in_placeholder(mut self, ptr: *mut u8) -> Self {
        self.place = Place::In(ptr.addr());
        self
    }

    /// Sets or clears a flag of the backend's.
    #[allow(dead_code)]
    #[inline]
    pub(crate) fn with_extra(mut self, flag: u32, set: bool) -> Self {
        if set {
            self.extra |= flag;
        } else {
            self.extra &= !flag;
        }
        self
    }

    /// Refuses the placements no system would take the same way.
    fn check(&self, len: usize) -> Result<()> {
        let (addr, unit) = match self.place {
            Place::Anywhere => return Ok(()),
            Place::At(addr) => (addr, allocation_granularity()),
            Place::In(addr) => (addr, page_size()),
        };
        let fits = len
            .checked_next_multiple_of(page_size())
            .is_some_and(|len| addr.checked_add(len).is_some());
        if addr == 0 || !addr.is_multiple_of(unit) || !fits {
            return Err(ErrorKind::InvalidInput.into());
        }
        Ok(())
    }

    /// Maps `len` bytes of new, zero-filled memory that belongs to this
    /// process alone, and returns its address: see [`map_anonymous`].
    pub fn map_anonymous(&self, len: usize) -> Result<*mut u8> {
        if len == 0 {
            return Err(ErrorKind::InvalidInput.into());
        }
        self.check(len)?;
        sys::mem::map_anonymous(len, self)
    }

    /// Maps `len` bytes of `file`, starting at `offset`, and returns the
    /// address of the mapping: see [`map_file`].
    pub fn map_file<H: AsHandle + ?Sized>(
        &self,
        file: &H,
        offset: u64,
        len: usize,
        sharing: Sharing,
    ) -> Result<*mut u8> {
        if len == 0 || !offset.is_multiple_of(allocation_granularity() as u64) {
            return Err(ErrorKind::InvalidInput.into());
        }
        self.check(len)?;
        sys::mem::map_file(file.as_handle(), offset, len, sharing, self)
    }

    /// Reserves `len` bytes of address space, with no memory behind it, and
    /// returns its address: see [`reserve`]. The protection is not used.
    ///
    /// A reservation cannot be made
    /// [inside a placeholder](Self::in_placeholder): asking for it fails
    /// with [`ErrorKind::InvalidInput`].
    pub fn reserve(&self, len: usize) -> Result<*mut u8> {
        if len == 0 || matches!(self.place, Place::In(_)) {
            return Err(ErrorKind::InvalidInput.into());
        }
        self.check(len)?;
        sys::mem::reserve(len, self, false)
    }

    /// Reserves `len` bytes of address space as a placeholder, and returns
    /// its address: see [`reserve_placeholder`]. The protection is not
    /// used.
    ///
    /// A placeholder cannot be made
    /// [inside another](Self::in_placeholder): asking for it fails with
    /// [`ErrorKind::InvalidInput`].
    pub fn reserve_placeholder(&self, len: usize) -> Result<*mut u8> {
        if len == 0 || matches!(self.place, Place::In(_)) {
            return Err(ErrorKind::InvalidInput.into());
        }
        self.check(len)?;
        sys::mem::reserve(len, self, true)
    }
}

/// Maps `len` bytes of new, zero-filled memory that belongs to this process
/// alone, and returns its address: never null, and a multiple of
/// [`allocation_granularity`].
///
/// `len` is rounded up to the next page; a null `len` fails with
/// [`ErrorKind::InvalidInput`]. The memory is released with [`unmap`].
///
/// This is `mmap` with `MAP_PRIVATE | MAP_ANONYMOUS`, and `VirtualAlloc`
/// with `MEM_RESERVE | MEM_COMMIT` on Windows.
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
pub fn map_anonymous(len: usize, protection: Protection) -> Result<*mut u8> {
    MapOptions::new().protection(protection).map_anonymous(len)
}

/// Maps `len` bytes of `file`, starting at `offset`, and returns the address
/// of the mapping: never null, and a multiple of [`allocation_granularity`].
///
/// `offset` must be a multiple of [`allocation_granularity`] and `len` must
/// not be null, or the call fails with [`ErrorKind::InvalidInput`]. The
/// mapping stays valid after `file` is closed, and is released with
/// [`unmap`].
///
/// A [`Sharing::Shared`] mapping can only be given the access `file` was
/// opened with: asking for [`Protection::WRITE`] on a file opened for
/// reading only fails with [`ErrorKind::PermissionDenied`].
///
/// `file` can also be memory made by [`create_shared`], which is mapped the
/// same way.
///
/// This is `mmap` on Linux and macOS, `CreateFileMappingW` and
/// `MapViewOfFile` on Windows.
///
/// # What is not the same everywhere
///
/// - **The range must lie within the file.** Linux and macOS let a mapping
///   extend past the end of the file, and deliver a fatal signal (`SIGBUS`)
///   when a page wholly beyond it is touched; Windows refuses to make the
///   mapping, and cannot map an empty file at all. The bytes between the end
///   of the file and the end of its last page read as zero, and writing them
///   does not grow the file.
/// - **Truncating a mapped file** makes the pages past its new end fault on
///   Linux and macOS; on Windows the truncation itself fails while a mapping
///   exists.
/// - **[`Protection::EXECUTE`]** needs, on Windows, a file opened with the
///   right to execute it (`FILE_EXECUTE`), which is not part of the usual
///   read access.
/// - **Raising the protection later** with [`protect`] is only portable up
///   to the protection the mapping was made with (Windows fixes the maximum
///   then; Linux and macOS allow whatever the file's access allows).
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
pub fn map_file<H: AsHandle + ?Sized>(
    file: &H,
    offset: u64,
    len: usize,
    protection: Protection,
    sharing: Sharing,
) -> Result<*mut u8> {
    MapOptions::new()
        .protection(protection)
        .map_file(file, offset, len, sharing)
}

/// Reserves `len` bytes of address space, with no memory behind it, and
/// returns its address: never null, and a multiple of
/// [`allocation_granularity`].
///
/// Nothing in the range can be accessed until [`commit`] has made it memory;
/// reserving costs address space only, so a reservation can be far larger
/// than the memory of the machine. `len` is rounded up to the next page; a
/// null `len` fails with [`ErrorKind::InvalidInput`]. The reservation, with
/// whatever was committed in it, is released with [`unmap`].
///
/// This is `VirtualAlloc` with `MEM_RESERVE` on Windows, and an inaccessible
/// mapping (`PROT_NONE`, `MAP_NORESERVE`) on Linux and macOS.
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
pub fn reserve(len: usize) -> Result<*mut u8> {
    MapOptions::new().reserve(len)
}

/// Creates `len` bytes of zero-filled memory that belongs to no mapping yet,
/// and returns a handle to it: memory to be shared.
///
/// The memory is mapped with [`map_file`] and [`Sharing::Shared`], as a
/// file would be, any number of times: every mapping is the same memory,
/// whatever is written through one is read through the others. It lives as
/// long as a handle to it or a mapping of it does, and has no name: another
/// process gets at it by being given the handle (inherited by a child, or
/// sent over a socket), and maps it likewise.
///
/// `len` is rounded up to the next page and cannot be changed afterwards; a
/// null `len` fails with [`ErrorKind::InvalidInput`].
///
/// # The handle
///
/// The handle is for [`map_file`] and [`MapOptions::map_file`], for
/// [`io::duplicate`](crate::io::duplicate) and for passing to another
/// process, and nothing else: it is a file descriptor on Linux
/// (`memfd_create`) and on macOS (`shm_open`, of a name that is removed at
/// once), but a section object on Windows (`CreateFileMappingW` of the
/// paging file), which is not a file and cannot be read, written or
/// resized. [`flush`] has no meaning for it.
///
/// # What is not the same everywhere
///
/// - **[`Sharing::Private`]** mappings of it (a copy-on-write view of the
///   memory) are refused by macOS with [`ErrorKind::InvalidInput`].
/// - **[`Protection::EXECUTE`]** is refused by Windows with
///   [`ErrorKind::PermissionDenied`], and elsewhere depends on the
///   configuration of the system.
/// - **The range mapped must lie within the memory**, as within a file: see
///   [`map_file`].
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
pub fn create_shared(len: usize) -> Result<OwnedHandle> {
    if len == 0 {
        return Err(ErrorKind::InvalidInput.into());
    }
    sys::mem::create_shared(len)
}

/// Reserves `len` bytes of address space to be filled with mappings, and
/// returns its address: never null, and a multiple of
/// [`allocation_granularity`].
///
/// A placeholder is address space set aside, like a reservation, but for
/// another use: where the pages of a reservation are [`commit`]ted, ranges
/// of a placeholder are replaced by whole mappings, of files or of
/// anonymous memory, made [`in_placeholder`](MapOptions::in_placeholder).
/// The two do not mix: nothing can be committed in a placeholder, and
/// nothing mapped in a reservation.
///
/// `len` is rounded up to the next page; a null `len` fails with
/// [`ErrorKind::InvalidInput`]. A placeholder, or what remains of one, is
/// released with [`unmap`].
///
/// This is `VirtualAlloc2` with `MEM_RESERVE_PLACEHOLDER` on Windows, which
/// has it since Windows 10 version 1803: before that, the call fails with
/// [`ErrorKind::Unsupported`]. On Linux and macOS it is the inaccessible
/// mapping [`reserve`] makes.
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
pub fn reserve_placeholder(len: usize) -> Result<*mut u8> {
    MapOptions::new().reserve_placeholder(len)
}

/// Releases a whole mapping: one made by [`map_anonymous`], [`map_file`],
/// [`reserve`] or [`reserve_placeholder`], through [`MapOptions`] or not.
///
/// `ptr` and `len` must be the address the mapping was made at and the
/// length it was made with: a mapping cannot be released in parts (Windows
/// has no such operation). A null `len` fails with
/// [`ErrorKind::InvalidInput`], as does, on Windows, a `ptr` that is not the
/// start of a mapping.
///
/// This is `munmap`, and on Windows `UnmapViewOfFile` or `VirtualFree` with
/// `MEM_RELEASE`, according to what `VirtualQuery` says the mapping is.
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
///
/// # Safety
///
/// `ptr` and `len` must describe a whole mapping made by this module, and
/// nothing may use the range afterwards: the system is free to place
/// something else there.
pub unsafe fn unmap(ptr: *mut u8, len: usize) -> Result<()> {
    check_range(ptr, len)?;
    // SAFETY: the caller's contract.
    unsafe { sys::mem::unmap(ptr, len) }
}

/// Changes the protection of the pages of a range (`mprotect`,
/// `VirtualProtect`).
///
/// The range must be memory: in a reservation, the pages must have been
/// committed ([`commit`] is also how their protection is first set). For a
/// file mapping, see the limits in [`map_file`].
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
///
/// # Safety
///
/// The range must lie within a mapping this process owns, and taking an
/// access away must not break the code that still uses the pages: no
/// reference may exist to memory that becomes inaccessible, no `&mut` to
/// memory that becomes read-only.
pub unsafe fn protect(ptr: *mut u8, len: usize, protection: Protection) -> Result<()> {
    check_range(ptr, len)?;
    // SAFETY: the caller's contract.
    unsafe { sys::mem::protect(ptr, len, protection) }
}

/// Turns a range of a reservation into memory, accessible as `protection`
/// says.
///
/// The pages that were not committed yet read as zero; those that already
/// were keep their contents and take the new protection. The system
/// accounts for the memory from now on, so this can fail with
/// [`ErrorKind::OutOfMemory`] where reserving did not.
///
/// This is `VirtualAlloc` with `MEM_COMMIT` on Windows and `mprotect` on
/// Linux and macOS.
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
///
/// # Safety
///
/// The range must lie within a mapping made by [`reserve`] or
/// [`map_anonymous`], and the change of protection must respect the rules of
/// [`protect`].
pub unsafe fn commit(ptr: *mut u8, len: usize, protection: Protection) -> Result<()> {
    check_range(ptr, len)?;
    // SAFETY: the caller's contract.
    unsafe { sys::mem::commit(ptr, len, protection) }
}

/// Gives the memory of a range back to the system, keeping the address
/// space: the opposite of [`commit`].
///
/// The contents are lost and the pages become inaccessible, as they were
/// when reserved; committing them again gives zero-filled memory. Pages of
/// the range that are not committed are left as they are.
///
/// This is `VirtualFree` with `MEM_DECOMMIT` on Windows; on Linux and macOS
/// a fresh inaccessible mapping replaces the range (`mmap` with
/// `MAP_FIXED`), which frees the memory at once.
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
///
/// # Safety
///
/// The range must lie within a mapping made by [`reserve`] or
/// [`map_anonymous`], and nothing may use its contents afterwards.
pub unsafe fn decommit(ptr: *mut u8, len: usize) -> Result<()> {
    check_range(ptr, len)?;
    // SAFETY: the caller's contract.
    unsafe { sys::mem::decommit(ptr, len) }
}

/// Tells the system what to expect of a range of memory, so that it can
/// manage it better (`madvise`; on Windows `PrefetchVirtualMemory` and
/// `VirtualAlloc` with `MEM_RESET`).
///
/// Only the hints that mean the same on every system are offered.
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
///
/// # Safety
///
/// The range must lie within a mapping this process owns and, for
/// [`Advice::Discard`], nothing may rely on its contents afterwards: they
/// are unspecified, and can change (to zeroes) at any time until the pages
/// are written again.
pub unsafe fn advise(ptr: *mut u8, len: usize, advice: Advice) -> Result<()> {
    check_range(ptr, len)?;
    // SAFETY: the caller's contract.
    unsafe { sys::mem::advise(ptr, len, advice) }
}

/// Writes the modified pages of a range of a [`Sharing::Shared`] mapping of
/// `file` to the storage, and returns once they are there.
///
/// Without it, the changes are written at a time of the system's choosing;
/// they are never lost when the mapping or the file is closed, only when the
/// system crashes.
///
/// This is `msync` with `MS_SYNC` on Linux and macOS, which do not need
/// `file`. On Windows it is `FlushViewOfFile`, which only hands the pages to
/// the file system, followed by `FlushFileBuffers` on `file`, which must
/// therefore be the mapped file, open for writing; all of the file's pending
/// writes are flushed with it. On macOS the data reaches the drive, but as
/// with every synchronisation there the drive may still hold it in its own
/// cache.
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
pub fn flush<H: AsHandle + ?Sized>(ptr: *const u8, len: usize, file: &H) -> Result<()> {
    check_range(ptr, len)?;
    sys::mem::flush(ptr, len, file.as_handle())
}

/// Locks the pages of a range in physical memory: they are brought in, and
/// are not written to swap until unlocked or unmapped (`mlock`,
/// `VirtualLock`).
///
/// The range must be accessible memory: whether locking reserved or
/// inaccessible pages fails depends on the system (macOS accepts it). Locks
/// do not nest: one [`unlock`]
/// undoes any number of locks. The amount a process may lock is small by
/// default (`RLIMIT_MEMLOCK`; on Windows, the minimum working set), and
/// exceeding it fails with [`ErrorKind::OutOfMemory`] or
/// [`ErrorKind::WouldBlock`] according to the system.
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
pub fn lock(ptr: *const u8, len: usize) -> Result<()> {
    check_range(ptr, len)?;
    sys::mem::lock(ptr, len)
}

/// Unlocks the pages of a range locked by [`lock`] (`munlock`,
/// `VirtualUnlock`).
///
/// Unlocking pages that are not locked is an error on Windows and succeeds
/// elsewhere.
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
pub fn unlock(ptr: *const u8, len: usize) -> Result<()> {
    check_range(ptr, len)?;
    sys::mem::unlock(ptr, len)
}

/// Makes the processor forget what it knew of the instructions in a range
/// of memory: to be called after writing code, before running it. See
/// [executable memory](self#executable-memory).
///
/// Processors keep instructions in a cache of their own. On x86 that cache
/// follows what is written to memory, and this function does nothing; on
/// ARM and RISC-V it does not, and code that was just written, or changed,
/// may run as whatever the memory held before unless the range is flushed.
/// The flush is for every thread of the process.
///
/// The range is any `len` bytes, not necessarily whole pages. A null `len`,
/// or a range that wraps around the address space, fails with
/// [`ErrorKind::InvalidInput`].
///
/// - Linux: nothing on x86; the cache maintenance instructions on aarch64
///   (`dc cvau`, `ic ivau`); the `cacheflush` system call on arm and
///   `riscv_flush_icache` on RISC-V.
/// - macOS: `sys_icache_invalidate`.
/// - Windows: `FlushInstructionCache`.
///
/// Fails with [`ErrorKind::Unsupported`] on WebAssembly.
///
/// # Safety
///
/// The whole range must be readable memory of this process: on aarch64 the
/// instructions that flush a line of the cache fault on an address that is
/// not mapped.
pub unsafe fn flush_instruction_cache(ptr: *const u8, len: usize) -> Result<()> {
    if len == 0 || ptr.addr().checked_add(len).is_none() {
        return Err(ErrorKind::InvalidInput.into());
    }
    // SAFETY: the caller's contract.
    unsafe { sys::mem::flush_instruction_cache(ptr, len) }
}

/// An owned mapping: unmapped when dropped.
///
/// It is the pointer and length of a mapping made by [`map_anonymous`],
/// [`map_file`], [`reserve`] or [`reserve_placeholder`], and nothing more: every function of the
/// module can be used on (ranges of) it through [`as_ptr`](Self::as_ptr).
pub struct Mapping {
    ptr: NonNull<u8>,
    len: usize,
}

// SAFETY: a mapping is plain memory owned by the value, like a `Box<[u8]>`;
// access to its bytes goes through raw pointers or `unsafe` methods whose
// callers answer for data races.
unsafe impl Send for Mapping {}
// SAFETY: as above.
unsafe impl Sync for Mapping {}

impl Mapping {
    fn new(ptr: *mut u8, len: usize) -> Result<Self> {
        match NonNull::new(ptr) {
            Some(ptr) => Ok(Self { ptr, len }),
            // No system returns a null mapping; never panic on its word.
            None => Err(ErrorKind::Other.into()),
        }
    }

    /// Maps new zero-filled memory: see [`map_anonymous`].
    pub fn anonymous(len: usize, protection: Protection) -> Result<Self> {
        Self::new(map_anonymous(len, protection)?, len)
    }

    /// Maps part of a file: see [`map_file`].
    pub fn file<H: AsHandle + ?Sized>(
        file: &H,
        offset: u64,
        len: usize,
        protection: Protection,
        sharing: Sharing,
    ) -> Result<Self> {
        Self::new(map_file(file, offset, len, protection, sharing)?, len)
    }

    /// Reserves address space: see [`reserve`].
    pub fn reserve(len: usize) -> Result<Self> {
        Self::new(reserve(len)?, len)
    }

    /// Maps new zero-filled memory as `options` say: see
    /// [`MapOptions::map_anonymous`].
    pub fn anonymous_with(len: usize, options: &MapOptions) -> Result<Self> {
        Self::new(options.map_anonymous(len)?, len)
    }

    /// Maps part of a file as `options` say: see [`MapOptions::map_file`].
    pub fn file_with<H: AsHandle + ?Sized>(
        file: &H,
        offset: u64,
        len: usize,
        sharing: Sharing,
        options: &MapOptions,
    ) -> Result<Self> {
        Self::new(options.map_file(file, offset, len, sharing)?, len)
    }

    /// Reserves address space as `options` say: see
    /// [`MapOptions::reserve`].
    pub fn reserve_with(len: usize, options: &MapOptions) -> Result<Self> {
        Self::new(options.reserve(len)?, len)
    }

    /// Reserves a placeholder as `options` say: see
    /// [`MapOptions::reserve_placeholder`].
    pub fn placeholder_with(len: usize, options: &MapOptions) -> Result<Self> {
        Self::new(options.reserve_placeholder(len)?, len)
    }

    /// Takes ownership of a mapping.
    ///
    /// # Safety
    ///
    /// `ptr` and `len` must be a whole mapping made by this module, as
    /// [`unmap`] requires, that nothing else will unmap; `ptr` must not be
    /// null.
    #[inline]
    pub const unsafe fn from_raw(ptr: *mut u8, len: usize) -> Self {
        // SAFETY: the caller guarantees `ptr` is not null.
        let ptr = unsafe { NonNull::new_unchecked(ptr) };
        Self { ptr, len }
    }

    /// Releases ownership: the caller is now responsible for [`unmap`]ping
    /// the pointer and length returned.
    #[inline]
    pub fn into_raw(self) -> (*mut u8, usize) {
        let this = ManuallyDrop::new(self);
        (this.ptr.as_ptr(), this.len)
    }

    /// The address of the mapping. It is a multiple of
    /// [`allocation_granularity`].
    #[inline]
    pub const fn as_ptr(&self) -> *mut u8 {
        self.ptr.as_ptr()
    }

    /// The length of the mapping in bytes, as it was asked for: the mapping
    /// extends to the end of the page of its last byte.
    #[inline]
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Whether the mapping is empty, which it never is.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// The contents of the mapping.
    ///
    /// # Safety
    ///
    /// The whole mapping must be readable memory (committed, and not
    /// protected against reading), and nothing may modify it while the
    /// slice is alive: not this process through another pointer, and for a
    /// file mapping not another process through the file. A mapped file
    /// must not be truncated either.
    #[inline]
    pub const unsafe fn as_slice(&self) -> &[u8] {
        // SAFETY: the mapping is `len` bytes, initialised by the system; the
        // caller answers for the rest.
        unsafe { core::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
    }

    /// The contents of the mapping, to modify.
    ///
    /// # Safety
    ///
    /// The whole mapping must be readable and writable memory, and nothing
    /// else may read or modify it while the slice is alive: see
    /// [`as_slice`](Self::as_slice).
    #[inline]
    pub const unsafe fn as_mut_slice(&mut self) -> &mut [u8] {
        // SAFETY: as in `as_slice`, and `&mut self` makes the slice unique
        // among the users of this value.
        unsafe { core::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
    }
}

impl Drop for Mapping {
    fn drop(&mut self) {
        // SAFETY: the mapping is whole and owned by `self`. A failure to
        // unmap is ignored: there is nothing to do about it.
        let _ = unsafe { unmap(self.ptr.as_ptr(), self.len) };
    }
}

impl fmt::Debug for Mapping {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Mapping")
            .field("ptr", &self.ptr)
            .field("len", &self.len)
            .finish()
    }
}

/// What only Linux offers.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub mod linux {
    use super::{MapOptions, check_range};
    use crate::macros::flags;
    use crate::{ErrorKind, Result, sys};

    /// The options of a mapping that only Linux has.
    pub trait MapOptionsExt: Sized {
        /// Has the kernel bring every page of the mapping in before the
        /// call returns (`MAP_POPULATE`): memory is allocated, and a file
        /// read, at once and not at the first access to each page. Pages
        /// the kernel could not bring in are no error; they are when they
        /// are accessed, as without the option.
        fn populate(self, populate: bool) -> Self;

        /// Maps memory in the huge pages the administrator set aside
        /// (`MAP_HUGETLB`, of the default size: `Hugepagesize` in
        /// `/proc/meminfo`), which is not the transparent kind of
        /// [`huge_pages`].
        ///
        /// For anonymous mappings and reservations. The length must be a
        /// multiple of the size of a huge page, when mapping and when
        /// [`unmap`](super::unmap)ping, or the call fails with
        /// [`ErrorKind::InvalidInput`]; the address is a multiple of it.
        /// The call fails with [`ErrorKind::OutOfMemory`] when no huge
        /// page is free, which is the case of a system that was not
        /// configured to have any.
        fn huge_tlb(self, huge_tlb: bool) -> Self;

        /// Keeps the mapping out of the kernel's accounting of memory
        /// (`MAP_NORESERVE`): no swap space is set aside for it, and the
        /// call cannot fail for lack of it, whatever the overcommit policy.
        /// The price is paid when a page is first written and there is no
        /// memory for it: the process is killed. Reservations are always
        /// made this way.
        fn no_reserve(self, no_reserve: bool) -> Self;
    }

    impl MapOptionsExt for MapOptions {
        #[inline]
        fn populate(self, populate: bool) -> Self {
            self.with_extra(sys::mem::EXTRA_POPULATE, populate)
        }

        #[inline]
        fn huge_tlb(self, huge_tlb: bool) -> Self {
            self.with_extra(sys::mem::EXTRA_HUGE_TLB, huge_tlb)
        }

        #[inline]
        fn no_reserve(self, no_reserve: bool) -> Self {
            self.with_extra(sys::mem::EXTRA_NO_RESERVE, no_reserve)
        }
    }

    /// What only Linux can be told of a range of memory: see [`advise`].
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum Advice {
        /// Leave the range out of core dumps (`MADV_DONTDUMP`): for secrets,
        /// and for what is large and of no use to a debugger.
        DontDump,
        /// Include the range in core dumps again (`MADV_DODUMP`).
        DoDump,
        /// Do not give the range to the children made by `fork`
        /// (`MADV_DONTFORK`): the range does not exist for them.
        DontFork,
        /// Give the range to children again (`MADV_DOFORK`).
        DoFork,
        /// Bring every page of the range in, for reading
        /// (`MADV_POPULATE_READ`), and fail if one cannot be. Linux 5.14;
        /// before, [`ErrorKind::InvalidInput`].
        PopulateRead,
        /// Bring every page of the range in, for writing
        /// (`MADV_POPULATE_WRITE`): memory is allocated and private copies
        /// are made now, so that no access fails or waits later. The
        /// contents do not change. Linux 5.14; before,
        /// [`ErrorKind::InvalidInput`].
        PopulateWrite,
    }

    /// Tells the kernel what Linux alone can be told of a range of memory
    /// (`madvise`). None of it changes the contents of the range.
    ///
    /// The range follows the rules of the [module](super#ranges).
    pub fn advise(ptr: *const u8, len: usize, advice: Advice) -> Result<()> {
        check_range(ptr, len)?;
        sys::mem::advise_linux(ptr, len, advice)
    }

    /// Locks the pages of a range in physical memory as [`lock`](super::lock)
    /// does, but only as each is first accessed (`mlock2` with
    /// `MLOCK_ONFAULT`): nothing is brought in by the call itself, so a
    /// large range that is sparsely used costs what is used.
    /// [`unlock`](super::unlock) undoes it.
    ///
    /// The range follows the rules of the [module](super#ranges).
    pub fn lock_on_fault(ptr: *const u8, len: usize) -> Result<()> {
        check_range(ptr, len)?;
        sys::mem::lock_on_fault(ptr, len)
    }

    flags! {
        /// What [`lock_all`] locks.
        pub struct LockAll: u32 {
            /// Everything that is mapped now (`MCL_CURRENT`).
            const CURRENT = 1;
            /// Everything that is mapped from now on (`MCL_FUTURE`): a
            /// mapping that would exceed the limit then fails.
            const FUTURE = 2;
            /// Lock each page when it is first accessed, instead of
            /// bringing them all in (`MCL_ONFAULT`); with one of the other
            /// two, which says of which mappings.
            const ON_FAULT = 4;
        }
    }

    /// Locks all the memory of the process in physical memory (`mlockall`):
    /// what [`lock`](super::lock) does to a range, for every mapping there
    /// is, there will be, or both.
    ///
    /// `what` must hold [`LockAll::CURRENT`] or [`LockAll::FUTURE`], or the
    /// call fails with [`ErrorKind::InvalidInput`]. The limit on locked
    /// memory (`RLIMIT_MEMLOCK`) applies as it does to `lock`, and few
    /// processes are within it. While a mapping is locked,
    /// [`Advice::Discard`](super::Advice::Discard) is refused for it.
    pub fn lock_all(what: LockAll) -> Result<()> {
        if !what.intersects(LockAll::CURRENT | LockAll::FUTURE) {
            return Err(ErrorKind::InvalidInput.into());
        }
        sys::mem::lock_all(what)
    }

    /// Unlocks all the memory of the process, and no longer locks what is
    /// mapped from now on (`munlockall`): it undoes [`lock_all`], and every
    /// [`lock`](super::lock) and [`lock_on_fault`] as well.
    pub fn unlock_all() -> Result<()> {
        sys::mem::unlock_all()
    }

    /// Changes the length of a mapping, in place or by moving it, and
    /// returns its address (`mremap`).
    ///
    /// The mapping keeps its contents, up to the shorter of the two lengths;
    /// new pages of an anonymous mapping read as zero. Growing in place is
    /// only possible when the address space after the mapping is free: with
    /// `may_move`, the kernel otherwise moves the mapping to a new address,
    /// by remapping its pages rather than copying them; without it, the
    /// call fails with [`ErrorKind::OutOfMemory`].
    ///
    /// `ptr` must be on a page boundary, and neither length may be null, or
    /// the call fails with [`ErrorKind::InvalidInput`]. The mapping is then
    /// released with [`unmap`](super::unmap) and its new address and length.
    ///
    /// # Safety
    ///
    /// `ptr` and `old_len` must be a whole mapping made by this module. When
    /// the mapping shrinks, nothing may use what is cut off; when it moves,
    /// nothing may use the old address.
    pub unsafe fn remap(
        ptr: *mut u8,
        old_len: usize,
        new_len: usize,
        may_move: bool,
    ) -> Result<*mut u8> {
        check_range(ptr, old_len)?;
        if new_len == 0 {
            return Err(ErrorKind::InvalidInput.into());
        }
        // SAFETY: the caller's contract.
        unsafe { sys::mem::remap(ptr, old_len, new_len, may_move) }
    }

    /// Asks for a range to be backed by huge pages when the kernel can
    /// (`enable`), or never (`!enable`): `madvise` with `MADV_HUGEPAGE` or
    /// `MADV_NOHUGEPAGE`.
    ///
    /// This is the transparent kind: nothing changes for the program but
    /// the speed of address translation, and the memory used by a range
    /// that is only sparsely touched. Whether the hint is needed, honoured
    /// or ignored depends on `/sys/kernel/mm/transparent_hugepage/enabled`;
    /// a kernel built without transparent huge pages fails with
    /// [`ErrorKind::InvalidInput`].
    ///
    /// The range follows the rules of the [module](super#ranges).
    pub fn huge_pages(ptr: *const u8, len: usize, enable: bool) -> Result<()> {
        check_range(ptr, len)?;
        sys::mem::huge_pages(ptr, len, enable)
    }
}

/// What only macOS offers.
#[cfg(target_os = "macos")]
pub mod macos {
    use super::{MapOptions, Protection};
    use crate::{Result, sys};

    /// What the system knows of a mapping: see [`query`].
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    #[non_exhaustive]
    pub struct Region {
        /// The address of the first page of the region.
        pub base: *mut u8,
        /// Its length in bytes.
        pub len: usize,
        /// How its pages may be accessed now.
        pub protection: Protection,
        /// The most [`protect`](super::protect) can give them.
        pub max_protection: Protection,
    }

    /// Returns the region of the address space that holds `ptr`, or `None`
    /// when nothing is mapped there (`mach_vm_region`).
    ///
    /// A region is a run of pages with the same properties: it may be part
    /// of a mapping of this module (after [`protect`](super::protect)ing
    /// some of its pages), or several of them that the kernel merged.
    /// A reservation is a region with no access. What is true when the
    /// function returns may no longer be when the answer is used, if other
    /// threads map memory.
    pub fn query(ptr: *const u8) -> Result<Option<Region>> {
        sys::mem::query(ptr)
    }

    /// The options of a mapping that only macOS has.
    pub trait MapOptionsExt: Sized {
        /// Makes the mapping one for code generated at run time
        /// (`MAP_JIT`), which may be writable and executable at once.
        ///
        /// It is meant for [`MapOptions::map_anonymous`] with
        /// [`Protection::READ`](super::Protection::READ),
        /// [`WRITE`](super::Protection::WRITE) and
        /// [`EXECUTE`](super::Protection::EXECUTE) together; the system
        /// refuses it for a file and
        /// [inside a placeholder](MapOptions::in_placeholder).
        ///
        /// On Apple silicon such a mapping is never writable and executable
        /// *at the same time for the same thread*: each thread sees it as
        /// one or the other, and switches with [`jit_write_protect`]. Where
        /// [`jit_write_protect_supported`] is false (Intel processors, some
        /// virtual machines) it is simply both.
        ///
        /// # The hardened runtime
        ///
        /// A program signed with the hardened runtime, as notarisation
        /// requires, can only make executable memory this way, and only
        /// with the `com.apple.security.cs.allow-jit` entitlement: without
        /// it the mapping fails with
        /// [`ErrorKind::PermissionDenied`](crate::ErrorKind::PermissionDenied).
        /// A program that is not hardened (what `cargo` builds) needs
        /// neither, and can also follow the
        /// [portable steps](super#executable-memory).
        fn jit(self, jit: bool) -> Self;
    }

    impl MapOptionsExt for MapOptions {
        #[inline]
        fn jit(self, jit: bool) -> Self {
            self.with_extra(sys::mem::EXTRA_JIT, jit)
        }
    }

    /// Whether [`jit_write_protect`] does anything
    /// (`pthread_jit_write_protect_supported_np`): true on Apple silicon,
    /// though not in every virtual machine, and false on Intel processors.
    #[inline]
    pub fn jit_write_protect_supported() -> bool {
        sys::mem::jit_write_protect_supported()
    }

    /// Makes every [`jit`](MapOptionsExt::jit) mapping executable and
    /// read-only (`protect`), or writable and not executable (`!protect`),
    /// **for the calling thread alone** (`pthread_jit_write_protect_np`).
    ///
    /// A thread starts with the protection on. A code generator turns it
    /// off, writes, turns it on again and
    /// [flushes](super::flush_instruction_cache) what it wrote; other
    /// threads go on executing the mapping meanwhile. Where
    /// [`jit_write_protect_supported`] is false, this does nothing and the
    /// mappings stay as they were made.
    ///
    /// # Safety
    ///
    /// The calling thread must not execute code in a `jit` mapping while
    /// the protection is off, nor write to one, or hold a `&mut` into one,
    /// while it is on: the access faults.
    #[inline]
    pub unsafe fn jit_write_protect(protect: bool) {
        // SAFETY: the caller's contract.
        unsafe { sys::mem::jit_write_protect(protect) }
    }
}

/// What only Windows offers.
#[cfg(windows)]
pub mod windows {
    use super::Protection;
    use crate::{Result, sys};

    /// What the pages of a [`Region`] are.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum RegionState {
        /// Nothing: address space that is free (`MEM_FREE`).
        Free,
        /// Address space that is reserved, with no memory behind it
        /// (`MEM_RESERVE`): a reservation, a placeholder.
        Reserved,
        /// Memory, or a view of a file (`MEM_COMMIT`).
        Committed,
    }

    /// What the system knows of a range of pages: see [`query`].
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    #[non_exhaustive]
    pub struct Region {
        /// The address of the page asked about.
        pub base: *mut u8,
        /// The number of bytes from `base` that are in the same mapping,
        /// the same state and under the same protection.
        pub len: usize,
        /// What the pages are.
        pub state: RegionState,
        /// How they may be accessed: no access unless committed. A
        /// copy-on-write page is reported writable, a guard page as the
        /// protection it gets once touched.
        pub protection: Protection,
        /// The address of the mapping the pages belong to, which is what
        /// [`unmap`](super::unmap) takes; null for free pages.
        pub allocation_base: *mut u8,
    }

    /// Returns what the pages at `ptr` are, and how far they are the same
    /// (`VirtualQuery`).
    ///
    /// Fails with [`ErrorKind::InvalidInput`](crate::ErrorKind::InvalidInput)
    /// for an address that is not one a program can have. What is true when
    /// the function returns may no longer be when the answer is used, if
    /// other threads map memory.
    pub fn query(ptr: *const u8) -> Result<Region> {
        sys::mem::query_region(ptr)
    }
}

/// What Linux and macOS have in common and Windows lacks.
#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
pub mod unix {
    use super::check_range;
    use crate::{Result, sys};

    /// The order in which a range of memory is going to be accessed: see
    /// [`advise_access`].
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum AccessPattern {
        /// No particular order: the default, and what undoes the other two
        /// (`MADV_NORMAL`).
        Normal,
        /// From the lowest address to the highest (`MADV_SEQUENTIAL`): the
        /// system reads further ahead, and may let go sooner of the pages
        /// that were read.
        Sequential,
        /// In no order that the system could predict (`MADV_RANDOM`):
        /// reading ahead is useless.
        Random,
    }

    /// Tells the system in what order a range of memory is going to be
    /// accessed, which decides how it reads a mapped file ahead (`madvise`).
    /// It is a hint: nothing changes but the speed.
    ///
    /// Windows has no such hint for a range of memory, only for a file as
    /// it is opened.
    ///
    /// The range follows the rules of the [module](super#ranges).
    pub fn advise_access(ptr: *const u8, len: usize, pattern: AccessPattern) -> Result<()> {
        check_range(ptr, len)?;
        sys::mem::advise_access(ptr, len, pattern)
    }
}