Skip to content

Commit d47ea46

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 d47ea46

2 files changed

Lines changed: 150 additions & 2 deletions

File tree

‎src/node_file.cc‎

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

2927+
// Past the first 8 KiB, read into one heap buffer sized from fstat(); the
2928+
// size is only a hint, reading continues until read() reports EOF.
29272929
std::string result{};
29282930
char buffer[8192];
29292931
uv_buf_t buf = uv_buf_init(buffer, sizeof(buffer));
29302932

2933+
char* big = nullptr;
2934+
size_t big_len = 0;
2935+
size_t big_cap = 0;
2936+
bool sized = false;
2937+
auto free_big = OnScopeLeave([&big]() { free(big); });
2938+
constexpr size_t kMinChunk = 64 * 1024;
2939+
constexpr size_t kMaxChunk = 8 * 1024 * 1024;
2940+
29312941
FS_SYNC_TRACE_BEGIN(read);
29322942
while (true) {
29332943
auto r = uv_fs_read(nullptr, &req, file, &buf, 1, -1, nullptr);
@@ -2940,12 +2950,62 @@ static void ReadFileUtf8(const FunctionCallbackInfo<Value>& args) {
29402950
if (r <= 0) {
29412951
break;
29422952
}
2943-
result.append(buf.base, r);
2953+
if (big == nullptr) {
2954+
result.append(buf.base, r);
2955+
if (static_cast<size_t>(r) < sizeof(buffer)) {
2956+
continue;
2957+
}
2958+
// Switch to the heap buffer.
2959+
uv_fs_req_cleanup(&req);
2960+
big_cap = kMinChunk;
2961+
big = UncheckedMalloc<char>(big_cap);
2962+
if (big == nullptr) {
2963+
FS_SYNC_TRACE_END(read);
2964+
return THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
2965+
}
2966+
memcpy(big, result.data(), result.size());
2967+
big_len = result.size();
2968+
result = std::string();
2969+
} else {
2970+
big_len += static_cast<size_t>(r);
2971+
}
2972+
if (big_len == big_cap) {
2973+
// +1 leaves room for the read() that reports EOF.
2974+
size_t new_cap =
2975+
big_cap + std::min(kMaxChunk, std::max(kMinChunk, big_cap));
2976+
if (!sized) {
2977+
sized = true;
2978+
uv_fs_req_cleanup(&req);
2979+
uv_fs_t stat_req;
2980+
if (uv_fs_fstat(nullptr, &stat_req, file, nullptr) == 0) {
2981+
const uv_stat_t* const st =
2982+
static_cast<const uv_stat_t*>(stat_req.ptr);
2983+
if ((st->st_mode & S_IFMT) == S_IFREG &&
2984+
static_cast<uint64_t>(st->st_size) > big_len &&
2985+
static_cast<uint64_t>(st->st_size) <
2986+
static_cast<uint64_t>(v8::String::kMaxLength)) {
2987+
new_cap = static_cast<size_t>(st->st_size) + 1;
2988+
}
2989+
}
2990+
uv_fs_req_cleanup(&stat_req);
2991+
}
2992+
char* const grown = UncheckedRealloc<char>(big, new_cap);
2993+
if (grown == nullptr) {
2994+
FS_SYNC_TRACE_END(read);
2995+
return THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
2996+
}
2997+
big = grown;
2998+
big_cap = new_cap;
2999+
}
3000+
buf = uv_buf_init(big + big_len, std::min(kMaxChunk, big_cap - big_len));
29443001
}
29453002
FS_SYNC_TRACE_END(read);
29463003

29473004
Local<Value> val;
2948-
if (!ToV8Value(env->context(), result, isolate).ToLocal(&val)) {
3005+
const std::string_view content = big != nullptr
3006+
? std::string_view(big, big_len)
3007+
: std::string_view(result);
3008+
if (!ToV8Value(env->context(), content, isolate).ToLocal(&val)) {
29493009
return;
29503010
}
29513011

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)