Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

buffer: add type check in bidirectionalIndexOf #32770

Closed
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -899,6 +899,10 @@ 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) {
if (!isArrayBufferView(buffer)) {
throw new ERR_INVALID_ARG_TYPE('buffer', 'Buffer', buffer);
}
Flarna marked this conversation as resolved.
Show resolved Hide resolved

if (typeof byteOffset === 'string') {
encoding = byteOffset;
byteOffset = undefined;
Expand All @@ -911,7 +915,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);
ZYSzys marked this conversation as resolved.
Show resolved Hide resolved
}
dir = !!dir; // Cast to bool.

Expand Down
14 changes: 14 additions & 0 deletions test/parallel/test-buffer-indexof.js
Original file line number Diff line number Diff line change
Expand Up @@ -606,3 +606,17 @@ 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. ' +
'Received an instance of lastIndexOf'
});
}