Skip to content

[WTF] FreeBSD: bound the main thread's stack by its real reservation, not RLIMIT_STACK - #424

Merged
dylan-conway merged 2 commits into
mainfrom
claude/freebsd-main-thread-stack-bounds
Aug 14, 2026
Merged

dylan-conway merged 2 commits into
mainfrom
claude/freebsd-main-thread-stack-bounds

Conversation

@dylan-conway

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

Copy link
Copy Markdown
Member

libthr reports the main thread's stack as RLIMIT_STACK below its top. When the executable carries a sized PT_GNU_STACK (ld -z stack-size, which Bun uses), FreeBSD's exec maps only trunc_page(p_memsz) for the main stack — raising rlim_cur to it if it was smaller, leaving it alone if it was larger. A binary linked with -z stack-size=12.8MB under the default 512 MB rlimit therefore gets a StackBounds 40× larger than its stack, so StackCheck users (Yarr, DFG, Wasm, CloneSerializer) recurse until the kernel kills the process (pid N comm bun has trashed its stack, killing, SIGILL) instead of failing gracefully. The same code on a secondary thread is fine because libthr sizes those itself.

Repro on FreeBSD 14.3 with a Bun release binary: new RegExp("(?:".repeat(100000) + "a" + ")".repeat(100000)) on the main thread → killed; in a Worker → SyntaxError.

This takes min(rlim_cur, trunc_page(PT_GNU_STACK.p_memsz)) below the origin on the main thread (via dl_iterate_phdr; elf_aux_info does not expose AT_PHDR), minus the kernel's guard page, mirroring the existing OS(LINUX) main-thread adjustment right above it.

Verified on FreeBSD 14.3 amd64 with a standalone build of this function: PIE and non-PIE, with/without -z stack-size, a size above the rlimit (clamped), and an unaligned size (truncated) — in each case every page down to the new bound is touchable and the page below it faults, whereas the range libthr reported is unmapped.

Review follow-up (second commit): the guard subtracted at the bottom is security.bsd.stack_guard_page pages (RWTUN; 1 by default, 512 on HardenedBSD), and none when the process runs with the stack gap disabled (procctl(PROC_STACKGAP_STATUS)), matching what OpenJDK's BSD port and Rust's std do; AT_USRSTACKLIM (rlim_cur as exec left it) is taken as a further upper bound. Cross-checked against exec_map_stack/vm_map_stack_locked/vm_map_growstack and libthr's init_main_thread on releng/13.2, 14.3, 15.0 and main: from 13.1 on the main stack mapping is placed whole (MAP_ASLR_STACK) and libthr's origin is round_page(vm_stacktop) = the mapping top in every ASLR configuration, so origin − reservation cannot undershoot; on 13.0's in-mapping stack gap the origin is sv_usrstack (also the mapping top). The change can only ever narrow the bounds libthr reported. Re-verified on 14.3 with stack_guard_page = 0/1/4 and with RLIMIT_STACK lowered below the PT_GNU_STACK size before exec.

… not RLIMIT_STACK

