Skip to content

Commit ff70ea5

Browse files
committed
fs: use sized reads for large files in readFileUtf8
fs.readFileSync(path, 'utf8') read the whole file in 8 KiB read() calls appended to a std::string, i.e. one syscall and a potential reallocation per 8 KiB (an 8 MiB file took ~1400 read() calls). Keep the exact old sequence for small files (one read into the 8 KiB stack buffer, one read reporting EOF). Once a read fills the stack buffer, read the rest directly into one heap buffer sized from fstat() (plus one byte so that the EOF read does not force growth), growing geometrically only when the size is unavailable or wrong. The size is only an allocation hint: reading continues until read() reports EOF, so procfs/sysfs files, FIFOs, files that change while being read and file descriptors positioned mid-file behave as before, and the bytes handed to StringBytes::Encode() are exactly the ones read. Signed-off-by: Shelley Vohr <shelley.vohr@gmail.com>
1 parent 30bff4a commit ff70ea5

2 files changed

Lines changed: 161 additions & 2 deletions

File tree

src/node_file.cc

Lines changed: 73 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2924,10 +2924,30 @@ static void ReadFileUtf8(const FunctionCallbackInfo<Value>& args) {
29242924
uv_fs_req_cleanup(&req);
29252925
});
29262926

2927+
// Small files (the common case, e.g. module sources) are read exactly as
2928+
// before: read() into an 8 KiB stack buffer until one reports EOF. Once a
2929+
// read fills the whole stack buffer the file is evidently larger; the rest
2930+
// is then read directly into one heap buffer -- first a 64 KiB step (so
2931+
// files up to that size still take exactly the reads they took before, and
2932+
// no fstat()), then, if that fills up too, sized from fstat() (falling back
2933+
// to geometric growth) -- instead of appending 8 KiB per syscall to a
2934+
// repeatedly reallocated std::string. The fstat() size is only a hint for
2935+
// the allocation: reading continues until read() reports EOF, so files
2936+
// whose size is misreported (procfs) or that change concurrently behave as
2937+
// before, and the bytes handed to StringBytes::Encode() are exactly the
2938+
// ones read.
29272939
std::string result{};
29282940
char buffer[8192];
29292941
uv_buf_t buf = uv_buf_init(buffer, sizeof(buffer));
29302942

