From b8e771a0b62db460b6739de6474a2f20fed044da Mon Sep 17 00:00:00 2001 From: Charles Hu <charles@hu.codes> Date: Wed, 14 Aug 2024 15:57:06 -0700 Subject: [PATCH] Hide Windows magic environment values from ProcessInfo.environment Windows GetEnvironmentStringsW API can return magic environment variables set by the cmd shell that starts with "=". We should hide these values to avoid surprising behavior. resolves: https://github.com/apple/swift-foundation/issues/847 --- .../FoundationEssentials/ProcessInfo/ProcessInfo.swift | 10 ++++++++++ Tests/FoundationEssentialsTests/ProcessInfoTests.swift | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift b/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift index 3108f414f..ce662f225 100644 --- a/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift +++ b/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift @@ -75,6 +75,16 @@ final class _ProcessInfo: Sendable { for env in environments { let environmentString = String(cString: env) +#if os(Windows) + // Windows GetEnvironmentStringsW API can return + // magic environment variables set by the cmd shell + // that starts with `=` + // We should exclude these values + if environmentString.utf8.first == ._equal { + continue + } +#endif // os(Windows) + guard let delimiter = environmentString.firstIndex(of: "=") else { continue } diff --git a/Tests/FoundationEssentialsTests/ProcessInfoTests.swift b/Tests/FoundationEssentialsTests/ProcessInfoTests.swift index 6cf540240..28c153bea 100644 --- a/Tests/FoundationEssentialsTests/ProcessInfoTests.swift +++ b/Tests/FoundationEssentialsTests/ProcessInfoTests.swift @@ -189,4 +189,14 @@ final class ProcessInfoTests : XCTestCase { processInfo.processName = originalProcessName XCTAssertEqual(processInfo.processName, originalProcessName) } + + func testWindowsEnvironmentDoesNotContainMagicValues() { + // Windows GetEnvironmentStringsW API can return + // magic environment variables set by the cmd shell + // that starts with `=` + // This test makes sure we don't include these + // magic variables + let env = ProcessInfo.processInfo.environment + XCTAssertNil(env[""]) + } }