oscall 0.0.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
//! `mem` on Windows: `VirtualAlloc` and its family for anonymous memory,
//! section objects (`CreateFileMappingW`) and their views for files.
//!
//! The two kinds are released differently (`VirtualFree`, `UnmapViewOfFile`):
//! [`unmap`] asks `VirtualQuery` which one it was given.
//!
//! Placeholders (`VirtualAlloc2`, `MapViewOfFile3`) came with Windows 10
//! version 1803, in `kernelbase.dll`: the two functions are looked up when
//! first needed, so that a program still starts on the versions before.

use core::ffi::CStr;
use core::ffi::c_void;
use core::mem::MaybeUninit;
use core::ptr::{null, null_mut};
use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};

use crate::mem::windows::{Region, RegionState};
use crate::mem::{Advice, MapOptions, Place, Protection, Sharing};
use crate::sys::{RawHandle, cvt, dll, last_error};
use crate::{BorrowedHandle, ErrorKind, OwnedHandle, Result};

/// `SYSTEM_INFO`.
#[repr(C)]
struct SystemInfo {
    _oem_id: u32,
    page_size: u32,
    _minimum_application_address: *mut c_void,
    _maximum_application_address: *mut c_void,
    _active_processor_mask: usize,
    _number_of_processors: u32,
    _processor_type: u32,
    allocation_granularity: u32,
    _processor_level: u16,
    _processor_revision: u16,
}

/// `MEMORY_BASIC_INFORMATION`.
#[repr(C)]
struct MemoryBasicInformation {
    base_address: *mut c_void,
    allocation_base: *mut c_void,
    /// `AllocationProtect`, a `DWORD`, and the padding after it, which on
    /// 64-bit targets also holds the `WORD` `PartitionId`: `RegionSize` is
    /// pointer-aligned.
    _allocation_protect: usize,
    region_size: usize,
    state: u32,
    protect: u32,
    kind: u32,
}

/// `UNICODE_STRING`, with which `PUBLIC_OBJECT_TYPE_INFORMATION` starts.
#[repr(C)]
struct UnicodeString {
    length: u16,
    _maximum_length: u16,
    buffer: *const u16,
}

dll!("ntdll.dll" {
    fn NtQueryObject(
        handle: RawHandle,
        class: u32,
        info: *mut c_void,
        len: u32,
        returned: *mut u32,
    ) -> i32;
});

/// `ObjectTypeInformation`, for `NtQueryObject`.
const OBJECT_TYPE_INFORMATION: u32 = 2;

/// `WIN32_MEMORY_RANGE_ENTRY`.
#[repr(C)]
struct MemoryRangeEntry {
    virtual_address: *mut c_void,
    number_of_bytes: usize,
}

dll!("kernel32.dll" {
    fn GetSystemInfo(info: *mut SystemInfo);
    fn GetCurrentProcess() -> RawHandle;
    fn VirtualAlloc(addr: *mut c_void, size: usize, kind: u32, protect: u32) -> *mut c_void;
    fn VirtualFree(addr: *mut c_void, size: usize, kind: u32) -> i32;
    fn VirtualProtect(addr: *mut c_void, size: usize, protect: u32, old: *mut u32) -> i32;
    fn VirtualQuery(addr: *const c_void, info: *mut MemoryBasicInformation, len: usize) -> usize;
    fn VirtualLock(addr: *mut c_void, size: usize) -> i32;
    fn VirtualUnlock(addr: *mut c_void, size: usize) -> i32;
    fn PrefetchVirtualMemory(
        process: RawHandle,
        entries: usize,
        ranges: *mut MemoryRangeEntry,
        flags: u32,
    ) -> i32;
    fn CreateFileMappingW(
        file: RawHandle,
        attributes: *mut c_void,
        protect: u32,
        maximum_size_high: u32,
        maximum_size_low: u32,
        name: *const u16,
    ) -> RawHandle;
    fn MapViewOfFileEx(
        mapping: RawHandle,
        access: u32,
        offset_high: u32,
        offset_low: u32,
        size: usize,
        base: *mut c_void,
    ) -> *mut c_void;
    fn GetModuleHandleW(name: *const u16) -> *mut c_void;
    fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void;
    fn UnmapViewOfFile(addr: *const c_void) -> i32;
    fn UnmapViewOfFileEx(addr: *mut c_void, flags: u32) -> i32;
    fn FlushViewOfFile(addr: *const c_void, size: usize) -> i32;
    fn FlushFileBuffers(file: RawHandle) -> i32;
    fn FlushInstructionCache(process: RawHandle, addr: *const c_void, size: usize) -> i32;
    fn CloseHandle(handle: RawHandle) -> i32;
});

