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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
use crate::{
types::{TrapCode, UntypedValue},
ExternRef, FuncRef, I64ValueSplit, Value, F32, F64, N_DEFAULT_STACK_SIZE, N_MAX_STACK_SIZE,
};
use alloc::vec::Vec;
use core::fmt::Debug;
use smallvec::{smallvec, SmallVec};
use wasmparser::ValType;
/// The value stack used to execute Wasm bytecode.
///
/// # Note
///
/// The [`ValueStack`] implementation heavily relies on the prior
/// validation of the executed Wasm bytecode for correct execution.
#[derive(Clone)]
pub struct ValueStack {
/// All currently live stack entries.
entries: SmallVec<[UntypedValue; N_DEFAULT_STACK_SIZE]>,
/// Index of the first free place in the stack.
stack_ptr: usize,
/// The maximum value stack height.
///
/// # Note
///
/// Extending the value stack beyond this limit during execution
/// will cause a stack overflow trap.
maximum_len: usize,
/// The maximum stack height
max_stack_height: usize,
/// Sticky flag raised once an operation tried to address a cell outside the value stack.
///
/// # Note
///
/// The flag travels with the [`ValueStackPtr`] handed out by [`ValueStack::stack_ptr`] and
/// comes back through [`ValueStack::sync_stack_ptr`], so the interpreter observes it no
/// matter how often it re-derives its stack pointer.
out_of_bounds: bool,
}
impl Debug for ValueStack {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ValueStack")
.field("stack_ptr", &self.stack_ptr)
.field("entries", &&self.entries[..self.stack_ptr])
.finish()
}
}
impl PartialEq for ValueStack {
fn eq(&self, other: &Self) -> bool {
self.stack_ptr == other.stack_ptr
&& self.entries[..self.stack_ptr] == other.entries[..other.stack_ptr]
}
}
impl Eq for ValueStack {}
impl Extend<UntypedValue> for ValueStack {
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = UntypedValue>,
{
for item in iter {
self.push(item)
}
}
}
impl Default for ValueStack {
fn default() -> Self {
Self::new(N_DEFAULT_STACK_SIZE, N_MAX_STACK_SIZE)
}
}
impl ValueStack {
/// Creates an empty [`ValueStack`] that does not allocate heap memor.
///
/// # Note
///
/// This is required for resumable functions to replace their
/// proper stack with an inexpensive fake one.
pub fn empty() -> Self {
Self {
entries: SmallVec::new(),
stack_ptr: 0,
maximum_len: 0,
max_stack_height: 0,
out_of_bounds: false,
}
}
/// Returns `true` if some operation tried to address a cell outside the value stack.
///
/// # Note
///
/// The offending access was suppressed, so this only reports that the executed bytecode is
/// invalid and that execution has to be aborted with [`TrapCode::StackOverflow`].
pub fn is_out_of_bounds(&self) -> bool {
self.out_of_bounds
}
pub fn max_stack_height(&self) -> usize {
self.max_stack_height
}
/// Returns the current [`ValueStackPtr`] of `self`.
///
/// The returned [`ValueStackPtr`] points to the top most value on the [`ValueStack`].
#[inline]
pub fn stack_ptr(&mut self) -> ValueStackPtr {
self.base_ptr().into_add(self.stack_ptr)
}
/// Calculates the length of the stack from a given stack pointer.
pub fn stack_len(&mut self, sp: ValueStackPtr) -> usize {
sp.offset_from(self.base_ptr()) as usize
}
/// Checks if the stack has overflowed based on the provided stack pointer.
pub fn has_stack_overflowed(&mut self, sp: ValueStackPtr) -> bool {
self.stack_len(sp) > self.maximum_len
}
/// Returns a slice of `UntypedValue` starting from the base pointer up to the given
/// `ValueStackPtr` (exclusive).
pub fn as_slice(&mut self) -> &mut [UntypedValue] {
&mut self.entries[0..self.stack_ptr]
}
/// Dumps a portion of the value stack into a `Vec<UntypedValue>`.
pub fn dump_stack(&mut self) -> Vec<UntypedValue> {
debug_assert!(
self.stack_ptr <= self.capacity(),
"stack_ptr={}, capacity={}",
self.stack_ptr,
self.capacity()
);
let len = self.stack_ptr.min(self.capacity());
self.entries[..len].to_vec()
}
/// Returns the base [`ValueStackPtr`] of `self`.
///
/// The returned [`ValueStackPtr`] points to the first value on the [`ValueStack`].
#[inline]
fn base_ptr(&mut self) -> ValueStackPtr {
let capacity = self.entries.len();
let mut base = ValueStackPtr::new(self.entries.as_mut_ptr(), capacity);
if self.out_of_bounds {
base.mark_out_of_bounds();
}
base
}
/// Synchronizes [`ValueStack`] with the new [`ValueStackPtr`].
#[inline]
pub fn sync_stack_ptr(&mut self, new_sp: ValueStackPtr) {
let offset = new_sp.offset_from(self.base_ptr());
debug_assert!(offset >= 0, "stack underflow: {}", offset);
self.out_of_bounds |= new_sp.is_out_of_bounds();
self.stack_ptr = offset.max(0) as usize;
#[cfg(debug_assertions)]
if self.stack_ptr > self.max_stack_height {
self.max_stack_height = self.stack_ptr;
}
}
#[cfg(debug_assertions)]
pub(crate) fn check_max_stack_height(&mut self, sp: ValueStackPtr) {
let offset = sp.offset_from(self.base_ptr());
debug_assert!(offset >= 0, "stack underflow: {}", offset);
if offset as usize > self.max_stack_height {
self.max_stack_height = offset as usize;
}
}
/// Returns `true` if the [`ValueStack`] is empty.
pub fn is_empty(&self) -> bool {
self.stack_ptr == 0
}
/// Creates a new empty [`ValueStack`].
///
/// # Panics
///
/// - If the `initial_len` is zero.
/// - If the `initial_len` is greater than `maximum_len`.
pub fn new(initial_len: usize, maximum_len: usize) -> Self {
assert!(
initial_len > 0,
"cannot initialize the value stack with zero length",
);
assert!(
initial_len <= maximum_len,
"the initial value stack length is greater than the maximum value stack length",
);
let entries = smallvec![UntypedValue::default(); initial_len];
Self {
entries,
stack_ptr: 0,
maximum_len,
max_stack_height: 0,
out_of_bounds: false,
}
}
/// Drops the last `depth` values on the [`ValueStack`].
#[inline]
pub fn drop(&mut self, depth: usize) {
match self.stack_ptr.checked_sub(depth) {
Some(stack_ptr) => self.stack_ptr = stack_ptr,
None => {
self.stack_ptr = 0;
self.out_of_bounds = true;
}
}
}
/// 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(&mut self, entry: UntypedValue) {
let Some(cell) = self.entries.get_mut(self.stack_ptr) else {
self.out_of_bounds = true;
return;
};
*cell = entry;
self.stack_ptr += 1;
#[cfg(test)]
if self.stack_ptr > self.max_stack_height {
self.max_stack_height = self.stack_ptr;
}
}
#[inline]
pub fn pop(&mut self) -> UntypedValue {
let entry = self
.stack_ptr
.checked_sub(1)
.and_then(|index| self.entries.get(index).copied());
match entry {
Some(entry) => {
self.stack_ptr -= 1;
entry
}
None => {
self.out_of_bounds = true;
UntypedValue::default()
}
}
}
/// Returns the capacity of the [`ValueStack`].
pub(crate) fn capacity(&self) -> usize {
self.entries.len()
}
/// Returns the current length of the [`ValueStack`].
pub(crate) fn len(&self) -> usize {
self.stack_ptr
}
/// Reserves enough space for `additional` entries in the [`ValueStack`].
///
/// # Note
///
/// This allows efficiently operating on the [`ValueStack`] through
/// [`ValueStackPtr`], which requires external resource management.
///
/// Before executing a function, the interpreter calls this function
/// to guarantee that enough space on the [`ValueStack`] exists for
/// the correct execution to occur.
/// For this to be working, we need a stack-depth analysis during Wasm
/// compilation so that we are aware of all stack-depths for every
/// function.
pub fn reserve(&mut self, additional: usize) -> Result<(), TrapCode> {
let new_len = self
.len()
.checked_add(additional)
.filter(|&new_len| new_len <= self.maximum_len)
.ok_or(TrapCode::StackOverflow)?;
if new_len > self.capacity() {
// Note: By extending the new length, we effectively double
// the current value stack length and add the additional flat amount
// on top. This avoids too many frequent reallocations.
self.entries
.extend(core::iter::repeat_n(UntypedValue::default(), new_len));
}
Ok(())
}
/// Extends the value stack by the `additional` number of zeros.
///
/// # Errors
///
/// If the value stack cannot fit `additional` stack values.
pub fn extend_zeros(&mut self, additional: usize) {
let cells = self
.entries
.get_mut(self.stack_ptr..)
.and_then(|slice| slice.get_mut(..additional))
.unwrap_or_else(|| panic!("did not reserve enough value stack space"));
cells.fill(UntypedValue::default());
self.stack_ptr += additional;
#[cfg(test)]
if self.stack_ptr > self.max_stack_height {
self.max_stack_height = self.stack_ptr;
}
}
/// Drains the remaining value stack.
///
/// # Note
///
/// This API is mostly used when writing results back to the
/// caller after function execution has finished.
#[inline]
pub fn drain(&mut self) -> &[UntypedValue] {
let len = self.stack_ptr;
self.stack_ptr = 0;
&self.entries[0..len]
}
/// Returns an exclusive slice to the last `depth` entries in the value stack.
#[inline]
pub fn peek_as_slice_mut(&mut self, depth: usize) -> &mut [UntypedValue] {
let Some(start) = self.stack_ptr.checked_sub(depth) else {
self.out_of_bounds = true;
return &mut [];
};
let end = self.stack_ptr;
&mut self.entries[start..end]
}
/// Clears the [`ValueStack`] entirely.
///
/// # Note
///
/// This is required since sometimes execution can halt in the middle of
/// function execution which leaves the [`ValueStack`] in an unspecified
/// state.
/// Therefore, the [`ValueStack`] is required to be reset before
/// function execution happens.
pub fn reset(&mut self) {
self.stack_ptr = 0;
self.max_stack_height = 0;
self.out_of_bounds = false;
}
}
/// A pointer on the [`ValueStack`].
///
/// Allows for efficient mutable access to the values of the [`ValueStack`].
///
/// # Note
///
/// Every operation is bounds-checked against the `[src, end)` window of the underlying
/// [`ValueStack`] in **all** build profiles. Bytecode reaching outside that window neither reads
/// nor writes memory: the pointer is parked on the stack base and [`ValueStackPtr::
/// is_out_of_bounds`] starts reporting `true`, which the interpreter turns into a
/// [`TrapCode::StackOverflow`] before the next instruction runs. Relying on the translator to only
/// emit valid stack offsets is not enough here, because [`RwasmModule::new_verified`] exists to
/// accept bytecode this crate did not produce.
///
/// [`ValueStack`]: super::ValueStack
/// [`RwasmModule::new_verified`]: crate::RwasmModule::new_verified
#[derive(Debug, Copy, Clone)]
pub struct ValueStackPtr {
src: *mut UntypedValue,
ptr: *mut UntypedValue,
end: *mut UntypedValue,
out_of_bounds: bool,
}
unsafe impl Send for ValueStackPtr {}
impl ValueStackPtr {
/// Creates a [`ValueStackPtr`] addressing the `capacity` cells starting at `ptr`.
pub fn new(ptr: *mut UntypedValue, capacity: usize) -> ValueStackPtr {
Self {
src: ptr,
ptr,
end: ptr.wrapping_add(capacity),
out_of_bounds: false,
}
}
/// Returns `true` if some operation tried to address a cell outside the value stack.
#[inline]
pub fn is_out_of_bounds(self) -> bool {
self.out_of_bounds
}
/// Records an out-of-bounds access and parks the pointer on the stack base.
///
/// # Note
///
/// Parking keeps every follow-up operation harmless until the interpreter observes the flag
/// and traps.
#[cold]
#[inline]
pub(crate) fn mark_out_of_bounds(&mut self) {
self.out_of_bounds = true;
self.ptr = self.src;
}
/// Returns the number of cells between the stack base and the current pointer.
#[inline]
fn len(self) -> usize {
(self.ptr as usize - self.src as usize) / size_of::<UntypedValue>()
}
/// Returns the number of cells between the current pointer and the end of the stack.
#[inline]
fn spare(self) -> usize {
(self.end as usize - self.ptr as usize) / size_of::<UntypedValue>()
}
/// Returns the cell `depth` entries below the current pointer if it is addressable.
#[inline]
fn cell_back(&mut self, depth: usize) -> Option<*mut UntypedValue> {
if depth == 0 || depth > self.len() {
self.mark_out_of_bounds();
return None;
}
Some(self.ptr.wrapping_sub(depth))
}
/// Calculates the distance between two [`ValueStackPtr] in units of [`UntypedValue`].
#[inline]
pub fn offset_from(self, other: Self) -> isize {
let distance = self.ptr as isize - other.ptr as isize;
distance / size_of::<UntypedValue>() as isize
}
/// Returns the [`UntypedValue`] at the current stack pointer.
#[must_use]
#[inline]
fn get(&mut self) -> UntypedValue {
if self.ptr >= self.end {
self.mark_out_of_bounds();
return UntypedValue::default();
}
// SAFETY: the check above proves that `ptr` addresses a live cell of the value stack.
unsafe { *self.ptr }
}
/// Writes `value` to the cell pointed at by [`ValueStackPtr`].
#[inline]
fn set(&mut self, value: UntypedValue) {
if self.ptr >= self.end {
self.mark_out_of_bounds();
return;
}
// SAFETY: the check above proves that `ptr` addresses a live cell of the value stack.
unsafe { *self.ptr = value };
}
/// Returns a [`ValueStackPtr`] with a pointer value increased by `delta`.
///
/// # Note
///
/// The amount of `delta` is in the number of bytes per [`UntypedValue`].
#[must_use]
#[inline]
pub fn into_add(mut self, delta: usize) -> Self {
self.inc_by(delta);
self
}
/// Returns a [`ValueStackPtr`] with a pointer value decreased by `delta`.
///
/// # Note
///
/// The amount of `delta` is in the number of bytes per [`UntypedValue`].
#[must_use]
#[inline]
pub fn into_sub(mut self, delta: usize) -> Self {
self.dec_by(delta);
self
}
/// Returns the last [`UntypedValue`] on the [`ValueStack`].
///
/// # Note
///
/// This has the same effect as [`ValueStackPtr::nth_back`]`(1)`.
///
/// [`ValueStack`]: super::ValueStack
#[inline]
#[must_use]
pub fn last(&mut self) -> UntypedValue {
self.nth_back(1)
}
/// Peeks the entry at the given depth from the last entry.
///
/// # Note
///
/// Given a `depth` of 1 has the same effect as [`ValueStackPtr::last`].
///
/// A `depth` of 0, or a depth reaching below the stack base, marks the pointer as out of
/// bounds and yields a default value instead of reading memory.
#[inline]
#[must_use]
pub fn nth_back(&mut self, depth: usize) -> UntypedValue {
match self.cell_back(depth) {
// SAFETY: `cell_back` only yields pointers to live cells of the value stack.
Some(cell) => unsafe { *cell },
None => UntypedValue::default(),
}
}
/// Writes `value` to the n-th [`UntypedValue`] from the back.
///
/// # Note
///
/// Given a `depth` of 1 has the same effect as mutating [`ValueStackPtr::last`].
///
/// A `depth` of 0, or a depth reaching below the stack base, marks the pointer as out of
/// bounds and discards the write.
#[inline]
pub fn set_nth_back(&mut self, depth: usize, value: UntypedValue) {
// SAFETY: `cell_back` only yields pointers to live cells of the value stack.
if let Some(cell) = self.cell_back(depth) {
unsafe { *cell = value }
}
}
/// Bumps the [`ValueStackPtr`] of `self` by `delta`.
#[inline]
fn inc_by(&mut self, delta: usize) {
if delta > self.spare() {
self.mark_out_of_bounds();
return;
}
self.ptr = self.ptr.wrapping_add(delta);
}
/// Decreases the [`ValueStackPtr`] of `self` by `delta`.
#[inline]
fn dec_by(&mut self, delta: usize) {
if delta > self.len() {
self.mark_out_of_bounds();
return;
}
self.ptr = self.ptr.wrapping_sub(delta);
}
/// convert stack pointer to the address number
#[cfg(feature = "tracing")]
pub fn to_relative_address(&self) -> u32 {
let offset = (self.ptr as usize)
.checked_sub(self.src as usize)
.unwrap_or_else(|| unreachable!("stack pointer is below stack base"));
let offset = offset / size_of::<UntypedValue>();
let offset = (offset as u32)
.checked_mul(crate::mem_index::UNIT)
.unwrap_or_else(|| unreachable!("stack pointer offset exceeds u32"));
crate::mem_index::SP_START
.checked_sub(offset)
.unwrap_or_else(|| unreachable!("stack pointer exceeds trace stack range"))
}
/// Pushes the `T` 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.
///
/// [`ValueStack`]: super::ValueStack
#[inline]
pub fn push_as<T>(&mut self, value: T)
where
T: Into<UntypedValue>,
{
self.push(value.into())
}
/// 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.
///
/// [`ValueStack`]: super::ValueStack
#[inline]
pub fn push(&mut self, value: UntypedValue) {
self.set(value);
self.inc_by(1);
}
/// Drops the last [`UntypedValue`] from the [`ValueStack`].
///
/// # Note
///
/// This operation heavily relies on the prior validation of
/// the executed WebAssembly bytecode for correctness.
///
/// [`ValueStack`]: super::ValueStack
#[inline]
#[allow(clippy::should_implement_trait)]
pub fn drop(&mut self) {
self.dec_by(1);
}
#[inline]
pub fn drop_n(&mut self, n: usize) {
self.dec_by(n);
}
/// Pops the last [`UntypedValue`] from the [`ValueStack`] as `T`.
///
/// [`ValueStack`]: super::ValueStack
#[inline]
pub fn pop_as<T>(&mut self) -> T
where
T: From<UntypedValue>,
{
T::from(self.pop())
}
/// Pops the last [`UntypedValue`] from the [`ValueStack`].
///
/// # Note
///
/// This operation heavily relies on the prior validation of
/// the executed WebAssembly bytecode for correctness.
///
/// [`ValueStack`]: super::ValueStack
#[inline]
pub fn pop(&mut self) -> UntypedValue {
self.dec_by(1);
self.get()
}
/// Pops the last pair of [`UntypedValue`] from the [`ValueStack`].
///
/// # Note
///
/// This operation heavily relies on the prior validation of
/// the executed WebAssembly bytecode for correctness.
///
/// [`ValueStack`]: super::ValueStack
#[inline]
pub fn pop2(&mut self) -> (UntypedValue, UntypedValue) {
let rhs = self.pop();
let lhs = self.pop();
(lhs, rhs)
}
/// Pops the last triple of [`UntypedValue`] from the [`ValueStack`].
///
/// # Note
///
/// This operation heavily relies on the prior validation of
/// the executed WebAssembly bytecode for correctness.
///
/// [`ValueStack`]: super::ValueStack
#[inline]
pub fn pop3(&mut self) -> (UntypedValue, UntypedValue, UntypedValue) {
let (snd, trd) = self.pop2();
let fst = self.pop();
(fst, snd, trd)
}
/// 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 last = self.nth_back(1);
self.set_nth_back(1, f(last))
}
/// 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.nth_back(1);
self.set_nth_back(1, f(lhs, rhs));
}
/// 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.nth_back(1);
self.set_nth_back(1, f(e1, e2, e3));
}
/// 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 last = self.nth_back(1);
self.set_nth_back(1, f(last)?);
Ok(())
}
/// 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.nth_back(1);
self.set_nth_back(1, f(lhs, rhs)?);
Ok(())
}
pub fn push_f32(&mut self, value: F32) {
self.push(value.into());
}
pub fn pop_f32(&mut self) -> F32 {
self.pop().as_f32()
}
pub fn push_f64(&mut self, value: F64) {
let bits = value.to_bits();
let lo = bits as i32;
self.push(lo.into());
let hi = (bits >> 32) as i32;
self.push(hi.into());
}
pub fn pop_f64(&mut self) -> F64 {
let (lo, hi) = self.pop2();
F64::from_bits(((hi.as_u64()) << 32) | (lo.as_u64()))
}
pub fn push_value(&mut self, value: &Value) {
match value {
Value::I32(value) => self.push_i32(*value),
Value::I64(value) => self.push_i64(*value),
Value::F32(value) => self.push_f32(*value),
Value::F64(value) => self.push_f64(*value),
Value::FuncRef(value) => self.push_i32(value.0 as i32),
Value::ExternRef(value) => self.push_i32(value.0 as i32),
}
}
pub fn push_i32(&mut self, value: i32) {
self.push(value.into());
}
pub fn pop_value(&mut self, value_type: ValType) -> Value {
match value_type {
ValType::I32 => Value::I32(self.pop_i32()),
ValType::I64 => Value::I64(self.pop_i64()),
ValType::F32 => Value::F32(self.pop_f32()),
ValType::F64 => Value::F64(self.pop_f64()),
ValType::V128 => unreachable!("can't invoke syscall with v128"),
ValType::FuncRef => Value::FuncRef(FuncRef::new(self.pop_i32() as u32)),
ValType::ExternRef => Value::ExternRef(ExternRef::new(self.pop_i32() as u32)),
}
}
pub fn pop_i32(&mut self) -> i32 {
self.pop().as_i32()
}
pub fn push_i64(&mut self, value: i64) {
let (lo, hi) = value.split_into_i32_tuple();
self.push(lo.into());
self.push(hi.into());
}
pub fn pop_i64(&mut self) -> i64 {
let (lo, hi) = self.pop2();
(hi.as_i64() << 32) | lo.as_i64()
}
}