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

Refs: #7051
PR-URL: #7221
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
addaleax authored and ChALkeR committed Jun 17, 2016
1 parent 21552bd commit 27785ae
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 @@ -163,8 +163,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 @@ -1438,3 +1438,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 27785ae

Please sign in to comment.