const INVALID_HANDLE_VALUE: RawHandle = -1isize as RawHandle;

const ERROR_INVALID_PARAMETER: i32 = 87;
const ERROR_INVALID_ADDRESS: i32 = 487;

const MEM_COMMIT: u32 = 0x1000;
const MEM_RESERVE: u32 = 0x2000;
const MEM_DECOMMIT: u32 = 0x4000;
const MEM_RELEASE: u32 = 0x8000;
const MEM_FREE: u32 = 0x1_0000;
const MEM_MAPPED: u32 = 0x4_0000;
const MEM_RESET: u32 = 0x8_0000;
const MEM_IMAGE: u32 = 0x100_0000;

// Placeholders: `VirtualAlloc2`, `MapViewOfFile3` and `VirtualFree`.
const MEM_COALESCE_PLACEHOLDERS: u32 = 0x1;
const MEM_PRESERVE_PLACEHOLDER: u32 = 0x2;
const MEM_REPLACE_PLACEHOLDER: u32 = 0x4000;
const MEM_RESERVE_PLACEHOLDER: u32 = 0x4_0000;

const PAGE_NOACCESS: u32 = 0x01;
const PAGE_READONLY: u32 = 0x02;
const PAGE_READWRITE: u32 = 0x04;
const PAGE_WRITECOPY: u32 = 0x08;
const PAGE_EXECUTE: u32 = 0x10;
const PAGE_EXECUTE_READ: u32 = 0x20;
const PAGE_EXECUTE_READWRITE: u32 = 0x40;
const PAGE_EXECUTE_WRITECOPY: u32 = 0x80;

const FILE_MAP_COPY: u32 = 0x01;
const FILE_MAP_WRITE: u32 = 0x02;
const FILE_MAP_READ: u32 = 0x04;
const FILE_MAP_EXECUTE: u32 = 0x20;

/// The page size and the allocation granularity, once known.
static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
static GRANULARITY: AtomicUsize = AtomicUsize::new(0);

#[cold]
fn system_info() -> (usize, usize) {
    let mut info = MaybeUninit::<SystemInfo>::zeroed();
    // SAFETY: GetSystemInfo fills the structure it is given, and cannot
    // fail.
    let info = unsafe {
        GetSystemInfo(info.as_mut_ptr());
        info.assume_init()
    };
    let sizes = (
        info.page_size as usize,
        info.allocation_granularity as usize,
    );
    // Racing threads store the same values.
    PAGE_SIZE.store(sizes.0, Ordering::Relaxed);
    GRANULARITY.store(sizes.1, Ordering::Relaxed);
    sizes
}

pub(crate) fn page_size() -> usize {
    match PAGE_SIZE.load(Ordering::Relaxed) {
        0 => system_info().0,
        size => size,
    }
}

pub(crate) fn allocation_granularity() -> usize {
    match GRANULARITY.load(Ordering::Relaxed) {
        0 => system_info().1,
        size => size,
    }
}

/// The page protection that grants `protection`, or the least that does:
/// there is no write-only page, nor a writable and executable one that
/// cannot be read.
fn page(protection: Protection) -> u32 {
    let read = protection.contains(Protection::READ);
    let write = protection.contains(Protection::WRITE);
    let execute = protection.contains(Protection::EXECUTE);
    match (execute, write, read) {
        (false, false, false) => PAGE_NOACCESS,
        (false, false, true) => PAGE_READONLY,
        (false, true, _) => PAGE_READWRITE,
        (true, false, false) => PAGE_EXECUTE,
        (true, false, true) => PAGE_EXECUTE_READ,
        (true, true, _) => PAGE_EXECUTE_READWRITE,
    }
}

