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
use super::ValueStack;
use crate::{
core::{TrapCode, UntypedValue},
engine::DropKeep,
};
use core::fmt;
/// A mutable view over the [`ValueStack`].
///
/// This allows for a more efficient access to the [`ValueStack`] during execution.
pub struct ValueStackRef<'a> {
pub(super) stack_ptr: usize,
pub(super) values: &'a mut [UntypedValue],
/// The original stack pointer required to keep in sync.
orig_sp: &'a mut usize,
}
impl<'a> fmt::Debug for ValueStackRef<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", &self.values[0..self.stack_ptr])
}
}
impl<'a> ValueStackRef<'a> {
/// Creates a new [`ValueStackRef`] from the given [`ValueStack`].
///
/// This also returns an exclusive reference to the stack pointer of
/// the underlying [`ValueStack`]. This is important in order to synchronize
/// the [`ValueStack`] with the changes done to the [`ValueStackRef`]
/// when necessary.
pub fn new(stack: &'a mut ValueStack) -> Self {
let sp = &mut stack.stack_ptr;
let stack_ptr = *sp;
Self {
stack_ptr,
values: &mut stack.entries[..],
orig_sp: sp,
}
}
/// Synchronizes the original value stack pointer.
pub fn sync(&mut self) {
*self.orig_sp = self.stack_ptr;
}
/// Returns the current capacity of the underlying [`ValueStack`].
fn capacity(&self) -> usize {
self.values.len()
}
/// Returns the [`UntypedValue`] at the given `index`.
///
/// # Note
///
/// This is an optimized convenience method that only asserts
/// that the index is within bounds in `debug` mode.
///
/// # Safety
///
/// This is safe since all wasmi bytecode has been validated
/// during translation and therefore cannot result in out of
/// bounds accesses.
///
/// # Panics (Debug)
///
/// If the `index` is out of bounds.
fn get_release_unchecked(&self, index: usize) -> UntypedValue {
debug_assert!(index < self.capacity());
// Safety: This is safe since all wasmi bytecode has been validated
// during translation and therefore cannot result in out of
// bounds accesses.
unsafe { *self.values.get_unchecked(index) }
}
/// Returns the [`UntypedValue`] at the given `index`.
///
/// # Note
///
/// This is an optimized convenience method that only asserts
/// that the index is within bounds in `debug` mode.
///
/// # Safety
///
/// This is safe since all wasmi bytecode has been validated
/// during translation and therefore cannot result in out of
/// bounds accesses.
///
/// # Panics (Debug)
///
/// If the `index` is out of bounds.
fn get_release_unchecked_mut(&mut self, index: usize) -> &mut UntypedValue {
debug_assert!(index < self.capacity());
// Safety: This is safe since all wasmi bytecode has been validated
// during translation and therefore cannot result in out of
// bounds accesses.
unsafe { self.values.get_unchecked_mut(index) }
}
/// Drops some amount of entries and keeps some amount of them at the new top.
///
/// # Note
///
/// For an amount of entries to keep `k` and an amount of entries to drop `d`
/// this has the following effect on stack `s` and stack pointer `sp`.
///
/// 1) Copy `k` elements from indices starting at `sp - k` to `sp - k - d`.
/// 2) Adjust stack pointer: `sp -= d`
///
/// After this operation the value stack will have `d` fewer entries and the
/// top `k` entries are the top `k` entries before this operation.
///
/// Note that `k + d` cannot be greater than the stack length.
pub fn drop_keep(&mut self, drop_keep: DropKeep) {
let drop = drop_keep.drop();
if drop == 0 {
// Nothing to do in this case.
return;
}
let keep = drop_keep.keep();
if keep == 0 {
// Bail out early when there are no values to keep.
} else if keep == 1 {
// Bail out early when there is only one value to copy.
*self.get_release_unchecked_mut(self.stack_ptr - 1 - drop) =
self.get_release_unchecked(self.stack_ptr - 1);
} else {
// Copy kept values over to their new place on the stack.
// Note: We cannot use `memcpy` since the slices may overlap.
let src = self.stack_ptr - keep;
let dst = self.stack_ptr - keep - drop;
for i in 0..keep {
*self.get_release_unchecked_mut(dst + i) = self.get_release_unchecked(src + i);
}
}
self.stack_ptr -= drop;
}
/// Returns the last stack entry of the [`ValueStackRef`].
///
/// # Note
///
/// This has the same effect as [`ValueStackRef::peek`]`(1)`.
#[inline]
pub fn last(&self) -> UntypedValue {
self.get_release_unchecked(self.stack_ptr - 1)
}
/// Returns the last stack entry of the [`ValueStack`].
///
/// # Note
///
/// This has the same effect as [`ValueStackRef::peek`]`(1)`.
#[inline]
pub fn last_mut(&mut self) -> &mut UntypedValue {
self.get_release_unchecked_mut(self.stack_ptr - 1)
}
/// Peeks the entry at the given depth from the last entry.
///
/// # Note
///
/// Given a `depth` of 1 has the same effect as [`ValueStackRef::last`].
///
/// A `depth` of 0 is invalid and undefined.
#[inline]
pub fn peek(&self, depth: usize) -> UntypedValue {
self.get_release_unchecked(self.stack_ptr - depth)
}
/// Peeks the `&mut` entry at the given depth from the last entry.
///
/// # Note
///
/// Given a `depth` of 1 has the same effect as [`ValueStackRef::last_mut`].
///
/// A `depth` of 0 is invalid and undefined.
#[inline]
pub fn peek_mut(&mut self, depth: usize) -> &mut UntypedValue {
self.get_release_unchecked_mut(self.stack_ptr - depth)
}
/// Pops the last [`UntypedValue`] from the [`ValueStack`].
///
/// # Note
///
/// This operation heavily relies on the prior validation of
/// the executed WebAssembly bytecode for correctness.
#[inline]
pub fn pop(&mut self) -> UntypedValue {
self.stack_ptr -= 1;
self.get_release_unchecked(self.stack_ptr)
}
/// Pops the last [`UntypedValue`] from the [`ValueStack`] as `T`.
#[inline]
pub fn pop_as<T>(&mut self) -> T
where
T: From<UntypedValue>,
{
T::from(self.pop())
}
/// Pops the last pair of [`UntypedValue`] from the [`ValueStack`].
///
/// # Note
///
/// - This operation is slightly more efficient than using
/// [`ValueStackRef::pop`] twice.
/// - This operation heavily relies on the prior validation of
/// the executed WebAssembly bytecode for correctness.
#[inline]
pub fn pop2(&mut self) -> (UntypedValue, UntypedValue) {
self.stack_ptr -= 2;
(
self.get_release_unchecked(self.stack_ptr),
self.get_release_unchecked(self.stack_ptr + 1),
)
}
/// Pops the last triple of [`UntypedValue`] from the [`ValueStack`].
///
/// # Note
///
/// - This operation is slightly more efficient than using
/// [`ValueStackRef::pop`] trice.
/// - This operation heavily relies on the prior validation of
/// the executed WebAssembly bytecode for correctness.
#[inline]
pub fn pop3(&mut self) -> (UntypedValue, UntypedValue, UntypedValue) {
self.stack_ptr -= 3;
(
self.get_release_unchecked(self.stack_ptr),
self.get_release_unchecked(self.stack_ptr + 1),
self.get_release_unchecked(self.stack_ptr + 2),
)
}
/// Evaluates the given closure `f` for the 3 top most stack values.
#[inline]
pub fn eval_top3<F>(&mut self, f: F)
where
F: FnOnce(UntypedValue, UntypedValue, UntypedValue) -> UntypedValue,
{
let (e2, e3) = self.pop2();
let e1 = self.last();
*self.last_mut() = f(e1, e2, e3)
}
/// Evaluates the given closure `f` for the top most stack value.
#[inline]
pub fn eval_top<F>(&mut self, f: F)
where
F: FnOnce(UntypedValue) -> UntypedValue,
{
let top = self.last();
*self.last_mut() = f(top);
}
/// Evaluates the given fallible closure `f` for the top most stack value.
///
/// # Errors
///
/// If the closure execution fails.
#[inline]
pub fn try_eval_top<F>(&mut self, f: F) -> Result<(), TrapCode>
where
F: FnOnce(UntypedValue) -> Result<UntypedValue, TrapCode>,
{
let top = self.last();
*self.last_mut() = f(top)?;
Ok(())
}
/// Evaluates the given closure `f` for the 2 top most stack values.
#[inline]
pub fn eval_top2<F>(&mut self, f: F)
where
F: FnOnce(UntypedValue, UntypedValue) -> UntypedValue,
{
let rhs = self.pop();
let lhs = self.last();
*self.last_mut() = f(lhs, rhs);
}
/// Evaluates the given fallible closure `f` for the 2 top most stack values.
///
/// # Errors
///
/// If the closure execution fails.
#[inline]
pub fn try_eval_top2<F>(&mut self, f: F) -> Result<(), TrapCode>
where
F: FnOnce(UntypedValue, UntypedValue) -> Result<UntypedValue, TrapCode>,
{
let rhs = self.pop();
let lhs = self.last();
*self.last_mut() = f(lhs, rhs)?;
Ok(())
}
/// Pushes the [`UntypedValue`] to the end of the [`ValueStack`].
///
/// # Note
///
/// - This operation heavily relies on the prior validation of
/// the executed WebAssembly bytecode for correctness.
/// - Especially the stack-depth analysis during compilation with
/// a manual stack extension before function call prevents this
/// procedure from panicking.
#[inline]
pub fn push<T>(&mut self, entry: T)
where
T: Into<UntypedValue>,
{
*self.get_release_unchecked_mut(self.stack_ptr) = entry.into();
self.stack_ptr += 1;
}
}