-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory.rs
378 lines (325 loc) · 9.69 KB
/
memory.rs
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
use crate::sync::rwlock_nb::*;
use crate::*;
use core::cell::UnsafeCell;
use core::marker::PhantomData;
use core::mem::{size_of, transmute};
use core::ops::{Deref, DerefMut};
use core::slice;
use core::sync::atomic::{fence, AtomicU32, Ordering};
/// WebAssembly memory object
pub struct WasmMemory {
data: RwLockNb<SharedDataStore>,
size: AtomicU32,
limit: u32,
}
impl WasmMemory {
pub const MAX_LIMIT: u32 = 0x1_0000;
#[inline]
pub const fn zero() -> Self {
Self {
data: RwLockNb::new(SharedDataStore::new()),
size: AtomicU32::new(0),
limit: 0,
}
}
#[inline]
pub fn new(limit: WasmLimit) -> Result<Self, WasmCompileErrorKind> {
let memory = Self {
data: RwLockNb::new(SharedDataStore::new()),
size: AtomicU32::new(0),
limit: limit.max().unwrap_or(u32::MAX).min(Self::MAX_LIMIT),
};
if limit.is_zero() {
return Ok(memory);
}
memory
.grow(limit.min())
.map(|_| memory)
.map_err(|_| WasmCompileErrorKind::OutOfMemory)
}
#[inline]
pub fn try_borrow(
&self,
) -> Result<RwLockNbReadGuard<'_, SharedDataStore>, WasmRuntimeErrorKind> {
self.data
.try_read()
.map_err(|_| WasmRuntimeErrorKind::MemoryBorrowError)
}
#[inline]
pub fn borrowing<F, R>(&self, kernel: F) -> Result<R, WasmRuntimeErrorKind>
where
F: FnOnce(&mut [u8]) -> R,
{
let memory = self.try_borrow()?;
let result = kernel(memory.as_mut_slice());
drop(memory);
Ok(result)
}
/// memory.size
#[inline]
pub fn size(&self) -> u32 {
self.size.load(Ordering::Acquire)
}
/// memory.grow
pub fn grow(&self, delta: u32) -> Result<u32, WasmRuntimeErrorKind> {
if delta > 0 {
let mut memory = self
.data
.try_write()
.map_err(|_| WasmRuntimeErrorKind::MemoryBorrowError)?;
let old_len = self.size();
let new_len = old_len.saturating_add(delta);
if new_len as u32 > self.limit {
return Err(WasmRuntimeErrorKind::InvalidParameter);
}
let additional = (delta as usize)
.checked_mul(WebAssembly::PAGE_SIZE)
.ok_or(WasmRuntimeErrorKind::InvalidParameter)?;
memory.try_grow(additional)?;
self.size.store(new_len, Ordering::Release);
Ok(old_len)
} else {
Ok(self.size())
}
}
/// Write slice to memory
pub fn write_slice(&self, offset: usize, src: &[u8]) -> Result<(), WasmRuntimeErrorKind> {
let memory = self.try_borrow()?;
let count = src.len();
let limit = memory.len();
let Some(end) = offset.checked_add(count) else {
return Err(WasmRuntimeErrorKind::OutOfBounds);
};
if offset < limit && end <= limit {
unsafe {
memory
.as_mut_ptr()
.add(offset)
.copy_from_nonoverlapping(src.as_ptr(), count);
}
Ok(())
} else {
Err(WasmRuntimeErrorKind::OutOfBounds)
}
}
#[inline]
pub fn check_bound(base: u64, count: usize, limit: usize) -> Result<(), WasmRuntimeErrorKind> {
if base.saturating_add(count as u64) <= limit as u64 {
Ok(())
} else {
Err(WasmRuntimeErrorKind::OutOfBounds)
}
}
#[inline]
pub fn effective_address<T: Sized>(
offset: u32,
index: u32,
limit: usize,
) -> Result<usize, WasmRuntimeErrorKind> {
let base = (offset as u64).wrapping_add(index as u64);
Self::check_bound(base, size_of::<T>(), limit).map(|_| base as usize)
}
}
#[repr(transparent)]
#[derive(Debug)]
pub struct SharedDataStore(UnsafeCell<Vec<u8>>);
impl SharedDataStore {
#[inline]
pub const fn new() -> Self {
Self(UnsafeCell::new(Vec::new()))
}
#[inline]
pub fn as_slice<'a>(&'a self) -> &'a [u8] {
unsafe { &*self.0.get() }.as_slice()
}
#[inline]
pub fn as_mut_slice<'a>(&'a self) -> &'a mut [u8] {
unsafe { &mut *self.0.get() }.as_mut_slice()
}
pub fn slice<'a, T: Sized + Copy>(
&self,
base: WasmPtr<T>,
count: usize,
) -> Result<&'a [T], WasmRuntimeErrorKind> {
let slice = self.as_slice();
let limit = slice.len();
let size_of_t = size_of::<T>();
WasmMemory::check_bound(base.as_usize() as u64, count * size_of_t, limit)?;
Ok(
unsafe {
slice::from_raw_parts(slice.as_ptr().add(base.as_usize()) as *const T, count)
},
)
}
pub fn slice_mut<'a, T: Sized + Copy>(
&self,
base: WasmPtrMut<T>,
count: usize,
) -> Result<&'a mut [T], WasmRuntimeErrorKind> {
let slice = self.as_mut_slice();
let limit = slice.len();
let size_of_t = size_of::<T>();
WasmMemory::check_bound(base.as_usize() as u64, count * size_of_t, limit)?;
Ok(unsafe {
slice::from_raw_parts_mut(slice.as_mut_ptr().add(base.as_usize()) as *mut T, count)
})
}
pub unsafe fn transmute<'a, T: Sized>(
&self,
offset: WasmPtr<T>,
) -> Result<&'a T, WasmRuntimeErrorKind> {
let slice = self.as_slice();
let limit = slice.len();
WasmMemory::check_bound(offset.as_usize() as u64, size_of::<T>(), limit)?;
Ok(unsafe { transmute(slice.as_ptr().add(offset.as_usize())) })
}
pub unsafe fn transmute_mut<'a, T: Sized>(
&self,
offset: WasmPtrMut<T>,
) -> Result<&'a mut T, WasmRuntimeErrorKind> {
let slice = self.as_mut_slice();
let limit = slice.len();
WasmMemory::check_bound(offset.as_usize() as u64, size_of::<T>(), limit)?;
Ok(unsafe { transmute(slice.as_mut_ptr().add(offset.as_usize())) })
}
#[inline]
pub fn as_ptr(&self) -> *const u8 {
unsafe { (&*self.0.get()).as_ptr() }
}
#[inline]
pub fn as_mut_ptr(&self) -> *mut u8 {
unsafe { (&mut *self.0.get()).as_mut_ptr() }
}
#[inline]
pub fn fence(&self, order: Ordering) {
fence(order)
}
#[inline]
pub fn len(&self) -> usize {
unsafe { &*self.0.get() }.len()
}
pub fn try_grow(&mut self, additional: usize) -> Result<(), WasmRuntimeErrorKind> {
let vec = self.0.get_mut();
let old_size = vec.len();
let new_size = old_size
.checked_add(additional)
.ok_or(WasmRuntimeErrorKind::InvalidParameter)?;
if vec.try_reserve(additional).is_err() {
return Err(WasmRuntimeErrorKind::OutOfMemory);
}
vec.resize(new_size, 0);
Ok(())
}
#[inline]
pub fn fill(&self, value: u8) {
self.as_mut_slice().fill(value);
}
#[cfg(test)]
pub(crate) fn read_i32(&self, offset: usize) -> i32 {
self.read_u32(offset) as i32
}
#[cfg(test)]
pub(crate) fn read_u32(&self, offset: usize) -> u32 {
let slice = &self.as_slice()[offset..offset + 4].try_into().unwrap();
u32::from_le_bytes(*slice)
}
#[cfg(test)]
pub(crate) fn read_f32(&self, offset: usize) -> f32 {
let slice = &self.as_slice()[offset..offset + 4].try_into().unwrap();
f32::from_le_bytes(*slice)
}
#[cfg(test)]
pub(crate) fn read_i64(&self, offset: usize) -> i64 {
self.read_u64(offset) as i64
}
#[cfg(test)]
pub(crate) fn read_u64(&self, offset: usize) -> u64 {
let slice = &self.as_slice()[offset..offset + 8].try_into().unwrap();
u64::from_le_bytes(*slice)
}
#[cfg(test)]
pub(crate) fn read_f64(&self, offset: usize) -> f64 {
let slice = &self.as_slice()[offset..offset + 8].try_into().unwrap();
f64::from_le_bytes(*slice)
}
}
impl Deref for SharedDataStore {
type Target = [u8];
#[inline]
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl DerefMut for SharedDataStore {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
self.as_mut_slice()
}
}
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct WasmPtr<T> {
repr: u32,
_phantom: PhantomData<*const T>,
}
impl<T> WasmPtr<T> {
#[inline]
pub const fn from_u32(value: u32) -> Self {
Self {
repr: value,
_phantom: PhantomData,
}
}
#[inline]
pub const fn as_u32(&self) -> u32 {
self.repr
}
#[inline]
pub const fn as_usize(&self) -> usize {
self.repr as usize
}
}
impl<T> From<WasmPtr<T>> for WasmValue {
#[inline]
fn from(value: WasmPtr<T>) -> Self {
WasmValue::I32(value.repr as i32)
}
}
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct WasmPtrMut<T> {
repr: u32,
_phantom: PhantomData<*mut T>,
}
impl<T> WasmPtrMut<T> {
#[inline]
pub const fn from_u32(value: u32) -> Self {
Self {
repr: value,
_phantom: PhantomData,
}
}
#[inline]
pub const fn as_u32(&self) -> u32 {
self.repr
}
#[inline]
pub const fn as_usize(&self) -> usize {
self.repr as usize
}
}
impl<T> From<WasmPtrMut<T>> for WasmPtr<T> {
#[inline]
fn from(value: WasmPtrMut<T>) -> Self {
Self {
repr: value.repr,
_phantom: PhantomData,
}
}
}
impl<T> From<WasmPtrMut<T>> for WasmValue {
#[inline]
fn from(value: WasmPtrMut<T>) -> Self {
WasmValue::I32(value.repr as i32)
}
}