Skip to content

Commit

Permalink
buffer: zero-fill uninitialized bytes in .concat()
Browse files Browse the repository at this point in the history
This makes sure that no uninitialized bytes are leaked when the specified
`totalLength` input value is greater than the actual total length of the
specified buffers array, e.g. in Buffer.concat([Buffer.alloc(0)], 100).

PR-URL: nodejs-private/node-private#67
Reviewed-By: Anna Henningsen <[email protected]>
Reviewed-By: Rod Vagg <[email protected]>
  • Loading branch information
ChALkeR authored and rvagg committed Sep 27, 2016
1 parent 88dcc7f commit fc259c7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,15 @@ Buffer.concat = function(list, length) {
buf.copy(buffer, pos);
pos += buf.length;
}

// Note: `length` is always equal to `buffer.length` at this point
if (pos < length) {
// Zero-fill the remaining bytes if the specified `length` was more than
// the actual total length, i.e. if we have some remaining allocated bytes
// there were not initialized.
buffer.fill(0, pos, length);
}

return buffer;
};

Expand Down
26 changes: 26 additions & 0 deletions test/simple/test-buffer-concat.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,30 @@ assert(flatOne === one[0]);
assert(flatLong.toString() === (new Array(10+1).join('asdf')));
assert(flatLongLen.toString() === (new Array(10+1).join('asdf')));

var ones = new Buffer(10);
ones.fill('1');
var empty = new Buffer(0);

var short = ones.slice(5); // needed for 0.10.x, can't start past the length

assert.equal(Buffer.concat([], 100).toString(), '');
assert.equal(Buffer.concat([ones], 0).toString(), ones.toString()); // 0.10.x
assert.equal(Buffer.concat([ones], 10).toString(), ones.toString());
assert.equal(Buffer.concat([short, ones], 10).toString(), ones.toString());
assert.equal(Buffer.concat([empty, ones]).toString(), ones.toString());
assert.equal(Buffer.concat([ones, empty, empty]).toString(), ones.toString());

var zeros100 = new Buffer(100);
zeros100.fill(0);
var zeros30 = new Buffer(30);
zeros30.fill(0);

// The tail should be zero-filled
assert.equal(
Buffer.concat([empty, empty], 100).toString(),
zeros100.toString());
assert.equal(
Buffer.concat([empty, ones], 40).toString(),
Buffer.concat([ones, zeros30]).toString());

console.log("ok");

0 comments on commit fc259c7

Please sign in to comment.