← All reports

[JSC] Cached `String#replace` width-confusion fix

String#replace checked every replacement was 8-bit, then called your function again.

Component: JSC | 61b3aec

Source/JavaScriptCore/runtime/StringPrototypeInlines.h

auto replacement = asString(slot)->value(globalObject);
- StringView { replacement }.getCharacters8(buffer.subspan(bufferPos));
+ StringView { replacement }.getCharacters(buffer.subspan(bufferPos));
bufferPos += replacement->length();

JSTests/stress/string-replace-cached-replacement-changes-width.js

+ let result = flat8Bit("x" + filler + "x" + filler + "x").replace(regExp, function () {
+ if (++count === 1)
+ return replacement;
+ table[replacement] = 2;
+ return count;
+ });

replaceAllWithCacheUsingRegExpSearchThreeArguments is JSC's fast path for str.replace(globalRegExp, fn): it calls the replacer per match, keeps results as JSString* in a vector, tracks whether every replacement is 8-bit, then allocates one output buffer sized for the all-8-bit or 16-bit case and copies the pieces in. A JSString wraps a StringImpl, and using it as a property key atomizes it — swapping its StringImpl for the existing canonical atom, which can hold equal content at a different width. The copy loop read each stored replacement with StringView::getCharacters8(); it now uses getCharacters(), which handles both widths. The stress test covers /x/g and /(x)/g with width changes in both directions.

  call #1: replacer returns R (8-bit)   ─► "all 8-bit" recorded
  call #2: table[R] = 2                 ─► R atomized: StringImpl swapped
                                           for existing 16-bit atom
  copy loop (8-bit buffer):
    Before: getCharacters8(buf)   16-bit data copied as Latin-1
    After:  getCharacters(buf)    width-aware copy

A replacer callback could change an already-collected replacement's width after the 8-bit check, so the copy loop treated 16-bit character data as Latin-1. That's width confusion in the JSC runtime, reachable from plain JS and timed by attacker-controlled callbacks.

This is the classic check-then-use bug across a user callback. Narrow: confirm that buffer allocation and copy still agree on width after the fix, and whether narrowing in getCharacters() is safe given that atomization preserves content. Wider: the sibling paths are the better targets — other replace/replaceAll/split/join fast paths that cache JSString* across callbacks, remaining getCharacters8() / span<Latin1Character> uses after user-code calls, and the two-argument and non-RegExp cached variants. Widest within JSC: other ways to swap a StringImpl under a live JSString (property-key atomization, rope resolution, string-to-identifier conversion) and any precomputed length or width they can make stale. Tell: a width or length flag computed in a loop that calls into JS, consumed after the loop without re-reading the string.