Skip to content

Commit 371be9c

Browse files
addaleaxrvagg
authored andcommitted
buffer: ignore negative allocation lengths
Treat negative length arguments to `Buffer()`/`allocUnsafe()` as if they were zero so the allocation does not affect the pool’s offset. Fixes: #7047 PR-URL: #7051 Reviewed-By: Sakthipriyan Vairamani <[email protected]> Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: Сковорода Никита Андреевич <[email protected]> Reviewed-By: Trevor Norris <[email protected]> Reviewed-By: Rod Vagg <[email protected]>
1 parent 1c12567 commit 371be9c

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

lib/buffer.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,8 @@ Object.setPrototypeOf(SlowBuffer, Uint8Array);
199199

200200

201201
function allocate(size) {
202-
if (size === 0) {
203-
return createBuffer(size);
202+
if (size <= 0) {
203+
return createBuffer(0);
204204
}
205205
if (size < (Buffer.poolSize >>> 1)) {
206206
if (size > (poolSize - poolOffset))

test/parallel/test-buffer.js

+11
Original file line numberDiff line numberDiff line change
@@ -1465,3 +1465,14 @@ assert.equal(Buffer.prototype.parent, undefined);
14651465
assert.equal(Buffer.prototype.offset, undefined);
14661466
assert.equal(SlowBuffer.prototype.parent, undefined);
14671467
assert.equal(SlowBuffer.prototype.offset, undefined);
1468+
1469+
{
1470+
// Test that large negative Buffer length inputs don't affect the pool offset.
1471+
assert.deepStrictEqual(Buffer(-Buffer.poolSize), Buffer.from(''));
1472+
assert.deepStrictEqual(Buffer(-100), Buffer.from(''));
1473+
assert.deepStrictEqual(Buffer.allocUnsafe(-Buffer.poolSize), Buffer.from(''));
1474+
assert.deepStrictEqual(Buffer.allocUnsafe(-100), Buffer.from(''));
1475+
1476+
// Check pool offset after that by trying to write string into the pool.
1477+
assert.doesNotThrow(() => Buffer.from('abc'));
1478+
}

0 commit comments

Comments
 (0)