Skip to content

Commit 7cf971d

Browse files
author
lazerg
committed
fs: fix readFileUtf8 overflow on short pipe reads
Assisted-by: Claude Signed-off-by: lazerg <lazerg2@gmail.com>
1 parent 2ce7a73 commit 7cf971d

2 files changed

Lines changed: 48 additions & 2 deletions

File tree

‎src/node_file.cc‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3508,7 +3508,7 @@ static void ReadFileUtf8(const FunctionCallbackInfo<Value>& args) {
35083508
}
35093509
// Switch to the heap buffer.
35103510
uv_fs_req_cleanup(&req);
3511-
big_cap = kMinChunk;
3511+
big_cap = std::max(kMinChunk, result.size() + sizeof(buffer));
35123512
big = UncheckedMalloc<char>(big_cap);
35133513
if (big == nullptr) {
35143514
FS_SYNC_TRACE_END(read);
@@ -3520,7 +3520,7 @@ static void ReadFileUtf8(const FunctionCallbackInfo<Value>& args) {
35203520
} else {
35213521
big_len += static_cast<size_t>(r);
35223522
}
3523-
if (big_len == big_cap) {
3523+
if (big_len >= big_cap) {
35243524
// +1 leaves room for the read() that reports EOF.
35253525
size_t new_cap =
35263526
big_cap + std::min(kMaxChunk, std::max(kMinChunk, big_cap));
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
'use strict';
2+
const common = require('../common');
3+
4+
// readFileSync(fd, 'utf8') on a pipe must not overflow its heap buffer when
5+
// more than 64 KiB arrive in short reads before the first full 8 KiB read.
6+
7+
if (common.isWindows)
8+
common.skip('short-read timing on Windows pipes is not reliable');
9+
10+
const assert = require('assert');
11+
const fs = require('fs');
12+
const { spawn } = require('child_process');
13+
14+
const kChunks = 24;
15+
const kChunkSize = 4000;
16+
const kTailSize = 400000;
17+
18+
if (process.argv[2] === 'child') {
19+
process.stderr.write('r');
20+
process.stdout.write(String(fs.readFileSync(0, 'utf8').length));
21+
return;
22+
}
23+
24+
const child = spawn(process.execPath, [__filename, 'child']);
25+
26+
// Pace the short writes so each arrives as its own read, then send one large
27+
// write to force the switch to the heap buffer.
28+
child.stderr.once('data', common.mustCall(() => {
29+
let i = 0;
30+
const timer = setInterval(() => {
31+
child.stdin.write('x'.repeat(kChunkSize));
32+
if (++i === kChunks) {
33+
clearInterval(timer);
34+
child.stdin.end('y'.repeat(kTailSize));
35+
}
36+
}, common.platformTimeout(15));
37+
}));
38+
39+
let stdout = '';
40+
child.stdout.setEncoding('utf8');
41+
child.stdout.on('data', (d) => { stdout += d; });
42+
child.on('close', common.mustCall((code, signal) => {
43+
assert.strictEqual(signal, null);
44+
assert.strictEqual(code, 0);
45+
assert.strictEqual(stdout, String(kChunks * kChunkSize + kTailSize));
46+
}));

0 commit comments

Comments
 (0)