diff options
author | Sakthipriyan Vairamani (thefourtheye) <thechargingvolcano@gmail.com> | 2016-11-06 19:01:19 +0530 |
---|---|---|
committer | Sakthipriyan Vairamani (thefourtheye) <thechargingvolcano@gmail.com> | 2016-11-26 11:15:34 +0530 |
commit | ca37fa527f174b547893817fe8c67a3befa02317 (patch) | |
tree | 97d7f74cb902b7c0074acdb8baa794d697b8c671 /lib | |
parent | 561eade31726348ddc377f69fdadc5d1ce7db687 (diff) | |
download | node-new-ca37fa527f174b547893817fe8c67a3befa02317.tar.gz |
buffer: convert offset & length to int properly
As per ecma-262 2015's #sec-%typedarray%-buffer-byteoffset-length,
`offset` would be an integer, not a 32 bit unsigned integer. Also,
`length` would be an integer with the maximum value of 2^53 - 1, not a
32 bit unsigned integer.
This would be a problem because, if we create a buffer from an
arraybuffer, from an offset which is greater than 2^32, it would be
actually pointing to a different location in arraybuffer. For example,
if we use 2^40 as offset, then the actual value used will be 0,
because `byteOffset >>>= 0` will convert `byteOffset` to a 32 bit
unsigned int, which is based on 2^32 modulo.
PR-URL: https://github.com/nodejs/node/pull/9492
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/buffer.js | 4 | ||||
-rw-r--r-- | lib/internal/util.js | 18 |
2 files changed, 20 insertions, 2 deletions
diff --git a/lib/buffer.js b/lib/buffer.js index b2325098bc..94bf9cdca3 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -238,7 +238,7 @@ function fromArrayLike(obj) { } function fromArrayBuffer(obj, byteOffset, length) { - byteOffset >>>= 0; + byteOffset = internalUtil.toInteger(byteOffset); const maxLength = obj.byteLength - byteOffset; @@ -248,7 +248,7 @@ function fromArrayBuffer(obj, byteOffset, length) { if (length === undefined) { length = maxLength; } else { - length >>>= 0; + length = internalUtil.toLength(length); if (length > maxLength) throw new RangeError("'length' is out of bounds"); } diff --git a/lib/internal/util.js b/lib/internal/util.js index 4ada8dd0cc..ae8b1e0b64 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -161,3 +161,21 @@ exports.cachedResult = function cachedResult(fn) { return result; }; }; + +/* + * Implementation of ToInteger as per ECMAScript Specification + * Refer: http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger + */ +const toInteger = exports.toInteger = function toInteger(argument) { + const number = +argument; + return Number.isNaN(number) ? 0 : Math.trunc(number); +}; + +/* + * Implementation of ToLength as per ECMAScript Specification + * Refer: http://www.ecma-international.org/ecma-262/6.0/#sec-tolength + */ +exports.toLength = function toLength(argument) { + const len = toInteger(argument); + return len <= 0 ? 0 : Math.min(len, Number.MAX_SAFE_INTEGER); +}; |