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
use crate::Module;
use memmap::Mmap;
use std::{
fs::{create_dir_all, File},
io::{self, Write},
path::PathBuf,
};
use wasmer_runtime_core::cache::Error as CacheError;
pub use wasmer_runtime_core::{
backend::Backend,
cache::{Artifact, Cache, WasmHash},
};
pub struct FileSystemCache {
path: PathBuf,
}
impl FileSystemCache {
pub unsafe fn new<P: Into<PathBuf>>(path: P) -> io::Result<Self> {
let path: PathBuf = path.into();
if path.exists() {
let metadata = path.metadata()?;
if metadata.is_dir() {
if !metadata.permissions().readonly() {
Ok(Self { path })
} else {
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("the supplied path is readonly: {}", path.display()),
))
}
} else {
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!(
"the supplied path already points to a file: {}",
path.display()
),
))
}
} else {
create_dir_all(&path)?;
Ok(Self { path })
}
}
}
impl Cache for FileSystemCache {
type LoadError = CacheError;
type StoreError = CacheError;
fn load(&self, key: WasmHash) -> Result<Module, CacheError> {
self.load_with_backend(key, Backend::default())
}
fn load_with_backend(&self, key: WasmHash, backend: Backend) -> Result<Module, CacheError> {
let filename = key.encode();
let mut new_path_buf = self.path.clone();
new_path_buf.push(backend.to_string());
new_path_buf.push(filename);
let file = File::open(new_path_buf)?;
let mmap = unsafe { Mmap::map(&file)? };
let serialized_cache = Artifact::deserialize(&mmap[..])?;
unsafe {
wasmer_runtime_core::load_cache_with(
serialized_cache,
super::compiler_for_backend(backend)
.ok_or_else(|| CacheError::UnsupportedBackend(backend))?
.as_ref(),
)
}
}
fn store(&mut self, key: WasmHash, module: Module) -> Result<(), CacheError> {
let filename = key.encode();
let backend_str = module.info().backend.to_string();
let mut new_path_buf = self.path.clone();
new_path_buf.push(backend_str);
let serialized_cache = module.cache()?;
let buffer = serialized_cache.serialize()?;
std::fs::create_dir_all(&new_path_buf)?;
new_path_buf.push(filename);
let mut file = File::create(new_path_buf)?;
file.write_all(&buffer)?;
Ok(())
}
}
#[cfg(all(test, not(feature = "singlepass")))]
mod tests {
use super::*;
use std::env;
#[test]
fn test_file_system_cache_run() {
use crate::{compile, imports, Func};
use wabt::wat2wasm;
static WAT: &'static str = r#"
(module
(type $t0 (func (param i32) (result i32)))
(func $add_one (export "add_one") (type $t0) (param $p0 i32) (result i32)
get_local $p0
i32.const 1
i32.add))
"#;
let wasm = wat2wasm(WAT).unwrap();
let module = compile(&wasm).unwrap();
let cache_dir = env::temp_dir();
println!("test temp_dir {:?}", cache_dir);
let mut fs_cache = unsafe {
FileSystemCache::new(cache_dir)
.map_err(|e| format!("Cache error: {:?}", e))
.unwrap()
};
let key = WasmHash::generate(&wasm);
fs_cache.store(key, module.clone()).unwrap();
let cached_module = fs_cache.load(key).unwrap();
let import_object = imports! {};
let instance = cached_module.instantiate(&import_object).unwrap();
let add_one: Func<i32, i32> = instance.func("add_one").unwrap();
let value = add_one.call(42).unwrap();
assert_eq!(value, 43);
}
}