Skip to content

[Linux] Prefer getrandom(2) over /dev/urandom; keep /proc/self/statm open - #394

Closed
dylan-conway wants to merge 4 commits into
mainfrom
claude/fs-sandbox-startup-reads
Closed

dylan-conway wants to merge 4 commits into
mainfrom
claude/fs-sandbox-startup-reads

Conversation

@dylan-conway

@dylan-conway dylan-conway commented Aug 8, 2026 •

Copy link
Copy Markdown
Member

Two small Linux-only changes so JSC can start inside a filesystem sandbox that hides /dev and /proc without crashing, and does less work on a GC path. No behaviour change on macOS/Windows/FreeBSD.

WTF::RandomDevice and bmalloc::ARC4RandomNumberGenerator::stir

Today both open /dev/urandom at startup and CRASH() / RELEASE_BASSERT if that fails, then keep the fd for the life of the process.

Now, on Linux, each probes getrandom(…, GRND_NONBLOCK) once:

  • returns 1 → the kernel pool is initialized; use getrandom for every subsequent read. No path is touched and no fd is held.
  • anything else — EAGAIN (pool not yet initialized, where a /dev/urandom read would have returned immediately), ENOSYS (kernel < 3.17), EPERM (seccomp) → fall through to the existing /dev/urandom code, unchanged.

So the only observable difference is on systems where getrandom already works and would return the same bytes from the same pool: one fewer open file and no dependency on /dev. The fallback open() gains O_CLOEXEC.

WTF::currentProcessMemoryStatus()

Reached from Heap::proportionalHeapSize → memoryFootprint() (because USE(BUN_JSC_ADDITIONS) turns on USE_MEMORY_FOOTPRINT_API), i.e. after collections. It did fopen("/proc/self/statm") + fgets + fclose on every call. It now opens the file once (O_RDONLY|O_CLOEXEC) and pread()s at offset 0, which is exactly what LinuxMemory in AvailableMemory.cpp already does for memoryStatus(). If the open fails it latches and keeps returning zeros as before, at zero cost.

Same caveat as LinuxMemory: the cached fd is bound to the pid that opened it, so a fork()-without-exec child would read the parent's numbers. JSCOnly never runs JSC in such a child (every fork is followed by exec), and upstream already accepted this trade-off for memoryStatus() on the same path.

Not built locally.

Options::useGetrandom (added 2026-08-21, with main merged in)

A JSC option that selects the source above. It defaults to true: WTF::RandomDevice reads getrandom(2) and opens /dev/urandom only when the syscall is unavailable, as described above. useGetrandom=false (BUN_JSC_useGetrandom=0 in bun) makes the device open /dev/urandom as it did before this change.

WTF::RandomDevice chooses its source when it is constructed, on the first request for randomness, so JSC::initialize() pushes the option into WTF (RandomDevice::setUseGetrandom) right after Options::initialize() and before ExecutableAllocator::initialize(), which can be that first request. That setter also forwards to bmalloc (setCryptoRandomUsesGetrandom): the ARC4 generator's source is now generator state under its mutex, chosen before the first stir and re-chosen by the setter in either direction, so the option governs every stir after JSC::initialize(). The one stir Gigacage triggers inside WTF::initialize() happens before any option is parsed and always uses the default (getrandom, then /dev/urandom); bmalloc re-stirs only after 1.6 MB of output, so in practice that first stir is the only one. Both setters are no-ops on platforms other than Linux.

