Skip to content

Commit 38d7258

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#66 Reviewed-By: Rod Vagg <[email protected]> Reviewed-By: Anna Henningsen <[email protected]>
1 parent 9dbde2f commit 38d7258

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

lib/buffer.js

+8
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,14 @@ Buffer.concat = function(list, length) {
216216
pos += buf.length;
217217
}
218218

219+
// Note: `length` is always equal to `buffer.length` at this point
220+
if (pos < length) {
221+
// Zero-fill the remaining bytes if the specified `length` was more than
222+
// the actual total length, i.e. if we have some remaining allocated bytes
223+
// there were not initialized.
224+
buffer.fill(0, pos, length);
225+
}
226+
219227
return buffer;
220228
};
221229

test/simple/test-buffer-concat.js

+18
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,22 @@ 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).fill('1');
42+
var empty = new Buffer(0);
43+
44+
assert.equal(Buffer.concat([], 100).toString(), '');
45+
assert.equal(Buffer.concat([ones], 0).toString(), ones.toString()); // 0.12.x
46+
assert.equal(Buffer.concat([ones], 10).toString(), ones.toString());
47+
assert.equal(Buffer.concat([ones, ones], 10).toString(), ones.toString());
48+
assert.equal(Buffer.concat([empty, ones]).toString(), ones.toString());
49+
assert.equal(Buffer.concat([ones, empty, empty]).toString(), ones.toString());
50+
51+
// The tail should be zero-filled
52+
assert.equal(
53+
Buffer.concat([empty, empty], 100).toString(),
54+
new Buffer(100).fill(0).toString());
55+
assert.equal(
56+
Buffer.concat([empty, ones], 40).toString(),
57+
Buffer.concat([ones, new Buffer(30).fill(0)]).toString());
58+
4159
console.log("ok");

0 commit comments

Comments
 (0)