Skip to content

Remove dead code from the WebSocket client, ncrypto, bun_core, and misc JSC bindings - #40413

Merged
alii merged 3 commits into
mainfrom
farm/e032f20d/dead-code-websocket-ncrypto-core
Aug 25, 2026
Merged

alii merged 3 commits into
mainfrom
farm/e032f20d/dead-code-websocket-ncrypto-core

Conversation

@robobun

@robobun robobun commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • Four Rust host exports have no C++ caller: Bun__WebSocketClient__writeBlob, Bun__WebSocketClientTLS__writeBlob, Bun__WebSocketClientTLS__initWithTunnel, and Bun__internal_drainTimers. WebSocket.cpp converts a Blob to bytes itself and calls writeBinaryData, and the tunnel path only creates the non-TLS client. The HOST_EXPORT marker roots each of them, so neither rustc nor hawk can see that they are dead.
  • A handful of C++ methods are declared and defined but never called: HTTPParser::lessThan, one JSNodePerformanceHooksHistogram::create overload, JSAbortAlgorithm::callbackData and toJS(AbortAlgorithm&), JSPerformance::toWrapped, JSCStackFrame::typeName, root(CryptoKey*), the String overload of throwNodeRangeError, and 16 ncrypto helpers.
  • Two pub Rust items have no caller in any crate: bun_base64::simdutf_encode_url_safe_alloc and CowSliceZ::init_unchecked.

Fix

  • Delete the items above. WebSocketClient::write_blob goes with its exports. encode_append_impl folds into encode_append, its only remaining caller. The ncrypto Ec class keeps its one live member, GetCurveIdFromName.
  • Every deletion is confirmed two ways: rg over src/, build/debug/codegen/, src/codegen/, packages/, and vendor/WebKit finds no reference, and a bun-debug relink with --gc-sections --print-gc-sections discards each symbol. host_fn_this_value and root(MessagePort*) looked the same way and stay: codegen emits the first, and MessagePort: a close() made inside a handler completes after the drain loop, not inside close() #39841 is editing MessagePort.cpp, so the second waits for that fix to land.
  • New source lint test/internal/source-lints/host-export-callers.test.ts: every c/jsc HOST_EXPORT marker must be named by a C or C++ source. It fails on main with exactly the four exports above and passes here.
  • Verified: bun bd builds, bun run rust:check-all passes on all 12 targets, clang-format and cargo fmt are clean. Ran test/js/web/websocket/ (blob, client, bidir proxy), test/js/node/crypto/ (crypto, ecdh, hmac, sign, x509), node-http, node-http-parser, perf_hooks, and abort.

Background

  • // HOST_EXPORT(Name, c) marks a Rust fn that src/codegen/generate-host-exports.ts wraps in an extern "C" thunk for C++. The thunk exists whether or not C++ calls it, so an orphaned export compiles without a warning.
  • ncrypto (src/jsc/bindings/ncrypto.{cpp,h}) is Bun's copy of Node's OpenSSL helper layer. Node still uses the removed helpers; Bun's callers never did.
  • The linker check: a debug link with -Wl,--gc-sections -Wl,--print-gc-sections lists every function section nothing references. A function that is discarded and also absent from the linked binary has no caller on that platform. Platform-gated code then needs a source check, which is why the darwin-only Bun__noOrphans_* and the Windows-only windowsEnv builtin stay.
Notes

