Skip to content

tls: report out of memory instead of segfaulting when the loop's TLS buffer cannot be allocated - #33326

Merged
Jarred-Sumner merged 3 commits into
mainfrom
farm/c2789dea/tls-loop-buffer-oom
Jul 4, 2026
Merged

Jarred-Sumner merged 3 commits into
mainfrom
farm/c2789dea/tls-loop-buffer-oom

Conversation

@robobun

@robobun robobun commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator

Fixes a Segmentation fault at address 0x00000040 (sometimes 0x00000030) reported from Windows x64 builds, crashing inside boringssl's record copy from uSockets' TLS read loop:

memcpy                            src/vctools/crt/vcruntime/src/string/amd64/memcpy.asm
bssl::OPENSSL_memcpy              vendor/boringssl/crypto/internal.h:868
SSL_peek                          vendor/boringssl/ssl/ssl_lib.cc:947
SSL_read                          vendor/boringssl/ssl/ssl_lib.cc:918
us_internal_ssl_on_data           packages/bun-usockets/src/crypto/openssl.c:1797
us_internal_dispatch_ready_poll   packages/bun-usockets/src/loop.c:600
uv__fast_poll_process_poll_req    vendor/libuv/src/win/poll.c:208
uv_run                            vendor/libuv/src/win/core.c:737

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:

loop_ssl_data->ssl_read_output =
    us_malloc(LIBUS_RECV_BUFFER_LENGTH + LIBUS_RECV_BUFFER_PADDING * 2);

With ssl_read_output == NULL, every later SSL_read hands boringssl

loop_ssl_data->ssl_read_output + LIBUS_RECV_BUFFER_PADDING + read

as its plaintext destination, so the first record of application data memcpy's to NULL + 32. SSL_peek's OPENSSL_memcpy(buf, ...) at ssl_lib.cc:947 is the write, and the access violation confirms it is a write fault.

0x30/0x40 rather than 0x20 is 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:

memcpy variant first faulting store for dst = NULL + 32
32-byte vectors (AVX) 0x40
16-byte vectors (SSE) 0x30

So the two strikingly stable fault addresses are just CPU dispatch across the affected machines, and read is always 0: 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 malloc there effectively never returns NULL. Windows fails the commit cleanly, and the loop's much smaller us_calloc still succeeds out of an already-committed page, leaving exactly the observed shape: a valid loop_ssl_data whose ssl_read_output is NULL.

Fix

  • Null-check the buffer allocation, the us_calloc of loop_ssl_data, and the BIO_meth_new/BIO_new calls beside them, and route the failure through Bun's out-of-memory crash path (Bun__outOfMemory, new C entry point next to Bun__panic). The process now dies with Bun ran out of memory and a stack trace that names the allocation, instead of faulting on the first TLS byte.
  • Apply the same check to the sibling site: recv_buf/send_buf in us_internal_loop_data_init are the same unchecked malloc(LIBUS_RECV_BUFFER_LENGTH + LIBUS_RECV_BUFFER_PADDING * 2). A NULL recv_buf does not fault, it makes every read on the loop fail with EFAULT for the life of the process, which is worse to diagnose.
  • us_internal_free_loop_ssl_data 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 existing socket fault injector to be reachable from a test. This adds an ssl_loop_buffer rule 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_buffer before 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)
==19592==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000040
==19592==The signal is caused by a WRITE memory access.
==19592==Hint: address points to the zero page.
    #0 __memcpy_evex_unaligned_erms
    #1 bssl::OPENSSL_memcpy(void*, void const*, unsigned long) vendor/boringssl/crypto/internal.h:868:10
    #2 SSL_peek vendor/boringssl/ssl/ssl_lib.cc:947:3
    #3 SSL_read vendor/boringssl/ssl/ssl_lib.cc:918:13
    #4 us_internal_ssl_on_data packages/bun-usockets/src/crypto/openssl.c:1847:21
    #5 us_internal_dispatch_ready_poll packages/bun-usockets/src/loop.c:625:38

With the fix:

panic(main thread): Bun ran out of memory
Bun__outOfMemory              src/bun_bin/phase_c_exports.rs:81:5
us_internal_init_loop_ssl_data packages/bun-usockets/src/crypto/openssl.c:696:42
us_internal_ssl_attach        packages/bun-usockets/src/crypto/openssl.c:1275:3

test/js/node/tls/tls-syscall-fault.test.ts (11 pass), test/js/bun/util/socket-fault-injection.test.ts (15 pass), plus socket-syscall-fault, serve-syscall-fault and fetch-syscall-fault (19 pass) are green. The three failures in test/js/node/tls/ on this machine are pre-existing: two also fail on an unmodified 1.4.0, and tls.connect should ignore invalid NODE_EXTRA_CA_CERTS takes 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_data after its loop's SSL data has been freed. us_internal_free_loop_ssl_data is only reachable from us_loop_free, and the only loop Bun frees today is SpawnSyncEventLoop's, which never has a TLS socket attached (its loop->data.ssl_data is 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) calls us_internal_loop_data_free(loop) and then runs uv_run(loop->uv_loop, UV_RUN_NOWAIT), which is a full libuv iteration that can dispatch socket poll callbacks into the just-freed recv_buf and ssl_data. The POSIX us_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.

…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.
@coderabbitai

coderabbitai Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 86d2bd12-774e-4119-a91d-cde895001bc2

📥 Commits

Reviewing files that changed from the base of the PR and between ef36a8a and cc87e9f.

📒 Files selected for processing (3)
  • src/js/internal-for-testing.ts
  • src/runtime/socket/socket_body.rs
  • test/js/bun/util/socket-fault-injection.test.ts

Walkthrough

This PR adds a Bun__outOfMemory noreturn abort path for allocation failures, introduces ssl_loop_buffer as a fault-injection target for TLS loop buffer allocation, wires that target through Rust and JS fault APIs, and adds tests plus a TLS fixture for the OOM case.

Changes

SSL loop buffer OOM handling and fault injection

Layer / File(s) Summary
Bun__outOfMemory and allocation checks
packages/bun-usockets/src/internal/internal.h, src/bun_bin/phase_c_exports.rs, packages/bun-usockets/src/loop.c, packages/bun-usockets/src/crypto/openssl.c
Declares and exports Bun__outOfMemory(), checks loop buffer allocations before use, allocates the TLS read output buffer through a helper with fault-injection support, and clears loop->data.ssl_data during teardown.
ssl_loop_buffer fault identifier
packages/bun-usockets/src/internal/fault_inject.h
Adds US_FAULT_SSL_LOOP_BUFFER and documents it as a non-syscall target that only accepts US_FAULT_ERRNO.
Rust and JS fault wiring
src/uws_sys/lib.rs, src/runtime/socket/socket_body.rs, src/js/internal-for-testing.ts
Adds the SSL_LOOP_BUFFER constant, accepts "ssl_loop_buffer" in socket fault validation, and extends the TypeScript fault syscall type and fd documentation.
Validation tests and TLS OOM fixture
test/js/bun/util/socket-fault-injection.test.ts, test/js/node/tls/tls-loop-buffer-oom-fixture.ts, test/js/node/tls/tls-syscall-fault.test.ts
Expands fault validation coverage, adds a fixture that arms the TLS loop-buffer ENOMEM fault, and adds a skipped end-to-end test that runs the fixture and checks for the OOM message.

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
Loading

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,
A fault made the buffer run cold.
With ENOMEM near,
The path stayed clear,
And aborts were made explicit and bold.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: converting TLS loop-buffer allocation failure from segfault to OOM handling.
Description check ✅ Passed It explains the change and includes verification details, even though it uses different section headings than the template.
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.

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

@github-actions github-actions Bot added the claude label Jul 4, 2026
@robobun

robobun commented Jul 4, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:19 PM PT - Jul 4th, 2026

⏳ @robobun, your commit cc87e9f is still building in Build #68337, but has 2 failures so far (All Failures):

@robobun

robobun commented Jul 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: open at cc87e9fa31, Buildkite running. All GitHub Actions checks green.

Review: Claude Code Review found no bugs and deferred to a human. CodeRabbit found one real issue, now fixed and resolved: ssl_loop_buffer's hook checks with fd = -1, and us_fault_hit matches on target_fd < 0 || target_fd == fd, so a rule carrying a concrete descriptor would arm, report success, and silently never fire. cc87e9fa31 rejects a non-default rule.fd for it, alongside the existing short/zero guards.

Reproduced by arming the ssl_loop_buffer fault rule before a process's first TLS socket, which makes the 512 KiB us_malloc in us_internal_init_loop_ssl_data return NULL. On the unfixed build that faults at 0x40 inside SSL_peek's OPENSSL_memcpy, matching the reported Windows crash frame for frame. With the fix the process reports Bun ran out of memory and names the allocation. Full before/after output is in the PR description.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@robobun

robobun commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

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.

Bun__outOfMemory is a #[no_mangle] extern "C" wrapper over bun_core::out_of_memory(), the same function handle_oom and .unwrap_or_oom() already route to. It sits next to Bun__panic in phase_c_exports.rs and is declared next to it in internal.h, so the shape is not new, only the C-callable door to an existing path. The two call sites added here are its only callers.

The alternative was the already-exported BUN_PANIC("out of memory"), which needs no new symbol. I did not use it because the crash handler branches on CrashReason::OutOfMemory to emit the out-of-memory report rather than a panic report (src/crash_handler/lib.rs:691, :1011, :1206), and that distinction is the point of the change: the user should get Bun ran out of memory naming the failed allocation, not a panic.

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 if (!p) Bun__outOfMemory(); after an allocation that previously went unchecked, plus clearing loop->data.ssl_data after the free that already happened.

Current state: every GitHub Actions check is green, Buildkite is still running. The libuv us_loop_free teardown window described at the end of the PR body is the only thing deliberately left out of scope; happy to fold it in here instead of a follow-up if a maintainer would rather have it together.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between a8d0692 and ef36a8a.

📒 Files selected for processing (11)
  • packages/bun-usockets/src/crypto/openssl.c
  • packages/bun-usockets/src/internal/fault_inject.h
  • packages/bun-usockets/src/internal/internal.h
  • packages/bun-usockets/src/loop.c
  • src/bun_bin/phase_c_exports.rs
  • src/js/internal-for-testing.ts
  • src/runtime/socket/socket_body.rs
  • src/uws_sys/lib.rs
  • test/js/bun/util/socket-fault-injection.test.ts
  • test/js/node/tls/tls-loop-buffer-oom-fixture.ts
  • test/js/node/tls/tls-syscall-fault.test.ts

Comment thread src/runtime/socket/socket_body.rs Resolved
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.
@Jarred-Sumner
Jarred-Sumner merged commit c7ae04c into main Jul 4, 2026
77 of 79 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/c2789dea/tls-loop-buffer-oom branch July 4, 2026 20:22
Jarred-Sumner pushed a commit that referenced this pull request Jul 5, 2026
….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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants