Repository navigation
tls: report out of memory instead of segfaulting when the loop's TLS buffer cannot be allocated - #33326
Conversation
…buffer cannot be allocated us_internal_init_loop_ssl_data() allocates one 512 KiB plaintext buffer per event loop, lazily, on the loop's first TLS socket, and ignored a NULL return. Every subsequent SSL_read then passed BoringSSL `loop_ssl_data->ssl_read_output + LIBUS_RECV_BUFFER_PADDING` as the plaintext destination, so the first record of application data memcpy'd to NULL + 32. Null-check that allocation (plus the us_calloc and the BIO allocations beside it) and route the failure through Bun's out-of-memory crash path. Apply the same check to recv_buf/send_buf in us_internal_loop_data_init, where a NULL recv_buf instead makes every read on the loop fail with EFAULT. us_internal_free_loop_ssl_data() also left loop->data.ssl_data dangling, which defeats the `if (!loop->data.ssl_data)` guard the init function relies on; it now clears the field. A 512 KiB malloc effectively never returns NULL on an overcommitting kernel, so the failure path needs the socket fault injector to be reachable from a test. Add an `ssl_loop_buffer` rule for it, which like the rest of the injector is compiled out of release builds.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (3)
WalkthroughThis PR adds a ChangesSSL loop buffer OOM handling and fault injection
Sequence Diagram(s)sequenceDiagram
participant tls-syscall-fault.test.ts
participant tls-loop-buffer-oom-fixture.ts
participant socketFaultInjection
participant openssl.c
tls-syscall-fault.test.ts->>tls-loop-buffer-oom-fixture.ts: spawn fixture
tls-loop-buffer-oom-fixture.ts->>socketFaultInjection: arm ssl_loop_buffer ENOMEM
tls-loop-buffer-oom-fixture.ts->>openssl.c: trigger TLS read path
openssl.c->>openssl.c: ssl_alloc_read_output() fails
openssl.c->>openssl.c: Bun__outOfMemory()
tls-loop-buffer-oom-fixture.ts-->>tls-syscall-fault.test.ts: stdout/stderr markers
Estimated code review effort: Medium Related issues: None identified. Related PRs: None identified. Suggested labels: area/tls, area/usockets, needs-tests-review Suggested reviewers: No specific reviewer information available. Poem A loop needed memory to hold, 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 1:19 PM PT - Jul 4th, 2026
⏳ @robobun, your commit cc87e9f is still building in
|
|
Status: open at Review: Reproduced by arming the |
There was a problem hiding this comment.
I didn't find any bugs and the OOM checks look correct, but this spans the TLS init path in openssl.c, event-loop init, and adds a new Bun__outOfMemory FFI export — worth a human look before merging.
Extended reasoning...
Overview
This PR hardens allocation-failure handling in bun-usockets' loop and TLS setup. It null-checks the per-loop 512 KiB TLS plaintext buffer, loop_ssl_data itself, the BIO_meth_new/BIO_new results, and the loop's recv_buf/send_buf, routing failures through a new Bun__outOfMemory() C entry point (backed by bun_core::out_of_memory()). It also nulls loop->data.ssl_data after free, extends the socket fault-injection framework with an ssl_loop_buffer rule (compiled out of release builds), and adds a spawned-fixture test that reproduces the original SEGV under ASAN when the guard is removed. 11 files across C (openssl.c, loop.c, internal.h, fault_inject.h), Rust (phase_c_exports.rs, socket_body.rs, uws_sys/lib.rs), and TS tests.
Security risks
The change is in packages/bun-usockets/src/crypto/openssl.c but does not alter any TLS handshake, verification, or crypto logic — it only adds abort-on-NULL after allocations. Bun__outOfMemory is __noreturn__ and calls the existing Rust OOM path, so no new attack surface. The fault injector addition is guarded by LIBUS_SOCKET_FAULT_INJECTION and only reachable from bun:internal-for-testing. I don't see a security regression here.
Level of scrutiny
Medium-high. The individual edits are mechanical (if (!p) abort), but they sit in the TLS attach path and the event loop's us_internal_loop_data_init, both of which run for every process. The PR also introduces a new cross-language linker symbol (Bun__outOfMemory) that other C callers will depend on. Those are the kinds of changes a maintainer should sign off on rather than a bot.
Other factors
The root-cause analysis is thorough, the test verifiably fails on the unfixed build (ASAN repro shown), and the sibling recv_buf/send_buf site is covered in the same PR per the "fix the whole class" guideline. The teardown-ordering observation about libuv's us_loop_free is deliberately left out of scope with a stated reason. No prior reviewer comments to address. Given the file locations (crypto/, loop init, new FFI export) I'm deferring rather than approving.
|
No code changes come out of this review, but recording the reasoning behind the one piece of new surface it flags, so a human reviewer does not have to reconstruct it.
The alternative was the already-exported On the two file locations: nothing in the TLS handshake, verification, or crypto paths changes, and nothing in the loop's steady state does either. Every edit is an Current state: every GitHub Actions check is green, Buildkite is still running. The libuv |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/runtime/socket/socket_body.rs`:
- Around line 4879-4887: The ssl_loop_buffer rule path in socket_body.rs
currently allows fd to be configured even though US_FAULT_SSL_LOOP_BUFFER is
always checked with fd = -1, so those rules can never match. Update the
ssl_loop_buffer handling in the syscall/rule validation logic to either ignore
fd for this syscall or reject any non-default fd up front, mirroring the
existing short/zero guard behavior, and ensure the relevant match/validation
branch for ssl_loop_buffer enforces this consistently.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: e5d3acc7-dc53-40a5-9240-279765099cff
📒 Files selected for processing (11)
packages/bun-usockets/src/crypto/openssl.cpackages/bun-usockets/src/internal/fault_inject.hpackages/bun-usockets/src/internal/internal.hpackages/bun-usockets/src/loop.csrc/bun_bin/phase_c_exports.rssrc/js/internal-for-testing.tssrc/runtime/socket/socket_body.rssrc/uws_sys/lib.rstest/js/bun/util/socket-fault-injection.test.tstest/js/node/tls/tls-loop-buffer-oom-fixture.tstest/js/node/tls/tls-syscall-fault.test.ts
US_FAULT_SSL_LOOP_BUFFER's hook is an allocation, so it calls us_fault_hit with fd = -1. us_fault_hit matches on `target_fd < 0 || target_fd == fd`, so a rule armed with a specific fd would arm, report success, and then silently never fire. Reject it up front, the same way `short` and `zero` are rejected for the syscalls that cannot honor them.
….ts (#33348) ### What does this PR do? `test/js/node/tls/tls-syscall-fault.test.ts` fails on the `x64-asan` lane on some jobs and passes on others. It is not a real failure, and it is not a race: the assertion depends on an environment variable CI sets conditionally. #### Cause The test decides whether the child reported OOM with a single literal: ```js const outOfMemory = stderr.includes("Bun ran out of memory"); ``` That string comes from `Display for CrashReason` (`src/crash_handler/lib.rs:691`), which is printed on the `panic(main thread): {reason}` line. But for `CrashReason::OutOfMemory` that line is deliberately suppressed when a crash report is being generated: ```rust if !matches!(reason, CrashReason::OutOfMemory) || debug_trace { // panic(main thread): {reason} } ``` In that mode the child prints the banner instead (`src/crash_handler/lib.rs:1208`): ``` oh no: Bun has run out of memory. ``` `debug_trace` is false when `is_reporting_enabled()` is true, and `is_reporting_enabled()` returns true as soon as `BUN_CRASH_REPORT_URL` is set. The CI runner sets it only when its crash-report remap server came up (`scripts/runner.node.mjs:1326`): ```js ...(typeof remapPort == "number" ? { BUN_CRASH_REPORT_URL: `http://localhost:${remapPort}` } : { BUN_ENABLE_CRASH_REPORTING: "0" }), ``` so the same test passes or fails depending on the job. Locally there is no remap server, which is why it always passes during development. `OutOfMemory` is the only `CrashReason` whose `panic:` line is conditional, so this is the only test that can be bitten by it. `test/cli/run/run-crash-handler.test.ts:196` already special-cases it for exactly this reason: ```js if (approach !== "outOfMemory") { expect(stderr).toContain("oh no: Bun has crashed. This indicates a bug in Bun, not your code"); } else { expect(stderr.toLowerCase()).toContain("out of memory"); } ``` #### Fix Match either phrasing. Both are the same `CrashReason::OutOfMemory`, and which one prints is not what this test is about. ```js const OOM_CRASH_MESSAGES = ["Bun ran out of memory", "Bun has run out of memory"]; ... const outOfMemory = OOM_CRASH_MESSAGES.some(message => stderr.includes(message)); ``` The crash handler's two messages are left alone: they are deliberately different registers (a short reason on the `panic:` line, a full sentence in the report banner), and unifying them would change user-facing output for no user benefit. ### How did you verify your code works? `BUN_CRASH_REPORT_URL` reproduces the CI job that fails, since `bunEnv` spreads `process.env`: <details> <summary>Before, on <code>main</code></summary> ``` $ BUN_CRASH_REPORT_URL=http://localhost:1 bun bd test test/js/node/tls/tls-syscall-fault.test.ts -t "reports out of memory" + oh no: Bun has run out of memory. ... - Expected - 2 + Received + 21 (fail) a failed per-loop TLS buffer allocation reports out of memory instead of faulting inside SSL_read 0 pass 1 fail ``` </details> After, both modes: ``` $ BUN_CRASH_REPORT_URL=http://localhost:1 bun bd test test/js/node/tls/tls-syscall-fault.test.ts 11 pass 0 fail $ bun bd test test/js/node/tls/tls-syscall-fault.test.ts 11 pass 0 fail ``` Seen failing on build [#68424](https://buildkite.com/bun/bun/builds/68424) and build [#68416](https://buildkite.com/bun/bun/builds/68416), on two unrelated branches. The test arrived in #33326.
Fixes a
Segmentation fault at address 0x00000040(sometimes0x00000030) reported from Windows x64 builds, crashing inside boringssl's record copy from uSockets' TLS read loop:Cause
us_internal_init_loop_ssl_data(openssl.c:677) allocates one 512 KiB plaintext buffer per event loop, lazily, on the loop's first TLS socket, and never checked the result:With
ssl_read_output == NULL, every laterSSL_readhands boringsslas its plaintext destination, so the first record of application data memcpy's to
NULL + 32.SSL_peek'sOPENSSL_memcpy(buf, ...)atssl_lib.cc:947is the write, and the access violation confirms it is a write fault.0x30/0x40rather than0x20is memcpy's destination-alignment preamble (dst += VEC_SIZE; dst &= ~(VEC_SIZE - 1)), which moves the first faulting store for copies larger than eight vector registers. Measured on the copy sizes a real TLS record produces:dst = NULL + 320x400x30So the two strikingly stable fault addresses are just CPU dispatch across the affected machines, and
readis always0: the crash is always the connection's first record of application data.Only Windows reports it because Linux and macOS overcommit, so a 512 KiB
mallocthere effectively never returns NULL. Windows fails the commit cleanly, and the loop's much smallerus_callocstill succeeds out of an already-committed page, leaving exactly the observed shape: a validloop_ssl_datawhosessl_read_outputis NULL.Fix
us_callocofloop_ssl_data, and theBIO_meth_new/BIO_newcalls beside them, and route the failure through Bun's out-of-memory crash path (Bun__outOfMemory, new C entry point next toBun__panic). The process now dies withBun ran out of memoryand a stack trace that names the allocation, instead of faulting on the first TLS byte.recv_buf/send_bufinus_internal_loop_data_initare the same uncheckedmalloc(LIBUS_RECV_BUFFER_LENGTH + LIBUS_RECV_BUFFER_PADDING * 2). A NULLrecv_bufdoes not fault, it makes every read on the loop fail withEFAULTfor the life of the process, which is worse to diagnose.us_internal_free_loop_ssl_dataleftloop->data.ssl_datadangling, which defeats theif (!loop->data.ssl_data)guard the init function relies on. It now clears the field.A 512 KiB
malloceffectively never returns NULL on an overcommitting kernel, so the failure path needs the existing socket fault injector to be reachable from a test. This adds anssl_loop_bufferrule to it, which like the rest of the injector is compiled out of release builds.Verification
The new test spawns a child that arms
ssl_loop_bufferbefore its first TLS socket and asserts it reports out of memory rather than reaching a read loop.Reverting only
if (!loop_ssl_data->ssl_read_output) Bun__outOfMemory();reproduces the reported crash exactly, on Linux, from that same fixture: same fault address, same frames, same boringssl source lines.Reproduction on the unfixed build (
bun bd, ASAN)With the fix:
test/js/node/tls/tls-syscall-fault.test.ts(11 pass),test/js/bun/util/socket-fault-injection.test.ts(15 pass), plussocket-syscall-fault,serve-syscall-faultandfetch-syscall-fault(19 pass) are green. The three failures intest/js/node/tls/on this machine are pre-existing: two also fail on an unmodified 1.4.0, andtls.connect should ignore invalid NODE_EXTRA_CA_CERTStakes 5.75s, just over the 5s local default (CI triples the per-test timeout for ASAN builds).Teardown audit
The report also asked whether a socket can reach
us_internal_ssl_on_dataafter its loop's SSL data has been freed.us_internal_free_loop_ssl_datais only reachable fromus_loop_free, and the only loop Bun frees today isSpawnSyncEventLoop's, which never has a TLS socket attached (itsloop->data.ssl_datais always NULL, so the free is a no-op). So that is not the cause here.It is worth noting separately that the libuv
us_loop_free(eventing/libuv.c:201-206) callsus_internal_loop_data_free(loop)and then runsuv_run(loop->uv_loop, UV_RUN_NOWAIT), which is a full libuv iteration that can dispatch socket poll callbacks into the just-freedrecv_bufandssl_data. The POSIXus_loop_free(eventing/epoll_kqueue.c:56-60) has no such window. It is unreachable today for the reason above, so it is left out of this PR rather than changing loop teardown ordering without a test that can exercise it.