buffer: prevent abort on indexOf with lone surrogate needle

Signed-off-by: RafaelGSS <rafael.nunu@hotmail.com>
PR-URL: https://github.com/nodejs/node/pull/65430
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
Rafael Gonzaga authored and GitHub committed 2026-08-25 10:32:37 +00:00
1 parent f9f3fa96b2
commit 54b4e372f3
2 files changed
+30 -2

No files matched your search

+4 -2
View File
@@ -533,8 +533,10 @@ Maybe<size_t> StringBytes::Size(Isolate* isolate,
return Just<size_t>(simdutf::utf8_length_from_latin1(
reinterpret_cast<const char*>(view.data8()), view.length()));
}
return Just<size_t>(simdutf::utf8_length_from_utf16(
reinterpret_cast<const char16_t*>(view.data16()), view.length()));
return Just<size_t>(
simdutf::utf8_length_from_utf16_with_replacement(
reinterpret_cast<const char16_t*>(view.data16()), view.length())
.count);
case UCS2:
return Just(view.length() * sizeof(uint16_t));
+26
View File
@@ -619,6 +619,32 @@ assert.strictEqual(reallyLong.lastIndexOf(pattern), 0);
assert.strictEqual(haystack.lastIndexOf(needle), haystack.length - 3);
}
// UTF-8 string search should use the same replacement-character semantics
// as Buffer.from() for unpaired UTF-16 surrogates.
{
const prefix = 'a'.repeat(16);
const suffix = 'b'.repeat(16);
const needles = [
`${prefix}${String.fromCharCode(0xd800)}${suffix}`,
`${prefix}${String.fromCharCode(0xdc00)}${suffix}`,
JSON.parse(`{"needle":"${prefix}\\ud800${suffix}"}`).needle,
];
for (const needle of needles) {
const needleBuffer = Buffer.from(needle, 'utf8');
const haystack = Buffer.concat([
Buffer.from('xx'),
needleBuffer,
Buffer.from('yy'),
]);
assert.strictEqual(Buffer.byteLength(needle, 'utf8'), needleBuffer.length);
assert.strictEqual(haystack.indexOf(needle, 0, 'utf8'), 2);
assert.strictEqual(haystack.lastIndexOf(needle, haystack.length - 1, 'utf8'), 2);
assert.strictEqual(haystack.includes(needle, 0, 'utf8'), true);
}
}
// Avoid abort because of invalid usage
// see https://github.com/nodejs/node/issues/32753
{