Skip to content

Commit f2e1ed3

Browse files
committed
fs: align fs.ReadStream buffer pool writes to 8-byte boundary
Prevents alignment issues when creating a typed array from a buffer. Fixes: #24817
1 parent 1859769 commit f2e1ed3

2 files changed

Lines changed: 19 additions & 5 deletions

File tree

lib/internal/fs/streams.js

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,10 @@ function checkPosition(pos, name) {
4949
}
5050
}
5151

52+
function roundUpToMultipleOf8(n) {
53+
return (n + 7) & ~7; // Align to 8 byte boundary.
54+
}
55+
5256
function ReadStream(path, options) {
5357
if (!(this instanceof ReadStream))
5458
return new ReadStream(path, options);
@@ -170,10 +174,18 @@ ReadStream.prototype._read = function(n) {
170174
// Now that we know how much data we have actually read, re-wind the
171175
// 'used' field if we can, and otherwise allow the remainder of our
172176
// reservation to be used as a new pool later.
173-
if (start + toRead === thisPool.used && thisPool === pool)
174-
thisPool.used += bytesRead - toRead;
175-
else if (toRead - bytesRead > kMinPoolSpace)
176-
poolFragments.push(thisPool.slice(start + bytesRead, start + toRead));
177+
if (start + toRead === thisPool.used && thisPool === pool) {
178+
const newUsed = thisPool.used + bytesRead - toRead;
179+
thisPool.used = roundUpToMultipleOf8(newUsed);
180+
} else {
181+
// Round down to the next lowest multiple of 8 to ensure the new pool
182+
// fragment start and end positions are aligned to an 8 byte boundary.
183+
const alignedEnd = (start + toRead) & ~7;
184+
const alignedStart = roundUpToMultipleOf8(start + bytesRead);
185+
if (alignedEnd - alignedStart >= kMinPoolSpace) {
186+
poolFragments.push(thisPool.slice(alignedStart, alignedEnd));
187+
}
188+
}
177189

178190
if (bytesRead > 0) {
179191
this.bytesRead += bytesRead;
@@ -187,7 +199,8 @@ ReadStream.prototype._read = function(n) {
187199
// Move the pool positions, and internal position for reading.
188200
if (this.pos !== undefined)
189201
this.pos += toRead;
190-
pool.used += toRead;
202+
203+
pool.used = roundUpToMultipleOf8(pool.used + toRead);
191204
};
192205

193206
ReadStream.prototype._destroy = function(err, cb) {

test/parallel/test-fs-read-stream.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ const rangeFile = fixtures.path('x.txt');
5555

5656
file.on('data', function(data) {
5757
assert.ok(data instanceof Buffer);
58+
assert.ok(data.byteOffset % 8 === 0);
5859
assert.ok(!paused);
5960
file.length += data.length;
6061

0 commit comments

Comments
 (0)