/// Converts the address a function returned, null on failure.
fn cvt_ptr(ptr: *mut c_void) -> Result<*mut u8> {
    if ptr.is_null() {
        Err(last_error())
    } else {
        Ok(ptr.cast())
    }
}

/// `VirtualAlloc2`.
type VirtualAlloc2Fn = unsafe extern "system" fn(
    process: RawHandle,
    base: *mut c_void,
    size: usize,
    kind: u32,
    protect: u32,
    parameters: *mut c_void,
    count: u32,
) -> *mut c_void;

/// `MapViewOfFile3`.
type MapViewOfFile3Fn = unsafe extern "system" fn(
    mapping: RawHandle,
    process: RawHandle,
    base: *mut c_void,
    offset: u64,
    size: usize,
    kind: u32,
    protect: u32,
    parameters: *mut c_void,
    count: u32,
) -> *mut c_void;

static KERNELBASE: [u16; 15] = {
    let ascii = b"kernelbase.dll\0";
    let mut wide = [0; 15];
    let mut i = 0;
    while i < wide.len() {
        wide[i] = ascii[i] as u16;
        i += 1;
    }
    wide
};

/// The two functions, once found.
static VIRTUAL_ALLOC2: AtomicPtr<c_void> = AtomicPtr::new(null_mut());
static MAP_VIEW_OF_FILE3: AtomicPtr<c_void> = AtomicPtr::new(null_mut());

/// Looks up a function of kernelbase that not every Windows 10 has, so that
/// importing it would keep the program from starting there.
fn optional(cache: &AtomicPtr<c_void>, name: &CStr) -> Result<*mut c_void> {
    let known = cache.load(Ordering::Relaxed);
    if !known.is_null() {
        return Ok(known);
    }
    // SAFETY: both names are NUL-terminated; kernelbase is loaded in every
    // process, and never unloaded.
    let function = unsafe {
        let kernelbase = GetModuleHandleW(KERNELBASE.as_ptr());
        if kernelbase.is_null() {
            return Err(ErrorKind::Unsupported.into());
        }
        GetProcAddress(kernelbase, name.as_ptr().cast())
    };
    if function.is_null() {
        return Err(ErrorKind::Unsupported.into());
    }
    // Racing threads store the same address.
    cache.store(function, Ordering::Relaxed);
    Ok(function)
}

fn virtual_alloc2() -> Result<VirtualAlloc2Fn> {
    let function = optional(&VIRTUAL_ALLOC2, c"VirtualAlloc2")?;
    // SAFETY: the address of the function of that name, which has the type
    // its header declares.
    Ok(unsafe { core::mem::transmute::<*mut c_void, VirtualAlloc2Fn>(function) })
}

fn map_view_of_file3() -> Result<MapViewOfFile3Fn> {
    let function = optional(&MAP_VIEW_OF_FILE3, c"MapViewOfFile3")?;
    // SAFETY: as in `virtual_alloc2`.
    Ok(unsafe { core::mem::transmute::<*mut c_void, MapViewOfFile3Fn>(function) })
}

/// What the system knows of the pages at `addr`.
fn query(addr: *const u8) -> Result<MemoryBasicInformation> {
    let mut info = MaybeUninit::<MemoryBasicInformation>::zeroed();
    // SAFETY: VirtualQuery fills the structure it is given, whose size it is
    // told, for any address.
    unsafe {
        if VirtualQuery(addr.cast(), info.as_mut_ptr(), size_of_val(&info)) == 0 {
            return Err(last_error());
        }
        Ok(info.assume_init())
    }
}

/// The result of a mapping asked for at an address: an address that is not
/// free is refused as `ERROR_INVALID_ADDRESS`.
fn placed(result: Result<*mut u8>) -> Result<*mut u8> {
    match result {
        Err(error) if error.raw_os_error() == ERROR_INVALID_ADDRESS => {
            Err(ErrorKind::AlreadyExists.into())
        }
        result => result,
    }
}