2943+
char* big = nullptr;
2944+
size_t big_len = 0;
2945+
size_t big_cap = 0;
2946+
bool sized = false;
2947+
auto free_big = OnScopeLeave([&big]() { free(big); });
2948+
constexpr size_t kMinChunk = 64 * 1024;
2949+
constexpr size_t kMaxChunk = 8 * 1024 * 1024;
2950+
29312951
FS_SYNC_TRACE_BEGIN(read);
29322952
while (true) {
29332953
auto r = uv_fs_read(nullptr, &req, file, &buf, 1, -1, nullptr);
@@ -2940,12 +2960,63 @@ static void ReadFileUtf8(const FunctionCallbackInfo<Value>& args) {
29402960
if (r <= 0) {
29412961
break;
29422962
}
2943-
result.append(buf.base, r);
2963+
if (big == nullptr) {
2964+
result.append(buf.base, r);
2965+
if (static_cast<size_t>(r) < sizeof(buffer)) {
2966+
continue;
2967+
}
2968+
// Switch to the heap buffer.
2969+
uv_fs_req_cleanup(&req);
2970+
big_cap = kMinChunk;
2971+
big = UncheckedMalloc<char>(big_cap);
2972+
if (big == nullptr) {
2973+
FS_SYNC_TRACE_END(read);
2974+
return THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
2975+
}
2976+
memcpy(big, result.data(), result.size());
2977+
big_len = result.size();
2978+
result = std::string();
2979+
} else {
2980+
big_len += static_cast<size_t>(r);
2981+
}
2982+
if (big_len == big_cap) {
2983+
// Full: grow. The first time, size the buffer from fstat() when that
2984+
// looks trustworthy (+1 leaves room for the EOF-reporting read()).
2985+
size_t new_cap =
2986+
big_cap + std::min(kMaxChunk, std::max(kMinChunk, big_cap));
2987+
if (!sized) {
2988+
sized = true;
2989+
uv_fs_req_cleanup(&req);
2990+
uv_fs_t stat_req;
2991+
if (uv_fs_fstat(nullptr, &stat_req, file, nullptr) == 0) {
2992+
const uv_stat_t* const st =
2993+
static_cast<const uv_stat_t*>(stat_req.ptr);
2994+
if ((st->st_mode & S_IFMT) == S_IFREG &&
2995+
static_cast<uint64_t>(st->st_size) > big_len &&
2996+
static_cast<uint64_t>(st->st_size) <
2997+
static_cast<uint64_t>(v8::String::kMaxLength)) {
2998+
new_cap = static_cast<size_t>(st->st_size) + 1;
2999+
}
3000+
}
3001+
uv_fs_req_cleanup(&stat_req);
3002+
}
3003+
char* const grown = UncheckedRealloc<char>(big, new_cap);
3004+
if (grown == nullptr) {
3005+
FS_SYNC_TRACE_END(read);
3006+
return THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
3007+
}
3008+
big = grown;
3009+
big_cap = new_cap;
3010+
}
3011+
buf = uv_buf_init(big + big_len, std::min(kMaxChunk, big_cap - big_len));
29443012
}
29453013
FS_SYNC_TRACE_END(read);
29463014

29473015
Local<Value> val;
2948-
if (!ToV8Value(env->context(), result, isolate).ToLocal(&val)) {
3016+
const std::string_view content = big != nullptr
3017+
? std::string_view(big, big_len)
3018+
: std::string_view(result);
3019+
if (!ToV8Value(env->context(), content, isolate).ToLocal(&val)) {
29493020
return;
29503021
}
29513022

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
'use strict';
2+
// fs.readFileSync(path, 'utf8') takes a dedicated native path. Its result must
3+
// equal fs.readFileSync(path).toString('utf8') for every file size (in
4+
// particular around its internal 8 KiB stack buffer and for multi-megabyte
5+
// files), for file descriptors positioned mid-file, and for files whose
6+
// reported size is wrong (procfs reports 0, sysfs reports a page).
7+
const common = require('../common');
8+
const tmpdir = require('../common/tmpdir');
9+
const assert = require('assert');
10+
const fs = require('fs');
11+
12+
tmpdir.refresh();
13+
14+
function content(size) {
15+
// Multi-byte characters straddling every possible chunk boundary.
16+
const unit = 'abcdé€\u{1F600}\n';
17+
let s = unit.repeat(Math.ceil(size / unit.length));
18+
s = s.slice(0, size);
19+
// Avoid ending on a lone surrogate produced by slice().
20+
if (/[\ud800-\udbff]$/.test(s)) s = s.slice(0, -1) + 'x';
21+
return s;
22+
}
23+
24+
const sizes = [0, 1, 8190, 8191, 8192, 8193, 8194, 16383, 16384, 16385,
25+
65535, 65536, 65537, 100000, (1 << 20) - 1, 1 << 20, (1 << 20) + 1,
26+
(8 << 20) + 5];
27+
for (const size of sizes) {
28+
const file = tmpdir.resolve(`f-${size}.txt`);
29+
const str = content(size);
30+
fs.writeFileSync(file, str);
31+
const expected = fs.readFileSync(file).toString('utf8');
32+
assert.strictEqual(fs.readFileSync(file, 'utf8'), expected, `size ${size} by path`);
33+
assert.strictEqual(fs.readFileSync(file, { encoding: 'utf-8' }), expected, `size ${size} utf-8 alias`);
34+
// By fd: from the start (leaves the fd at EOF), then at EOF, then from a
35+
// mid-file position on a fresh fd.
36+
let fd = fs.openSync(file, 'r');
37+
try {
38+
assert.strictEqual(fs.readFileSync(fd, 'utf8'), expected, `size ${size} by fd`);
39+
assert.strictEqual(fs.readFileSync(fd, 'utf8'), '', `size ${size} by fd at EOF`);
40+
} finally {
41+
fs.closeSync(fd);
42+
}
43+
if (size > 10) {
44+
fd = fs.openSync(file, 'r');
45+
try {
46+
// Advance the fd 3 bytes (inside the ASCII prefix, so still valid UTF-8).
47+
assert.strictEqual(fs.readSync(fd, Buffer.alloc(3), 0, 3, null), 3);
48+
assert.strictEqual(fs.readFileSync(fd, 'utf8'), Buffer.from(expected).subarray(3).toString('utf8'),
49+
`size ${size} by fd at offset 3`);
50+
} finally {
51+
fs.closeSync(fd);
52+
}
53+
}
54+
}
55+
56+
// Binary garbage is decoded with replacement characters identically.
57+
{
58+
const file = tmpdir.resolve('binary.bin');
59+
const buf = Buffer.alloc(20000);
60+
for (let i = 0; i < buf.length; i++) buf[i] = (i * 7919) & 0xff;
61+
fs.writeFileSync(file, buf);
62+
assert.strictEqual(fs.readFileSync(file, 'utf8'), buf.toString('utf8'));
63+
}
64+
65+
// Files whose st_size does not describe their content.
66+
if (common.isLinux) {
67+
for (const file of ['/proc/self/status', '/proc/self/maps', '/proc/cpuinfo',
68+
'/proc/version', '/sys/kernel/mm/transparent_hugepage/enabled']) {
69+
let viaBuffer;
70+
try {
71+
viaBuffer = fs.readFileSync(file);
72+
} catch {
73+
continue; // Not available in this environment.
74+
}
75+
const viaUtf8 = fs.readFileSync(file, 'utf8');
76+
if (file !== '/proc/version' && file.startsWith('/proc/')) {
77+
// Content legitimately differs between two reads; compare shape instead.
78+
assert.ok(viaUtf8.length > 0);
79+
assert.strictEqual(viaUtf8.split('\n').length > 5, true, file);
80+
if (file === '/proc/self/maps') assert.ok(viaUtf8.length > 8192, 'maps should exceed one stack buffer');
81+
} else {
82+
assert.strictEqual(viaUtf8, viaBuffer.toString('utf8'), file);
83+
}
84+
}
85+
}
86+
87+
// Directory: same error either way.
88+
assert.throws(() => fs.readFileSync(tmpdir.path, 'utf8'), { code: 'EISDIR' });

0 commit comments

Comments
 (0)