Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

bench-api: Fix compilation caching (#15273)

Nick Fitzgerald9905be28a678
diff --git a/Cargo.lock b/Cargo.lock
index d6d20ce3f3..307a44c8bf 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4622,6 +4622,7 @@ name = "wasmtime-bench-api"
version = "52.0.0-dev"
dependencies = [
"clap",
+ "libc",
"shuffling-allocator",
"target-lexicon 0.13.5",
"wasmtime",
@@ -4629,6 +4630,7 @@ dependencies = [
"wasmtime-wasi",
"wasmtime-wasi-nn",
"wat",
+ "windows-sys 0.61.2",
]
[[package]]
diff --git a/crates/bench-api/Cargo.toml b/crates/bench-api/Cargo.toml
index 12786f8d4f..47cee3efce 100644
--- a/crates/bench-api/Cargo.toml
+++ b/crates/bench-api/Cargo.toml
@@ -46,6 +46,15 @@ wasmtime-wasi = { workspace = true, features = ['p1', 'p2'] }
wasmtime-wasi-nn = { workspace = true, optional = true }
clap = { workspace = true }
+[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies]
+libc = { workspace = true }
+
+[target.'cfg(windows)'.dependencies]
+windows-sys = { workspace = true, features = [
+ "Win32_Foundation",
+ "Win32_System_LibraryLoader",
+] }
+
[dev-dependencies]
wat = { workspace = true }
diff --git a/crates/bench-api/src/lib.rs b/crates/bench-api/src/lib.rs
index 97086b1566..eb52f118a8 100644
--- a/crates/bench-api/src/lib.rs
+++ b/crates/bench-api/src/lib.rs
@@ -140,8 +140,10 @@ mod unsafe_send_sync;
use crate::unsafe_send_sync::UnsafeSendSync;
use clap::Parser;
+use std::hash::{DefaultHasher, Hasher};
use std::os::raw::{c_int, c_void};
use std::slice;
+use std::sync::OnceLock;
use std::{env, path::PathBuf};
use wasmtime::{
CodeBuilder, CodeHint, Engine, Linker, Module, Result, Store, error::Context as _, format_err,
@@ -640,11 +642,12 @@ impl BenchState {
// NB: set this either way, since `CommonOptions` enables the cache by
// default and we must not break compilation benchmarks.
- config.cache(if cache {
- Some(wasmtime::Cache::from_file(None)?)
+ if cache {
+ config.module_version(wasmtime::ModuleVersionStrategy::Custom(bench_api_hash()?))?;
+ config.cache(Some(wasmtime::Cache::from_file(None)?));
} else {
- None
- });
+ config.cache(None);
+ };
let engine = Engine::new(&config)?;
let mut linker = Linker::<HostState>::new(&engine);
@@ -812,3 +815,95 @@ impl BenchState {
}
}
}
+
+/// A hash of this dynamic library's contents, used as the cache's module
+/// version so that different builds never share cache entries.
+fn bench_api_hash() -> Result<String> {
+ static HASH: OnceLock<String> = OnceLock::new();
+ if let Some(hash) = HASH.get() {
+ return Ok(hash.clone());
+ }
+
+ let path = this_dynamic_library_path()?;
+ let bytes =
+ std::fs::read(&path).with_context(|| format!("failed to read `{}`", path.display()))?;
+ let mut hasher = DefaultHasher::new();
+ hasher.write(&bytes);
+ let hash = format!("bench-api-{:016x}", hasher.finish());
+
+ Ok(HASH.get_or_init(|| hash).clone())
+}
+
+cfg_select! {
+ any(target_os = "linux", target_os = "macos") => {
+ fn this_dynamic_library_path() -> Result<PathBuf> {
+ use std::ffi::{CStr, OsStr};
+ use std::os::unix::ffi::OsStrExt;
+
+ let mut info = libc::Dl_info {
+ dli_fname: std::ptr::null(),
+ dli_fbase: std::ptr::null_mut(),
+ dli_sname: std::ptr::null(),
+ dli_saddr: std::ptr::null_mut(),
+ };
+ let addr = this_dynamic_library_path as *const c_void;
+ let ok = unsafe { libc::dladdr(addr, &mut info) };
+ if ok == 0 || info.dli_fname.is_null() {
+ return Err(format_err!("`dladdr` failed to find the bench API library"));
+ }
+
+ let fname = unsafe { CStr::from_ptr(info.dli_fname) };
+ Ok(PathBuf::from(OsStr::from_bytes(fname.to_bytes())))
+ }
+ }
+ windows => {
+ fn this_dynamic_library_path() -> Result<PathBuf> {
+ use std::ffi::OsString;
+ use std::os::windows::ffi::OsStringExt;
+ use windows_sys::Win32::System::LibraryLoader::{
+ GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
+ GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameW,
+ GetModuleHandleExW,
+ };
+
+ let mut module = std::ptr::null_mut();
+ let addr = this_dynamic_library_path as *const u16;
+ let ok = unsafe {
+ GetModuleHandleExW(
+ GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
+ | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
+ addr,
+ &mut module,
+ )
+ };
+ if ok == 0 {
+ return Err(std::io::Error::last_os_error())
+ .context("`GetModuleHandleExW` failed to find the bench API library");
+ }
+
+ let mut buf = vec![0u16; 1024];
+ loop {
+ let size = u32::try_from(buf.len()).unwrap();
+ let len = unsafe { GetModuleFileNameW(module, buf.as_mut_ptr(), size) };
+ if len == 0 {
+ return Err(std::io::Error::last_os_error())
+ .context("`GetModuleFileNameW` failed");
+ }
+ // A full buffer means the path was truncated.
+ if len < size {
+ buf.truncate(len as usize);
+ return Ok(PathBuf::from(OsString::from_wide(&buf)));
+ }
+ buf.resize(buf.len() * 2, 0);
+ }
+ }
+ }
+ _ => {
+ fn this_dynamic_library_path() -> Result<PathBuf> {
+ Err(format_err!(
+ "the `wasmtime-bench-api` crate does not support this platform; \
+ implement support then recompile",
+ ))
+ }
+ }
+}