Skip to content

fix EnvironmentScope previous-value capture on windows - #18523

Merged
kevinushey merged 2 commits into
mainfrom
bugfix/environment-scope-win32-getenv
Aug 13, 2026
Merged

kevinushey merged 2 commits into
mainfrom
bugfix/environment-scope-win32-getenv

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Fixes the ide-os-windows/main build break introduced by #18520 (first red run: build 3710). The new core gtest EnvironmentTest.EnvironmentScopeRestoresPreviousValue fails deterministically on Windows:

src\cpp\core\system\EnvironmentTests.cpp(79): error: Expected equality of these values:
  "original"
  getenv("RSTUDIO_ENV_SCOPE_TEST")
    Which is: ""

Root cause

EnvironmentScope captured the previous value with raw ::getenv, but core::system::setenv writes through SetEnvironmentVariableW. On Windows those are two different stores: ::getenv reads the CRT's _environ snapshot taken at process start, which SetEnvironmentVariable never updates. Any variable set via core::system::setenv was invisible to the scope, so its destructor took the "was unset" path and deleted the variable instead of restoring it. On POSIX both calls hit the same libc environ, which is why the test was green locally and on the other platforms.

Fix

Add an existence-preserving accessor to core::system:

bool getenv(const std::string& name, std::string* pValue);
  • POSIX: ::getenv under the environment lock, nullptr -> false.
  • Windows: GetEnvironmentVariableW under the lock (the same store the setters write), with ERROR_ENVVAR_NOT_FOUND distinguishing unset.

EnvironmentScope now captures the previous value through this overload, keeping the unset vs set-but-empty distinction #18520 introduced (on POSIX; that distinction does not exist on Windows, where setting a variable to the empty string deletes it). This also removes the last raw ::getenv from the public header, along with the stdlib.h and EnvironmentLock.hpp includes it needed -- every remaining EnvironmentLock user includes that header directly.

The Windows brokenness predates #18520 but never had production impact: the only non-test EnvironmentScope user is Apple-only (SourceIndex.cpp), and XdgTests.cpp is compiled out on Windows, so the new test was the first code to exercise EnvironmentScope there.

Tests

  • New gtest EnvironmentTest.GetenvOverloadDistinguishesUnset covers unset/set round-trips through setenv (which on Windows exercises exactly the CRT-vs-process-block mismatch) plus the POSIX-only set-but-empty case.
  • macOS: full core suite green (491 passed / 8 skipped), full backend build clean.
  • Windows: not verifiable from this machine -- Win32Environment.cpp needs the Windows CI build; the failing test should flip to green on the next ide-os-windows run.

The core gtest added in #18520
(EnvironmentTest.EnvironmentScopeRestoresPreviousValue) fails
deterministically on Windows, turning the ide-os-windows pipeline red:
EnvironmentScope captured the previous value with raw ::getenv, which
reads the CRT's startup snapshot of the environment, while
core::system::setenv writes the process environment block via
SetEnvironmentVariableW. A variable set through core::system::setenv was
therefore invisible to the scope, which unset it on destruction instead
of restoring it.

Add a core::system::getenv overload that reports whether the variable is
set (preserving the unset vs set-but-empty distinction #18520 wanted) and
reads the same store the setters write on both platforms, and use it in
EnvironmentScope. This also removes the last raw ::getenv from the public
header, along with the stdlib.h and EnvironmentLock.hpp includes it
needed.

The pre-existing Windows brokenness never had production impact: the only
non-test EnvironmentScope user is Apple-only (SourceIndex.cpp), and
XdgTests.cpp is compiled out on Windows -- the #18520 test was the first
code to exercise EnvironmentScope there.
@kevinushey kevinushey added this to the 2026.09 (Autumn Hawkbit) milestone Aug 12, 2026
@github-actions

github-actions Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

1 test(s) failed

###################- 99% pass rate

Passed Failed Skipped Flaky
2108 1 394 0
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 2 0 8 0
✅ desktop-linux 526 0 90 0
✅ desktop-macos 522 0 95 0
❌ desktop-windows 522 1 99 0
✅ server-linux 514 0 94 0
✅ setup 22 0 8 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit c5df09e70bf0c300c8375dad384def9d84ea735b - Run #565

@gtritchie

Copy link
Copy Markdown
Member

Code review findings

Non-blocking. The fix itself looks right: reading through GetEnvironmentVariableW under the same lock the setters use is the correct store, the result > nSize truncation test is right (a required size equal to the buffer size would have fit and returned a success count instead), and dropping the header's EnvironmentLock.hpp / stdlib.h includes is safe — the four remaining EnvironmentLock users all include it directly.

One suggestion:

  1. src/cpp/core/system/Win32Environment.cpp:92 — the new two-arg getenv is a near-verbatim copy of detail::getenv (src/cpp/shared_core/system/Win32User.cpp:137): same 256-char buffer, same resize retry, same failure handling. The copies have already diverged on how they widen the name — the new one uses string_utils::utf8ToWide, detail::getenv widens byte-by-byte with std::wstring nameWide(name.begin(), name.end()). For a name with non-ASCII characters ("VÄR", UTF-8 56 C3 84 52) that yields L"VÃ�R" vs. L"VÄR", so the two overloads look up different variables. Having the one-arg getenv delegate to the new two-arg one removes the duplication and the divergence together, since the byte-wise widening is the incorrect copy.

    Minor, in the same function: on the resize-retry path a failed second call returns false, which callers read as "variable unset" rather than "read failed" — an EnvironmentScope would then unsetenv a variable it meant to restore. The window requires the variable to be deleted between the two calls by something outside the environment lock, so this is theoretical; worth a log rather than a silent false.

- one-arg getenv now delegates to the two-arg overload instead of
  wrapping detail::getenv, removing the duplicated read loop and its
  byte-wise name widening
- unsetenv goes through SetEnvironmentVariableW with a UTF-8 decoded
  name, matching setenv and getenv
- log when the resize-retry read fails instead of silently reporting
  the variable as unset
- add a round-trip test for non-ASCII variable names
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Both applied in c5df09e:

  1. The one-arg getenv now delegates to the two-arg overload, so core no longer goes through detail::getenv's byte-wise widening. The shared_core copy stays as-is -- shared_core can't depend on core, and its remaining callers only pass ASCII names (HOMEDRIVE/HOMEPATH/R_USER).
  2. The failed retry now logs the variable name via WLOGF before reporting unset.

Writing a round-trip test for the widening divergence turned up one more instance of the same class: unsetenv was calling the ANSI SetEnvironmentVariable with UTF-8 bytes, so under a non-UTF-8 ANSI code page it would delete the wrong variable for a non-ASCII name. Now goes through SetEnvironmentVariableW like the other accessors. The new AccessorsAgreeOnNonAsciiNames gtest covers all three accessors and fails on the old code on Windows.

@kevinushey
kevinushey merged commit 2ddf63b into main Aug 13, 2026
44 of 47 checks passed
@kevinushey
kevinushey deleted the bugfix/environment-scope-win32-getenv branch August 13, 2026 16:52
kevinushey added a commit that referenced this pull request Aug 13, 2026
Keep this branch's setenv/unsetenv CRT write-through (which subsumes
main's UTF-16 name widening from #18523) alongside main's new two-arg
getenv tests. EnvironmentTests.cpp now includes stdlib.h directly,
since #18523 removed it from Environment.hpp and the Windows CRT test
here uses raw ::getenv.
@gtritchie gtritchie mentioned this pull request Aug 31, 2026
3 of 4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants