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
use crate::unwind::UnwindRegistry;
use std::mem::ManuallyDrop;
use std::sync::Arc;
use std::{cmp, mem};
use wasmer_compiler::{CompiledFunctionUnwindInfo, FunctionBody, SectionBody};
use wasmer_types::entity::{EntityRef, PrimaryMap};
use wasmer_vm::{FunctionBodyPtr, Mmap, VMFunctionBody};
const ARCH_FUNCTION_ALIGNMENT: usize = 16;
struct CodeMemoryEntry {
mmap: ManuallyDrop<Mmap>,
}
impl CodeMemoryEntry {
fn new() -> Self {
let mmap = ManuallyDrop::new(Mmap::new());
Self { mmap }
}
fn with_capacity(cap: usize) -> Result<Self, String> {
let mmap = ManuallyDrop::new(Mmap::with_at_least(cap)?);
Ok(Self { mmap })
}
}
impl Drop for CodeMemoryEntry {
fn drop(&mut self) {
unsafe {
ManuallyDrop::drop(&mut self.mmap);
}
}
}
pub struct CodeMemory {
current: CodeMemoryEntry,
entries: Vec<CodeMemoryEntry>,
unwind_registries: Vec<Arc<UnwindRegistry>>,
read_sections: Vec<Vec<u8>>,
position: usize,
published: usize,
}
impl CodeMemory {
pub fn new() -> Self {
Self {
current: CodeMemoryEntry::new(),
entries: Vec::new(),
read_sections: Vec::new(),
unwind_registries: Vec::new(),
position: 0,
published: 0,
}
}
pub(crate) fn publish_unwind_registry(&mut self, unwind_registry: Arc<UnwindRegistry>) {
self.unwind_registries.push(unwind_registry);
}
pub fn allocate_functions<K>(
&mut self,
registry: &mut UnwindRegistry,
compilation: &PrimaryMap<K, FunctionBody>,
) -> Result<PrimaryMap<K, FunctionBodyPtr>, String>
where
K: EntityRef,
{
let total_len = compilation.values().fold(0, |acc, func| {
acc + get_align_padding_size(acc, ARCH_FUNCTION_ALIGNMENT)
+ Self::function_allocation_size(func)
});
let (mut buf, start) = self.allocate(total_len, ARCH_FUNCTION_ALIGNMENT)?;
let base_address = buf.as_ptr() as usize - start;
let mut result = PrimaryMap::with_capacity(compilation.len());
let mut start = start as u32;
let mut padding = 0usize;
for func in compilation.values() {
let (next_start, next_buf, vmfunc) = Self::copy_function(
registry,
base_address,
func,
start + padding as u32,
&mut buf[padding..],
);
assert!(vmfunc as *mut _ as *mut u8 as usize % ARCH_FUNCTION_ALIGNMENT == 0);
result.push(FunctionBodyPtr(vmfunc as *mut [VMFunctionBody]));
padding = get_align_padding_size(next_start as usize, ARCH_FUNCTION_ALIGNMENT);
start = next_start;
buf = next_buf;
}
Ok(result)
}
pub fn allocate_for_function(
&mut self,
registry: &mut UnwindRegistry,
func: &FunctionBody,
) -> Result<&mut [VMFunctionBody], String> {
let size = Self::function_allocation_size(func);
let (buf, start) = self.allocate(size, ARCH_FUNCTION_ALIGNMENT)?;
let base_address = buf.as_ptr() as usize - start;
let (_, _, vmfunc) = Self::copy_function(registry, base_address, func, start as u32, buf);
assert!(vmfunc as *mut _ as *mut u8 as usize % ARCH_FUNCTION_ALIGNMENT == 0);
Ok(vmfunc)
}
pub fn allocate_for_executable_custom_section(
&mut self,
section: &SectionBody,
) -> Result<&mut [u8], String> {
let section = section.as_slice();
let (buf, _) = self.allocate(section.len(), ARCH_FUNCTION_ALIGNMENT)?;
buf.copy_from_slice(section);
Ok(buf)
}
pub fn allocate_for_custom_section(
&mut self,
section: &SectionBody,
) -> Result<&mut [u8], String> {
let section = section.as_slice().to_vec();
self.read_sections.push(section);
Ok(self
.read_sections
.last_mut()
.ok_or_else(|| "Can't get last section".to_string())?)
}
pub fn publish(&mut self) {
self.push_current(0)
.expect("failed to push current memory map");
for CodeMemoryEntry { mmap: m } in &mut self.entries[self.published..] {
if !m.is_empty() {
unsafe {
region::protect(m.as_mut_ptr(), m.len(), region::Protection::READ_EXECUTE)
}
.expect("unable to make memory readonly and executable");
}
}
self.published = self.entries.len();
}
fn allocate(&mut self, size: usize, alignment: usize) -> Result<(&mut [u8], usize), String> {
assert!(alignment > 0);
let align_padding = get_align_padding_size(self.position, alignment);
let padded_size = size + align_padding;
let old_position;
if self.current.mmap.len() - self.position < padded_size {
self.push_current(cmp::max(0x10000, size))?;
old_position = 0;
self.position += size;
} else {
old_position = self.position + align_padding;
self.position += padded_size;
}
assert!(old_position % alignment == 0);
Ok((
&mut self.current.mmap.as_mut_slice()[old_position..self.position],
old_position,
))
}
fn function_allocation_size(func: &FunctionBody) -> usize {
match &func.unwind_info {
Some(CompiledFunctionUnwindInfo::WindowsX64(info)) => {
((func.body.len() + 3) & !3) + info.len()
}
_ => func.body.len(),
}
}
fn copy_function<'a>(
registry: &mut UnwindRegistry,
base_address: usize,
func: &FunctionBody,
func_start: u32,
buf: &'a mut [u8],
) -> (u32, &'a mut [u8], &'a mut [VMFunctionBody]) {
assert!((func_start as usize) % ARCH_FUNCTION_ALIGNMENT == 0);
let func_len = func.body.len();
let mut func_end = func_start + (func_len as u32);
let (body, mut remainder) = buf.split_at_mut(func_len);
body.copy_from_slice(&func.body);
let vmfunc = Self::view_as_mut_vmfunc_slice(body);
if let Some(CompiledFunctionUnwindInfo::WindowsX64(info)) = &func.unwind_info {
let unwind_start = (func_end + 3) & !3;
let unwind_size = info.len();
let padding = (unwind_start - func_end) as usize;
assert_eq!((func_start as usize + func_len + padding) % 4, 0);
let (slice, r) = remainder.split_at_mut(padding + unwind_size);
slice[padding..].copy_from_slice(&info);
func_end = unwind_start + (unwind_size as u32);
remainder = r;
}
if let Some(info) = &func.unwind_info {
registry
.register(base_address, func_start, func_len as u32, info)
.expect("failed to register unwind information");
}
(func_end, remainder, vmfunc)
}
fn view_as_mut_vmfunc_slice(slice: &mut [u8]) -> &mut [VMFunctionBody] {
let byte_ptr: *mut [u8] = slice;
let body_ptr = byte_ptr as *mut [VMFunctionBody];
unsafe { &mut *body_ptr }
}
fn push_current(&mut self, new_size: usize) -> Result<(), String> {
let previous = mem::replace(
&mut self.current,
if new_size == 0 {
CodeMemoryEntry::new()
} else {
CodeMemoryEntry::with_capacity(cmp::max(0x10000, new_size))?
},
);
if !previous.mmap.is_empty() {
self.entries.push(previous);
}
self.position = 0;
Ok(())
}
}
fn get_align_padding_size(position: usize, alignment: usize) -> usize {
match position % alignment {
0 => 0,
x => alignment - x,
}
}
#[cfg(test)]
mod tests {
use super::CodeMemory;
fn _assert() {
fn _assert_send_sync<T: Send + Sync>() {}
_assert_send_sync::<CodeMemory>();
}
}