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
use crate::mmap::Mmap;
use crate::vmcontext::VMMemoryDefinition;
use loupe::MemoryUsage;
use more_asserts::assert_ge;
#[cfg(feature = "enable-rkyv")]
use rkyv::{Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize};
use serde::{Deserialize, Serialize};
use std::borrow::BorrowMut;
use std::cell::UnsafeCell;
use std::convert::TryInto;
use std::fmt;
use std::ptr::NonNull;
use std::sync::Mutex;
use thiserror::Error;
use wasmer_types::{Bytes, MemoryType, Pages};
#[derive(Error, Debug, Clone, PartialEq, Hash)]
pub enum MemoryError {
#[error("Error when allocating memory: {0}")]
Region(String),
#[error("The memory could not grow: current size {} pages, requested increase: {} pages", current.0, attempted_delta.0)]
CouldNotGrow {
current: Pages,
attempted_delta: Pages,
},
#[error("The memory is invalid because {}", reason)]
InvalidMemory {
reason: String,
},
#[error("The minimum requested ({} pages) memory is greater than the maximum allowed memory ({} pages)", min_requested.0, max_allowed.0)]
MinimumMemoryTooLarge {
min_requested: Pages,
max_allowed: Pages,
},
#[error("The maximum requested memory ({} pages) is greater than the maximum allowed memory ({} pages)", max_requested.0, max_allowed.0)]
MaximumMemoryTooLarge {
max_requested: Pages,
max_allowed: Pages,
},
#[error("A user-defined error occurred: {0}")]
Generic(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, MemoryUsage)]
#[cfg_attr(
feature = "enable-rkyv",
derive(RkyvSerialize, RkyvDeserialize, Archive)
)]
pub enum MemoryStyle {
Dynamic {
offset_guard_size: u64,
},
Static {
bound: Pages,
offset_guard_size: u64,
},
}
impl MemoryStyle {
pub fn offset_guard_size(&self) -> u64 {
match self {
Self::Dynamic { offset_guard_size } => *offset_guard_size,
Self::Static {
offset_guard_size, ..
} => *offset_guard_size,
}
}
}
pub trait Memory: fmt::Debug + Send + Sync + MemoryUsage {
fn ty(&self) -> MemoryType;
fn style(&self) -> &MemoryStyle;
fn size(&self) -> Pages;
fn grow(&self, delta: Pages) -> Result<Pages, MemoryError>;
fn vmmemory(&self) -> NonNull<VMMemoryDefinition>;
}
#[derive(Debug, MemoryUsage)]
pub struct LinearMemory {
mmap: Mutex<WasmMmap>,
maximum: Option<Pages>,
memory: MemoryType,
style: MemoryStyle,
offset_guard_size: usize,
vm_memory_definition: VMMemoryDefinitionOwnership,
pub(crate) needs_signal_handlers: bool,
}
#[derive(Debug, MemoryUsage)]
enum VMMemoryDefinitionOwnership {
VMOwned(NonNull<VMMemoryDefinition>),
HostOwned(Box<UnsafeCell<VMMemoryDefinition>>),
}
unsafe impl Send for LinearMemory {}
unsafe impl Sync for LinearMemory {}
#[derive(Debug, MemoryUsage)]
struct WasmMmap {
alloc: Mmap,
size: Pages,
}
impl LinearMemory {
pub fn new(memory: &MemoryType, style: &MemoryStyle) -> Result<Self, MemoryError> {
unsafe { Self::new_internal(memory, style, None) }
}
pub unsafe fn from_definition(
memory: &MemoryType,
style: &MemoryStyle,
vm_memory_location: NonNull<VMMemoryDefinition>,
) -> Result<Self, MemoryError> {
Self::new_internal(memory, style, Some(vm_memory_location))
}
unsafe fn new_internal(
memory: &MemoryType,
style: &MemoryStyle,
vm_memory_location: Option<NonNull<VMMemoryDefinition>>,
) -> Result<Self, MemoryError> {
if memory.minimum > Pages::max_value() {
return Err(MemoryError::MinimumMemoryTooLarge {
min_requested: memory.minimum,
max_allowed: Pages::max_value(),
});
}
if let Some(max) = memory.maximum {
if max > Pages::max_value() {
return Err(MemoryError::MaximumMemoryTooLarge {
max_requested: max,
max_allowed: Pages::max_value(),
});
}
if max < memory.minimum {
return Err(MemoryError::InvalidMemory {
reason: format!(
"the maximum ({} pages) is less than the minimum ({} pages)",
max.0, memory.minimum.0
),
});
}
}
let offset_guard_bytes = style.offset_guard_size() as usize;
let needs_signal_handlers = offset_guard_bytes > 0
|| match style {
MemoryStyle::Dynamic { .. } => false,
MemoryStyle::Static { .. } => true,
};
let minimum_pages = match style {
MemoryStyle::Dynamic { .. } => memory.minimum,
MemoryStyle::Static { bound, .. } => {
assert_ge!(*bound, memory.minimum);
*bound
}
};
let minimum_bytes = minimum_pages.bytes().0;
let request_bytes = minimum_bytes.checked_add(offset_guard_bytes).unwrap();
let mapped_pages = memory.minimum;
let mapped_bytes = mapped_pages.bytes();
let mut mmap = WasmMmap {
alloc: Mmap::accessible_reserved(mapped_bytes.0, request_bytes)
.map_err(MemoryError::Region)?,
size: memory.minimum,
};
let base_ptr = mmap.alloc.as_mut_ptr();
let mem_length = memory.minimum.bytes().0.try_into().unwrap();
Ok(Self {
mmap: Mutex::new(mmap),
maximum: memory.maximum,
offset_guard_size: offset_guard_bytes,
needs_signal_handlers,
vm_memory_definition: if let Some(mem_loc) = vm_memory_location {
{
let mut ptr = mem_loc;
let md = ptr.as_mut();
md.base = base_ptr;
md.current_length = mem_length;
}
VMMemoryDefinitionOwnership::VMOwned(mem_loc)
} else {
VMMemoryDefinitionOwnership::HostOwned(Box::new(UnsafeCell::new(
VMMemoryDefinition {
base: base_ptr,
current_length: mem_length,
},
)))
},
memory: *memory,
style: style.clone(),
})
}
unsafe fn get_vm_memory_definition(&self) -> NonNull<VMMemoryDefinition> {
match &self.vm_memory_definition {
VMMemoryDefinitionOwnership::VMOwned(ptr) => *ptr,
VMMemoryDefinitionOwnership::HostOwned(boxed_ptr) => {
NonNull::new_unchecked(boxed_ptr.get())
}
}
}
}
impl Memory for LinearMemory {
fn ty(&self) -> MemoryType {
let minimum = self.size();
let mut out = self.memory.clone();
out.minimum = minimum;
out
}
fn style(&self) -> &MemoryStyle {
&self.style
}
fn size(&self) -> Pages {
unsafe {
let md_ptr = self.get_vm_memory_definition();
let md = md_ptr.as_ref();
Bytes::from(md.current_length).try_into().unwrap()
}
}
fn grow(&self, delta: Pages) -> Result<Pages, MemoryError> {
let mut mmap_guard = self.mmap.lock().unwrap();
let mmap = mmap_guard.borrow_mut();
if delta.0 == 0 {
return Ok(mmap.size);
}
let new_pages = mmap
.size
.checked_add(delta)
.ok_or(MemoryError::CouldNotGrow {
current: mmap.size,
attempted_delta: delta,
})?;
let prev_pages = mmap.size;
if let Some(maximum) = self.maximum {
if new_pages > maximum {
return Err(MemoryError::CouldNotGrow {
current: mmap.size,
attempted_delta: delta,
});
}
}
if new_pages >= Pages::max_value() {
return Err(MemoryError::CouldNotGrow {
current: mmap.size,
attempted_delta: delta,
});
}
let delta_bytes = delta.bytes().0;
let prev_bytes = prev_pages.bytes().0;
let new_bytes = new_pages.bytes().0;
if new_bytes > mmap.alloc.len() - self.offset_guard_size {
let guard_bytes = self.offset_guard_size;
let request_bytes =
new_bytes
.checked_add(guard_bytes)
.ok_or_else(|| MemoryError::CouldNotGrow {
current: new_pages,
attempted_delta: Bytes(guard_bytes).try_into().unwrap(),
})?;
let mut new_mmap =
Mmap::accessible_reserved(new_bytes, request_bytes).map_err(MemoryError::Region)?;
let copy_len = mmap.alloc.len() - self.offset_guard_size;
new_mmap.as_mut_slice()[..copy_len].copy_from_slice(&mmap.alloc.as_slice()[..copy_len]);
mmap.alloc = new_mmap;
} else if delta_bytes > 0 {
mmap.alloc
.make_accessible(prev_bytes, delta_bytes)
.map_err(MemoryError::Region)?;
}
mmap.size = new_pages;
unsafe {
let mut md_ptr = self.get_vm_memory_definition();
let md = md_ptr.as_mut();
md.current_length = new_pages.bytes().0.try_into().unwrap();
md.base = mmap.alloc.as_mut_ptr() as _;
}
Ok(prev_pages)
}
fn vmmemory(&self) -> NonNull<VMMemoryDefinition> {
let _mmap_guard = self.mmap.lock().unwrap();
unsafe { self.get_vm_memory_definition() }
}
}