/// The address of `place`, null for none.
fn base(place: Place) -> *mut c_void {
    match place {
        Place::Anywhere => null_mut(),
        Place::At(addr) | Place::In(addr) => addr as *mut c_void,
    }
}

/// Replaces `len` bytes at `addr`, inside a placeholder, with what `replace`
/// maps there, given the range as whole pages. The range is first made a
/// placeholder of its own, which is what can be replaced; should `replace`
/// fail, the parts are joined again.
///
/// # Safety
///
/// The caller of `MapOptions::in_placeholder` owns the placeholder.
unsafe fn in_placeholder(
    addr: usize,
    len: usize,
    replace: impl FnOnce(*mut c_void, usize) -> Result<*mut u8>,
) -> Result<*mut u8> {
    // The portable layer checked that neither overflows.
    let len = len.next_multiple_of(page_size());
    let end = addr + len;
    let info = query(addr as *const u8)?;
    // The placeholder the range is in: an allocation of its own, whose
    // pages are all in the same state.
    let whole = info.allocation_base as usize;
    let whole_end = (info.base_address as usize).saturating_add(info.region_size);
    if info.state != MEM_RESERVE || end > whole_end {
        return Err(ErrorKind::InvalidInput.into());
    }
    let split = whole != addr || whole_end != end;
    if split {
        // SAFETY: the caller's contract. What is not a placeholder is
        // refused.
        cvt(unsafe {
            VirtualFree(
                addr as *mut c_void,
                len,
                MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
            )
        })?;
    }
    let view = replace(addr as *mut c_void, len);
    if view.is_err() && split {
        // SAFETY: the placeholders cut above are the caller's; joined, they
        // are the one there was.
        unsafe {
            VirtualFree(
                whole as *mut c_void,
                whole_end - whole,
                MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS,
            )
        };
    }
    view
}

pub(crate) fn map_anonymous(len: usize, options: &MapOptions) -> Result<*mut u8> {
    let protect = page(options.protection);
    match options.place {
        Place::Anywhere | Place::At(_) => {
            // SAFETY: a new allocation, wherever the system likes or at an
            // address that must be free.
            placed(cvt_ptr(unsafe {
                VirtualAlloc(base(options.place), len, MEM_RESERVE | MEM_COMMIT, protect)
            }))
        }
        Place::In(addr) => {
            let alloc = virtual_alloc2()?;
            // SAFETY: the caller of `MapOptions::in_placeholder` owns the
            // range; a null process is the current one, and there are no
            // extended parameters.
            unsafe {
                in_placeholder(addr, len, |base, size| {
                    cvt_ptr(alloc(
                        null_mut(),
                        base,
                        size,
                        MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER,
                        protect,
                        null_mut(),
                        0,
                    ))
                })
            }
        }
    }
}

