Skip to content

Commit

Permalink
Auto merge of #86467 - ChrisDenton:win-env-clear, r=JohnTitor
Browse files Browse the repository at this point in the history
Windows: Fix `Command::env_clear` so it works if no variables are set

Previously, it would error unless at least one new environment variable was added. The missing null presumably meant that Windows was reading random memory in that case.

See: [CreateProcessW](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw) (scroll down to `lpEnvironment`). Essentially the environment block is a null terminated list of null terminated strings and an empty list is `\0\0` and not `\0`.

EDIT: Oh, [CreateEnvironmentBlock](https://docs.microsoft.com/en-gb/windows/win32/api/userenv/nf-userenv-createenvironmentblock) states this much more explicitly.

Fixes #31259
  • Loading branch information
bors committed Jun 24, 2021
2 parents d95745e + 16145a9 commit cbeda5c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
9 changes: 9 additions & 0 deletions library/std/src/process/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,3 +399,12 @@ fn test_command_implements_send_sync() {
fn take_send_sync_type<T: Send + Sync>(_: T) {}
take_send_sync_type(Command::new(""))
}

// Ensure that starting a process with no environment variables works on Windows.
// This will fail if the environment block is ill-formed.
#[test]
#[cfg(windows)]
fn env_empty() {
let p = Command::new("cmd").args(&["/C", "exit 0"]).env_clear().spawn();
assert!(p.is_ok());
}
6 changes: 6 additions & 0 deletions library/std/src/sys/windows/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,12 @@ fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) -> io::Result<(*mut
if let Some(env) = maybe_env {
let mut blk = Vec::new();

// If there are no environment variables to set then signal this by
// pushing a null.
if env.is_empty() {
blk.push(0);
}

for (k, v) in env {
blk.extend(ensure_no_nuls(k.0)?.encode_wide());
blk.push('=' as u16);
Expand Down

0 comments on commit cbeda5c

Please sign in to comment.