Skip to content

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

Add `Config::without_compiler` (#12089)

Nick Fitzgerald9bb96d51e707
diff --git a/crates/cranelift/src/builder.rs b/crates/cranelift/src/builder.rs
index 7c36f93093..ebf7b2830a 100644
--- a/crates/cranelift/src/builder.rs
+++ b/crates/cranelift/src/builder.rs
@@ -39,7 +39,7 @@ pub struct LinkOptions {
}
pub fn builder(triple: Option<Triple>) -> Result<Box<dyn CompilerBuilder>> {
- Ok(Box::new(Builder {
+ let mut builder = Builder {
tunables: None,
inner: IsaBuilder::new(triple, |triple| isa::lookup(triple).map_err(|e| e.into()))?,
linkopts: LinkOptions::default(),
@@ -47,7 +47,20 @@ pub fn builder(triple: Option<Triple>) -> Result<Box<dyn CompilerBuilder>> {
clif_dir: None,
wmemcheck: false,
emit_debug_checks: false,
- }))
+ };
+
+ builder.set("enable_verifier", "false").unwrap();
+ builder.set("opt_level", "speed").unwrap();
+
+ // When running under MIRI try to optimize for compile time of Wasm code
+ // itself as much as possible. Disable optimizations by default and use the
+ // fastest regalloc available to us.
+ if cfg!(miri) {
+ builder.set("opt_level", "none").unwrap();
+ builder.set("regalloc_algorithm", "single_pass").unwrap();
+ }
+
+ Ok(Box::new(builder))
}
impl CompilerBuilder for Builder {
diff --git a/crates/fuzzing/tests/oom.rs b/crates/fuzzing/tests/oom.rs
index 544d27034f..dc8ac8dfd9 100644
--- a/crates/fuzzing/tests/oom.rs
+++ b/crates/fuzzing/tests/oom.rs
@@ -1,5 +1,5 @@
use std::alloc::{Layout, alloc};
-use wasmtime::Result;
+use wasmtime::{Config, Result};
use wasmtime_fuzzing::oom::{OomTest, OomTestAllocator};
#[global_allocator]
@@ -25,3 +25,12 @@ fn smoke_test_missed_oom() -> Result<()> {
);
Ok(())
}
+
+#[test]
+fn config_new() -> Result<()> {
+ OomTest::new().test(|| {
+ let mut config = Config::new();
+ config.enable_compiler(false);
+ Ok(())
+ })
+}
diff --git a/crates/wasmtime/src/compile.rs b/crates/wasmtime/src/compile.rs
index 5ebb978d07..5e63afcc90 100644
--- a/crates/wasmtime/src/compile.rs
+++ b/crates/wasmtime/src/compile.rs
@@ -70,6 +70,7 @@ pub(crate) fn build_module_artifacts<T: FinishedObject>(
T,
Option<(CompiledModuleInfo, CompiledFunctionsTable, ModuleTypes)>,
)> {
+ let compiler = engine.try_compiler()?;
let tunables = engine.tunables();
// First a `ModuleEnvironment` is created which records type information
@@ -101,7 +102,7 @@ pub(crate) fn build_module_artifacts<T: FinishedObject>(
// Emplace all compiled functions into the object file with any other
// sections associated with code as well.
- let mut object = engine.compiler().object(ObjectKind::Module)?;
+ let mut object = compiler.object(ObjectKind::Module)?;
// Insert `Engine` and type-level information into the compiled
// artifact so if this module is deserialized later it contains all
// information necessary.
@@ -111,7 +112,7 @@ pub(crate) fn build_module_artifacts<T: FinishedObject>(
// They're only used during deserialization and not during runtime for
// the module itself. Currently there's no need for that, however, so
// it's left as an exercise for later.
- engine.append_compiler_info(&mut object);
+ engine.append_compiler_info(&mut object)?;
engine.append_bti(&mut object);
let (mut object, compilation_artifacts) = indices.link_and_append_code(
@@ -150,8 +151,8 @@ pub(crate) fn build_component_artifacts<T: FinishedObject>(
CompiledComponentInfo, ComponentArtifacts, ComponentTypesBuilder,
};
+ let compiler = engine.try_compiler()?;
let tunables = engine.tunables();
- let compiler = engine.compiler();
let scope = ScopeVec::new();
let mut validator = wasmparser::Validator::new_with_features(engine.features());
@@ -185,7 +186,7 @@ pub(crate) fn build_component_artifacts<T: FinishedObject>(
}
let mut object = compiler.object(ObjectKind::Component)?;
- engine.append_compiler_info(&mut object);
+ engine.append_compiler_info(&mut object)?;
engine.append_bti(&mut object);
let (mut object, compilation_artifacts) = indices.link_and_append_code(
@@ -520,7 +521,7 @@ impl<'a> CompileInputs<'a> {
/// Compile these `CompileInput`s (maybe in parallel) and return the
/// resulting `UnlinkedCompileOutput`s.
fn compile(self, engine: &Engine) -> Result<UnlinkedCompileOutputs<'a>> {
- let compiler = engine.compiler();
+ let compiler = engine.try_compiler()?;
if self.inputs.len() > 0 && cfg!(miri) {
bail!(
@@ -912,7 +913,7 @@ the use case.
}
fn compile_required_builtins(engine: &Engine, raw_outputs: &mut Vec<CompileOutput>) -> Result<()> {
- let compiler = engine.compiler();
+ let compiler = engine.try_compiler()?;
let mut builtins = HashSet::new();
let mut new_inputs: Vec<CompileInput<'_>> = Vec::new();
@@ -1040,7 +1041,7 @@ impl FunctionIndices {
// The result is a vector parallel to `compiled_funcs` where
// `symbol_ids_and_locs[i]` is the symbol ID and function location of
// `compiled_funcs[i]`.
- let compiler = engine.compiler();
+ let compiler = engine.try_compiler()?;
let tunables = engine.tunables();
let symbol_ids_and_locs = compiler.append_code(
&mut obj,
diff --git a/crates/wasmtime/src/compile/code_builder.rs b/crates/wasmtime/src/compile/code_builder.rs
index eb9ba33471..029cbe1803 100644
--- a/crates/wasmtime/src/compile/code_builder.rs
+++ b/crates/wasmtime/src/compile/code_builder.rs
@@ -808,10 +808,11 @@ pub struct HashedEngineCompileEnv<'a>(pub &'a Engine);
impl std::hash::Hash for HashedEngineCompileEnv<'_> {
fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
// Hash the compiler's state based on its target and configuration.
- let compiler = self.0.compiler();
- compiler.triple().hash(hasher);
- compiler.flags().hash(hasher);
- compiler.isa_flags().hash(hasher);
+ if let Some(compiler) = self.0.compiler() {
+ compiler.triple().hash(hasher);
+ compiler.flags().hash(hasher);
+ compiler.isa_flags().hash(hasher);
+ }
// Hash configuration state read for compilation
let config = self.0.config();
diff --git a/crates/wasmtime/src/config.rs b/crates/wasmtime/src/config.rs
index 07fed8ccf8..49e4b537c9 100644
--- a/crates/wasmtime/src/config.rs
+++ b/crates/wasmtime/src/config.rs
@@ -120,7 +120,7 @@ impl core::hash::Hash for ModuleVersionStrategy {
#[derive(Clone)]
pub struct Config {
#[cfg(any(feature = "cranelift", feature = "winch"))]
- compiler_config: CompilerConfig,
+ compiler_config: Option<CompilerConfig>,
target: Option<target_lexicon::Triple>,
#[cfg(feature = "gc")]
collector: Collector,
@@ -228,7 +228,7 @@ impl Config {
let mut ret = Self {
tunables: ConfigTunables::default(),
#[cfg(any(feature = "cranelift", feature = "winch"))]
- compiler_config: CompilerConfig::default(),
+ compiler_config: Some(CompilerConfig::default()),
target: None,
#[cfg(feature = "gc")]
collector: Collector::default(),
@@ -276,25 +276,67 @@ impl Config {
x86_float_abi_ok: None,
shared_memory: false,
};
- #[cfg(any(feature = "cranelift", feature = "winch"))]
- {
- ret.cranelift_debug_verifier(false);
- ret.cranelift_opt_level(OptLevel::Speed);
-
- // When running under MIRI try to optimize for compile time of wasm
- // code itself as much as possible. Disable optimizations by
- // default and use the fastest regalloc available to us.
- if cfg!(miri) {
- ret.cranelift_opt_level(OptLevel::None);
- ret.cranelift_regalloc_algorithm(RegallocAlgorithm::SinglePass);
- }
- }
-
ret.wasm_backtrace_details(WasmBacktraceDetails::Environment);
-
ret
}
+ #[cfg(any(feature = "cranelift", feature = "winch"))]
+ pub(crate) fn has_compiler(&self) -> bool {
+ self.compiler_config.is_some()
+ }
+
+ #[track_caller]
+ #[cfg(any(feature = "cranelift", feature = "winch"))]
+ fn compiler_config_mut(&mut self) -> &mut CompilerConfig {
+ self.compiler_config.as_mut().expect(
+ "cannot configure compiler settings for `Config`s \
+ created by `Config::without_compiler`",
+ )
+ }
+
+ /// Configure whether Wasm compilation is enabled.
+ ///
+ /// Disabling Wasm compilation will allow you to load and run
+ /// [pre-compiled][crate::Engine::precompile_module] Wasm programs, but not
+ /// to compile and run new Wasm programs that have not already been
+ /// pre-compiled.
+ ///
+ /// Many compilation-related configuration methods will panic if compilation
+ /// has been disabled.
+ ///
+ /// Note that there are two ways to disable Wasm compilation:
+ ///
+ /// 1. Statically, by disabling the `"cranelift"` and `"winch"` cargo
+ /// features when building Wasmtime. These builds of Wasmtime will have
+ /// smaller code size, since they do not include any of the code to
+ /// compile Wasm.
+ ///
+ /// 2. Dynamically, by passing `false` to this method at run-time when
+ /// configuring Wasmtime. The Wasmtime binary will still include the code
+ /// for compiling Wasm, it just won't be executed, so code size is larger
+ /// than with the first approach.
+ ///
+ /// The static approach is better in most cases, however dynamically calling
+ /// `enable_compiler(false)` is useful whenever you create multiple
+ /// `Engine`s in the same process, some of which must be able to compile
+ /// Wasm and some of which should never do so. Tests are a common example of
+ /// such a situation, especially when there are multiple Rust binaries in
+ /// the same cargo workspace, and cargo's feature resolution enables the
+ /// `"cranelift"` or `"winch"` features across the whole workspace.
+ #[cfg(any(feature = "cranelift", feature = "winch"))]
+ pub fn enable_compiler(&mut self, enable: bool) -> &mut Self {
+ match (enable, &self.compiler_config) {
+ (true, Some(_)) | (false, None) => {}
+ (true, None) => {
+ self.compiler_config = Some(CompilerConfig::default());
+ }
+ (false, Some(_)) => {
+ self.compiler_config = None;
+ }
+ }
+ self
+ }
+
/// Configures the target platform of this [`Config`].
///
/// This method is used to configure the output of compilation in an
@@ -327,12 +369,16 @@ impl Config {
/// Enables the incremental compilation cache in Cranelift, using the provided `CacheStore`
/// backend for storage.
+ ///
+ /// # Panics
+ ///
+ /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
#[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
pub fn enable_incremental_compilation(
&mut self,
cache_store: Arc<dyn CacheStore>,
) -> Result<&mut Self> {
- self.compiler_config.cache_store = Some(cache_store);
+ self.compiler_config_mut().cache_store = Some(cache_store);
Ok(self)
}
@@ -1275,9 +1321,13 @@ impl Config {
/// and its documentation.
///
/// The default value for this is `Strategy::Auto`.
+ ///
+ /// # Panics
+ ///
+ /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
#[cfg(any(feature = "cranelift", feature = "winch"))]
pub fn strategy(&mut self, strategy: Strategy) -> &mut Self {
- self.compiler_config.strategy = strategy.not_auto();
+ self.compiler_config_mut().strategy = strategy.not_auto();
self
}
@@ -1321,10 +1371,14 @@ impl Config {
/// developers of wasmtime itself.
///
/// The default value for this is `false`
+ ///
+ /// # Panics
+ ///
+ /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
#[cfg(any(feature = "cranelift", feature = "winch"))]
pub fn cranelift_debug_verifier(&mut self, enable: bool) -> &mut Self {
let val = if enable { "true" } else { "false" };
- self.compiler_config
+ self.compiler_config_mut()
.settings
.insert("enable_verifier".to_string(), val.to_string());
self
@@ -1334,6 +1388,10 @@ impl Config {
/// Wasmtime-generated code by Cranelift.
///
/// The default value for this is `false`
+ ///
+ /// # Panics
+ ///
+ /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
#[cfg(any(feature = "cranelift", feature = "winch"))]
pub fn cranelift_wasmtime_debug_checks(&mut self, enable: bool) -> &mut Self {
unsafe { self.cranelift_flag_set("wasmtime_debug_checks", &enable.to_string()) }
@@ -1346,6 +1404,10 @@ impl Config {
/// more information see the documentation of [`OptLevel`].
///
/// The default value for this is `OptLevel::Speed`.
+ ///
+ /// # Panics
+ ///
+ /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
#[cfg(any(feature = "cranelift", feature = "winch"))]
pub fn cranelift_opt_level(&mut self, level: OptLevel) -> &mut Self {
let val = match level {
@@ -1353,7 +1415,7 @@ impl Config {
OptLevel::Speed => "speed",
OptLevel::SpeedAndSize => "speed_and_size",
};
- self.compiler_config
+ self.compiler_config_mut()
.settings
.insert("opt_level".to_string(), val.to_string());
self
@@ -1368,13 +1430,17 @@ impl Config {
/// For more information see the documentation of [`RegallocAlgorithm`].
///
/// The default value for this is `RegallocAlgorithm::Backtracking`.
+ ///
+ /// # Panics
+ ///
+ /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
#[cfg(any(feature = "cranelift", feature = "winch"))]
pub fn cranelift_regalloc_algorithm(&mut self, algo: RegallocAlgorithm) -> &mut Self {
let val = match algo {
RegallocAlgorithm::Backtracking => "backtracking",
RegallocAlgorithm::SinglePass => "single_pass",
};
- self.compiler_config
+ self.compiler_config_mut()
.settings
.insert("regalloc_algorithm".to_string(), val.to_string());
self
@@ -1393,10 +1459,14 @@ impl Config {
/// them to normalize NaN values as needed.
///
/// The default value for this is `false`
+ ///
+ /// # Panics
+ ///
+ /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
#[cfg(any(feature = "cranelift", feature = "winch"))]
pub fn cranelift_nan_canonicalization(&mut self, enable: bool) -> &mut Self {
let val = if enable { "true" } else { "false" };
- self.compiler_config
+ self.compiler_config_mut()
.settings
.insert("enable_nan_canonicalization".to_string(), val.to_string());
self
@@ -1415,10 +1485,14 @@ impl Config {
/// solvers or logic engines to verify, but only a linear pass
/// over a trail of "breadcrumbs" or facts at each intermediate
/// value. Thus, it is appropriate to enable in production.
+ ///
+ /// # Panics
+ ///
+ /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
#[cfg(any(feature = "cranelift", feature = "winch"))]
pub fn cranelift_pcc(&mut self, enable: bool) -> &mut Self {
let val = if enable { "true" } else { "false" };
- self.compiler_config
+ self.compiler_config_mut()
.settings
.insert("enable_pcc".to_string(), val.to_string());
self
@@ -1440,9 +1514,13 @@ impl Config {
/// The validation of the flags are deferred until the engine is being built, and thus may
/// cause `Engine::new` fail if the flag's name does not exist, or the value is not appropriate
/// for the flag type.
+ ///
+ /// # Panics
+ ///
+ /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
#[cfg(any(feature = "cranelift", feature = "winch"))]
pub unsafe fn cranelift_flag_enable(&mut self, flag: &str) -> &mut Self {
- self.compiler_config.flags.insert(flag.to_string());
+ self.compiler_config_mut().flags.insert(flag.to_string());
self
}
@@ -1465,9 +1543,13 @@ impl Config {
///
/// For example, feature `wasm_backtrace` will set `unwind_info` to `true`, but if it's
/// manually set to false then it will fail.
+ ///
+ /// # Panics
+ ///
+ /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
#[cfg(any(feature = "cranelift", feature = "winch"))]
pub unsafe fn cranelift_flag_set(&mut self, name: &str, value: &str) -> &mut Self {
- self.compiler_config
+ self.compiler_config_mut()
.settings
.insert(name.to_string(), value.to_string());
self
@@ -2057,10 +2139,14 @@ impl Config {
/// Enables memory error checking for wasm programs.
///
/// This option is disabled by default.
+ ///
+ /// # Panics
+ ///
+ /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
#[cfg(any(feature = "cranelift", feature = "winch"))]
pub fn wmemcheck(&mut self, enable: bool) -> &mut Self {
self.wmemcheck = enable;
- self.compiler_config.wmemcheck = enable;
+ self.compiler_config_mut().wmemcheck = enable;
self
}
@@ -2184,7 +2270,7 @@ impl Config {
let mut unsupported = !features_known_to_wasmtime;
#[cfg(any(feature = "cranelift", feature = "winch"))]
- match self.compiler_config.strategy {
+ match self.compiler_config.as_ref().and_then(|c| c.strategy) {
None | Some(Strategy::Cranelift) => {
// Pulley at this time fundamentally doesn't support the
// `threads` proposal, notably shared memory, because Rust can't
@@ -2392,7 +2478,10 @@ impl Config {
// If we're going to compile with winch, we must use the winch calling convention.
#[cfg(any(feature = "cranelift", feature = "winch"))]
{
- tunables.winch_callable = self.compiler_config.strategy == Some(Strategy::Winch);
+ tunables.winch_callable = self
+ .compiler_config
+ .as_ref()
+ .is_some_and(|c| c.strategy == Some(Strategy::Winch));
}
tunables.collector = if features.gc_types() {
@@ -2530,7 +2619,7 @@ impl Config {
Some(target.clone())
};
- let mut compiler = match self.compiler_config.strategy {
+ let mut compiler = match self.compiler_config_mut().strategy {
#[cfg(feature = "cranelift")]
Some(Strategy::Cranelift) => wasmtime_cranelift::builder(target_for_builder)?,
#[cfg(not(feature = "cranelift"))]
@@ -2543,14 +2632,14 @@ impl Config {
None | Some(Strategy::Auto) => unreachable!(),
};
- if let Some(path) = &self.compiler_config.clif_dir {
+ if let Some(path) = &self.compiler_config_mut().clif_dir {
compiler.clif_dir(path)?;
}
// If probestack is enabled for a target, Wasmtime will always use the
// inline strategy which doesn't require us to define a `__probestack`
// function or similar.
- self.compiler_config
+ self.compiler_config_mut()
.settings
.insert("probestack_strategy".into(), "inline".into());
@@ -2559,19 +2648,19 @@ impl Config {
// commits its stacks, but it's also a good idea on other
// platforms to ensure guard pages are hit for large frame
// sizes.
- self.compiler_config
+ self.compiler_config_mut()
.flags
.insert("enable_probestack".into());
// The current wasm multivalue implementation depends on this.
// FIXME(#9510) handle this in wasmtime-cranelift instead.
- self.compiler_config
+ self.compiler_config_mut()
.flags
.insert("enable_multi_ret_implicit_sret".into());
if let Some(unwind_requested) = self.native_unwind_info {
if !self
- .compiler_config
+ .compiler_config_mut()
.ensure_setting_unset_or_given("unwind_info", &unwind_requested.to_string())
{
bail!(
@@ -2582,7 +2671,7 @@ impl Config {
if target.operating_system == target_lexicon::OperatingSystem::Windows {
if !self
- .compiler_config
+ .compiler_config_mut()
.ensure_setting_unset_or_given("unwind_info", "true")
{
bail!("`native_unwind_info` cannot be disabled on Windows");
@@ -2592,16 +2681,16 @@ impl Config {
// We require frame pointers for correct stack walking, which is safety
// critical in the presence of reference types, and otherwise it is just
// really bad developer experience to get wrong.
- self.compiler_config
+ self.compiler_config_mut()
.settings
.insert("preserve_frame_pointers".into(), "true".into());
if !tunables.signals_based_traps {
let mut ok = self
- .compiler_config
+ .compiler_config_mut()
.ensure_setting_unset_or_given("enable_table_access_spectre_mitigation", "false");
ok = ok
- && self.compiler_config.ensure_setting_unset_or_given(
+ && self.compiler_config_mut().ensure_setting_unset_or_given(
"enable_heap_access_spectre_mitigation",
"false",
);
@@ -2633,7 +2722,7 @@ impl Config {
};
if !self
- .compiler_config
+ .compiler_config_mut()
.ensure_setting_unset_or_given("stack_switch_model", model)
{
bail!(
@@ -2644,20 +2733,20 @@ impl Config {
// Apply compiler settings and flags
compiler.set_tunables(tunables.clone())?;
- for (k, v) in self.compiler_config.settings.iter() {
+ for (k, v) in self.compiler_config_mut().settings.iter() {
compiler.set(k, v)?;
}
- for flag in self.compiler_config.flags.iter() {
+ for flag in self.compiler_config_mut().flags.iter() {
compiler.enable(flag)?;
}
*tunables = compiler.tunables().cloned().unwrap();
#[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
- if let Some(cache_store) = &self.compiler_config.cache_store {
+ if let Some(cache_store) = &self.compiler_config_mut().cache_store {
compiler.enable_incremental_compilation(cache_store.clone())?;
}
- compiler.wmemcheck(self.compiler_config.wmemcheck);
+ compiler.wmemcheck(self.compiler_config_mut().wmemcheck);
Ok((self, compiler.build()?))
}
@@ -2674,7 +2763,7 @@ impl Config {
/// Enables clif output when compiling a WebAssembly module.
#[cfg(any(feature = "cranelift", feature = "winch"))]
pub fn emit_clif(&mut self, path: &Path) -> &mut Self {
- self.compiler_config.clif_dir = Some(path.to_path_buf());
+ self.compiler_config_mut().clif_dir = Some(path.to_path_buf());
self
}
diff --git a/crates/wasmtime/src/engine.rs b/crates/wasmtime/src/engine.rs
index dad9dfaa0d..6fcfe63957 100644
--- a/crates/wasmtime/src/engine.rs
+++ b/crates/wasmtime/src/engine.rs
@@ -51,7 +51,7 @@ struct EngineInner {
features: WasmFeatures,
tunables: Tunables,
#[cfg(any(feature = "cranelift", feature = "winch"))]
- compiler: Box<dyn wasmtime_environ::Compiler>,
+ compiler: Option<Box<dyn wasmtime_environ::Compiler>>,
#[cfg(feature = "runtime")]
allocator: Box<dyn crate::runtime::vm::InstanceAllocator + Send + Sync>,
#[cfg(feature = "runtime")]
@@ -113,7 +113,12 @@ impl Engine {
}
#[cfg(any(feature = "cranelift", feature = "winch"))]
- let (config, compiler) = config.build_compiler(&mut tunables, features)?;
+ let (config, compiler) = if config.has_compiler() {
+ let (config, compiler) = config.build_compiler(&mut tunables, features)?;
+ (config, Some(compiler))
+ } else {
+ (config.clone(), None)
+ };
#[cfg(not(any(feature = "cranelift", feature = "winch")))]
let _ = &mut tunables;
@@ -335,13 +340,14 @@ impl Engine {
#[cfg(any(feature = "cranelift", feature = "winch"))]
{
- let compiler = self.compiler();
- // Also double-check all compiler settings
- for (key, value) in compiler.flags().iter() {
- self.check_compatible_with_shared_flag(key, value)?;
- }
- for (key, value) in compiler.isa_flags().iter() {
- self.check_compatible_with_isa_flag(key, value)?;
+ if let Some(compiler) = self.compiler() {
+ // Also double-check all compiler settings
+ for (key, value) in compiler.flags().iter() {
+ self.check_compatible_with_shared_flag(key, value)?;
+ }
+ for (key, value) in compiler.isa_flags().iter() {
+ self.check_compatible_with_isa_flag(key, value)?;
+ }
}
}
@@ -625,8 +631,13 @@ information about this check\
#[cfg(any(feature = "cranelift", feature = "winch"))]
impl Engine {
- pub(crate) fn compiler(&self) -> &dyn wasmtime_environ::Compiler {
- &*self.inner.compiler
+ pub(crate) fn compiler(&self) -> Option<&dyn wasmtime_environ::Compiler> {
+ self.inner.compiler.as_deref()
+ }
+
+ pub(crate) fn try_compiler(&self) -> Result<&dyn wasmtime_environ::Compiler> {
+ self.compiler()
+ .ok_or_else(|| anyhow!("Engine was not configured with a compiler"))
}
/// Ahead-of-time (AOT) compiles a WebAssembly module.
@@ -672,8 +683,9 @@ impl Engine {
///
/// The blob of bytes is inserted into the object file specified to become part
/// of the final compiled artifact.
- pub(crate) fn append_compiler_info(&self, obj: &mut Object<'_>) {
- serialization::append_compiler_info(self, obj, &serialization::Metadata::new(&self))
+ pub(crate) fn append_compiler_info(&self, obj: &mut Object<'_>) -> Result<()> {
+ serialization::append_compiler_info(self, obj, &serialization::Metadata::new(&self)?);
+ Ok(())
}
#[cfg(any(feature = "cranelift", feature = "winch"))]
@@ -683,7 +695,10 @@ impl Engine {
wasmtime_environ::obj::ELF_WASM_BTI.as_bytes().to_vec(),
object::SectionKind::ReadOnlyData,
);
- let contents = if self.compiler().is_branch_protection_enabled() {
+ let contents = if self
+ .compiler()
+ .is_some_and(|c| c.is_branch_protection_enabled())
+ {
1
} else {
0
diff --git a/crates/wasmtime/src/engine/serialization.rs b/crates/wasmtime/src/engine/serialization.rs
index d1f843896b..ba1b1a7813 100644
--- a/crates/wasmtime/src/engine/serialization.rs
+++ b/crates/wasmtime/src/engine/serialization.rs
@@ -179,14 +179,15 @@ pub struct Metadata<'a> {
impl Metadata<'_> {
#[cfg(any(feature = "cranelift", feature = "winch"))]
- pub fn new(engine: &Engine) -> Metadata<'static> {
- Metadata {
- target: engine.compiler().triple().to_string(),
- shared_flags: engine.compiler().flags(),
- isa_flags: engine.compiler().isa_flags(),
+ pub fn new(engine: &Engine) -> Result<Metadata<'static>> {
+ let compiler = engine.try_compiler()?;
+ Ok(Metadata {
+ target: compiler.triple().to_string(),
+ shared_flags: compiler.flags(),
+ isa_flags: compiler.isa_flags(),
tunables: engine.tunables().clone(),
features: engine.features().bits(),
- }
+ })
}
fn check_compatible(mut self, engine: &Engine) -> Result<()> {
@@ -441,7 +442,7 @@ mod test {
#[test]
fn test_architecture_mismatch() -> Result<()> {
let engine = Engine::default();
- let mut metadata = Metadata::new(&engine);
+ let mut metadata = Metadata::new(&engine)?;
metadata.target = "unknown-generic-linux".to_string();
match metadata.check_compatible(&engine) {
@@ -460,7 +461,7 @@ mod test {
#[cfg(all(target_arch = "x86_64", not(miri)))]
fn test_os_mismatch() -> Result<()> {
let engine = Engine::default();
- let mut metadata = Metadata::new(&engine);
+ let mut metadata = Metadata::new(&engine)?;
metadata.target = format!(
"{}-generic-unknown",
@@ -481,7 +482,7 @@ mod test {
#[test]
fn test_cranelift_flags_mismatch() -> Result<()> {
let engine = Engine::default();
- let mut metadata = Metadata::new(&engine);
+ let mut metadata = Metadata::new(&engine)?;
metadata
.shared_flags
@@ -504,7 +505,7 @@ Caused by:
#[test]
fn test_isa_flags_mismatch() -> Result<()> {
let engine = Engine::default();
- let mut metadata = Metadata::new(&engine);
+ let mut metadata = Metadata::new(&engine)?;
metadata
.isa_flags
@@ -532,7 +533,7 @@ Caused by:
#[cfg(target_pointer_width = "64")] // different defaults on 32-bit platforms
fn test_tunables_int_mismatch() -> Result<()> {
let engine = Engine::default();
- let mut metadata = Metadata::new(&engine);
+ let mut metadata = Metadata::new(&engine)?;
metadata.tunables.memory_guard_size = 0;
@@ -553,7 +554,7 @@ Caused by:
config.epoch_interruption(true);
let engine = Engine::new(&config)?;
- let mut metadata = Metadata::new(&engine);
+ let mut metadata = Metadata::new(&engine)?;
metadata.tunables.epoch_interruption = false;
match metadata.check_compatible(&engine) {
@@ -568,7 +569,7 @@ Caused by:
config.epoch_interruption(false);
let engine = Engine::new(&config)?;
- let mut metadata = Metadata::new(&engine);
+ let mut metadata = Metadata::new(&engine)?;
metadata.tunables.epoch_interruption = true;
match metadata.check_compatible(&engine) {
@@ -590,7 +591,7 @@ Caused by:
config.wasm_threads(true);
let engine = Engine::new(&config)?;
- let mut metadata = Metadata::new(&engine);
+ let mut metadata = Metadata::new(&engine)?;
metadata.features &= !wasmparser::WasmFeatures::THREADS.bits();
// If a feature is disabled in the module and enabled in the host,
@@ -601,7 +602,7 @@ Caused by:
config.wasm_threads(false);
let engine = Engine::new(&config)?;
- let mut metadata = Metadata::new(&engine);
+ let mut metadata = Metadata::new(&engine)?;
metadata.features |= wasmparser::WasmFeatures::THREADS.bits();
match metadata.check_compatible(&engine) {
diff --git a/tests/all/engine.rs b/tests/all/engine.rs
new file mode 100644
index 0000000000..e681242a85
--- /dev/null
+++ b/tests/all/engine.rs
@@ -0,0 +1,14 @@
+use super::*;
+use wasmtime::*;
+
+#[test]
+fn engine_without_compiler_cannot_compile() -> Result<()> {
+ let mut config = Config::new();
+ config.enable_compiler(false);
+ let engine = Engine::new(&config)?;
+ match Module::new(&engine, r#"(module (func (export "f") nop))"#) {
+ Ok(_) => panic!("should not compile without a compiler"),
+ Err(err) => err.assert_contains("Engine was not configured with a compiler"),
+ }
+ Ok(())
+}
diff --git a/tests/all/main.rs b/tests/all/main.rs
index 820dbc6ba8..e3f3198dc2 100644
--- a/tests/all/main.rs
+++ b/tests/all/main.rs
@@ -13,6 +13,7 @@ mod coredump;
mod custom_code_memory;
mod debug;
mod defaults;
+mod engine;
mod epoch_interruption;
mod eqref;
mod exceptions;