pub(crate) fn map_file(
    file: BorrowedHandle<'_>,
    offset: u64,
    len: usize,
    sharing: Sharing,
    options: &MapOptions,
) -> Result<*mut u8> {
    let protection = options.protection;
    let file = file.as_raw();
    if file == INVALID_HANDLE_VALUE {
        // CreateFileMappingW takes it to mean the paging file.
        return Err(ErrorKind::BadHandle.into());
    }
    let write = protection.contains(Protection::WRITE);
    let execute = protection.contains(Protection::EXECUTE);
    // The protection of the section is the most its views can ever have;
    // `access` is what this view asks of it, and `granted` the protection
    // its pages get as a result.
    let (section, mut access, granted) = match (sharing, write, execute) {
        (Sharing::Shared, false, false) => (PAGE_READONLY, FILE_MAP_READ, PAGE_READONLY),
        (Sharing::Shared, false, true) => (PAGE_EXECUTE_READ, FILE_MAP_READ, PAGE_EXECUTE_READ),
        (Sharing::Shared, true, false) => (
            PAGE_READWRITE,
            FILE_MAP_READ | FILE_MAP_WRITE,
            PAGE_READWRITE,
        ),
        (Sharing::Shared, true, true) => (
            PAGE_EXECUTE_READWRITE,
            FILE_MAP_READ | FILE_MAP_WRITE,
            PAGE_EXECUTE_READWRITE,
        ),
        // A copy-on-write view is always made writable, so that `protect`
        // can make it so later; the file only needs to be readable.
        (Sharing::Private, _, false) => (PAGE_WRITECOPY, FILE_MAP_COPY, PAGE_READWRITE),
        (Sharing::Private, _, true) => (
            PAGE_EXECUTE_WRITECOPY,
            FILE_MAP_COPY,
            PAGE_EXECUTE_READWRITE,
        ),
    };
    if execute {
        access |= FILE_MAP_EXECUTE;
    }
    let wanted = page(protection);
    // Gives the pages of a new view the protection asked for, where the
    // section could not; `keep` is what becomes of the range otherwise.
    let protect = |view: *mut u8, keep: u32| {
        if wanted != granted {
            let mut old = 0;
            // SAFETY: the view was just made and nothing knows of it yet.
            if let Err(error) = cvt(unsafe { VirtualProtect(view.cast(), len, wanted, &mut old) }) {
                // SAFETY: as above.
                unsafe { UnmapViewOfFileEx(view.cast(), keep) };
                return Err(error);
            }
        }
        Ok(view)
    };
    let map3 = match options.place {
        Place::In(_) => Some(map_view_of_file3()?),
        _ => None,
    };

    // A maximum size of zero is the current size of the file: a larger one
    // would grow the file.
    // SAFETY: the name and the security attributes are optional; a handle
    // that is not a file makes the call fail.
    let created = unsafe { CreateFileMappingW(file, null_mut(), section, 0, 0, null()) };
    let mapping = if created.is_null() {
        let error = last_error();
        // What `create_shared` made is a section already.
        if !is_section(file) {
            return Err(error);
        }
        file
    } else {
        created
    };
    let view = match (options.place, map3) {
        (Place::In(addr), Some(map3)) => {
            // SAFETY: `mapping` is the section created above, and the
            // caller of `MapOptions::in_placeholder` owns the range. The
            // view is given the protection of the section, as its pages
            // would have from `access`; its size is the caller's, which
            // cannot exceed the file, and the system rounds it to the pages
            // of the placeholder.
            unsafe {
                in_placeholder(addr, len, |base, _| {
                    let view = cvt_ptr(map3(
                        mapping,
                        GetCurrentProcess(),
                        base,
                        offset,
                        len,
                        MEM_REPLACE_PLACEHOLDER,
                        section,
                        null_mut(),
                        0,
                    ))?;
                    protect(view, MEM_PRESERVE_PLACEHOLDER)
                })
            }
        }
        // SAFETY: `mapping` is the section created above; the view goes
        // wherever the system likes, or at an address that must be free.
        _ => placed(cvt_ptr(unsafe {
            MapViewOfFileEx(
                mapping,
                access,
                (offset >> 32) as u32,
                offset as u32,
                len,
                base(options.place),
            )
        }))
        .and_then(|view| protect(view, 0)),
    };
    if !created.is_null() {
        // The view keeps the section alive.
        // SAFETY: `created` is open and used by nothing else.
        unsafe { CloseHandle(created) };
    }
    view
}

/// Whether `handle` is a section object, which is mapped as it is, and not
/// a file, of which a section is made first.
fn is_section(handle: RawHandle) -> bool {
    // `PUBLIC_OBJECT_TYPE_INFORMATION`: a `UNICODE_STRING`, reserved words,
    // then the characters of the name, which is a short one.
    let mut info = [0u64; 64];
    let mut returned = 0;
    // SAFETY: the call fills the buffer it is given, whose size it is told,
    // or fails; a handle that is not one makes it fail.
    let status = unsafe {
        NtQueryObject(
            handle,
            OBJECT_TYPE_INFORMATION,
            info.as_mut_ptr().cast(),
            size_of_val(&info) as u32,
            &mut returned,
        )
    };
    if status < 0 {
        return false;
    }
    // SAFETY: on success the buffer starts with the string, whose
    // characters follow in the same buffer: the length is theirs, in bytes.
    let name = unsafe {
        let name = &*info.as_ptr().cast::<UnicodeString>();
        if name.buffer.is_null() {
            return false;
        }
        core::slice::from_raw_parts(name.buffer, name.length as usize / 2)
    };
    name.iter().copied().eq("Section".encode_utf16())
}

