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 806 807 808 809 810 811 812 813 814 815 816 817
//! The `wasmi` interpreter.
pub mod bytecode;
mod cache;
pub mod code_map;
mod config;
mod const_pool;
pub mod executor;
mod func_args;
mod func_builder;
mod func_types;
mod resumable;
pub mod stack;
mod traits;
#[cfg(test)]
mod tests;
pub use self::{
bytecode::DropKeep,
code_map::CompiledFunc,
config::{Config, FuelConsumptionMode, FuelCosts},
func_builder::{
FuncBuilder,
FuncTranslatorAllocations,
Instr,
RelativeDepth,
TranslationError,
},
resumable::{ResumableCall, ResumableInvocation, TypedResumableCall, TypedResumableInvocation},
stack::StackLimits,
traits::{CallParams, CallResults},
};
use self::{
bytecode::Instruction,
cache::InstanceCache,
code_map::CodeMap,
const_pool::{ConstPool, ConstPoolView, ConstRef},
executor::{execute_wasm, WasmOutcome},
func_types::FuncTypeRegistry,
resumable::ResumableCallBase,
stack::{FuncFrame, Stack, ValueStack},
};
pub(crate) use self::{
func_args::{FuncFinished, FuncParams, FuncResults},
func_types::DedupFuncType,
};
use crate::{
core::{Trap, TrapCode},
func::FuncEntity,
AsContext,
AsContextMut,
Func,
FuncType,
StoreContextMut,
};
use alloc::{sync::Arc, vec::Vec};
use core::sync::atomic::{AtomicU32, Ordering};
use spin::{Mutex, RwLock};
use wasmi_arena::{ArenaIndex, GuardedEntity};
use wasmi_core::UntypedValue;
/// A unique engine index.
///
/// # Note
///
/// Used to protect against invalid entity indices.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct EngineIdx(u32);
impl ArenaIndex for EngineIdx {
fn into_usize(self) -> usize {
self.0 as _
}
fn from_usize(value: usize) -> Self {
let value = value.try_into().unwrap_or_else(|error| {
panic!("index {value} is out of bounds as engine index: {error}")
});
Self(value)
}
}
impl EngineIdx {
/// Returns a new unique [`EngineIdx`].
fn new() -> Self {
/// A static store index counter.
static CURRENT_STORE_IDX: AtomicU32 = AtomicU32::new(0);
let next_idx = CURRENT_STORE_IDX.fetch_add(1, Ordering::AcqRel);
Self(next_idx)
}
}
/// An entity owned by the [`Engine`].
type Guarded<Idx> = GuardedEntity<EngineIdx, Idx>;
/// The `wasmi` interpreter.
///
/// # Note
///
/// - The current `wasmi` engine implements a bytecode interpreter.
/// - This structure is intentionally cheap to copy.
/// Most of its API has a `&self` receiver, so can be shared easily.
#[derive(Debug, Clone)]
pub struct Engine {
inner: Arc<EngineInner>,
}
impl Default for Engine {
fn default() -> Self {
Self::new(&Config::default())
}
}
impl Engine {
/// Creates a new [`Engine`] with default configuration.
///
/// # Note
///
/// Users should ues [`Engine::default`] to construct a default [`Engine`].
pub fn new(config: &Config) -> Self {
Self {
inner: Arc::new(EngineInner::new(config)),
}
}
/// Returns a shared reference to the [`Config`] of the [`Engine`].
pub fn config(&self) -> &Config {
self.inner.config()
}
/// Returns `true` if both [`Engine`] references `a` and `b` refer to the same [`Engine`].
pub fn same(a: &Engine, b: &Engine) -> bool {
Arc::ptr_eq(&a.inner, &b.inner)
}
/// Allocates a new function type to the [`Engine`].
pub(super) fn alloc_func_type(&self, func_type: FuncType) -> DedupFuncType {
self.inner.alloc_func_type(func_type)
}
/// Allocates a new constant value to the [`Engine`].
///
/// # Errors
///
/// If too many constant values have been allocated for the [`Engine`] this way.
pub(super) fn alloc_const(&self, value: UntypedValue) -> Result<ConstRef, TranslationError> {
self.inner.alloc_const(value)
}
/// Resolves a deduplicated function type into a [`FuncType`] entity.
///
/// # Panics
///
/// - If the deduplicated function type is not owned by the engine.
/// - If the deduplicated function type cannot be resolved to its entity.
pub(super) fn resolve_func_type<F, R>(&self, func_type: &DedupFuncType, f: F) -> R
where
F: FnOnce(&FuncType) -> R,
{
self.inner.resolve_func_type(func_type, f)
}
/// Allocates a new uninitialized [`CompiledFunc`] to the [`Engine`].
///
/// Returns a [`CompiledFunc`] reference to allow accessing the allocated [`CompiledFunc`].
pub(super) fn alloc_func(&self) -> CompiledFunc {
self.inner.alloc_func()
}
/// Initializes the uninitialized [`CompiledFunc`] for the [`Engine`].
///
/// # Panics
///
/// - If `func` is an invalid [`CompiledFunc`] reference for this [`CodeMap`].
/// - If `func` refers to an already initialized [`CompiledFunc`].
pub(super) fn init_func<I>(
&self,
func: CompiledFunc,
len_locals: usize,
local_stack_height: usize,
instrs: I,
) where
I: IntoIterator<Item = Instruction>,
{
self.inner
.init_func(func, len_locals, local_stack_height, instrs)
}
/// Resolves the [`CompiledFunc`] to the underlying `wasmi` bytecode instructions.
///
/// # Note
///
/// - This API is mainly intended for unit testing purposes and shall not be used
/// outside of this context. The function bodies are intended to be data private
/// to the `wasmi` interpreter.
///
/// # Panics
///
/// If the [`CompiledFunc`] is invalid for the [`Engine`].
#[cfg(test)]
pub(crate) fn resolve_instr(
&self,
func_body: CompiledFunc,
index: usize,
) -> Option<Instruction> {
self.inner.resolve_instr(func_body, index)
}
/// Executes the given [`Func`] with parameters `params`.
///
/// Stores the execution result into `results` upon a successful execution.
///
/// # Note
///
/// - Assumes that the `params` and `results` are well typed.
/// Type checks are done at the [`Func::call`] API or when creating
/// a new [`TypedFunc`] instance via [`Func::typed`].
/// - The `params` out parameter is in a valid but unspecified state if this
/// function returns with an error.
///
/// # Errors
///
/// - If `params` are overflowing or underflowing the expected amount of parameters.
/// - If the given `results` do not match the the length of the expected results of `func`.
/// - When encountering a Wasm or host trap during the execution of `func`.
///
/// [`TypedFunc`]: [`crate::TypedFunc`]
#[inline]
pub(crate) fn execute_func<T, Results>(
&self,
ctx: StoreContextMut<T>,
func: &Func,
params: impl CallParams,
results: Results,
) -> Result<<Results as CallResults>::Results, Trap>
where
Results: CallResults,
{
self.inner.execute_func(ctx, func, params, results)
}
/// Executes the given [`Func`] resumably with parameters `params` and returns.
///
/// Stores the execution result into `results` upon a successful execution.
/// If the execution encounters a host trap it will return a handle to the user
/// that allows to resume the execution at that point.
///
/// # Note
///
/// - Assumes that the `params` and `results` are well typed.
/// Type checks are done at the [`Func::call`] API or when creating
/// a new [`TypedFunc`] instance via [`Func::typed`].
/// - The `params` out parameter is in a valid but unspecified state if this
/// function returns with an error.
///
/// # Errors
///
/// - If `params` are overflowing or underflowing the expected amount of parameters.
/// - If the given `results` do not match the the length of the expected results of `func`.
/// - When encountering a Wasm trap during the execution of `func`.
/// - When `func` is a host function that traps.
///
/// [`TypedFunc`]: [`crate::TypedFunc`]
#[inline]
pub(crate) fn execute_func_resumable<T, Results>(
&self,
ctx: StoreContextMut<T>,
func: &Func,
params: impl CallParams,
results: Results,
) -> Result<ResumableCallBase<<Results as CallResults>::Results>, Trap>
where
Results: CallResults,
{
self.inner
.execute_func_resumable(ctx, func, params, results)
}
/// Resumes the given `invocation` given the `params`.
///
/// Stores the execution result into `results` upon a successful execution.
/// If the execution encounters a host trap it will return a handle to the user
/// that allows to resume the execution at that point.
///
/// # Note
///
/// - Assumes that the `params` and `results` are well typed.
/// Type checks are done at the [`Func::call`] API or when creating
/// a new [`TypedFunc`] instance via [`Func::typed`].
/// - The `params` out parameter is in a valid but unspecified state if this
/// function returns with an error.
///
/// # Errors
///
/// - If `params` are overflowing or underflowing the expected amount of parameters.
/// - If the given `results` do not match the the length of the expected results of `func`.
/// - When encountering a Wasm trap during the execution of `func`.
/// - When `func` is a host function that traps.
///
/// [`TypedFunc`]: [`crate::TypedFunc`]
#[inline]
pub(crate) fn resume_func<T, Results>(
&self,
ctx: StoreContextMut<T>,
invocation: ResumableInvocation,
params: impl CallParams,
results: Results,
) -> Result<ResumableCallBase<<Results as CallResults>::Results>, Trap>
where
Results: CallResults,
{
self.inner.resume_func(ctx, invocation, params, results)
}
/// Recycles the given [`Stack`] for reuse in the [`Engine`].
pub(crate) fn recycle_stack(&self, stack: Stack) {
self.inner.recycle_stack(stack)
}
}
/// The internal state of the `wasmi` [`Engine`].
#[derive(Debug)]
pub struct EngineInner {
/// The [`Config`] of the engine.
config: Config,
/// Engine resources shared across multiple engine executors.
res: RwLock<EngineResources>,
/// Reusable engine stacks for Wasm execution.
///
/// Concurrently executing Wasm executions each require their own stack to
/// operate on. Therefore a Wasm engine is required to provide stacks and
/// ideally recycles old ones since creation of a new stack is rather expensive.
stacks: Mutex<EngineStacks>,
}
/// The engine's stacks for reuse.
///
/// Rquired for efficient concurrent Wasm executions.
#[derive(Debug)]
pub struct EngineStacks {
/// Stacks to be (re)used.
stacks: Vec<Stack>,
/// Stack limits for newly constructed engine stacks.
limits: StackLimits,
/// How many stacks should be kept for reuse at most.
keep: usize,
}
impl EngineStacks {
/// Creates new [`EngineStacks`] with the given [`StackLimits`].
pub fn new(config: &Config) -> Self {
Self {
stacks: Vec::new(),
limits: config.stack_limits(),
keep: config.cached_stacks(),
}
}
/// Reuse or create a new [`Stack`] if none was available.
pub fn reuse_or_new(&mut self) -> Stack {
match self.stacks.pop() {
Some(stack) => stack,
None => Stack::new(self.limits),
}
}
/// Disose and recycle the `stack`.
pub fn recycle(&mut self, stack: Stack) {
if !stack.is_empty() && self.stacks.len() < self.keep {
self.stacks.push(stack);
}
}
}
impl EngineInner {
/// Creates a new [`EngineInner`] with the given [`Config`].
fn new(config: &Config) -> Self {
Self {
config: *config,
res: RwLock::new(EngineResources::new()),
stacks: Mutex::new(EngineStacks::new(config)),
}
}
/// Returns a shared reference to the [`Config`] of the [`EngineInner`].
fn config(&self) -> &Config {
&self.config
}
/// Allocates a new function type to the [`EngineInner`].
fn alloc_func_type(&self, func_type: FuncType) -> DedupFuncType {
self.res.write().func_types.alloc_func_type(func_type)
}
/// Allocates a new constant value to the [`EngineInner`].
///
/// # Errors
///
/// If too many constant values have been allocated for the [`EngineInner`] this way.
fn alloc_const(&self, value: UntypedValue) -> Result<ConstRef, TranslationError> {
self.res.write().const_pool.alloc(value)
}
/// Allocates a new uninitialized [`CompiledFunc`] to the [`EngineInner`].
///
/// Returns a [`CompiledFunc`] reference to allow accessing the allocated [`CompiledFunc`].
fn alloc_func(&self) -> CompiledFunc {
self.res.write().code_map.alloc_func()
}
/// Initializes the uninitialized [`CompiledFunc`] for the [`EngineInner`].
///
/// # Panics
///
/// - If `func` is an invalid [`CompiledFunc`] reference for this [`CodeMap`].
/// - If `func` refers to an already initialized [`CompiledFunc`].
fn init_func<I>(
&self,
func: CompiledFunc,
len_locals: usize,
local_stack_height: usize,
instrs: I,
) where
I: IntoIterator<Item = Instruction>,
{
self.res
.write()
.code_map
.init_func(func, len_locals, local_stack_height, instrs)
}
fn resolve_func_type<F, R>(&self, func_type: &DedupFuncType, f: F) -> R
where
F: FnOnce(&FuncType) -> R,
{
f(self.res.read().func_types.resolve_func_type(func_type))
}
#[cfg(test)]
fn resolve_instr(&self, func_body: CompiledFunc, index: usize) -> Option<Instruction> {
self.res
.read()
.code_map
.get_instr(func_body, index)
.copied()
}
fn execute_func<T, Results>(
&self,
ctx: StoreContextMut<T>,
func: &Func,
params: impl CallParams,
results: Results,
) -> Result<<Results as CallResults>::Results, Trap>
where
Results: CallResults,
{
let res = self.res.read();
let mut stack = self.stacks.lock().reuse_or_new();
let results = EngineExecutor::new(&res, &mut stack)
.execute_func(ctx, func, params, results)
.map_err(TaggedTrap::into_trap);
self.stacks.lock().recycle(stack);
results
}
fn execute_func_resumable<T, Results>(
&self,
mut ctx: StoreContextMut<T>,
func: &Func,
params: impl CallParams,
results: Results,
) -> Result<ResumableCallBase<<Results as CallResults>::Results>, Trap>
where
Results: CallResults,
{
let res = self.res.read();
let mut stack = self.stacks.lock().reuse_or_new();
let results = EngineExecutor::new(&res, &mut stack).execute_func(
ctx.as_context_mut(),
func,
params,
results,
);
match results {
Ok(results) => {
self.stacks.lock().recycle(stack);
Ok(ResumableCallBase::Finished(results))
}
Err(TaggedTrap::Wasm(trap)) => {
self.stacks.lock().recycle(stack);
Err(trap)
}
Err(TaggedTrap::Host {
host_func,
host_trap,
}) => Ok(ResumableCallBase::Resumable(ResumableInvocation::new(
ctx.as_context().store.engine().clone(),
*func,
host_func,
host_trap,
stack,
))),
}
}
fn resume_func<T, Results>(
&self,
ctx: StoreContextMut<T>,
mut invocation: ResumableInvocation,
params: impl CallParams,
results: Results,
) -> Result<ResumableCallBase<<Results as CallResults>::Results>, Trap>
where
Results: CallResults,
{
let res = self.res.read();
let host_func = invocation.host_func();
let results = EngineExecutor::new(&res, &mut invocation.stack)
.resume_func(ctx, host_func, params, results);
match results {
Ok(results) => {
self.stacks.lock().recycle(invocation.take_stack());
Ok(ResumableCallBase::Finished(results))
}
Err(TaggedTrap::Wasm(trap)) => {
self.stacks.lock().recycle(invocation.take_stack());
Err(trap)
}
Err(TaggedTrap::Host {
host_func,
host_trap,
}) => {
invocation.update(host_func, host_trap);
Ok(ResumableCallBase::Resumable(invocation))
}
}
}
fn recycle_stack(&self, stack: Stack) {
self.stacks.lock().recycle(stack);
}
}
/// Engine resources that are immutable during function execution.
///
/// Can be shared by multiple engine executors.
#[derive(Debug)]
pub struct EngineResources {
/// Stores all Wasm function bodies that the interpreter is aware of.
code_map: CodeMap,
/// A pool of reusable, deduplicated constant values.
const_pool: ConstPool,
/// Deduplicated function types.
///
/// # Note
///
/// The engine deduplicates function types to make the equality
/// comparison very fast. This helps to speed up indirect calls.
func_types: FuncTypeRegistry,
}
impl EngineResources {
/// Creates a new [`EngineResources`].
fn new() -> Self {
let engine_idx = EngineIdx::new();
Self {
code_map: CodeMap::default(),
const_pool: ConstPool::default(),
func_types: FuncTypeRegistry::new(engine_idx),
}
}
}
/// Either a Wasm trap or a host trap with its originating host [`Func`].
#[derive(Debug)]
enum TaggedTrap {
/// The trap is originating from Wasm.
Wasm(Trap),
/// The trap is originating from a host function.
Host { host_func: Func, host_trap: Trap },
}
impl TaggedTrap {
/// Creates a [`TaggedTrap`] from a host error.
pub fn host(host_func: Func, host_trap: Trap) -> Self {
Self::Host {
host_func,
host_trap,
}
}
/// Returns the [`Trap`] of the [`TaggedTrap`].
pub fn into_trap(self) -> Trap {
match self {
TaggedTrap::Wasm(trap) => trap,
TaggedTrap::Host { host_trap, .. } => host_trap,
}
}
}
impl From<Trap> for TaggedTrap {
fn from(trap: Trap) -> Self {
Self::Wasm(trap)
}
}
impl From<TrapCode> for TaggedTrap {
fn from(trap_code: TrapCode) -> Self {
Self::Wasm(trap_code.into())
}
}
/// The internal state of the `wasmi` engine.
#[derive(Debug)]
pub struct EngineExecutor<'engine> {
/// Shared and reusable generic engine resources.
res: &'engine EngineResources,
/// The value and call stacks.
stack: &'engine mut Stack,
}
impl<'engine> EngineExecutor<'engine> {
/// Creates a new [`EngineExecutor`] with the given [`StackLimits`].
fn new(res: &'engine EngineResources, stack: &'engine mut Stack) -> Self {
Self { res, stack }
}
/// Executes the given [`Func`] using the given `params`.
///
/// Stores the execution result into `results` upon a successful execution.
///
/// # Errors
///
/// - If the given `params` do not match the expected parameters of `func`.
/// - If the given `results` do not match the the length of the expected results of `func`.
/// - When encountering a Wasm or host trap during the execution of `func`.
fn execute_func<T, Results>(
&mut self,
mut ctx: StoreContextMut<T>,
func: &Func,
params: impl CallParams,
results: Results,
) -> Result<<Results as CallResults>::Results, TaggedTrap>
where
Results: CallResults,
{
self.stack.reset();
let call_params = params.call_params();
self.stack.values.reserve(call_params.len())?;
self.stack.values.extend(call_params);
match ctx.as_context().store.inner.resolve_func(func) {
FuncEntity::Wasm(wasm_func) => {
self.stack
.prepare_wasm_call(wasm_func, &self.res.code_map)?;
self.execute_wasm_func(ctx.as_context_mut())?;
}
FuncEntity::Host(host_func) => {
let host_func = *host_func;
self.stack.call_host_as_root(
ctx.as_context_mut(),
host_func,
&self.res.func_types,
)?;
}
};
let results = self.write_results_back(results);
Ok(results)
}
/// Resumes the execution of the given [`Func`] using `params`.
///
/// Stores the execution result into `results` upon a successful execution.
///
/// # Errors
///
/// - If the given `params` do not match the expected parameters of `func`.
/// - If the given `results` do not match the the length of the expected results of `func`.
/// - When encountering a Wasm or host trap during the execution of `func`.
fn resume_func<T, Results>(
&mut self,
mut ctx: StoreContextMut<T>,
host_func: Func,
params: impl CallParams,
results: Results,
) -> Result<<Results as CallResults>::Results, TaggedTrap>
where
Results: CallResults,
{
self.stack
.values
.drop(host_func.ty(ctx.as_context()).params().len());
let call_params = params.call_params();
self.stack.values.reserve(call_params.len())?;
self.stack.values.extend(call_params);
assert!(
self.stack.frames.peek().is_some(),
"a frame must be on the call stack upon resumption"
);
self.execute_wasm_func(ctx.as_context_mut())?;
let results = self.write_results_back(results);
Ok(results)
}
/// Writes the results of the function execution back into the `results` buffer.
///
/// # Note
///
/// The value stack is empty after this operation.
///
/// # Panics
///
/// - If the `results` buffer length does not match the remaining amount of stack values.
#[inline]
fn write_results_back<Results>(&mut self, results: Results) -> <Results as CallResults>::Results
where
Results: CallResults,
{
results.call_results(self.stack.values.drain())
}
/// Executes the top most Wasm function on the [`Stack`] until the [`Stack`] is empty.
///
/// # Errors
///
/// When encountering a Wasm or host trap during the execution of `func`.
#[inline(never)]
fn execute_wasm_func<T>(&mut self, mut ctx: StoreContextMut<T>) -> Result<(), TaggedTrap> {
let mut cache = self
.stack
.frames
.peek()
.map(FuncFrame::instance)
.map(InstanceCache::from)
.expect("must have frame on the call stack");
loop {
match self.execute_wasm(ctx.as_context_mut(), &mut cache)? {
WasmOutcome::Return => return Ok(()),
WasmOutcome::Call {
ref host_func,
instance,
} => {
let func = host_func;
let host_func = match ctx.as_context().store.inner.resolve_func(func) {
FuncEntity::Wasm(_) => unreachable!("`func` must be a host function"),
FuncEntity::Host(host_func) => *host_func,
};
let result = self.stack.call_host_impl(
ctx.as_context_mut(),
host_func,
Some(&instance),
&self.res.func_types,
);
if self.stack.frames.peek().is_some() {
// Case: There is a frame on the call stack.
//
// This is the default case and we can easily make host function
// errors return a resumable call handle.
result.map_err(|trap| TaggedTrap::host(*func, trap))?;
} else {
// Case: No frame is on the call stack. (edge case)
//
// This can happen if the host function was called by a tail call.
// In this case we treat host function errors the same as if we called
// the host function as root and do not allow to resume the call.
result.map_err(TaggedTrap::Wasm)?;
}
}
}
}
}
/// Executes the given function `frame`.
///
/// # Note
///
/// This executes Wasm instructions until either the execution calls
/// into a host function or the Wasm execution has come to an end.
///
/// # Errors
///
/// If the Wasm execution traps.
#[inline(always)]
fn execute_wasm<T>(
&mut self,
ctx: StoreContextMut<T>,
cache: &mut InstanceCache,
) -> Result<WasmOutcome, Trap> {
/// Converts a [`TrapCode`] into a [`Trap`].
///
/// This function exists for performance reasons since its `#[cold]`
/// annotation has severe effects on performance.
#[inline]
#[cold]
fn make_trap(code: TrapCode) -> Trap {
code.into()
}
let (store_inner, mut resource_limiter) = ctx.store.store_inner_and_resource_limiter_ref();
let value_stack = &mut self.stack.values;
let call_stack = &mut self.stack.frames;
let code_map = &self.res.code_map;
let const_pool = self.res.const_pool.view();
execute_wasm(
store_inner,
cache,
value_stack,
call_stack,
code_map,
const_pool,
&mut resource_limiter,
)
.map_err(make_trap)
}
}