From 1d0f2cbf87cf14a332642d06ac1733ba2a7982a9 Mon Sep 17 00:00:00 2001 From: Trevor Norris Date: Fri, 23 Oct 2015 12:34:11 -0600 Subject: [PATCH] buffer: fix value check for writeUInt{B,L}E Fixes: https://github.com/nodejs/node/issues/3497 PR-URL: https://github.com/nodejs/node/pull/3500 Reviewed-By: Ben Noordhuis --- lib/buffer.js | 12 ++++++++---- test/parallel/test-writeuint.js | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 0fdfcecfdf9360..52b362f1a43c22 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -836,8 +836,10 @@ Buffer.prototype.writeUIntLE = function(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; byteLength = byteLength >>> 0; - if (!noAssert) - checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0); + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } var mul = 1; var i = 0; @@ -853,8 +855,10 @@ Buffer.prototype.writeUIntBE = function(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; byteLength = byteLength >>> 0; - if (!noAssert) - checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0); + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } var i = byteLength - 1; var mul = 1; diff --git a/test/parallel/test-writeuint.js b/test/parallel/test-writeuint.js index 22579ceecaef2d..baa12aa57666f3 100644 --- a/test/parallel/test-writeuint.js +++ b/test/parallel/test-writeuint.js @@ -122,6 +122,25 @@ function test32(clazz) { } +function testUint(clazz) { + const data = new clazz(8); + var val = 1; + + // Test 0 to 5 bytes. + for (var i = 0; i <= 5; i++) { + const errmsg = `byteLength: ${i}`; + ASSERT.throws(function() { + data.writeUIntBE(val, 0, i); + }, /value is out of bounds/, errmsg); + ASSERT.throws(function() { + data.writeUIntLE(val, 0, i); + }, /value is out of bounds/, errmsg); + val *= 0x100; + } +} + + test8(Buffer); test16(Buffer); test32(Buffer); +testUint(Buffer);