From 38d7258d89ca9bb91caaa09e61e69f61422c6a65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=BA=D0=BE=D0=B2=D0=BE=D1=80=D0=BE=D0=B4=D0=B0=20?= =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=B8=D1=82=D0=B0=20=D0=90=D0=BD=D0=B4=D1=80?= =?UTF-8?q?=D0=B5=D0=B5=D0=B2=D0=B8=D1=87?= Date: Fri, 16 Sep 2016 08:07:23 +0300 Subject: [PATCH] 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: https://github.com/nodejs/node-private/pull/66 Reviewed-By: Rod Vagg Reviewed-By: Anna Henningsen --- lib/buffer.js | 8 ++++++++ test/simple/test-buffer-concat.js | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/lib/buffer.js b/lib/buffer.js index 1a9f7caeb5aba9..09db899d19d76f 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -216,6 +216,14 @@ Buffer.concat = function(list, length) { 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; }; diff --git a/test/simple/test-buffer-concat.js b/test/simple/test-buffer-concat.js index 858d6924f95fac..ea237cd6d6089c 100644 --- a/test/simple/test-buffer-concat.js +++ b/test/simple/test-buffer-concat.js @@ -38,4 +38,22 @@ 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).fill('1'); +var empty = new Buffer(0); + +assert.equal(Buffer.concat([], 100).toString(), ''); +assert.equal(Buffer.concat([ones], 0).toString(), ones.toString()); // 0.12.x +assert.equal(Buffer.concat([ones], 10).toString(), ones.toString()); +assert.equal(Buffer.concat([ones, ones], 10).toString(), ones.toString()); +assert.equal(Buffer.concat([empty, ones]).toString(), ones.toString()); +assert.equal(Buffer.concat([ones, empty, empty]).toString(), ones.toString()); + +// The tail should be zero-filled +assert.equal( + Buffer.concat([empty, empty], 100).toString(), + new Buffer(100).fill(0).toString()); +assert.equal( + Buffer.concat([empty, ones], 40).toString(), + Buffer.concat([ones, new Buffer(30).fill(0)]).toString()); + console.log("ok");