Skip to content

Commit 0a329d2

Browse files
committed
buffer: don't set zero fill for zero-length buffer
Instantiating a Buffer of length zero would set the kNoZeroFill flag to true but never actually call ArrayBuffer::Allocator(). Which means the flag was never set back to false. The result was that the next allocation would unconditionally not be zero filled. Add test to ensure Uint8Array's are zero-filled after creating a Buffer of length zero. This test may falsely succeed, but will not falsely fail. Fix: #2930 PR-URL: #2931 Reviewed-By: Rod Vagg <rod@vagg.org>
1 parent e0c3d2a commit 0a329d2

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

lib/buffer.js

+14-5
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ const kNoZeroFill = 0;
2222

2323
function createPool() {
2424
poolSize = Buffer.poolSize;
25-
flags[kNoZeroFill] = 1;
25+
if (poolSize > 0)
26+
flags[kNoZeroFill] = 1;
2627
allocPool = new Uint8Array(poolSize);
2728
Object.setPrototypeOf(allocPool, Buffer.prototype);
2829
poolOffset = 0;
@@ -64,7 +65,8 @@ Buffer.__proto__ = Uint8Array;
6465
function SlowBuffer(length) {
6566
if (+length != length)
6667
length = 0;
67-
flags[kNoZeroFill] = 1;
68+
if (length > 0)
69+
flags[kNoZeroFill] = 1;
6870
const ui8 = new Uint8Array(+length);
6971
Object.setPrototypeOf(ui8, Buffer.prototype);
7072
return ui8;
@@ -75,8 +77,11 @@ SlowBuffer.__proto__ = Buffer;
7577

7678

7779
function allocate(size) {
78-
if (size === 0)
79-
return SlowBuffer(0);
80+
if (size === 0) {
81+
const ui8 = new Uint8Array(size);
82+
Object.setPrototypeOf(ui8, Buffer.prototype);
83+
return ui8;
84+
}
8085
if (size < (Buffer.poolSize >>> 1)) {
8186
if (size > (poolSize - poolOffset))
8287
createPool();
@@ -85,7 +90,11 @@ function allocate(size) {
8590
alignPool();
8691
return b;
8792
} else {
88-
flags[kNoZeroFill] = 1;
93+
// Even though this is checked above, the conditional is a safety net and
94+
// sanity check to prevent any subsequent typed array allocation from not
95+
// being zero filled.
96+
if (size > 0)
97+
flags[kNoZeroFill] = 1;
8998
const ui8 = new Uint8Array(size);
9099
Object.setPrototypeOf(ui8, Buffer.prototype);
91100
return ui8;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
'use strict';
2+
3+
require('../common');
4+
const assert = require('assert');
5+
6+
7+
function testUint8Array(ui) {
8+
const length = ui.length;
9+
for (let i = 0; i < length; i++)
10+
if (ui[i] !== 0) return false;
11+
return true;
12+
}
13+
14+
15+
for (let i = 0; i < 100; i++) {
16+
new Buffer(0);
17+
let ui = new Uint8Array(65);
18+
assert.ok(testUint8Array(ui), 'Uint8Array is not zero-filled');
19+
}

0 commit comments

Comments
 (0)