Repository navigation
harden session startup against silent background-thread crashes - #18520
Conversation
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.
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.
|
Second commit extends the environment locking based on a survey of remaining raw
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.
|
Third commit addresses the Snyk Code check failure (LOW path-traversal on 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 -- Verified empirically by reproducing the Jenkins scan locally ( Behavior parity notes: empty PATH entries are now skipped explicitly (previously |
Code review findingsOne actionable item from an automated review. Non-blocking.
|
gtritchie
left a comment
There was a problem hiding this comment.
LGTM! One non-blocking finding.
|
Good catch -- the disclaimer only named the read side. Reworded in a913e9d: neither reads nor writes made outside the |
RStudio E2E - all platformsAll tests passed!
View / download the full reportView report online -- opens in the browser, no download needed. Available for 14 days. Download playwright-report.zip -- extract and open
All platforms - commit |
* 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
Background
Investigating the silent
c++-unit-testssegfault 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 -- andsafeLaunchThread/core::thread::runblock 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
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.POSIX
core::system::{getenv,setenv,unsetenv,environment}are now serialized on a mutex. glibc'ssetenvcan reallocate (and free) theenvironarray while a concurrentgetenvwalks it without locking; the codebase already documents this crash class for the resolver'sLOCALDOMAINread (mainThreadWorkaround(), rstudio-pro#4628), but the general race remained. The mutex is a plain pthread mutex registered withpthread_atfork(lock in prepare, unlock in parent/child) because forked children read the environment before exec (launchChildProcessreadsSHELL), and a fork must not snapshot the mutex in a locked state. Direct::getenvcallers (libc internals, R) are unaffected either way.The desktop parent-termination monitor no longer reads the environment on its own thread.
waitForParentTermination()readRS_PPM_FD_READ/RS_PPM_FD_WRITEas the first act of a freshly spawned, fully signal-masked thread, while the main thread's very next statement after spawning it callssetenv("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 whatrstudio-testsruns on the Electron CI flavor viardesktop-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 newparentTerminationFds()helper and passed into the thread; the no-argwaitForParentTermination()remains for compatibility, and the Windows/macOS variants are unchanged.initializeLogConfigReload()now starts at most one SIGHUP reload thread. Desktop mode initializes logging twice, which previously left two detached threadssigwaiting the same SIGHUP and both re-initializing the log on receipt.Testing
SafeLaunchThreadLeavesFaultSignalsUnblockedasserts 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).