Skip to content

Commit 4438550

Browse files
addaleaxFishrock123
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 29200ed commit 4438550

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

‎lib/buffer.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,8 @@ Object.setPrototypeOf(SlowBuffer, Uint8Array);
199199

200200

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

‎test/parallel/test-buffer.js‎

Lines changed: 11 additions & 0 deletions
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)