Evidence for the sandbox case: Sentry BUN-4NQQ is a 1.4.0 Linux aarch64 bun run that aborted in RandomDevice::RandomDevice() during JSC::VM::VM (symbolized against the right build in oven-sh/bun#39801's notes), so /dev/urandom being unavailable does happen to users.

Verified: RandomDevice.cpp, OSRandomSource.cpp and bmalloc's CryptoRandom.cpp compile warning-free (-Wall -Wextra) with clang 21 against the tree, each in both the SYS_getrandom and the no-getrandom configuration. The JSC side (one option entry and one call) is left to CI.

…open

Two small changes so a JSC embedder can start inside a filesystem
sandbox that hides /dev and /proc without crashing, and with fewer
syscalls on a GC path.

RandomDevice / bmalloc CryptoRandom:
  On Linux, probe getrandom(GRND_NONBLOCK) once. If the pool is already
  initialized, use getrandom for all subsequent reads and never open
  /dev/urandom (no path access, no fd held for the process lifetime).
  If the probe returns anything else -- EAGAIN (pool not yet ready,
  where /dev/urandom would have returned without blocking), ENOSYS
  (kernel < 3.17) or EPERM (seccomp) -- fall back to the existing
  /dev/urandom code unchanged, so behaviour is identical wherever
  getrandom is not a strict improvement. The urandom fd is now opened
  O_CLOEXEC.

currentProcessMemoryStatus():
  This is reached from Heap::proportionalHeapSize via memoryFootprint()
  after collections. Open /proc/self/statm once and pread() it instead
  of fopen/fgets/fclose per call, matching what LinuxMemory in
  AvailableMemory.cpp already does for memoryStatus(). If the open
  fails the function keeps returning zeros as before, but now costs
  nothing on later calls. As with LinuxMemory, the cached fd is bound
  to the opening pid; JSCOnly never runs JSC in a fork()-without-exec
  child.
@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

Your included review limit has been reached.

You’re in a promotional period — use the checkbox below to run this review for free:

  • Run review for free

On-demand reviews are free for the next 30 days. After that, they cost $0.25 per reviewed file.

How can I continue?

Run this review now using the option above, or comment @coderabbitai review --use-credits.

You can also wait for the limit to reset (next review available in 1 minute), then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: ba6a3808-e3a7-4d8e-97a6-a386ff93ee8e

📥 Commits

Reviewing files that changed from the base of the PR and between 51a6d25 and 83df2b7.

📒 Files selected for processing (7)
  • Source/JavaScriptCore/runtime/InitializeThreading.cpp
  • Source/JavaScriptCore/runtime/OptionsList.h
  • Source/WTF/wtf/RandomDevice.cpp
  • Source/WTF/wtf/RandomDevice.h
  • Source/WTF/wtf/linux/CurrentProcessMemoryStatus.cpp
  • Source/bmalloc/bmalloc/CryptoRandom.cpp
  • Source/bmalloc/bmalloc/CryptoRandom.h

Walkthrough

Changes

Linux entropy source selection

Layer / File(s) Summary
getrandom detection and probing
Source/WTF/wtf/RandomDevice.cpp, Source/bmalloc/bmalloc/CryptoRandom.cpp
Linux builds define getrandom compatibility support. RandomDevice and CryptoRandom probe getrandom with GRND_NONBLOCK and select the fallback when unavailable.
Fallback descriptors and random-byte reads
Source/WTF/wtf/RandomDevice.cpp
Fallback descriptors use O_CLOEXEC. Destructors close valid descriptors. Random-byte reads select getrandom or /dev/urandom reads.

Process memory status collection

Layer / File(s) Summary
Persistent statm reads
Source/WTF/wtf/linux/CurrentProcessMemoryStatus.cpp
currentProcessMemoryStatus opens /proc/self/statm once, uses pread with EINTR retries, terminates the buffer explicitly, and preserves failure returns.
🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the implementation and rationale, but it omits the required Bugzilla link, review status, and template-style changed-function list. Add the Bugzilla issue URL, “Reviewed by NOBODY (OOPS!).”, and a template-formatted explanation with the affected paths and functions.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies both primary Linux changes: getrandom preference over /dev/urandom and persistent /proc/self/statm access.

Comment @coderabbitai help to get the list of available commands.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I reviewed this PR and didn't find any bugs. Because it modifies the cryptographic randomness sources in both WTF and bmalloc (and the author notes it wasn't built locally), a human look would still be worthwhile.

What was reviewed:

  • Verified m_fd defaults to -1 in RandomDevice.h so the early-return path is sound; destructor now guards close().
  • Checked the getrandom probe/fallback: EAGAIN/ENOSYS/EPERM all fall through to the unchanged /dev/urandom path, and the read loop's existing EINTR/EAGAIN handling covers the blocking getrandom call.
  • Confirmed the statm open-once + pread pattern matches the existing LinuxMemory precedent in AvailableMemory.cpp; buffer is null-terminated with a byte reserved.
