Skip to content

Commit 27785ae

Browse files
addaleaxChALkeR
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 Refs: #7051 PR-URL: #7221 Reviewed-By: Trevor Norris <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 21552bd commit 27785ae

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
@@ -163,8 +163,8 @@ Object.setPrototypeOf(SlowBuffer, Uint8Array);
163163

164164

165165
function allocate(size) {
166-
if (size === 0) {
167-
return createBuffer(size);
166+
if (size <= 0) {
167+
return createBuffer(0);
168168
}
169169
if (size < (Buffer.poolSize >>> 1)) {
170170
if (size > (poolSize - poolOffset))

test/parallel/test-buffer.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1438,3 +1438,14 @@ assert.equal(Buffer.prototype.parent, undefined);
14381438
assert.equal(Buffer.prototype.offset, undefined);
14391439
assert.equal(SlowBuffer.prototype.parent, undefined);
14401440
assert.equal(SlowBuffer.prototype.offset, undefined);
1441+
1442+
{
1443+
// Test that large negative Buffer length inputs don't affect the pool offset.
1444+
assert.deepStrictEqual(Buffer(-Buffer.poolSize), Buffer.from(''));
1445+
assert.deepStrictEqual(Buffer(-100), Buffer.from(''));
1446+
assert.deepStrictEqual(Buffer.allocUnsafe(-Buffer.poolSize), Buffer.from(''));
1447+
assert.deepStrictEqual(Buffer.allocUnsafe(-100), Buffer.from(''));
1448+
1449+
// Check pool offset after that by trying to write string into the pool.
1450+
assert.doesNotThrow(() => Buffer.from('abc'));
1451+
}

0 commit comments

Comments
 (0)