diff --git a/lib/buffer.js b/lib/buffer.js index d83a5a30d9e1b8..52e499241ea58c 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -95,6 +95,7 @@ const { hideStackFrames } = require('internal/errors'); const { + validateBuffer, validateInt32, validateString } = require('internal/validators'); @@ -899,6 +900,8 @@ Buffer.prototype.compare = function compare(target, // - encoding - an optional encoding, relevant if val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + validateBuffer(buffer); + if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = undefined; @@ -911,7 +914,7 @@ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { byteOffset = +byteOffset; // If the offset is undefined, "foo", {}, coerces to NaN, search whole buffer. if (NumberIsNaN(byteOffset)) { - byteOffset = dir ? 0 : buffer.length; + byteOffset = dir ? 0 : (buffer.length || buffer.byteLength); } dir = !!dir; // Cast to bool. diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index d789c9b46cf868..b17520366e506a 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -606,3 +606,18 @@ assert.strictEqual(reallyLong.lastIndexOf(pattern), 0); assert.strictEqual(haystack.indexOf(needle), 2); assert.strictEqual(haystack.lastIndexOf(needle), haystack.length - 3); } + +// Avoid abort because of invalid usage +// see https://github.com/nodejs/node/issues/32753 +{ + assert.throws(() => { + const buffer = require('buffer'); + new buffer.Buffer.prototype.lastIndexOf(1, 'str'); + }, { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + message: 'The "buffer" argument must be an instance of Buffer, ' + + 'TypedArray, or DataView. ' + + 'Received an instance of lastIndexOf' + }); +}