Extended reasoning...

Overview

Three Linux-only changes: (1) WTF::RandomDevice and (2) bmalloc::ARC4RandomNumberGenerator::stir now probe getrandom(2) with GRND_NONBLOCK at init and use it for all subsequent reads if the kernel entropy pool is initialized, falling back to the existing /dev/urandom path otherwise. (3) currentProcessMemoryStatus() switches from per-call fopen/fgets/fclose to a once-opened fd + pread, mirroring LinuxMemory::footprint() in AvailableMemory.cpp. All open() calls gain O_CLOEXEC.

Security risks

The first two changes touch the seeding path for cryptographic randomness — RandomDevice backs WTF::cryptographicallyRandomValues() and ARC4RandomNumberGenerator seeds bmalloc's CSPRNG. getrandom(2) without GRND_RANDOM draws from the same pool as /dev/urandom, so entropy quality is unchanged. The probe only commits to getrandom when it successfully returns 1 byte (pool initialized), and the pool cannot become uninitialized afterward, so subsequent blocking getrandom calls won't hang. The fallback path is byte-identical to the old code plus O_CLOEXEC. I don't see a way this weakens randomness, but any change to a CSPRNG seed source deserves a second set of eyes.

Level of scrutiny

High — this is security-critical infrastructure (crypto RNG seeding) even though the diff is small and mechanically straightforward. The author also notes "Not built locally", so CI is the first compile check.

Other factors

The statm change is a low-risk performance/robustness improvement with direct upstream precedent in the same tree. The fork-without-exec caveat is explicitly called out and matches what upstream already accepts for memoryStatus(). The #if guarding is careful (SYS_getrandom presence checked, GRND_NONBLOCK fallback-defined), and non-Linux platforms are unaffected by preprocessor construction.

@github-actions

github-actions Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

Preview Builds

Commit Release Date
83df2b7c autobuild-preview-pr-394-83df2b7c 2026-08-22 01:25:52 UTC
458db1d2 autobuild-preview-pr-394-458db1d2 2026-08-08 01:05:33 UTC

The option defaults to true, which keeps the behaviour of the previous
commit: WTF::RandomDevice reads getrandom(2) and opens /dev/urandom only
when the syscall is unavailable. Setting it to false (BUN_JSC_useGetrandom=0
in bun) makes the device open /dev/urandom as before.

The device chooses its source when it is constructed, on the first request
for randomness, so JSC::initialize() pushes the option into WTF right after
Options::initialize() and before ExecutableAllocator::initialize(), which
can be that first request. bmalloc's CryptoRandom is used before any option
is parsed and is not covered by the option.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I reviewed this PR and didn't find any bugs. Because it changes the OS entropy source for both WTF::RandomDevice and bmalloc's CryptoRandom (security-sensitive CSPRNG seeding), a human look would still be worthwhile.

What was reviewed:

  • getrandom(2) probe/fallback logic in both RandomDevice and CryptoRandom — the GRND_NONBLOCK probe correctly falls through to /dev/urandom on EAGAIN/ENOSYS/EPERM, and the m_fd < 0 sentinel is only reachable when the probe succeeded.
  • currentProcessMemoryStatus cached-fd + pread rewrite — buffer is explicitly NUL-terminated at length, EINTR is retried, and open failure latches to the same zero-return behaviour as before.
  • setUseGetrandom ordering in JSC::initialize — placed after Options::initialize() and before ExecutableAllocator::initialize(); no-op on non-Linux via UNUSED_PARAM.
Extended reasoning...

Overview

