Skip to content

Commit fc259c7

Browse files
ChALkeRrvagg
authored andcommitted
buffer: zero-fill uninitialized bytes in .concat()
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 <anna@addaleax.net> Reviewed-By: Rod Vagg <rod@vagg.org>
1 parent 88dcc7f commit fc259c7

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lib/buffer.js

+9
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,15 @@ Buffer.concat = function(list, length) {
499499
buf.copy(buffer, pos);
500500
pos += buf.length;
501501
}
502+
503+
// Note: `length` is always equal to `buffer.length` at this point
504+
if (pos < length) {
505+
// Zero-fill the remaining bytes if the specified `length` was more than
506+
// the actual total length, i.e. if we have some remaining allocated bytes
507+
// there were not initialized.
508+
buffer.fill(0, pos, length);
509+
}
510+
502511
return buffer;
503512
};
504513

test/simple/test-buffer-concat.js

+26
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,30 @@ assert(flatOne === one[0]);
3838
assert(flatLong.toString() === (new Array(10+1).join('asdf')));
3939
assert(flatLongLen.toString() === (new Array(10+1).join('asdf')));
4040

41+
var ones = new Buffer(10);
42+
ones.fill('1');
43+
var empty = new Buffer(0);
44+
45+
var short = ones.slice(5); // needed for 0.10.x, can't start past the length
46+
47+
assert.equal(Buffer.concat([], 100).toString(), '');
48+
assert.equal(Buffer.concat([ones], 0).toString(), ones.toString()); // 0.10.x
49+
assert.equal(Buffer.concat([ones], 10).toString(), ones.toString());
50+
assert.equal(Buffer.concat([short, ones], 10).toString(), ones.toString());
51+
assert.equal(Buffer.concat([empty, ones]).toString(), ones.toString());
52+
assert.equal(Buffer.concat([ones, empty, empty]).toString(), ones.toString());
53+
54+
var zeros100 = new Buffer(100);
55+
zeros100.fill(0);
56+
var zeros30 = new Buffer(30);
57+
zeros30.fill(0);
58+
59+
// The tail should be zero-filled
60+
assert.equal(
61+
Buffer.concat([empty, empty], 100).toString(),
62+
zeros100.toString());
63+
assert.equal(
64+
Buffer.concat([empty, ones], 40).toString(),
65+
Buffer.concat([ones, zeros30]).toString());
66+
4167
console.log("ok");

0 commit comments

Comments
 (0)