Skip to content

zlib: fix crash when async buffers are detached or resized - #67603

Open
ShogunPanda wants to merge 1 commit into
nodejs:mainfrom
ShogunPanda:zlib-pin-async-buffers
Open

ShogunPanda wants to merge 1 commit into
nodejs:mainfrom
ShogunPanda:zlib-pin-async-buffers

Conversation

@ShogunPanda

Copy link
Copy Markdown
Contributor

Asynchronous zlib, brotli and zstd operations run on the libuv threadpool, where the worker thread accesses JavaScript-owned backing stores through raw pointers. If the input or output ArrayBuffer is detached (for example with ArrayBuffer.prototype.transfer() or a transferred postMessage()) or resized (ArrayBuffer.prototype.resize()) while the operation is in flight, the worker reads or writes invalid memory and the process crashes.

Non-resizable input and output buffers are now pinned with a std::shared_ptr<v8::BackingStore> for the duration of the operation, and resizable buffers are copied into engine-owned memory, because resize() decommits pages even when a backing store is pinned. The resulting "buffer invalidated" errors are surfaced as stream errors rather than uncaught exceptions. The documentation now states that these buffers must not be detached or resized until the operation completes.

@nodejs-github-bot nodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. needs-ci PRs that need a full CI run. zlib Issues and PRs related to the zlib module and its compression dependencies. labels Nov 19, 2026
@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.92929% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.58%. Comparing base (cdd0687) to head (8475775).
⚠️ Report is 366 commits behind head on main.

Files with missing lines Patch % Lines
src/node_zlib.cc 88.33% 0 Missing and 7 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #67603      +/-   ##
==========================================
- Coverage   90.73%   90.58%   -0.15%     
==========================================
  Files         801      802       +1     
  Lines      280794   287117    +6323     
  Branches    54202    55440    +1238     
==========================================
+ Hits       254771   260086    +5315     
- Misses      16202    17111     +909     
- Partials     9821     9920      +99     
Files with missing lines Coverage Δ
lib/zlib.js 98.45% <100.00%> (+0.03%) ⬆️
src/node_zlib.cc 81.10% <88.33%> (+0.38%) ⬆️

... and 210 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ShogunPanda ShogunPanda added the request-ci Add this label to start a Jenkins CI on a PR. Only starts once the PR has an approving review. label Dec 3, 2026
@mcollina

mcollina commented Dec 3, 2026

Copy link
Copy Markdown
Member

Seems some lines are not covered by tests

Comment thread lib/zlib.js Outdated
// If the input/output buffer was detached or resized while the operation
// was in flight, the native bindings throw ERR_OUT_OF_RANGE. That must be
// surfaced as a stream error rather than an uncaught exception.
const reprocess = () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

can you avoid to allocate this closure?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. The closure is gone: the retry now goes through a top-level writeRemainingInput(self, handle) helper that wraps handle.write() in the try/catch, so nothing is allocated per pass.

Comment thread lib/zlib.js
reprocess();
} else {
const oldRead = self._read;
self._read = (n) => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This branch isn't new: it's the existing backpressure path from 9052ef4 ("zlib: pause stream if outgoing buffer is full"). The diff only made it look new because the write moved into a helper. When push() returns false we defer the next pass until the consumer reads again, so a highly compressible input can't grow the readable buffer without bound. The only change is that the deferred write now goes through the same helper, so an input that was detached or resized while the stream was paused is reported as a stream error. I added a comment there, and a test (test-zlib-arraybuffer-detach-reprocess.js) that hits this deferred path and checks the error comes from it.

Asynchronous zlib, brotli and zstd operations run on the libuv
threadpool, where the worker thread reads and writes through raw
pointers into JavaScript-owned backing stores. Detaching or resizing
the input or output ArrayBuffer while the operation is in flight frees
or decommits the backing store the worker is still accessing, which
crashes the process.

Pin non-resizable input and output buffers with a
std::shared_ptr<v8::BackingStore> for the duration of the operation, and
copy resizable buffers into engine-owned memory because resize()
decommits pages even when a backing store is pinned. Surface the
resulting "buffer invalidated" errors as stream errors rather than
uncaught exceptions.

Assisted-By: OpenAI GPT-5.6 Sol <openai/gpt-5.6-sol>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
Signed-off-by: Paolo Insogna <paolo@cowtech.it>
@ShogunPanda
ShogunPanda force-pushed the zlib-pin-async-buffers branch from 2bd9d84 to 8475775 Compare December 4, 2026 13:45
@ShogunPanda

Copy link
Copy Markdown
Contributor Author

Added test/parallel/test-zlib-arraybuffer-detach-reprocess.js to cover the lines Codecov reported: invalidating the input between passes (both the immediate and the deferred path), resizable output staging (normal round-trip, passes with no output, shrinking to zero), async errors with a staged output buffer, and flush-only writes with a null input. I also simplified CopyBackOutput() (dropped an unreachable check, used std::min), and moved the release of the pins/copies into Close(), so the UV_ECANCELED path, which zlib can't trigger, no longer has its own uncovered line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

c++ Issues and PRs that require attention from people who are familiar with C++. needs-ci PRs that need a full CI run. request-ci Add this label to start a Jenkins CI on a PR. Only starts once the PR has an approving review. zlib Issues and PRs related to the zlib module and its compression dependencies.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants