wasmtime_runtime/instance/allocator/pooling/
unix.rs

1use anyhow::{Context, Result};
2
3fn decommit(addr: *mut u8, len: usize) -> Result<()> {
4    if len == 0 {
5        return Ok(());
6    }
7
8    unsafe {
9        cfg_if::cfg_if! {
10            if #[cfg(target_os = "linux")] {
11                use rustix::mm::{madvise, Advice};
12
13                // On Linux, this is enough to cause the kernel to initialize
14                // the pages to 0 on next access
15                madvise(addr as _, len, Advice::LinuxDontNeed)
16                    .context("madvise failed to decommit: {}")?;
17            } else {
18                use rustix::mm::{mmap_anonymous, ProtFlags, MapFlags};
19
20                // By creating a new mapping at the same location, this will
21                // discard the mapping for the pages in the given range.
22                // The new mapping will be to the CoW zero page, so this
23                // effectively zeroes the pages.
24                mmap_anonymous(
25                    addr as _,
26                    len,
27                    ProtFlags::READ | ProtFlags::WRITE,
28                    MapFlags::PRIVATE | MapFlags::FIXED,
29                )
30                .context("mmap failed to remap pages: {}")?;
31            }
32        }
33    }
34
35    Ok(())
36}
37
38pub fn commit_table_pages(_addr: *mut u8, _len: usize) -> Result<()> {
39    // A no-op as table pages remain READ|WRITE
40    Ok(())
41}
42
43pub fn decommit_table_pages(addr: *mut u8, len: usize) -> Result<()> {
44    decommit(addr, len)
45}
46
47#[cfg(feature = "async")]
48pub fn commit_stack_pages(_addr: *mut u8, _len: usize) -> Result<()> {
49    // A no-op as stack pages remain READ|WRITE
50    Ok(())
51}
52
53#[cfg(feature = "async")]
54pub fn reset_stack_pages_to_zero(addr: *mut u8, len: usize) -> Result<()> {
55    decommit(addr, len)
56}