diff --git a/lib/runtime-core/src/backing.rs b/lib/runtime-core/src/backing.rs index 2493e9d35..7449403fa 100644 --- a/lib/runtime-core/src/backing.rs +++ b/lib/runtime-core/src/backing.rs @@ -591,16 +591,21 @@ fn import_functions( // ^^^^^^^^ `vm::FuncCtx` is purposely leaked. // It is dropped by the specific `Drop` // implementation of `ImportBacking`. - vmctx: NonNull::new(vmctx).expect("`vmctx` must not be null."), - func_env: match ctx { - Context::External(ctx) => { - NonNull::new(ctx).map(NonNull::cast) - // ^^^^^^^^^^^^^ - // `*mut vm::FuncEnv` was casted to - // `*mut vm::Ctx` to fit in - // `Context::External`. Cast it back. + vmctx: NonNull::new(match ctx { + Context::External(vmctx) => vmctx, + Context::ExternalWithEnv(vmctx_, _) => { + if vmctx_.is_null() { + vmctx + } else { + vmctx_ + } } - Context::Internal => None, + _ => vmctx, + }) + .expect("`vmctx` must not be null."), + func_env: match ctx { + Context::ExternalWithEnv(_, func_env) => Some(func_env), + _ => None, }, }))) .unwrap(), diff --git a/lib/runtime-core/src/export.rs b/lib/runtime-core/src/export.rs index 7960d76e6..88ec07e40 100644 --- a/lib/runtime-core/src/export.rs +++ b/lib/runtime-core/src/export.rs @@ -3,11 +3,12 @@ use crate::{ module::ModuleInner, table::Table, types::FuncSig, vm, }; use indexmap::map::Iter as IndexMapIter; -use std::sync::Arc; +use std::{ptr::NonNull, sync::Arc}; #[derive(Debug, Copy, Clone)] pub enum Context { External(*mut vm::Ctx), + ExternalWithEnv(*mut vm::Ctx, NonNull), Internal, } diff --git a/lib/runtime-core/src/instance.rs b/lib/runtime-core/src/instance.rs index 5cf92a312..53a5681ff 100644 --- a/lib/runtime-core/src/instance.rs +++ b/lib/runtime-core/src/instance.rs @@ -413,6 +413,7 @@ impl InstanceInner { ctx: match ctx { Context::Internal => Context::External(self.vmctx), ctx @ Context::External(_) => ctx, + func_ctx @ Context::ExternalWithEnv(_, _) => func_ctx, }, signature, } @@ -463,7 +464,6 @@ impl InstanceInner { }; let signature = SigRegistry.lookup_signature_ref(&module.info.signatures[sig_index]); - // let signature = &module.info.signatures[sig_index]; (unsafe { FuncPointer::new(func_ptr) }, ctx, signature) } diff --git a/lib/runtime-core/src/typed_func.rs b/lib/runtime-core/src/typed_func.rs index 8c6a7826d..cce058182 100644 --- a/lib/runtime-core/src/typed_func.rs +++ b/lib/runtime-core/src/typed_func.rs @@ -724,11 +724,7 @@ where fn to_export(&self) -> Export { let func = unsafe { FuncPointer::new(self.func.as_ptr()) }; let ctx = match self.func_env { - Some(func_env) => Context::External(func_env.cast().as_ptr()), - // ^^^^^^ - // `Context::External` expects a `vm::Ctx`. - // Casting to `vm::FuncCtx` happens in the - // `backing` module. + Some(func_env) => Context::ExternalWithEnv(self.vmctx, func_env), None => Context::Internal, }; let signature = Arc::new(FuncSig::new(Args::types(), Rets::types()));