From 27785aeb3797a132023b644254c24bb8e18e9897 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sun, 29 May 2016 20:03:32 +0200 Subject: [PATCH] buffer: ignore negative allocation lengths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Refs: https://github.com/nodejs/node/pull/7051 PR-URL: https://github.com/nodejs/node/pull/7221 Reviewed-By: Trevor Norris Reviewed-By: James M Snell --- lib/buffer.js | 4 ++-- test/parallel/test-buffer.js | 11 +++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index fc1d1a74458650..6dbb46a4d99ce3 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -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)) diff --git a/test/parallel/test-buffer.js b/test/parallel/test-buffer.js index ba58ffcdf21922..93aef824188e3e 100644 --- a/test/parallel/test-buffer.js +++ b/test/parallel/test-buffer.js @@ -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')); +}