libthr reports the main thread's stack as RLIMIT_STACK below its top. When the
executable carries a sized PT_GNU_STACK (ld -z stack-size), exec maps only
trunc_page(p_memsz) for the main stack, raising rlim_cur to it if it was
smaller and leaving it alone if it was larger. A binary linked with
-z stack-size=12.8MB under the default 512 MB rlimit therefore got a
StackBounds 40x larger than its stack: StackCheck users (Yarr, DFG, Wasm,
CloneSerializer) recursed until the kernel killed the process ("has trashed
its stack", SIGILL) instead of failing gracefully; the same code on a
secondary thread was fine.

Take min(rlim_cur, trunc_page(PT_GNU_STACK.p_memsz)) below the origin on the
main thread, minus the kernel's guard page, mirroring the existing Linux
main-thread adjustment. Verified on FreeBSD 14.3 amd64 (PIE and non-PIE,
with/without -z stack-size, size above the rlimit, unaligned size): every page
down to the new bound is usable and the page below it faults.
@coderabbitai

coderabbitai Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 1 minute

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 16e7de37-ee99-40c3-ae1a-f1a7d5bb4e25

📥 Commits

Reviewing files that changed from the base of the PR and between caad865 and ab94a08.

📒 Files selected for processing (1)
  • Source/WTF/wtf/StackBounds.cpp

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 changes main-thread stack-bounds computation based on FreeBSD kernel/rtld semantics I can't independently verify, a human look would still be worthwhile.

What was reviewed:

  • The new bound is only applied when strictly tighter than libthr's (bound > ret.end()), so worst case falls back to current behavior; origin is unchanged so conservative GC scanning is unaffected.
  • dl_iterate_phdr callback returns 1 after the first object so only the main executable's phdrs are inspected; reservation stays 0 when no sized PT_GNU_STACK is present and the rlimit path handles that.
  • Checked the min(rlim_cur, trunc_page(p_memsz)) arithmetic, page-mask truncation, guard-page subtraction, and the underflow guard (reservation < origin) — all look consistent with the description.
Extended reasoning...

Overview

The PR adds a FreeBSD-only branch to StackBounds::currentThreadStackBoundsInternal() in Source/WTF/wtf/StackBounds.cpp. On the main thread it reads the executable's PT_GNU_STACK.p_memsz via dl_iterate_phdr, page-truncates it, takes the min with RLIMIT_STACK, subtracts one guard page, and — only if that yields a tighter bound than what pthread_attr_getstack reported — returns the tighter StackBounds. New headers <link.h>, <sys/resource.h>, <unistd.h> are added under OS(FREEBSD). No other platforms are touched.

Security risks

None identified. This computes a smaller usable stack extent for recursion checks; it does not introduce parsing of untrusted input, allocation, or privilege changes. The pointer arithmetic is guarded against underflow (reservation < reinterpret_cast<uintptr_t>(origin)) and against producing a looser bound (bound > ret.end()). origin is left as reported by libthr, so conservative GC root scanning (which walks SP → origin) is unaffected; only the overflow-check low-water mark moves.

Level of scrutiny

Medium-high. The code is small, defensively written, and gated to FreeBSD, and it structurally mirrors the existing OS(LINUX) main-thread adjustment directly above it. However, its correctness rests on specific FreeBSD kernel/rtld behaviors (exec mapping trunc_page(p_memsz) for a sized PT_GNU_STACK, rtld handing the main program to the dl_iterate_phdr callback first, security.bsd.stack_guard_page accounting) that I can reason about from the description but cannot execute against. Stack bounds feed StackCheck across Yarr/DFG/Wasm, so a mistake here would manifest as either premature "stack overflow" errors or the crash this PR is fixing.

Other factors

  • The bound > ret.end() guard makes this strictly a tightening: if any assumption is wrong, behavior degrades to the status quo rather than a looser (unsafe) bound.
  • The PR description documents hands-on verification on FreeBSD 14.3 across PIE/non-PIE, with/without -z stack-size, oversized and unaligned sizes, including probing that pages down to the new bound are touchable and the page below faults.
  • No CODEOWNERS entry covers Source/WTF/.
  • Recent history in this fork shows active FreeBSD porting work, so a maintainer with a FreeBSD box is the right reviewer to confirm the kernel-semantics claims and sign off.

@github-actions

github-actions Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Preview Builds

Commit Release Date
ab94a08e autobuild-preview-pr-424-ab94a08e 2026-08-14 01:46:51 UTC
14077e57 autobuild-preview-pr-424-14077e57 2026-08-14 01:00:26 UTC

…ess disabled the stack gap); also bound by AT_USRSTACKLIM