Removed, by file:

  • src/http_jsc/websocket_client.rs: bun__websocketclient__write_blob, bun__websocketclienttls__write_blob, bun__websocketclienttls__init_with_tunnel, WebSocketClient::write_blob, and the now unused JSValue import.
  • src/runtime/timer/Timer.rs: drain_timers_export (Bun__internal_drainTimers).
  • src/base64/lib.rs: simdutf_encode_url_safe_alloc; encode_append_impl folded into encode_append.
  • src/ptr/CowSlice.rs: CowSliceZ::init_unchecked.
  • src/jsc/bindings/node/http/NodeHTTPParser.{cpp,h}: HTTPParser::lessThan.
  • src/jsc/bindings/JSNodePerformanceHooksHistogram.{cpp,h}: create(VM&, Structure*, JSGlobalObject*, HistogramData&&).
  • src/jsc/bindings/webcore/JSAbortAlgorithm.{cpp,h}: callbackData(), toJS(AbortAlgorithm&), toJS(AbortAlgorithm*).
  • src/jsc/bindings/webcore/JSPerformance.{cpp,h}: JSPerformance::toWrapped.
  • src/jsc/bindings/ErrorStackTrace.{cpp,h}: JSCStackFrame::typeName, retrieveTypeName, m_typeName.
  • src/jsc/bindings/webcrypto/CryptoKey.{cpp,h}: root(CryptoKey*) and the WebCoreOpaqueRoot forward declaration and include it needed.
  • src/jsc/bindings/webcore/JSDOMOperation.{cpp,h}: throwNodeRangeError(JSGlobalObject*, ThrowScope&, const String&); every caller passes an ASCIILiteral.
  • src/jsc/bindings/ncrypto.{cpp,h}: CryptoErrorList::add, CryptoErrorList::pop_front, BignumPointer::encode, BignumPointer::encodeInto, X509View::clone, BIOPointer::New(const BIO_METHOD*), BIOPointer::Write, EVPKeyPointer::bits, Cipher::EMPTY, ECKeyPointer::New(const EC_GROUP*), EVPKeyCtxPointer::derive, HMACCtxPointer::digest, Ec::Ec(), Ec::Ec(const EC_KEY*), Ec::getGroup, and the Ec conversion operators and field.

