Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/node_file.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3508,7 +3508,7 @@ static void ReadFileUtf8(const FunctionCallbackInfo<Value>& args) {
}
// Switch to the heap buffer.
uv_fs_req_cleanup(&req);
big_cap = kMinChunk;
big_cap = std::max(kMinChunk, result.size() + sizeof(buffer));
big = UncheckedMalloc<char>(big_cap);
if (big == nullptr) {
FS_SYNC_TRACE_END(read);
Expand All @@ -3520,7 +3520,7 @@ static void ReadFileUtf8(const FunctionCallbackInfo<Value>& args) {
} else {
big_len += static_cast<size_t>(r);
}
if (big_len == big_cap) {
if (big_len >= big_cap) {
// +1 leaves room for the read() that reports EOF.
size_t new_cap =
big_cap + std::min(kMaxChunk, std::max(kMinChunk, big_cap));
Expand Down
46 changes: 46 additions & 0 deletions test/parallel/test-fs-readfilesync-pipe-short-reads.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
'use strict';
const common = require('../common');

// readFileSync(fd, 'utf8') on a pipe must not overflow its heap buffer when
// more than 64 KiB arrive in short reads before the first full 8 KiB read.

if (common.isWindows)
common.skip('short-read timing on Windows pipes is not reliable');

const assert = require('assert');
const fs = require('fs');
const { spawn } = require('child_process');

const kChunks = 24;
const kChunkSize = 4000;
const kTailSize = 400000;

if (process.argv[2] === 'child') {
process.stderr.write('r');
process.stdout.write(String(fs.readFileSync(0, 'utf8').length));
return;
}

const child = spawn(process.execPath, [__filename, 'child']);

// Pace the short writes so each arrives as its own read, then send one large
// write to force the switch to the heap buffer.
child.stderr.once('data', common.mustCall(() => {
let i = 0;
const timer = setInterval(() => {
child.stdin.write('x'.repeat(kChunkSize));
if (++i === kChunks) {
clearInterval(timer);
child.stdin.end('y'.repeat(kTailSize));
}
}, common.platformTimeout(15));
}));

let stdout = '';
child.stdout.setEncoding('utf8');
child.stdout.on('data', (d) => { stdout += d; });
child.on('close', common.mustCall((code, signal) => {
assert.strictEqual(signal, null);
assert.strictEqual(code, 0);
assert.strictEqual(stdout, String(kChunks * kChunkSize + kTailSize));
}));
Loading