diff --git a/lib/clif-backend/src/code.rs b/lib/clif-backend/src/code.rs index 157187e77..1bd1958e3 100644 --- a/lib/clif-backend/src/code.rs +++ b/lib/clif-backend/src/code.rs @@ -776,7 +776,7 @@ impl FuncEnvironment for FunctionEnvironment { let imported_func_ctx_vmctx_addr = pos.func.create_global_value(ir::GlobalValueData::Load { base: imported_func_ctx_addr, - offset: (0 as i32).into(), + offset: (vm::FuncCtx::offset_vmctx() as i32).into(), global_type: ptr_type, readonly: true, }); diff --git a/lib/runtime-core/src/vm.rs b/lib/runtime-core/src/vm.rs index 1c9a8b7ad..6f9ff5c47 100644 --- a/lib/runtime-core/src/vm.rs +++ b/lib/runtime-core/src/vm.rs @@ -518,7 +518,7 @@ pub struct FuncEnv { /// only. #[derive(Debug)] #[repr(C)] -pub(crate) struct FuncCtx { +pub struct FuncCtx { /// The `Ctx` pointer. pub(crate) vmctx: NonNull, @@ -529,6 +529,20 @@ pub(crate) struct FuncCtx { pub(crate) func_env: Option>, } +impl FuncCtx { + pub fn offset_vmctx() -> u8 { + 0 * (mem::size_of::() as u8) + } + + pub fn offset_func_env() -> u8 { + 1 * (mem::size_of::() as u8) + } + + pub fn size() -> u8 { + mem::size_of::() as u8 + } +} + /// An imported function is a function pointer associated to a /// function context. #[derive(Debug, Clone)] @@ -687,7 +701,9 @@ impl Anyfunc { #[cfg(test)] mod vm_offset_tests { - use super::{Anyfunc, Ctx, ImportedFunc, InternalCtx, LocalGlobal, LocalMemory, LocalTable}; + use super::{ + Anyfunc, Ctx, FuncCtx, ImportedFunc, InternalCtx, LocalGlobal, LocalMemory, LocalTable, + }; #[test] fn vmctx() { @@ -764,6 +780,19 @@ mod vm_offset_tests { ); } + #[test] + fn func_ctx() { + assert_eq!( + FuncCtx::offset_vmctx() as usize, + offset_of!(FuncCtx => vmctx).get_byte_offset(), + ); + + assert_eq!( + FuncCtx::offset_func_env() as usize, + offset_of!(FuncCtx => func_env).get_byte_offset(), + ); + } + #[test] fn imported_func() { assert_eq!( diff --git a/lib/singlepass-backend/src/codegen_x64.rs b/lib/singlepass-backend/src/codegen_x64.rs index 3ee60babf..7a71a289f 100644 --- a/lib/singlepass-backend/src/codegen_x64.rs +++ b/lib/singlepass-backend/src/codegen_x64.rs @@ -558,6 +558,7 @@ impl ModuleCodeGenerator let imported_func = vm::ImportedFunc::size() as usize * id; let imported_func_addr = imported_func + vm::ImportedFunc::offset_func() as usize; let imported_func_ctx_addr = imported_func + vm::ImportedFunc::offset_func_ctx() as usize; + let imported_func_ctx_vmctx_addr = vm::FuncCtx::offset_vmctx() as usize; a.emit_mov( Size::S64, @@ -569,6 +570,11 @@ impl ModuleCodeGenerator Location::Memory(GPR::RAX, imported_func_ctx_addr as i32), Location::GPR(GPR::RDI), ); + a.emit_mov( + Size::S64, + Location::Memory(GPR::RDI, imported_func_ctx_vmctx_addr as i32), + Location::GPR(GPR::RDI), + ); a.emit_mov( Size::S64, Location::Memory(GPR::RAX, imported_func_addr as i32),