Scan summary for this run. Areas: Rust in src/runtime, src/http_jsc, src/bun_core, src/base64, src/ptr, and the JSC bindings outside the files that open dead-code PRs (#39929, #40232, #40367, #40294, #40172, #40122) already touch; the TS builtins in src/js.

  • hawk over x86_64-unknown-linux-gnu, x86_64-pc-windows-msvc, aarch64-apple-darwin (release profile, per hawk.toml): 847 dead_public findings. 668 are fields of FFI mirror structs (libuv.rs, windows_sys/externs.rs, boringssl.rs). Most of the rest are in files the open PRs own, are debug-only (has_resolve_breakpoint, StoredTrace::capture, ArrayHashMap::unlock_pointers), are codegen targets (host_fn_this_value), or are FFI enum mirrors (tty::Mode::Io, ImplementationVisibility).
  • oxlint with no-unused-vars, no-unused-private-class-members, no-unreachable over src/js: 0 findings. No src/js file is unimported. No .rs file is outside a mod tree except the three [[bench]] targets.
  • --gc-sections relink of bun-debug: 1005 non-generated discarded symbols, 283 of them in files no open PR touches. After removing sqlite3.c, llhttp, vendored shims, platform-gated code, and generated ZigGeneratedClasses helpers, the list above is what remains.

Possibly dead, left alone:

  • bun_core::strings::split_once / rsplit_once: no caller today, but clippy.toml names them as the replacement for the denied str::split_once / bstr::split_once_str forms. Kept as API surface.

  • src/jsc/bindings/webcore/streams/JSCrossRealmTransformState.{cpp,h} (135 lines): the CrossRealm source and sink kinds in StreamsForward.h are never constructed. It reads as scaffolding for stream transfer in the native streams work, so it stays.

  • ECDSASigPointer, ECGroupPointer, ECPointPointer, HMACCtxPointer: default constructor, move constructor, and release() are unreferenced, but they are the smart-pointer idiom the rest of ncrypto follows.

  • src/threading/Futex.rs wasm_impl and unsupported_impl: no shipped target compiles them.

  • bun_core::Global::StoredTrace::{EMPTY, capture}, has_resolve_breakpoint, ArrayHashMap::unlock_pointers, TaskTag::name: release-dead, used under debug_assertions.

…sc JSC bindings

Rust: the three WebSocket host exports that no C++ caller names
(Bun__WebSocketClient__writeBlob, Bun__WebSocketClientTLS__writeBlob,
Bun__WebSocketClientTLS__initWithTunnel) and the WebSocketClient::write_blob
body behind them, the Bun__internal_drainTimers export,
bun_base64::simdutf_encode_url_safe_alloc, bun_core::strings::split_once and
rsplit_once, and CowSliceZ::init_unchecked.

C++: HTTPParser::lessThan, the HistogramData&& overload of
JSNodePerformanceHooksHistogram::create, JSAbortAlgorithm::callbackData and
toJS(AbortAlgorithm), JSPerformance::toWrapped, JSCStackFrame::typeName,
root(CryptoKey*), the String overload of throwNodeRangeError, and the ncrypto
helpers nothing calls (CryptoErrorList::add and pop_front, BignumPointer::encode
and encodeInto, X509View::clone, BIOPointer::New(const BIO_METHOD*) and Write,
EVPKeyPointer::bits, Cipher::EMPTY, ECKeyPointer::New(const EC_GROUP*),
EVPKeyCtxPointer::derive, HMACCtxPointer::digest, and the Ec instance API).
@coderabbitai

coderabbitai Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

  • Run on-demand review

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

Or wait 12 minutes for your next included review.

View limit details

Limit details: You’ve used all 5 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 40e781a0-8ef6-40e3-b7d0-79da3515ebb3

📥 Commits

Reviewing files that changed from the base of the PR and between 0823e50 and f3d78cd.

📒 Files selected for processing (21)
  • src/base64/lib.rs
  • src/http_jsc/websocket_client.rs
  • src/jsc/bindings/ErrorStackTrace.cpp
  • src/jsc/bindings/ErrorStackTrace.h
  • src/jsc/bindings/JSNodePerformanceHooksHistogram.cpp
  • src/jsc/bindings/JSNodePerformanceHooksHistogram.h
  • src/jsc/bindings/ncrypto.cpp
  • src/jsc/bindings/ncrypto.h
  • src/jsc/bindings/node/http/NodeHTTPParser.cpp
  • src/jsc/bindings/node/http/NodeHTTPParser.h
  • src/jsc/bindings/webcore/JSAbortAlgorithm.cpp
  • src/jsc/bindings/webcore/JSAbortAlgorithm.h
  • src/jsc/bindings/webcore/JSDOMOperation.cpp
  • src/jsc/bindings/webcore/JSDOMOperation.h
  • src/jsc/bindings/webcore/JSPerformance.cpp
  • src/jsc/bindings/webcore/JSPerformance.h
  • src/jsc/bindings/webcrypto/CryptoKey.cpp
  • src/jsc/bindings/webcrypto/CryptoKey.h
  • src/ptr/CowSlice.rs
  • src/runtime/timer/Timer.rs
  • test/internal/source-lints/host-export-callers.test.ts

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

@robobun

robobun commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 10:48 PM PT - Aug 24th, 2026

✅ @robobun, your commit f3d78cde78b83e982de1fb59e0aa480469c17763 passed in Build #105393! 🎉


🧪   To try this PR locally:

bunx bun-pr 40413

That installs a local version of the PR into your bun-40413 executable, so you can run:

bun-40413 --bun

@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 reviewed this PR and didn't find any bugs. Because it removes ~30 items across 21 files spanning several subsystems (WebSocket client, ncrypto/webcrypto, JSC bindings, timers, bun_core), a human glance would still be worthwhile — mainly to confirm none of the removed ncrypto helpers or the gutted Ec wrapper are wanted for near-term Node-compat work.

What was reviewed:

  • Grepped for every removed HOST_EXPORT symbol, throwNodeRangeError (all callers pass ASCIILiteral), JSPerformance::toWrapped, root(CryptoKey*), typeName/m_typeName, lessThan, callbackData(), init_unchecked, split_once/rsplit_once, simdutf_encode_url_safe_alloc — no remaining references.
  • Confirmed Bun__WebSocketClient__initWithTunnel (non-TLS) is the only tunnel init C++ calls; the TLS variant is unreferenced.
  • Confirmed the remaining .getGroup() calls are on ECKeyPointer, not the removed Ec::getGroup.
Extended reasoning...

Overview

Pure dead-code removal across 21 files: four orphaned Rust HOST_EXPORT thunks (WebSocket writeBlob × 2, TLS initWithTunnel, Bun__internal_drainTimers) plus the write_blob impl; three unused pub Rust items (simdutf_encode_url_safe_alloc, strings::{split_once,rsplit_once}, CowSliceZ::init_unchecked); and a dozen-plus unreferenced C++ methods in ncrypto, ErrorStackTrace, JSNodePerformanceHooksHistogram, JSAbortAlgorithm, JSPerformance, JSDOMOperation, CryptoKey, and NodeHTTPParser. The only non-deletion is folding encode_append_impl into its sole caller encode_append (inlining the constant false for is_urlsafe).

Security risks

None introduced — only deletions. The touched ncrypto/webcrypto helpers (BignumPointer::encode, X509View::clone, HMACCtxPointer::digest, root(CryptoKey*), etc.) are unreferenced wrappers over BoringSSL; removing them cannot change runtime crypto behavior. No validation, auth, or TLS-gating logic is weakened.

Level of scrutiny

Medium. Each individual deletion is mechanical and self-verifying (a live reference would fail the link/compile, and the PR states bun bd + rust:check-all on all 12 targets pass). I spot-checked ~15 of the removed symbols with grep and found no remaining callers. The verification methodology (rg over src/codegen/packages/vendor + --gc-sections --print-gc-sections relink) is sound.

Other factors

The breadth (8+ subsystems, including ncrypto which is a vendored Node compat layer) and the note about coordinating with several other open dead-code PRs (#39929, #40232, #40367, #40294, #40172, #40122) suggest a maintainer should confirm none of the removed ncrypto surface is slated for imminent use. That coordination question, not correctness, is why I'm deferring rather than approving.

The generated extern "C" thunk roots the Rust implementation, so an export
whose C++ caller was deleted compiles without a warning. The lint fails on
the four exports this branch removes.
Comment thread src/bun_core/string/immutable.rs Resolved
clippy.toml names bun_core::strings::split_once and rsplit_once as the
sanctioned replacement for the denied str and bstr forms, so they stay.

The lint now skips rust-abi markers (their consumers are extern "Rust"
blocks, not C++) and pins git grep output format against user config.

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

Thanks for addressing the earlier feedback — f3d78cd restored strings::split_once/rsplit_once, pinned the git grep output format with -c overrides, and now filters rust-abi markers out of the orphan check. I re-reviewed and found no bugs this pass. Given the breadth (21 files across ncrypto/webcrypto, JSC bindings, WebSocket client, timers) and that this adds a new CI-enforced source lint, a maintainer sign-off would still be worthwhile.

What was reviewed:

  • Confirmed the three prior nits are resolved in f3d78cd (immutable.rs restored; grep.lineNumber/grep.column/color.grep pinned; rustAbi set excludes rust-abi markers).
  • Spot-checked JSPerformance::toWrapped removal against JSDOMWrapperConverterTraits / IDLInterface<Performance> — no template callers found.
  • Verified the new lint's guard tests (exports.size > 50, named.size > 50, duplicate detection) prevent vacuous passes.
Extended reasoning...

Overview

This PR deletes ~340 lines of dead code across 21 files: four orphaned Rust HOST_EXPORT thunks (WebSocket writeBlob × 2, initWithTunnel for TLS, drainTimers) plus their implementations; sixteen unused ncrypto helpers; assorted unreferenced C++ methods in JSC bindings (JSCStackFrame::typeName, HTTPParser::lessThan, one histogram create overload, JSAbortAlgorithm toJS/callbackData, JSPerformance::toWrapped, root(CryptoKey*), the String overload of throwNodeRangeError); and two Rust helpers (simdutf_encode_url_safe_alloc, CowSliceZ::init_unchecked). It also adds test/internal/source-lints/host-export-callers.test.ts, a new CI lint that fails if any HOST_EXPORT marker has no C/C++-side reference.

Since my previous review (three inline nits at c143bd4), commit f3d78cd restored bun_core::strings::{split_once, rsplit_once} (dropping the clippy.toml stale-reference concern entirely), added -c grep.lineNumber=false -c grep.column=false -c color.grep=never to the gitGrep helper, and made the MARKER regex capture the abi so rust-abi symbols are excluded from the C++ caller check. All three prior concerns are resolved.

Security risks

The deletions touch ncrypto and webcrypto (CryptoKey), which are crypto-adjacent. However, every removed item is a helper with no caller — verified by the PR author via rg over src/codegen/packages/vendor and a --gc-sections --print-gc-sections relink, and compilation on all 12 targets. Pure deletions of unreferenced symbols do not change runtime crypto behavior. No new attack surface is introduced. The new lint spawns git grep over the tracked tree with fixed pathspecs and no shell interpolation of untrusted input.

Level of scrutiny

Medium-high. Dead-code removal is mechanically verifiable (the compiler and linker are the ground truth), and the PR's methodology is thorough. But three factors push this past auto-approval: (1) breadth — 21 files across WebSocket client, timers, ncrypto, webcrypto, and multiple JSC binding subsystems; (2) the Ec class in ncrypto is reduced from a stateful wrapper to a static-method-only holder, which is a shape change to a vendored Node helper layer that a maintainer should confirm is desired; (3) the new host-export-callers lint is a CI policy addition that will gate every future PR adding a HOST_EXPORT marker, and REVIEW.md notes that new cross-cutting checks warrant maintainer agreement.

Other factors

The bug hunting system found nothing this run. I spot-checked JSPerformance::toWrapped for template-instantiated callers via JSDOMWrapperConverterTraits<Performance> / IDLInterface<Performance> and found none. The new lint now has guard tests against vacuous passes (marker count > 50, named count > 50, duplicate detection) and is hermetic against user git config. The PR description lists open dead-code PRs it deliberately avoided overlapping with, and calls out items it examined but left alone (e.g. root(MessagePort*) for an open PR).

@alii

alii commented Aug 25, 2026

Copy link
Copy Markdown
Member

@robobun binary size impact?

@robobun

robobun commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

None that the size check can measure. CI's binary-size step for the current head (f3d78cde78, build 105393) against canary main #105251:

target delta
bun-darwin-aarch64 -16.1 KB
the other 11 targets (linux, musl, android, freebsd, windows, darwin-x64) +0.0 KB

That is the expected result. Release links run with --gc-sections (Linux, FreeBSD), -dead_strip (macOS) and /OPT:REF (Windows), and every function this PR deletes was already unreferenced, so the linker was discarding them before. The 16 KB on darwin-aarch64 is within the step's build-to-build noise. The gain is source only: about 320 lines the compiler still had to build and people still had to read.

@alii

alii commented Aug 25, 2026

Copy link
Copy Markdown
Member

@robobun how can we be confident this doesn't break anything? and is strictly dead code?

@robobun

robobun commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

Two different arguments, one per kind of symbol.

The C++ methods and the two Rust pub fns: the toolchain is the proof. Every removed C++ function has a mangled name (HTTPParser::lessThan, the HistogramData&& overload of JSNodePerformanceHooksHistogram::create, JSAbortAlgorithm::callbackData, JSPerformance::toWrapped, JSCStackFrame::typeName, root(CryptoKey*), the String overload of throwNodeRangeError, the ncrypto helpers). A mangled symbol can only be reached from a compiled call site, including template instantiations, so any caller anywhere would be an undefined reference at link time. Build 105393 compiled and linked all 12 targets and ran the whole test suite: 182 jobs, 0 failed. Same for CowSliceZ::init_unchecked and simdutf_encode_url_safe_alloc: a Rust pub fn with a caller cannot be deleted without a compile error, and rust:check-all passes on every target. None of the removed overloads can change overload resolution silently either: the remaining throwNodeRangeError takes ASCIILiteral, which a String does not convert to, and the other removed overloads differ in arity or name from what stays.

The four HOST_EXPORT thunks are the one place the compiler cannot decide, because extern "C" symbols can be named from C++ by declaration alone. Three checks cover that gap:

  1. No tracked C, C++, header, JS, or codegen file names Bun__WebSocketClient__writeBlob, Bun__WebSocketClientTLS__writeBlob, Bun__WebSocketClientTLS__initWithTunnel, or Bun__internal_drainTimers. The new host-export-callers lint encodes this and fails on main with exactly those four.
  2. A relink of bun-debug with --gc-sections --print-gc-sections discarded all four sections, so nothing in the final link referenced them. A C++ reference to a missing extern "C" symbol would also have been an undefined-symbol link error on every CI lane.
  3. They are not in src/symbols.{txt,dyn,def}, so no native addon can dlsym them.

Behavior cannot change because no code path changed: the diff is deletions plus one fold of encode_append_impl into encode_append with its constant false inlined. The binary-size table above says the same thing from the other side: the release linker was already dropping every one of these, so the shipped bytes are identical.

Two items I removed earlier and then kept because the evidence was not that clean: bun_core::strings::split_once/rsplit_once (no caller, but clippy.toml points people at them) and root(MessagePort*) (owned by #39929).

@alii

alii commented Aug 25, 2026

Copy link
Copy Markdown
Member

but clippy.toml points people at them) and root(MessagePort*) (owned by #39929).

Explain?

@robobun

robobun commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator Author

Both are functions nothing calls that I chose not to delete in this PR.

bun_core::strings::split_once / rsplit_once (src/bun_core/string/immutable.rs). They take a multi-byte delimiter; every caller in the tree uses the single-byte split_once_char / rsplit_once_char instead, so both hawk and a grep report them as dead. The first head of this PR deleted them. A review comment pointed out that clippy.toml denies str::split_once, str::rsplit_once, str::splitn, str::rsplitn, bstr::ByteSlice::split_once_str and rsplit_once_str, and each of those entries has a reason string that tells the developer to call bun_core::strings::split_once / rsplit_once (clippy.toml lines 38, 39, 42, 43, 75, 76). So these two functions are the sanctioned replacement for a banned std API. With them gone, the lint would send people to a helper that does not exist, and they would hand-roll index_of plus slicing. I restored them in f3d78cde78 and the PR no longer touches bun_core.

root(MessagePort*) (src/jsc/bindings/webcore/MessagePort.cpp:557, declared in MessagePort.h:177). WebCore's opaque-root idiom: JSXOwner::isReachableFromOpaqueRoots normally marks root(&wrapped) so a wrapper stays alive while its C++ object is reachable. JSMessagePortOwner::isReachableFromOpaqueRoots decides on hasPendingActivity() instead and never calls root(), so the linker drops it, same as the root(CryptoKey*) this PR does remove. I left it because MessagePort.cpp and MessagePort.h are being edited by #39841 (a MessagePort.close() bug fix), and a deletion in the same file would only create a conflict for a behavior fix that should land first. One correction: my earlier comment said #39929 owns it. That was wrong, #39841 is the PR touching those files. It is five lines, and a later sweep can take it once #39841 merges.

@alii
alii enabled auto-merge (squash) August 25, 2026 06:57
@alii
alii merged commit 023e84a into main Aug 25, 2026
9 checks passed
@alii
alii deleted the farm/e032f20d/dead-code-websocket-ncrypto-core branch August 25, 2026 06:57
robobun added a commit that referenced this pull request Oct 15, 2026
ECKeyPointer::New(const EC_GROUP*) no longer exists on main. It was
removed as dead code in #40413. TryParseECSubjectPublicKeyInfo was its
only caller, so create the EC_KEY and set its group directly.
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.

3 participants