Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bytecodealliance
GitHub Repository: bytecodealliance/wasmtime
Path: blob/main/tests/all/custom_code_memory.rs
1690 views
1
#[cfg(all(not(target_os = "windows"), not(miri)))]
2
mod not_for_windows {
3
use rustix::mm::{MprotectFlags, mprotect};
4
use rustix::param::page_size;
5
use std::sync::Arc;
6
use wasmtime::*;
7
8
struct CustomCodePublish;
9
impl CustomCodeMemory for CustomCodePublish {
10
fn required_alignment(&self) -> usize {
11
page_size()
12
}
13
14
fn publish_executable(&self, ptr: *const u8, len: usize) -> anyhow::Result<()> {
15
unsafe {
16
mprotect(
17
ptr as *mut _,
18
len,
19
MprotectFlags::READ | MprotectFlags::EXEC,
20
)?;
21
}
22
Ok(())
23
}
24
25
fn unpublish_executable(&self, ptr: *const u8, len: usize) -> anyhow::Result<()> {
26
unsafe {
27
mprotect(
28
ptr as *mut _,
29
len,
30
MprotectFlags::READ | MprotectFlags::WRITE,
31
)?;
32
}
33
Ok(())
34
}
35
}
36
37
#[test]
38
fn custom_code_publish() {
39
let mut config = Config::default();
40
config.with_custom_code_memory(Some(Arc::new(CustomCodePublish)));
41
let engine = Engine::new(&config).unwrap();
42
let module = Module::new(
43
&engine,
44
"(module (func (export \"main\") (result i32) i32.const 42))",
45
)
46
.unwrap();
47
let mut store = Store::new(&engine, ());
48
let instance = Instance::new(&mut store, &module, &[]).unwrap();
49
let func: TypedFunc<(), i32> = instance.get_typed_func(&mut store, "main").unwrap();
50
let result = func.call(&mut store, ()).unwrap();
51
assert_eq!(result, 42);
52
}
53
}
54
55