Skip to content

Commit

Permalink
buffer: ignore negative allocation lengths
Browse files Browse the repository at this point in the history
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 <thechargingvolcano@gmail.com>
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: Сковорода Никита Андреевич <chalkerx@gmail.com>
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Reviewed-By: Rod Vagg <rod@vagg.org>
  • Loading branch information
addaleax authored and Fishrock123 committed Jun 1, 2016
1 parent 29200ed commit 4438550
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,8 @@ Object.setPrototypeOf(SlowBuffer, Uint8Array);


function allocate(size) {
if (size === 0) {
return createBuffer(size);
if (size <= 0) {
return createBuffer(0);
}
if (size < (Buffer.poolSize >>> 1)) {
if (size > (poolSize - poolOffset))
Expand Down
11 changes: 11 additions & 0 deletions test/parallel/test-buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -1465,3 +1465,14 @@ assert.equal(Buffer.prototype.parent, undefined);
assert.equal(Buffer.prototype.offset, undefined);
assert.equal(SlowBuffer.prototype.parent, undefined);
assert.equal(SlowBuffer.prototype.offset, undefined);

{
// Test that large negative Buffer length inputs don't affect the pool offset.
assert.deepStrictEqual(Buffer(-Buffer.poolSize), Buffer.from(''));
assert.deepStrictEqual(Buffer(-100), Buffer.from(''));
assert.deepStrictEqual(Buffer.allocUnsafe(-Buffer.poolSize), Buffer.from(''));
assert.deepStrictEqual(Buffer.allocUnsafe(-100), Buffer.from(''));

// Check pool offset after that by trying to write string into the pool.
assert.doesNotThrow(() => Buffer.from('abc'));
}

0 comments on commit 4438550

Please sign in to comment.