This PR makes three related Linux-only changes across WTF, bmalloc, and JSC:

  1. WTF::RandomDevice and bmalloc::ARC4RandomNumberGenerator::stir now probe getrandom(2) with GRND_NONBLOCK at construction/first-stir time. If the probe returns 1 byte, subsequent reads use the syscall directly (no fd, no filesystem dependency); otherwise they fall back to the existing open("/dev/urandom") path, which now also gets O_CLOEXEC.
  2. WTF::currentProcessMemoryStatus switches from per-call fopen/fgets/fclose on /proc/self/statm to a one-time open + per-call pread at offset 0, mirroring the existing pattern in AvailableMemory.cpp.
  3. A new Options::useGetrandom (default true) is plumbed through RandomDevice::setUseGetrandom in JSC::initialize, letting users force the old /dev/urandom behaviour.

Security risks

The core of this PR is a change to how cryptographic randomness is sourced. getrandom(2) draws from the same kernel CSPRNG pool as /dev/urandom and is the modern recommended interface (used by glibc's getentropy, OpenSSL, BoringSSL, etc.), so the change is sound in principle. The probe-then-commit design is careful: the constructor only commits to getrandom after a successful non-blocking read proves the pool is initialized, so the later flag-0 reads in cryptographicallyRandomValues won't block indefinitely at early boot. The m_fd < 0 / fd < 0 sentinel meaning "use getrandom" is only reachable when RANDOM_DEVICE_USE_GETRANDOM/CRYPTO_RANDOM_USE_GETRANDOM is compiled in and the probe succeeded — in the fallback branch, open failure still hits crashUnableToOpenURandom() / RELEASE_BASSERT, so there's no path where m_fd == -1 silently degrades to a bad read. That said, any change to CSPRNG seeding is inherently security-sensitive and merits a second pair of eyes.

Level of scrutiny

High. Even though the diff is modest and the logic reads correctly, this touches the entropy source that seeds JSC's and bmalloc's random number generators (used for ASLR-adjacent decisions, StructureID randomization, hash seeds, etc.). The PR description also notes the initial change was "not built locally" and the JSC option wiring was "left to CI", so a maintainer confirming the CI matrix passed on all Linux variants (glibc/musl, x64/arm64) is worthwhile.

Other factors

  • The currentProcessMemoryStatus change is a straightforward performance improvement with an acknowledged fork-without-exec caveat that already applies to LinuxMemory in the same codebase; no concerns there.
  • The new setUseGetrandom static uses a relaxed atomic bool, which is fine for a write-once-before-first-read configuration flag; the setter is defined on all platforms (no-op via UNUSED_PARAM where getrandom isn't compiled in), so there's no link/ODR issue on macOS/Windows.
  • No prior human or bot reviews to consider beyond automated summaries.

bmalloc's ARC4 generator picked its OS source once, in a function-local
once_flag inside stir(), and Gigacage stirs it during WTF::initialize(),
before any option exists. The source is now generator state under its
mutex: chooseSource() runs before the first stir and again from
setCryptoRandomUsesGetrandom(), switching between getrandom(2) and an open
/dev/urandom in either direction, so the option governs every stir after
JSC::initialize(). WTF::RandomDevice::setUseGetrandom() forwards to it, so
JSC still makes one call.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I reviewed this PR and didn't find any bugs. Because it changes the OS entropy source for both WTF's and bmalloc's cryptographic RNGs, adds a new WTF→bmalloc configuration hook, and threads an option through JSC::initialize() ordering, a human look would still be worthwhile.

Checked: the GRND_NONBLOCK probe falls through to the existing /dev/urandom path on EAGAIN/ENOSYS/EPERM, so no new blocking or crash on old kernels/seccomp.
Checked: m_fd < 0 is only reachable when the probe succeeded (constructor crashes otherwise), so cryptographicallyRandomValues can't hit getrandom with an uninitialized pool.
Checked: setUseGetrandom/setCryptoRandomUsesGetrandom compile to no-ops on non-Linux; the unconditional <bmalloc/CryptoRandom.h> include is the only new cross-layer surface there.
Checked: pread into buffer[128] reads at most 127 and NUL-terminates, matching the old fgets bound.

Extended reasoning...

Overview

This PR touches seven files across three layers to make JSC start cleanly inside Linux filesystem sandboxes that hide /dev and /proc:

  • bmalloc (CryptoRandom.{h,cpp}): the ARC4 generator's entropy source moves from a function-local std::once_flag-guarded fd into per-generator state (m_fd, m_sourceChosen, m_usesGetrandom) with a new chooseSource() that probes getrandom(2) and can switch directions. A new exported setCryptoRandomUsesGetrandom(bool) reconfigures it under the generator's mutex.
  • WTF (RandomDevice.{h,cpp}): the constructor probes getrandom(GRND_NONBLOCK) before opening /dev/urandom; if the probe returns 1, m_fd stays −1 and reads use the syscall. A new static setUseGetrandom(bool) writes an atomic flag and forwards to bmalloc. O_CLOEXEC is added to the fallback open.
  • WTF (linux/CurrentProcessMemoryStatus.cpp): fopen/fgets/fclose per call is replaced with a one-time open(O_RDONLY|O_CLOEXEC) cached in a static, then pread() at offset 0.
  • JSC (OptionsList.h, InitializeThreading.cpp): a new useGetrandom bool option (default true) is pushed into WTF right after Options::initialize() and before ExecutableAllocator::initialize().

Security risks

This is squarely security-sensitive: it changes how the process obtains cryptographic randomness. The design is conservative — getrandom(2) and /dev/urandom draw from the same kernel pool, the probe uses GRND_NONBLOCK so it never blocks at boot, and any probe failure falls through to the pre-existing /dev/urandom code unchanged. The read loop still crashes on errors other than EAGAIN/EINTR, so it stays fail-closed. I did not find a path where randomness is silently degraded or where an uninitialized pool is read via the syscall (the only way m_fd stays −1 past construction is a probe that returned exactly 1). Still, changes to CSPRNG seeding warrant a second pair of eyes.

Level of scrutiny

High. Beyond the crypto surface, the PR:

  • Adds a new dependency edge: RandomDevice.cpp now unconditionally includes <bmalloc/CryptoRandom.h> and calls into bmalloc from WTF on every platform (a no-op off Linux, but a build-graph change).
  • Relies on initialization ordering in JSC::initialize() — the setter must land after Options::initialize() but before the first RandomDevice construction, and the PR description acknowledges Gigacage's stir inside WTF::initialize() predates any option parsing.
  • Replaces a std::once_flag static with mutable per-instance state in bmalloc's generator, protected by the existing StaticPerProcess mutex.

None of these are simple mechanical edits.

Other factors

The author notes the original portion was "not built locally" and the JSC side is "left to CI"; a preview build exists for an earlier commit (458db1d2) but the current head (83df2b7c) added the option plumbing afterward. The /proc/self/statm change carries the same fork-without-exec caveat the description calls out for AvailableMemory.cpp. Given the security surface and cross-layer plumbing, deferring to a human reviewer.

@robobun

robobun commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator

I ran the prebuilt jsc from this PR on a root where /dev/urandom does not exist. It fixes a startup abort that main has.

Method: Linux x64, glibc 2.41. A seccomp user-notification supervisor answers ENOENT for every path syscall on /dev/urandom and lets all other syscalls continue, so no mount namespace is needed. The binary is bin/jsc from bun-webkit-linux-amd64-lto.tar.gz.

build jsc -e 'print("ok")' with /dev/urandom absent
main 000c4899 SIGABRT, exit 134
autobuild-preview-pr-394-83df2b7c prints ok, exit 0, and never tries to open /dev/urandom

On main the release backtrace is WTF::RandomDevice::RandomDevice() (RandomDevice.cpp:95), from cryptographicallyRandomValuesFromOS, from VM::VM (VM.cpp:263). Bun 1.4.3-canary on that WebKit aborts at the same frame before any JS runs (panic(main thread): abort() called). Bun also aborts at startup with RLIMIT_NOFILE 4 or 5, where the open fails with EMFILE. I did not take a backtrace for that trigger.

Not checked: Bun built against this branch. With /proc hidden this build still aborts. That is the separate StackBounds problem, which #556 removes.

@dylan-conway

Copy link
Copy Markdown
Member Author

Replaced by #749, which keeps the getrandom(2) change with /dev/urandom as the fallback and drops Options::useGetrandom and the cached /proc/self/statm descriptor. The reasons and measurements for dropping each are in that description.

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