Skip to content

harden session startup against silent background-thread crashes - #18520

Merged
kevinushey merged 4 commits into
mainfrom
bugfix/startup-signal-and-environ-hardening
Aug 11, 2026
Merged

kevinushey merged 4 commits into
mainfrom
bugfix/startup-signal-and-environ-hardening

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Background

Investigating the silent c++-unit-tests segfault on PR #18509's Jenkins run (rsession died ~250ms into startup, before any test ran, with libSegFault preloaded yet zero output) established the mechanics of why such crashes are silent, and turned up several startup hazards that fit the failure signature. Container experiments on the CI image's OS (jammy + glibc-tools libSegFault) confirmed that a fault on a thread with SIGSEGV blocked dies with no handler output whatsoever -- and safeLaunchThread / core::thread::run block all signals on every background thread we start. This is the same family as #10756, which has been observed intermittently for years and never root-caused.

Addresses #10756.

Changes

  1. SignalBlocker::blockAll() no longer blocks synchronous fault signals (SIGSEGV, SIGBUS, SIGILL, SIGFPE). These are always delivered to the faulting thread, so blocking them cannot route them to the main thread like the async signals this mask exists for -- the kernel simply bypasses any installed crash handler and terminates the process with no diagnostics. Unblocking them costs nothing and makes every background-thread crash reportable.

  2. POSIX core::system::{getenv,setenv,unsetenv,environment} are now serialized on a mutex. glibc's setenv can reallocate (and free) the environ array while a concurrent getenv walks it without locking; the codebase already documents this crash class for the resolver's LOCALDOMAIN read (mainThreadWorkaround(), rstudio-pro#4628), but the general race remained. The mutex is a plain pthread mutex registered with pthread_atfork (lock in prepare, unlock in parent/child) because forked children read the environment before exec (launchChildProcess reads SHELL), and a fork must not snapshot the mutex in a locked state. Direct ::getenv callers (libc internals, R) are unaffected either way.

  3. The desktop parent-termination monitor no longer reads the environment on its own thread. waitForParentTermination() read RS_PPM_FD_READ/RS_PPM_FD_WRITE as the first act of a freshly spawned, fully signal-masked thread, while the main thread's very next statement after spawning it calls setenv("RS_RPOSTBACK_PATH", ...) -- a new variable, i.e. the environ-realloc case. This is the best-fitting candidate for the observed crash: it exists only in desktop mode (exactly what rstudio-tests runs on the Electron CI flavor via rdesktop-dev.conf, and not in local server-mode runs), it is silent by mechanism, and it is scheduling-dependent (the CI stage runs in parallel with the GWT unit tests on the same node). The fds are now read on the main thread via a new parentTerminationFds() helper and passed into the thread; the no-arg waitForParentTermination() remains for compatibility, and the Windows/macOS variants are unchanged.

  4. initializeLogConfigReload() now starts at most one SIGHUP reload thread. Desktop mode initializes logging twice, which previously left two detached threads sigwaiting the same SIGHUP and both re-initializing the log on receipt.

Testing

  • New core gtests: SafeLaunchThreadLeavesFaultSignalsUnblocked asserts the spawned-thread mask (fault signals unblocked, SIGINT/SIGTERM/SIGHUP still blocked); WaitForParentTermination* cover the fd-based overload's no-parent / normal / abnormal semantics.
  • rstudio-tests --scope core: 487 tests pass; --scope rsession: 416 tests pass (the rsession suite exercises the full startup path -- env locking, new signal masks, parent monitor -- inside a live R session).
  • The paired diagnostics change (always capture a stack trace when a test process crashes #18517, merged) means any recurrence of the CI crash now yields a gdb backtrace from the core dump, which will confirm or refute the remaining candidates.

Investigation of the PR-18509 c++-unit-tests segfault (rsession died
~250ms into startup with no diagnostics) identified why such crashes
are silent and several startup hazards that fit the failure signature.
Addresses #10756.

Why crashes were silent: safeLaunchThread and core::thread::run block
ALL signals on every background thread. Synchronous fault signals are
always delivered to the faulting thread, so blocking them cannot route
them elsewhere -- the kernel just bypasses any installed crash handler
(libSegFault included) and kills the process with no output.

Changes:

- SignalBlocker::blockAll no longer blocks SIGSEGV/SIGBUS/SIGILL/
  SIGFPE, so crashes on background threads produce crash reports.

- core::system::{getenv,setenv,unsetenv,environment} on POSIX now
  serialize on a pthread mutex: glibc setenv can reallocate the environ
  array while a concurrent getenv walks it unlocked (the crash class
  already documented for getaddrinfo/LOCALDOMAIN, rstudio-pro#4628).
  The mutex participates in pthread_atfork because forked children read
  the environment before exec (launchChildProcess reads SHELL).

- the desktop parent-termination monitor thread no longer reads
  RS_PPM_FD_* from the environment on the freshly launched (fully
  signal-masked) thread; the fds are read on the main thread and passed
  in. This getenv raced the setenv(RS_RPOSTBACK_PATH) executed
  immediately after the thread spawn -- the best-fitting candidate for
  the observed crash: desktop-mode-only, silent, and scheduling-
  dependent. Windows/macOS variants unchanged.

- initializeLogConfigReload only starts one SIGHUP reload thread even
  though desktop mode initializes logging twice.

Tests: new core gtests assert the launched-thread signal mask (fault
signals unblocked, async signals blocked) and the fd-based
waitForParentTermination semantics. 487 core + 416 rsession tests
pass.
@kevinushey kevinushey added this to the 2026.09 (Autumn Hawkbit) milestone Aug 11, 2026
@kevinushey
kevinushey requested a review from gtritchie August 11, 2026 20:55
Survey of remaining raw ::getenv / ::setenv use found several sites that
bypassed the new lock, including one that shared_core cannot reach from
core (dependency direction). Promote the lock to a public cross-platform
primitive and cover them:

- new shared_core/system/EnvironmentLock.{hpp,cpp}: POSIX uses the
  pthread mutex + pthread_atfork integration (moved from core's
  PosixEnvironment.cpp); Windows uses a statically-initialized SRWLOCK.
  Windows' Get/SetEnvironmentVariable already serialize internally, but
  the lock gives uniform semantics so call sites need not special-case
  platforms. The lock is not recursive: it is taken at the lowest level
  that touches the environment, exactly once (Win32Environment::getenv
  delegates to detail::getenv and so does not lock).

- shared_core posix::getEnvironmentVariable now locks; it backs
  User::getUserHomePath's HOME reads, which are reachable from
  background threads.

- EnvironmentScope captured the char* returned by ::getenv and
  dereferenced it in its destructor, after intervening setenvs may have
  reallocated environ -- a dangling pointer independent of threading.
  It now copies the previous value under the lock (preserving the
  set-but-empty vs unset distinction).

- PosixParentProcessMonitor's getFdEnv/setFdEnv lock; also fix setenv's
  third argument, which was passing a string length where the API takes
  an overwrite flag (worked only by accident).

- SessionConsoleProcess's two ::getenv("ENV") reads lock, keeping the
  raw call for the set-but-empty vs unset distinction.

Left alone deliberately: r::util::getenv (R's Sys.getenv, main-thread
confined; R reads the environment internally either way), the
single-threaded rserver-url-ports binary and ServerSetupDb setup path,
test bodies, and libc-internal readers (getaddrinfo/LOCALDOMAIN), which
no lock of ours can cover.

Tests: EnvironmentScope restore/unset semantics (including an
environ-reshuffle case that dangled with the old char* member) and a
two-thread getenv/setenv hammer; a locking regression shows up there as
a watchdog-reported deadlock. 490 core + 416 rsession tests pass.
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Second commit extends the environment locking based on a survey of remaining raw ::getenv / ::setenv call sites, and makes the lock a public cross-platform primitive per discussion:

  • EnvironmentLock now lives in shared_core/system/EnvironmentLock.{hpp,cpp} -- POSIX keeps the pthread mutex + pthread_atfork integration; Windows uses a statically-initialized SRWLOCK. Windows' Get/SetEnvironmentVariableW already serialize internally (the environ-realloc UAF is a glibc behavior), so the Windows lock exists for uniform semantics and cross-call atomicity rather than crash-safety. The lock is non-recursive and is taken at the lowest level that touches the environment, exactly once -- Win32Environment::getenv delegates to detail::getenv and deliberately does not lock.
  • Newly covered raw sites: shared_core posix::getEnvironmentVariable (backs User::getUserHomePath's HOME reads, reachable from background threads, and unreachable by a core-level lock due to dependency direction -- this is what forced the move to shared_core); EnvironmentScope (which also had a latent dangling-pointer bug: it stored the char* from ::getenv and dereferenced it in its destructor after intervening setenvs could have reallocated environ -- it now copies the value under the lock); PosixParentProcessMonitor's fd env helpers (plus a fix for setenv's third argument, which was passing a string length where the API takes an overwrite flag); and SessionConsoleProcess's ::getenv("ENV") reads (raw call kept for the set-but-empty vs unset distinction).
  • Deliberately left: r::util::getenv (delegates to R's Sys.getenv, main-thread confined; R reads the environment internally with its own raw getenv either way), the single-threaded rserver-url-ports binary, ServerSetupDb's setup-time read, test bodies, and libc-internal readers (getaddrinfo/LOCALDOMAIN), which no lock of ours can cover.
  • New tests: EnvironmentScope restore/unset semantics (including an environ-reshuffle case that dangled with the old char* member) and a two-thread getenv/setenv hammer -- it can't prove the race gone, but a locking regression (e.g. accidental recursive acquisition) manifests there as a deadlock, which the test watchdog reports with a backtrace.

490 core + 416 rsession tests pass locally. Windows bits are compile-unverified from this machine; they are small (SRWLOCK + two lock statements) but deserve a look from the Windows CI build.

The Snyk Code PR scan flags findProgramOnPath's PATH loop with a LOW
path-traversal finding: env data (PATH) flows into ::open. The open was
only anchoring fstatat/faccessat against each PATH directory; the check
can be expressed directly against the joined candidate path with
::stat + ::faccessat(AT_FDCWD, ...), matching the path-qualified branch
above. stat/access do not read file contents, so the taint path to a
file-read sink is gone -- verified with a local 'snyk code test' on the
same changed-file set the Jenkins stage scans (1 issue -> 0).

The finding only fired on this PR because the diff-scoped scan finally
saw both the taint source (PosixEnvironment.cpp, core::system::getenv)
and the sink file together; the flagged code itself is from #9620.

Behavior notes: empty PATH entries are now skipped explicitly (open("")
failed naturally before; completeChildPath would otherwise resolve them
against the working directory), and symlinks are still followed. The
FindProgram* gtests pass unchanged.
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Third commit addresses the Snyk Code check failure (LOW path-traversal on findProgramOnPath, PosixSystem.cpp:323).

The flagged code predates this PR (#9620); it fired here because the diff-scoped scan finally saw the taint source and the sink in one scanned file set -- PosixEnvironment.cpp (which defines core::system::getenv) and PosixSystem.cpp have never shared a PR diff before. The finding itself is a false positive (a PATH search opens the process's own PATH directory entries by definition; no trust boundary is crossed), but since suppression channels aren't available, the loop is restructured so the taint path to a file-read sink no longer exists: the directory-fd anchor (open + fstatat/faccessat relative to it) is replaced with direct ::stat + ::faccessat(AT_FDCWD, ...) checks on the joined candidate path, matching the style of the path-qualified branch above. Arguably a simplification -- no fd lifecycle to manage.

Verified empirically by reproducing the Jenkins scan locally (snyk code test over the same changed-file set): 1 issue before, 0 after. For the record, obfuscating the "PATH" literal (e.g. #define kPathEnvVar "" "PATH") does not dodge it -- tested; the taint source is the getenv call, not the variable name.

Behavior parity notes: empty PATH entries are now skipped explicitly (previously open("") failed naturally; completeChildPath would otherwise resolve them against the cwd, a behavior change we don't want), symlinks are still followed, and the effective-uid execute check is unchanged. FindProgram* gtests pass, full core scope green (490).

@gtritchie

Copy link
Copy Markdown
Member

Code review findings

One actionable item from an automated review. Non-blocking.

  1. src/cpp/shared_core/include/shared_core/system/EnvironmentLock.hpp:38 — the header disclaims
    third-party reads ("libc internals, R"), but it is third-party writes that cause the
    use-after-free this lock exists to prevent. A user running Sys.setenv(NEW_VAR = "x") goes
    straight to glibc setenv on the main thread and reallocates environ; a background thread
    walking environ inside core::system::environment() is holding the new mutex but gets no
    protection from it, because R never takes it. As written the disclaimer reads as though the
    write side is now covered. Fix: state that writes made outside the core::system accessors
    (notably R's Sys.setenv) are not serialized, so the race is closed only between RStudio's own
    callers.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! One non-blocking finding.

@kevinushey

Copy link
Copy Markdown
Collaborator Author

Good catch -- the disclaimer only named the read side. Reworded in a913e9d: neither reads nor writes made outside the core::system accessors take the lock (R's Sys.setenv calls ::setenv directly and can reallocate environ under a locked reader), so the race is closed only among RStudio's own callers. Kept the read side in the wording too, since libc-internal reads racing our locked writes are the rstudio-pro#4628 case this comment already referenced.

@kevinushey
kevinushey merged commit 9902e28 into main Aug 11, 2026
2 of 6 checks passed
@kevinushey
kevinushey deleted the bugfix/startup-signal-and-environ-hardening branch August 11, 2026 23:39
@github-actions

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
1837 0 317 10
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 1 0 8 0
✅ desktop-linux 515 0 90 2
✅ desktop-macos 519 0 86 3
✅ desktop-windows 520 0 90 3
✅ server-linux 263 0 35 2
✅ setup 19 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 a913e9d261a2d513d284eeaed6d221c804c91ba3 - Run #548

kevinushey added a commit that referenced this pull request Aug 13, 2026
* fix EnvironmentScope previous-value capture on windows

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.

* address review: deduplicate win32 getenv, widen unsetenv name correctly

- 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
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