The kernel keeps stack_guard_page pages (RWTUN, 1 by default, 512 on
HardenedBSD) unusable at the bottom of the main stack mapping, and none when
the process runs with the stack gap disabled (procctl PROC_STACKGAP_STATUS),
so read both instead of assuming one page — as OpenJDK's BSD port and Rust's
std do. Take AT_USRSTACKLIM (rlim_cur as exec left it) as a further upper
bound so a later privileged setrlimit raise cannot widen the result past the
mapping.

Verified on FreeBSD 14.3 amd64 with stack_guard_page = 0, 1 and 4, PIE and
non-PIE, sized and unsized PT_GNU_STACK, and RLIMIT_STACK lowered below the
PT_GNU_STACK size before exec: the returned bound is the lowest usable page
and the page below it faults (when a lowered rlimit is what binds, the bound
is one page conservative, since the kernel does not charge guard pages
against the rlimit).
dylan-conway added a commit to oven-sh/bun that referenced this pull request Aug 14, 2026
- StackCheck (FreeBSD main thread): same computation as the WTF fix
  (oven-sh/WebKit#424) — PT_GNU_STACK of the main program via
  dl_iterate_phdr, bounded by AT_USRSTACKLIM and RLIMIT_STACK, less
  security.bsd.stack_guard_page pages (none when the stack gap is disabled
  for the process); computed once. Becomes a no-op once WTF carries it.
- usockets IPC recvmsg: with the CMSG_SPACE-sized buffer a peer can pack more
  than one descriptor into a message; keep the first and close the rest.
- bun completions (zsh): fall back to the known directory when the platform
  cannot name the fd (FreeBSD/UFS), instead of expect()ing.
- BUN_FEATURE_FLAG_FORCE_WAITER_THREAD is ignored off Linux in one place
  (bun_spawn_sys::waiter_thread_flag) rather than at each call site; tests
  that opt into the waiter thread are gated to Linux/Android to match.
- read_file/write_file use Environment::IS_KQUEUE instead of listing kqueue
  targets; kqueue cancels get udata 0 inside the change match; Injected::new
  replaces four pasted constructions; stale comments trimmed.

@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. The change is well-scoped (FreeBSD main thread only, and can only ever narrow the bounds libthr reported), but since it's ~60 lines of new platform-specific stack-bounds logic that depends on FreeBSD kernel/libthr internals, a human look from someone who can sanity-check the FreeBSD semantics would still be worthwhile.

What was reviewed:

  • The narrow min-of-nonzero accumulator and trunc_page masking match the described min(rlim_cur, trunc_page(p_memsz)) semantics.
  • dl_iterate_phdr callback returns 1 after the first object so only the main executable's PT_GNU_STACK is read.
  • The final bound > ret.end() guard ensures this only narrows and falls back to libthr's answer otherwise, so it can't regress the no-PT_GNU_STACK case.
  • Guard-page arithmetic (reservation > guard, reservation < origin) is checked before the pointer subtraction, avoiding underflow.
Extended reasoning...

Overview

The PR adds a FreeBSD-specific branch to StackBounds::currentThreadStackBoundsInternal() in Source/WTF/wtf/StackBounds.cpp. On the main thread only, it recomputes the stack bound as origin − (min(PT_GNU_STACK size, AT_USRSTACKLIM, RLIMIT_STACK) − guard), where the guard is derived from security.bsd.stack_guard_page and PROC_STACKGAP_STATUS. The result is applied only if it is strictly narrower than what libthr reported. New headers (link.h, sys/auxv.h, sys/procctl.h, sys/resource.h, sys/sysctl.h) are added under OS(FREEBSD).

Security risks

Stack bounds feed StackCheck, which gates recursion in Yarr, DFG, Wasm, and CloneSerializer. Overreporting (the bug being fixed) causes hard crashes; underreporting causes premature soft stack-overflow errors. The change is structured so it can only narrow the reported bounds (if (bound > ret.end())), so the worst case is being more conservative than necessary — it cannot introduce a new overrun. There is no untrusted input; all values come from the process's own ELF headers, auxv, rlimits, and sysctls.

Level of scrutiny

This warrants human review. It is not a mechanical change: it encodes non-obvious FreeBSD kernel behavior (exec_map_stack, vm_map_growstack, libthr's init_main_thread, ASLR stack-gap handling across 13.0/13.1+/14.x/15.0) that I cannot independently verify from the diff alone. The PR description is unusually thorough and cites cross-checks against OpenJDK and Rust std, and the code is defensively written, but correctness here hinges on platform details best confirmed by someone with FreeBSD access or expertise.

Other factors

  • No prior human or bot review comments with substantive content (CodeRabbit was rate-limited; preview build succeeded for the first commit).
  • The change is fully #elif OS(FREEBSD)-gated, so it cannot affect Linux/macOS/Windows builds.
  • The dl_iterate_phdr lambda is captureless (required for the C function-pointer conversion) and passes gnuStackSize via the data pointer correctly.
  • Every syscall/library call is return-value-checked before its output is used; on any failure the code falls through to libthr's answer.

@dylan-conway
dylan-conway merged commit 687eb8e into main Aug 14, 2026
47 checks passed
dylan-conway added a commit to oven-sh/bun that referenced this pull request Aug 14, 2026
oven-sh/WebKit#424 makes WTF::StackBounds report the FreeBSD main thread's
real reservation, so Bun__StackCheck__initialize needs no FreeBSD-specific
code and JSC's own recursion guards (Yarr, Wasm, DFG) are covered too. That
is the only commit between the previous pin and this one.
dylan-conway added a commit to oven-sh/bun that referenced this pull request Aug 14, 2026
### What does this PR do?

Running the full test suite on the `bun-freebsd-x64` artifact (FreeBSD
14.3 VM, `scripts/runner.node.mjs` exactly as CI drives it) surfaced
several FreeBSD-only runtime bugs. This fixes the ones with clear root
causes and teaches the runner/harness that `freebsd` (and `android`)
hosts exist so the suite can run there at all.

- **Deep recursion → SIGILL, no crash report.** FreeBSD's exec reserves
the *main-thread* stack from the executable's `PT_GNU_STACK` (`-z
stack-size=12.8MB`, which Linux ignores for the main thread), while
libthr — and so `WTF::StackBounds` — reports `RLIMIT_STACK` (512 MB by
default). `StackCheck` therefore never fired and the
TOML/YAML/JSONC/transpiler depth tests overflowed for real; the kernel
SIGILL-kills when it can't push a signal frame. The general fix is in
WTF (oven-sh/WebKit#424: `StackBounds` bounds the FreeBSD main thread by
`min(RLIMIT_STACK, AT_USRSTACKLIM, trunc_page(PT_GNU_STACK.p_memsz))`
less the kernel's guard pages, verified page-by-page on 14.3); until Bun
picks that up, `Bun__StackCheck__initialize` applies the same
computation for Bun's own recursion guards, and becomes a no-op
afterwards. JSC's own `StackCheck` users (Yarr, Wasm, DFG) on the main
thread need the WebKit change: e.g. 100k nested `(?:…)` groups still
overrun the stack there today (a Worker throws `SyntaxError`). The link
flag stays so the main stack is the same size as on Linux — dropping it
instead gives FreeBSD a 512 MB stack, and `bun build --no-bundle` on a
200k-deep TOML then sails past the printer's recursion guard into
quadratic output until the machine runs out of memory.
- **Handles sent over IPC were silently dropped** (all of
`node:cluster`, `fork()` + server/socket): the usockets `recvmsg`
control buffer was sized with `CMSG_LEN` instead of `CMSG_SPACE` (20 vs
24 bytes with FreeBSD's 12-byte `cmsghdr`); FreeBSD sets `MSG_CTRUNC`
and discards the fd. Linux tolerates the short buffer; on macOS the two
are equal. With the full buffer a peer could pack a second descriptor
into one message; extras are now closed rather than leaked.
- **`Bun.file()` on a FIFO/pipe → `ENOENT: kevent`.** After a one-shot
knote fired, teardown still submitted an `EV_DELETE`, and FreeBSD
reports the failed change as `flags == EV_ERROR` (xnu ORs the bit in, so
the old `== EV_ERROR` test happened to miss it on macOS), which was
forwarded to the reader as an I/O error. Now: cancel entries carry
`udata = 0` so any receipt for them lands on the existing empty-tag
early return (never on a stale owner), `EV_ERROR` is tested as a bit on
both kqueue platforms so real registration failures still reach the
owner, and ReadFile/WriteFile skip the post-completion cancel on FreeBSD
as they already did on macOS. (macOS note: xnu ORs `EV_ERROR` into the
flags, so the old equality never matched there — a failed `EV_ADD` used
to fall through to `on_ready` and a failed `EV_DELETE` receipt was
dispatched to a possibly finished owner; now the former reports the
kevent errno and the latter is ignored.)
- **`bun build --compile` on UFS**: `inject()` returns the (absolute)
temp path it created instead of the caller reverse-mapping fd→path via
`F_KINFO`, which yields an empty path there so the final rename failed;
`get_fd_path` itself now returns ENOENT rather than `Ok("")` in that
case (and `bun completions`, the one caller that `expect()`ed it, falls
back to the directory it opened), and the no-writable-temp-location path
reports an error instead of hitting `unreachable!()`.
- **`uname`**: go through the `libc` crate (which calls `__xuname(256,
…)` on FreeBSD) instead of binding the compat `uname` symbol with
32-byte fields (crash reports printed `FreeBSD Kernel v`).
- **`Bun.Terminal`/PTY**: FreeBSD links libutil, so bind `openpty`
directly like macOS; `resize()` uses `libc::TIOCSWINSZ` (FreeBSD's is
the BSD encoding, not Linux's `0x5414`).
- `BUN_FEATURE_FLAG_FORCE_WAITER_THREAD` is only honoured on
Linux/Android (in `bun_spawn_sys::waiter_thread_flag`; it is the
pidfd-less fallback, and its loop has no wakeup on kqueue platforms so
it hung), and the tests that opt into it are gated to match.

### How did you verify your code works?

Each item was reproduced in isolation on the VM and root-caused with
`procstat`/`ktrace`/`truss`/`lldb` and small C probes
(`pthread_attr_get_np` vs `-z stack-size`, `SCM_RIGHTS` recv with
`CMSG_LEN` vs `CMSG_SPACE`, `dlsym("uname")` field layout, a standalone
build of the new stack-reservation function for
non-PIE/PIE/no-flag/flag>rlimit binaries). Then re-verified on-target
with the CI-built artifact from this branch: 200k/8M-deep TOML parses
throw `RangeError` with a 12.8 MB main stack and `bun build --no-bundle
deep.toml` errors instead of exhausting memory (toml/jsonc/yaml suites
12/46/85/642 pass);
`test-cluster-message.js`/`-dgram-1.js`/`test-child-process-fork-net-server.js`
pass (unpatched: hang); FIFO read returns data; `--compile` succeeds on
an md-backed UFS mount (unpatched still fails there); crash header shows
`FreeBSD Kernel v14.3-RELEASE-p16`; `new Bun.Terminal()` works. Linux
debug build: `build --compile` (plain/`--bytecode`/nested outfile, no
temp leftovers), the same cluster/fork tests, FIFO read,
`terminal.resize()` + terminal tests, streams/filesink/spawn-pipe
suites.

May also fix #12318 / #10046 (Docker virtiofs `failed to rename
….bun-build`, same fd→path reverse-mapping), untested.

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
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.

1 participant