pub(crate) fn create_shared(len: usize) -> Result<OwnedHandle> {
    let len = len as u64;
    // The invalid handle stands for the paging file: memory that belongs to
    // no file. The handle returned is not inheritable.
    // SAFETY: the name and the security attributes are optional.
    let section = unsafe {
        CreateFileMappingW(
            INVALID_HANDLE_VALUE,
            null_mut(),
            PAGE_READWRITE,
            (len >> 32) as u32,
            len as u32,
            null(),
        )
    };
    if section.is_null() {
        return Err(last_error());
    }
    // SAFETY: the handle was just made and belongs to nothing else.
    Ok(unsafe { OwnedHandle::from_raw(section) })
}

pub(crate) fn query_region(ptr: *const u8) -> Result<Region> {
    let info = query(ptr)?;
    let state = match info.state {
        MEM_FREE => RegionState::Free,
        MEM_RESERVE => RegionState::Reserved,
        MEM_COMMIT => RegionState::Committed,
        // Never panic on the system's word.
        _ => return Err(ErrorKind::Other.into()),
    };
    // The low byte is the access; guard and caching modifiers are above.
    let protection = match info.protect & 0xff {
        PAGE_READONLY => Protection::READ,
        PAGE_READWRITE | PAGE_WRITECOPY => Protection::READ_WRITE,
        PAGE_EXECUTE => Protection::EXECUTE,
        PAGE_EXECUTE_READ => Protection::READ_EXECUTE,
        PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY => {
            Protection::READ_WRITE | Protection::EXECUTE
        }
        // PAGE_NOACCESS, and the zero of pages that are not committed.
        _ => Protection::NONE,
    };
    Ok(Region {
        base: info.base_address.cast(),
        len: info.region_size,
        state,
        protection,
        allocation_base: info.allocation_base.cast(),
    })
}

pub(crate) fn reserve(len: usize, options: &MapOptions, placeholder: bool) -> Result<*mut u8> {
    let base = base(options.place);
    if placeholder {
        let alloc = virtual_alloc2()?;
        // SAFETY: a new placeholder, wherever the system likes or at an
        // address that must be free; a null process is the current one, and
        // there are no extended parameters.
        placed(cvt_ptr(unsafe {
            alloc(
                null_mut(),
                base,
                len,
                MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
                PAGE_NOACCESS,
                null_mut(),
                0,
            )
        }))
    } else {
        // SAFETY: a new reservation, wherever the system likes or at an
        // address that must be free.
        placed(cvt_ptr(unsafe {
            VirtualAlloc(base, len, MEM_RESERVE, PAGE_NOACCESS)
        }))
    }
}

/// # Safety
///
/// The range must be a whole mapping that nothing uses afterwards.
pub(crate) unsafe fn unmap(ptr: *mut u8, _len: usize) -> Result<()> {
    let info = query(ptr)?;
    if info.state == MEM_FREE || info.allocation_base != ptr.cast() {
        return Err(ErrorKind::InvalidInput.into());
    }
    if info.kind == MEM_MAPPED || info.kind == MEM_IMAGE {
        // SAFETY: the caller's contract.
        cvt(unsafe { UnmapViewOfFile(ptr.cast()) })
    } else {
        // Private memory, a reservation or a placeholder.
        // SAFETY: the caller's contract; a release takes no size.
        cvt(unsafe { VirtualFree(ptr.cast(), 0, MEM_RELEASE) })
    }
}

/// # Safety
///
/// The range must be the caller's, and the new protection must suit those
/// who use it.
pub(crate) unsafe fn protect(ptr: *mut u8, len: usize, protection: Protection) -> Result<()> {
    let mut old = 0;
    let wanted = page(protection);
    // SAFETY: the caller's contract; `old` receives the former protection.
    let result = cvt(unsafe { VirtualProtect(ptr.cast(), len, wanted, &mut old) });
    // The pages of a copy-on-write view cannot be made writable under that
    // name, only copy-on-write, a protection that nothing else accepts.
    // Which one the range belongs to is not known here, short of asking
    // VirtualQuery before every change: the refusal is what tells.
    let copy = match wanted {
        PAGE_READWRITE => PAGE_WRITECOPY,
        PAGE_EXECUTE_READWRITE => PAGE_EXECUTE_WRITECOPY,
        _ => return result,
    };
    match result {
        Err(error) if error.raw_os_error() == ERROR_INVALID_PARAMETER => {
            // SAFETY: as above.
            cvt(unsafe { VirtualProtect(ptr.cast(), len, copy, &mut old) })
        }
        result => result,
    }
}

/// # Safety
///
/// As [`protect`], in a reservation or an anonymous mapping.
pub(crate) unsafe fn commit(ptr: *mut u8, len: usize, protection: Protection) -> Result<()> {
    // SAFETY: the caller's contract.
    cvt_ptr(unsafe { VirtualAlloc(ptr.cast(), len, MEM_COMMIT, page(protection)) }).map(drop)
}

/// # Safety
///
/// The range must be anonymous memory of the caller's that nothing uses
/// afterwards.
pub(crate) unsafe fn decommit(ptr: *mut u8, len: usize) -> Result<()> {
    // SAFETY: the caller's contract.
    cvt(unsafe { VirtualFree(ptr.cast(), len, MEM_DECOMMIT) })
}

/// # Safety
///
/// The range must be the caller's, with contents nothing relies on if they
/// are discarded.
pub(crate) unsafe fn advise(ptr: *mut u8, len: usize, advice: Advice) -> Result<()> {
    match advice {
        Advice::WillNeed => {
            let mut range = MemoryRangeEntry {
                virtual_address: ptr.cast(),
                number_of_bytes: len,
            };
            // SAFETY: one range is passed, as announced; the pseudo-handle
            // of the current process is always valid.
            cvt(unsafe { PrefetchVirtualMemory(GetCurrentProcess(), 1, &mut range, 0) })
        }
        Advice::Discard => {
            // MEM_RESET spares a page that is only partly in the range,
            // where every other operation rounds the range up.
            let Some(len) = len.checked_next_multiple_of(page_size()) else {
                return Err(ErrorKind::InvalidInput.into());
            };
            // The protection is required to be valid, and ignored.
            // SAFETY: the caller's contract.
            cvt_ptr(unsafe { VirtualAlloc(ptr.cast(), len, MEM_RESET, PAGE_NOACCESS) }).map(drop)
        }
    }
}

pub(crate) fn flush(ptr: *const u8, len: usize, file: BorrowedHandle<'_>) -> Result<()> {
    // SAFETY: the pages of a view are written to its file; a range that is
    // not one makes the call fail.
    cvt(unsafe { FlushViewOfFile(ptr.cast(), len) })?;
    // FlushViewOfFile hands the pages to the file system and returns:
    // flushing the file is what waits for them to be on the storage.
    // SAFETY: the handle is open for as long as it is borrowed.
    cvt(unsafe { FlushFileBuffers(file.as_raw()) })
}

pub(crate) fn lock(ptr: *const u8, len: usize) -> Result<()> {
    // SAFETY: locking changes nothing a program can observe in its memory; a
    // range that is not committed makes it fail.
    cvt(unsafe { VirtualLock(ptr.cast_mut().cast(), len) })
}

pub(crate) fn unlock(ptr: *const u8, len: usize) -> Result<()> {
    // SAFETY: as `lock`.
    cvt(unsafe { VirtualUnlock(ptr.cast_mut().cast(), len) })
}

/// # Safety
///
/// None on Windows: the system checks the range itself.
pub(crate) unsafe fn flush_instruction_cache(ptr: *const u8, len: usize) -> Result<()> {
    // SAFETY: the pseudo-handle of the current process is always valid, and
    // the call touches the caches only.
    cvt(unsafe { FlushInstructionCache(GetCurrentProcess(), ptr.cast(), len) })
}