Repository: bytecodealliance/wasmtime
Pull request #8127 (2024-03-14 00:18:24)

[19.0.0] Fix `wasmtime settings` command. 
Backport of #8060 to the 19.0.0 release branch

github-actions[bot]: #### Subscribe to Label Action

cc @peterhuene

<details>
This issue or pull request has been labeled: "wasmtime:api", "wasmtime:config"

Thus the following users have been cc'd because of the following labels:

* peterhuene: wasmtime:api

To subscribe or unsubscribe from this label, edit the <code>.github/subscribe-to-label.json</code> configuration file.

[Learn more.](https://github.com/bytecodealliance/subscribe-to-label-action)
</details>
github-actions[bot]: #### Label Messager: wasmtime:config

It looks like you are changing Wasmtime's configuration options. Make sure to
complete this check list:

* [ ] If you added a new `Config` method, you wrote extensive documentation for
      it.

  <details>

  Our documentation should be of the following form:

  ```text
  Short, simple summary sentence.

  More details. These details can be multiple paragraphs. There should be
  information about not just the method, but its parameters and results as
  well.

  Is this method fallible? If so, when can it return an error?

  Can this method panic? If so, when does it panic?

  # Example

  Optional example here.
  ```

  </details>

* [ ] If you added a new `Config` method, or modified an existing one, you
  ensured that this configuration is exercised by the fuzz targets.

  <details>

  For example, if you expose a new strategy for allocating the next instance
  slot inside the pooling allocator, you should ensure that at least one of our
  fuzz targets exercises that new strategy.

  Often, all that is required of you is to ensure that there is a knob for this
  configuration option in [`wasmtime_fuzzing::Config`][fuzzing-config] (or one
  of its nested `struct`s).

  Rarely, this may require authoring a new fuzz target to specifically test this
  configuration. See [our docs on fuzzing][fuzzing-docs] for more details.

  </details>

* [ ] If you are enabling a configuration option by default, make sure that it
  has been fuzzed for at least two weeks before turning it on by default.

[fuzzing-config]: https://github.com/bytecodealliance/wasmtime/blob/ca0e8d0a1d8cefc0496dba2f77a670571d8fdcab/crates/fuzzing/src/generators.rs#L182-L194
[fuzzing-docs]: https://docs.wasmtime.dev/contributing-fuzzing.html


--------------------------------------------------------------------------------

<details>

To modify this label's message, edit the <code>.github/label-messager/wasmtime-config.md</code> file.

To add new label messages or remove existing label messages, edit the
<code>.github/label-messager.json</code> configuration file.

[Learn more.](https://github.com/bytecodealliance/label-messager-action)

</details>

Patch:
diff --git a/crates/environ/src/tunables.rs b/crates/environ/src/tunables.rs
index 4ff360fcb..7328345ee 100644
--- a/crates/environ/src/tunables.rs
+++ b/crates/environ/src/tunables.rs
@@ -1,4 +1,6 @@
+use anyhow::{anyhow, bail, Result};
 use serde_derive::{Deserialize, Serialize};
+use target_lexicon::{PointerWidth, Triple};
 
 /// Tunable parameters for WebAssembly compilation.
 #[derive(Clone, Hash, Serialize, Deserialize, Debug)]
@@ -70,6 +72,18 @@ impl Tunables {
         }
     }
 
+    /// Returns the default set of tunables for the given target triple.
+    pub fn default_for_target(target: &Triple) -> Result<Self> {
+        match target
+            .pointer_width()
+            .map_err(|_| anyhow!("failed to retrieve target pointer width"))?
+        {
+            PointerWidth::U32 => Ok(Tunables::default_u32()),
+            PointerWidth::U64 => Ok(Tunables::default_u64()),
+            _ => bail!("unsupported target pointer width"),
+        }
+    }
+
     /// Returns the default set of tunables for running under MIRI.
     pub fn default_miri() -> Tunables {
         Tunables {
diff --git a/crates/wasmtime/src/config.rs b/crates/wasmtime/src/config.rs
index b9a22efdf..35e9fe4ba 100644
--- a/crates/wasmtime/src/config.rs
+++ b/crates/wasmtime/src/config.rs
@@ -6,7 +6,7 @@ use std::fmt;
 use std::path::Path;
 use std::str::FromStr;
 use std::sync::Arc;
-use target_lexicon::{Architecture, PointerWidth};
+use target_lexicon::Architecture;
 use wasmparser::WasmFeatures;
 #[cfg(feature = "cache")]
 use wasmtime_cache::CacheConfig;
@@ -1684,11 +1684,7 @@ impl Config {
         let mut tunables = Tunables::default_host();
         #[cfg(any(feature = "cranelift", feature = "winch"))]
         let mut tunables = match &self.compiler_config.target.as_ref() {
-            Some(target) => match target.pointer_width() {
-                Ok(PointerWidth::U32) => Tunables::default_u32(),
-                Ok(PointerWidth::U64) => Tunables::default_u64(),
-                _ => bail!("unknown pointer width"),
-            },
+            Some(target) => Tunables::default_for_target(target)?,
             None => Tunables::default_host(),
         };
 
diff --git a/src/commands/settings.rs b/src/commands/settings.rs
index 1a4a967f0..7055f9203 100644
--- a/src/commands/settings.rs
+++ b/src/commands/settings.rs
@@ -5,7 +5,7 @@ use clap::Parser;
 use serde::{ser::SerializeMap, Serialize};
 use std::collections::BTreeMap;
 use std::str::FromStr;
-use wasmtime_environ::{CompilerBuilder, FlagValue, Setting, SettingKind};
+use wasmtime_environ::{CompilerBuilder, FlagValue, Setting, SettingKind, Tunables};
 
 /// Displays available Cranelift settings for a target.
 #[derive(Parser, PartialEq)]
@@ -108,10 +108,16 @@ impl SettingsCommand {
     pub fn execute(self) -> Result<()> {
         // Gather settings from the cranelift compiler builder
         let mut builder = wasmtime_cranelift::builder(None)?;
-        if let Some(target) = &self.target {
+        let tunables = if let Some(target) = &self.target {
             let target = target_lexicon::Triple::from_str(target).map_err(|e| anyhow!(e))?;
+            let tunables = Tunables::default_for_target(&target)?;
             builder.target(target)?;
-        }
+            tunables
+        } else {
+            Tunables::default_host()
+        };
+
+        builder.set_tunables(tunables)?;
         let mut settings = Settings::from_builder(&builder);
 
         // Add inferred settings if no target specified


Test patch:
diff --git a/tests/all/cli_tests.rs b/tests/all/cli_tests.rs
index 175d3de1a..8fab74ac6 100644
--- a/tests/all/cli_tests.rs
+++ b/tests/all/cli_tests.rs
@@ -1588,3 +1588,10 @@ mod test_programs {
         Ok(())
     }
 }
+
+#[test]
+fn settings_command() -> Result<()> {
+    let output = run_wasmtime(&["settings"])?;
+    assert!(output.contains("Cranelift settings for target"));
+    Ok(())
+}