Skip to content

Commit cbeda5c

Browse files
committed
Auto merge of #86467 - ChrisDenton:win-env-clear, r=JohnTitor
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
2 parents d95745e + 16145a9 commit cbeda5c

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

library/std/src/process/tests.rs

+9
Original file line numberDiff line numberDiff line change
@@ -399,3 +399,12 @@ fn test_command_implements_send_sync() {
399399
fn take_send_sync_type<T: Send + Sync>(_: T) {}
400400
take_send_sync_type(Command::new(""))
401401
}
402+
403+
// Ensure that starting a process with no environment variables works on Windows.
404+
// This will fail if the environment block is ill-formed.
405+
#[test]
406+
#[cfg(windows)]
407+
fn env_empty() {
408+
let p = Command::new("cmd").args(&["/C", "exit 0"]).env_clear().spawn();
409+
assert!(p.is_ok());
410+
}

library/std/src/sys/windows/process.rs

+6
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,12 @@ fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) -> io::Result<(*mut
530530
if let Some(env) = maybe_env {
531531
let mut blk = Vec::new();
532532

533+
// If there are no environment variables to set then signal this by
534+
// pushing a null.
535+
if env.is_empty() {
536+
blk.push(0);
537+
}
538+
533539
for (k, v) in env {
534540
blk.extend(ensure_no_nuls(k.0)?.encode_wide());
535541
blk.push('=' as u16);

0 commit comments

Comments
 (0)