From e53b79cdd0a30ae12022772f95100e115f6f71e3 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 9473e1a8b827f2..e78e2e3bb6053e 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -841,12 +841,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 f4adf64c8d9129..1167654dcf0773 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); +largeBuffer.toString('utf8', threshold + 0xF, threshold + 0xFF);