Skip to content

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

Implement WASI initial cwd configuration (#13468)

Angel Nereira78676bc722cb
diff --git a/crates/cli-flags/src/lib.rs b/crates/cli-flags/src/lib.rs
index 5a81ca87fc..be0c1f8837 100644
--- a/crates/cli-flags/src/lib.rs
+++ b/crates/cli-flags/src/lib.rs
@@ -546,6 +546,8 @@ wasmtime_option_group! {
pub inherit_stdout: Option<bool>,
/// Inherit stderr from the parent process. On by default.
pub inherit_stderr: Option<bool>,
+ /// Initial current working directory reported through `wasi:cli/environment`.
+ pub cwd: Option<String>,
/// Pass a wasi config variable to the program.
#[serde(skip)]
pub config_var: Vec<KeyValuePair>,
diff --git a/crates/test-programs/src/bin/p2_cli_initial_cwd.rs b/crates/test-programs/src/bin/p2_cli_initial_cwd.rs
new file mode 100644
index 0000000000..42bc7a6a8b
--- /dev/null
+++ b/crates/test-programs/src/bin/p2_cli_initial_cwd.rs
@@ -0,0 +1,5 @@
+use test_programs::wasi::cli::environment;
+
+fn main() {
+ assert_eq!(environment::initial_cwd().as_deref(), Some("/sandbox"));
+}
diff --git a/crates/wasi/src/ctx.rs b/crates/wasi/src/ctx.rs
index 0b84bc2dc2..7279122d02 100644
--- a/crates/wasi/src/ctx.rs
+++ b/crates/wasi/src/ctx.rs
@@ -242,6 +242,15 @@ impl WasiCtxBuilder {
self
}
+ /// Configures the initial current working directory reported to the guest.
+ ///
+ /// By default no initial current working directory is configured and
+ /// `wasi:cli/environment.initial-cwd` returns `none`.
+ pub fn initial_cwd(&mut self, path: impl AsRef<str>) -> &mut Self {
+ self.cli.initial_cwd = Some(path.as_ref().to_owned());
+ self
+ }
+
/// Configures a "preopened directory" to be available to WebAssembly.
///
/// By default WebAssembly does not have access to the filesystem because
diff --git a/src/common.rs b/src/common.rs
index 167d838548..4749bdc8b4 100644
--- a/src/common.rs
+++ b/src/common.rs
@@ -354,6 +354,9 @@ impl RunCommon {
wasmtime_wasi::FilePerms::all(),
)?;
}
+ if let Some(cwd) = &self.common.wasi.cwd {
+ builder.initial_cwd(cwd);
+ }
if self.common.wasi.listenfd == Some(true) {
bail!("components do not support --listenfd");
diff --git a/tests/all/cli_tests.rs b/tests/all/cli_tests.rs
index 3fa1daff94..047847fc03 100644
--- a/tests/all/cli_tests.rs
+++ b/tests/all/cli_tests.rs
@@ -1149,6 +1149,17 @@ mod test_programs {
Ok(())
}
+ #[test]
+ fn p2_cli_initial_cwd() -> Result<()> {
+ run_wasmtime(&[
+ "run",
+ "-Wcomponent-model",
+ "-Scwd=/sandbox",
+ P2_CLI_INITIAL_CWD_COMPONENT,
+ ])?;
+ Ok(())
+ }
+
#[test]
fn p2_cli_stdin_empty() -> Result<()> {
let mut child = get_wasmtime_command()?