Browse Source

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: https://github.com/nodejs/node/issues/7047
PR-URL: https://github.com/nodejs/node/pull/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>
v7.x
Anna Henningsen 9 years ago
parent
commit
ef9a8fa35b
No known key found for this signature in database GPG Key ID: D8B9F5AEAE84E4CF
  1. 4
      lib/buffer.js
  2. 11
      test/parallel/test-buffer.js

4
lib/buffer.js

@ -199,8 +199,8 @@ Object.setPrototypeOf(SlowBuffer, Uint8Array);
function allocate(size) { function allocate(size) {
if (size === 0) { if (size <= 0) {
return createBuffer(size); return createBuffer(0);
} }
if (size < (Buffer.poolSize >>> 1)) { if (size < (Buffer.poolSize >>> 1)) {
if (size > (poolSize - poolOffset)) if (size > (poolSize - poolOffset))

11
test/parallel/test-buffer.js

@ -1465,3 +1465,14 @@ assert.equal(Buffer.prototype.parent, undefined);
assert.equal(Buffer.prototype.offset, undefined); assert.equal(Buffer.prototype.offset, undefined);
assert.equal(SlowBuffer.prototype.parent, undefined); assert.equal(SlowBuffer.prototype.parent, undefined);
assert.equal(SlowBuffer.prototype.offset, 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'));
}

Loading…
Cancel
Save