From 1c67899ffb32871461c7ff2d82597d8f9c5cd6af Mon Sep 17 00:00:00 2001 From: Jason Zhang Date: Sat, 7 Sep 2024 03:09:24 +0930 Subject: [PATCH] buffer: fix out of range for toString MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michaƫl Zasso PR-URL: https://github.com/nodejs/node/pull/54553 Fixes: https://github.com/nodejs/node/issues/52298 Reviewed-By: James M Snell Reviewed-By: Jake Yuesong Li --- lib/buffer.js | 4 ++-- test/parallel/test-buffer-tostring-range.js | 10 +++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 4467a555c71..6294eae2fb5 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -843,12 +843,12 @@ Buffer.prototype.toString = function toString(encoding, start, end) { else if (start >= len) return ''; else - start |= 0; + start = MathTrunc(start) || 0; if (end === undefined || end > len) end = len; else - end |= 0; + end = MathTrunc(end) || 0; if (end <= start) return ''; diff --git a/test/parallel/test-buffer-tostring-range.js b/test/parallel/test-buffer-tostring-range.js index f4adf64c8d9..d033cd204b3 100644 --- a/test/parallel/test-buffer-tostring-range.js +++ b/test/parallel/test-buffer-tostring-range.js @@ -1,6 +1,6 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const rangeBuffer = Buffer.from('abc'); @@ -98,3 +98,11 @@ assert.throws(() => { name: 'TypeError', message: 'Unknown encoding: null' }); + +// Must not throw when start and end are within kMaxLength +// Cannot test on 32bit machine as we are testing the case +// when start and end are above the threshold +common.skipIf32Bits(); +const threshold = 0xFFFFFFFF; +const largeBuffer = Buffer.alloc(threshold + 20); +largeBuffer.toString('utf8', threshold, threshold + 20);