Skip to content

Commit 609fc1c

Browse files
committed
[JSC] JSON.parse should match more repeated string values against the source text
https://bugs.webkit.org/show_bug.cgi?id=329490 rdar://191351073 Reviewed by Keith Miller. JSONCache matched a repeated string value against the source text only when its quoted text fit in the short value table's 32 characters. A longer value was scanned for its closing quote before m_longJSStrings was consulted, so every repeat still paid for the scan. This patch replaces existing m_longJSStrings with a 4-way table of 256 entries that is looked up both before a property value is lexed and after. 1. findLongString searches at most 64 characters for the closing quote and indexes the value by its length and its first and last 8 characters, or by its first 8 and characters 56 to 63 when it is 64 characters or longer. A hit skips lexing the value, and so does a miss on a value without escapes, which addLongString records right away. 2. makeLongJSString looks up and records every value of 17 to 256 characters after it is lexed. A value that needs escapes is recorded with a key bit cleared, so that only this lookup finds it. 3. Values of 64 characters or more are also kept in a direct-mapped table indexed by the whole value, so that values sharing their first 64 characters are still shared when more of them repeat than a set holds. 4. An entry packs its JSString with its text length and 10 hash bits into 8 bytes, using the low bits of the aligned pointer, so a probe reads the JSString only when the key matches. The short value table moves to the same entries, grows from 64 to 128 values, and compares both ways of a set against a single load of the source. Test: JSTests/stress/json-parse-repeated-long-string-values.js * JSTests/stress/json-parse-repeated-long-string-values.js: Added. (shouldBe): (try.catch): (try.a.nb.catch): (try.shouldBe): (try.gc): (try.string_appeared_here.catch): * Source/JavaScriptCore/runtime/JSONCache.cpp: (JSC::JSONCache::recordableName): (JSC::JSONCache::addLongString): * Source/JavaScriptCore/runtime/JSONCache.h: (JSC::JSONCache::StringEntry::makeKey): (JSC::JSONCache::StringEntry::StringEntry): (JSC::JSONCache::StringEntry::string const): (JSC::JSONCache::StringEntry::key const): (JSC::JSONCache::StringEntry::textLength const): (JSC::JSONCache::clearJSStrings): (JSC::JSONCache::textMatches): * Source/JavaScriptCore/runtime/JSONCacheInlines.h: (JSC::JSONCache::makeJSString): (JSC::JSONCache::hasUnsafeStringCharacter): (JSC::JSONCache::longStringMatches): (JSC::JSONCache::insertLongString): (JSC::JSONCache::makeLongJSString): (JSC::JSONCache::loadTextWindow): (JSC::JSONCache::textMatches): (JSC::JSONCache::stringPrefix): (JSC::JSONCache::stringIndex): (JSC::JSONCache::StringTable::match const): (JSC::JSONCache::StringTable::insert): (JSC::JSONCache::findShortString): (JSC::JSONCache::longStringHash): (JSC::JSONCache::longStringHashBits): (JSC::JSONCache::longStringIndex): (JSC::JSONCache::secondaryLongStringIndex): (JSC::JSONCache::boundedValueLength): (JSC::JSONCache::longTextMatches): (JSC::JSONCache::findLongString): (JSC::JSONCache::findOrCreateString): (JSC::JSONCache::findString const): Deleted. * Source/JavaScriptCore/runtime/LiteralParser.cpp: (JSC::reviverMode>::makeJSString): (JSC::reviverMode>::Lexer::currentStringIsSourceText const): (JSC::reviverMode>::Lexer::cacheString): (JSC::reviverMode>::Lexer::lexString): (JSC::reviverMode>::parsePrimitiveValue): (JSC::requires): * Source/JavaScriptCore/runtime/LiteralParser.h: (JSC::LiteralParser::Lexer::currentStringSource const): Canonical link: https://commits.webkit.org/325346@main
1 parent eaa7e09 commit 609fc1c

6 files changed

Lines changed: 624 additions & 110 deletions

File tree

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
function shouldBe(actual, expected) {
2+
if (actual !== expected)
3+
throw new Error(`bad value: ${JSON.stringify(actual)}, expected: ${JSON.stringify(expected)}`);
4+
}
5+
6+
const prefix = "https://example.com/a/very/long/common/prefix/shared/by/all/";
7+
const values = [
8+
prefix + "one.js",
9+
prefix + "two.js",
10+
prefix + "one.jsx",
11+
prefix + "one.j",
12+
prefix + "onf.js",
13+
prefix + "one.js" + "x".repeat(150),
14+
"x".repeat(31),
15+
"y".repeat(256),
16+
"z".repeat(257),
17+
prefix + "\u00e9t\u00e9.js",
18+
prefix + "escaped\\\"quote.js",
19+
prefix + "tab\there.js",
20+
];
21+
22+
for (let iteration = 0; iteration < 20; ++iteration) {
23+
const objects = [];
24+
for (let i = 0; i < 200; ++i)
25+
objects.push({ url: values[(i * 7 + iteration) % values.length], line: i });
26+
const text = JSON.stringify(objects);
27+
const parsed = JSON.parse(text);
28+
shouldBe(parsed.length, objects.length);
29+
for (let i = 0; i < objects.length; ++i) {
30+
shouldBe(parsed[i].url, objects[i].url);
31+
shouldBe(parsed[i].line, i);
32+
}
33+
shouldBe(JSON.stringify(parsed), text);
34+
if (iteration % 5 === 4)
35+
gc();
36+
}
37+
38+
// A cached value followed by something other than its closing quote must not match.
39+
for (let i = 0; i < 10; ++i)
40+
JSON.parse(`{"url":"${values[0]}","x":1}`);
41+
shouldBe(JSON.parse(`{"url":"${values[0]}x","x":1}`).url, values[0] + "x");
42+
shouldBe(JSON.parse(`{"url":"${values[0]}\\n","x":1}`).url, values[0] + "\n");
43+
shouldBe(JSON.parse(`{"url":"${values[0]}"}`).url, values[0]);
44+
45+
let threw = false;
46+
try {
47+
JSON.parse(`{"url":"${values[0]}`);
48+
} catch (e) {
49+
threw = e instanceof SyntaxError;
50+
}
51+
shouldBe(threw, true);
52+
53+
// Values that differ only in their last character, around the lengths where the comparison changes strides.
54+
for (const length of [31, 32, 33, 47, 48, 49, 63, 64, 65, 95, 96, 97, 255, 256]) {
55+
const base = prefix.repeat(5).slice(0, length - 1);
56+
const a = base + "a";
57+
const b = base + "b";
58+
for (let i = 0; i < 20; ++i) {
59+
const value = i % 3 ? a : b;
60+
shouldBe(JSON.parse(`{"url":"${value}","x":${i}}`).url, value);
61+
}
62+
shouldBe(JSON.parse(`{"url":"${base}c","x":1}`).url, base + "c");
63+
shouldBe(JSON.parse(`{"url":"${base}","x":1}`).url, base);
64+
}
65+
66+
// Shorter long values are compared as two overlapping halves.
67+
for (const length of [17, 18, 24, 30]) {
68+
const base = prefix.slice(0, length - 1);
69+
for (let i = 0; i < 20; ++i) {
70+
const value = base + (i % 3 ? "a" : "b");
71+
shouldBe(JSON.parse(`{"url":"${value}","x":${i}}`).url, value);
72+
shouldBe(JSON.parse(`["${value}",${i}]`)[0], value);
73+
}
74+
}
75+
76+
// A value that needs escapes must not match source text that holds its characters as is.
77+
for (const [escaped, unescaped] of [[`${prefix}a\\"b`, `${prefix}a"b`], [`${prefix}a\\\\x`, `${prefix}a\\x`], [`${prefix}a\\nb`, `${prefix}a\nb`]]) {
78+
for (let i = 0; i < 10; ++i)
79+
shouldBe(JSON.parse(`{"url":"${escaped}","x":${i}}`).url, unescaped);
80+
let threw = false;
81+
try {
82+
JSON.parse(`{"url":"${unescaped}","x":1}`);
83+
} catch (e) {
84+
threw = e instanceof SyntaxError;
85+
}
86+
shouldBe(threw, true);
87+
}
88+
89+
// A value that was escaped only where JSON allows it is the same value as its unescaped text.
90+
{
91+
const escaped = prefix.replaceAll("/", "\\/") + "slashes.js";
92+
const unescaped = prefix + "slashes.js";
93+
for (let i = 0; i < 10; ++i) {
94+
shouldBe(JSON.parse(`{"url":"${escaped}","x":${i}}`).url, unescaped);
95+
shouldBe(JSON.parse(`["${escaped}",${i}]`)[0], unescaped);
96+
shouldBe(JSON.parse(`{"url":"${unescaped}","x":${i}}`).url, unescaped);
97+
}
98+
}
99+
100+
// Atomizing a parsed value, here by using it as a property key, can replace its characters.
101+
{
102+
const atomized = prefix + "atomized.js";
103+
const holder = { [atomized]: 1 };
104+
for (let i = 0; i < 20; ++i) {
105+
const parsed = JSON.parse(`{"url":"${atomized}","x":${i}}`).url;
106+
shouldBe(parsed, atomized);
107+
shouldBe(holder[parsed], 1);
108+
shouldBe(JSON.parse(`{"url":"${atomized}","x":${i}}`).url, atomized);
109+
shouldBe(JSON.parse(`{"url":"${atomized}","\u3042":${i}}`).url, atomized);
110+
if (i % 5 === 4)
111+
gc();
112+
}
113+
}
114+
115+
// More values sharing their first 64 characters than a set holds, of different lengths and suffixes, in turn.
116+
{
117+
const shared = prefix.repeat(2).slice(0, 64);
118+
const values = [];
119+
for (let i = 0; i < 9; ++i)
120+
values.push(shared + "x".repeat(i % 3) + "/" + i);
121+
for (let round = 0; round < 6; ++round) {
122+
const objects = values.map((url, i) => ({ url, i }));
123+
const parsed = JSON.parse(JSON.stringify(objects));
124+
for (let i = 0; i < values.length; ++i)
125+
shouldBe(parsed[i].url, values[i]);
126+
shouldBe(JSON.parse(`["${values[round]}","${values[8 - round]}"]`)[1], values[8 - round]);
127+
}
128+
}
129+
130+
// Shorter values that need escapes must not match source text that holds their characters as is.
131+
for (const [escaped, unescaped] of [["abcdefghijklmno\\\"pq", "abcdefghijklmno\"pq"], ["abcdefghijklmno\\\\pq", "abcdefghijklmno\\pq"], ["abcdefghijklmno\\npq", "abcdefghijklmno\npq"]]) {
132+
for (let i = 0; i < 10; ++i)
133+
shouldBe(JSON.parse(`{"url":"${escaped}","x":${i}}`).url, unescaped);
134+
let threw = false;
135+
try {
136+
JSON.parse(`{"url":"${unescaped}","x":1}`);
137+
} catch (e) {
138+
threw = e instanceof SyntaxError;
139+
}
140+
shouldBe(threw, true);
141+
}
142+
143+
// Values of 64 and 65 characters after a cached value with the same first 64, and 64 characters at the end of the input.
144+
{
145+
const base = prefix.repeat(2);
146+
const cached = base.slice(0, 70);
147+
for (let i = 0; i < 10; ++i)
148+
shouldBe(JSON.parse(`{"url":"${cached}","x":${i}}`).url, cached);
149+
shouldBe(JSON.parse(`{"url":"${base.slice(0, 64)}","x":1}`).url, base.slice(0, 64));
150+
shouldBe(JSON.parse(`{"url":"${base.slice(0, 65)}","x":1}`).url, base.slice(0, 65));
151+
let threw = false;
152+
try {
153+
JSON.parse(`{"url":"${base.slice(0, 64)}`);
154+
} catch (e) {
155+
threw = e instanceof SyntaxError;
156+
}
157+
shouldBe(threw, true);
158+
}
159+
160+
// Values of 64 characters or more that need escapes after their first 64, or that are too long to share.
161+
{
162+
const base = prefix.repeat(5);
163+
for (const value of [base.slice(0, 70) + "\"" + base.slice(0, 10), base.slice(0, 70) + "\\" + base.slice(0, 10), base.slice(0, 70) + "\t", base.slice(0, 256), base.slice(0, 257), base.slice(0, 300)]) {
164+
const text = JSON.stringify({ url: value, x: 1 });
165+
for (let i = 0; i < 5; ++i)
166+
shouldBe(JSON.parse(text).url, value);
167+
shouldBe(JSON.parse(`[${JSON.stringify(value)}]`)[0], value);
168+
}
169+
}
170+
171+
// A long value cached from 16-bit source is found in a later parse of 8-bit source.
172+
{
173+
const value = prefix + "from-16-bit-source.js";
174+
for (let i = 0; i < 5; ++i)
175+
shouldBe(JSON.parse(`{"\u3042":1,"url":"${value}"}`).url, value);
176+
for (let i = 0; i < 5; ++i)
177+
shouldBe(JSON.parse(`{"url":"${value}","x":${i}}`).url, value);
178+
}
179+
180+
// Sloppy JSON, which eval parses, can hold characters as is that strict JSON must escape.
181+
{
182+
const base = prefix.repeat(2).slice(0, 70);
183+
for (const [literal, value] of [[`'${base}"sloppy'`, `${base}"sloppy`], [`"${base}\tsloppy"`, `${base}\tsloppy`]]) {
184+
for (let i = 0; i < 5; ++i)
185+
shouldBe(eval(`({"url":${literal},"x":${i}})`).url, value);
186+
let threw = false;
187+
try {
188+
JSON.parse(`{"url":"${value}","x":1}`);
189+
} catch (e) {
190+
threw = e instanceof SyntaxError;
191+
}
192+
shouldBe(threw, true);
193+
}
194+
}

‎Source/JavaScriptCore/runtime/JSONCache.cpp‎

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,53 @@ std::span<const Latin1Character> JSONCache::recordableName(Structure* from, Stru
4343
return { };
4444
// Matching the raw source text is only equivalent to lexing the key when the key needs no escaping.
4545
auto characters = name->span8();
46-
for (auto character : characters) {
47-
if (character < ' ' || character == '"' || character == '\\')
48-
return { };
49-
}
46+
if (hasUnsafeStringCharacter(characters))
47+
return { };
5048
return characters;
5149
}
5250

51+
const JSONCache::StringEntry* JSONCache::addLongString(VM& vm, std::span<const Latin1Character> source, size_t searchedLength, LongStringIndex index, StructureID keepAlive)
52+
{
53+
ASSERT(maxAtomizeStringLength < searchedLength && searchedLength <= longStringSearchLength);
54+
EnsureStillAliveScope keepAliveScope(keepAlive ? keepAlive.decode() : nullptr);
55+
size_t length = searchedLength;
56+
if (length == longStringSearchLength) {
57+
auto characters = source.subspan(1, std::min<size_t>(source.size() - 1, maxLongStringLength + 1));
58+
auto vectorMatch = [](simde_uint8x16_t input) ALWAYS_INLINE_LAMBDA {
59+
return SIMD::findFirstNonZeroIndex(SIMD::equal(input, SIMD::splat<uint8_t>('"')));
60+
};
61+
auto scalarMatch = [](Latin1Character character) ALWAYS_INLINE_LAMBDA {
62+
return character == '"';
63+
};
64+
auto rest = characters.subspan(longStringSearchLength);
65+
length = longStringSearchLength + (SIMD::find(rest, vectorMatch, scalarMatch) - rest.data());
66+
if (length == characters.size())
67+
return nullptr;
68+
}
69+
auto characters = source.subspan(1, length);
70+
if (hasUnsafeStringCharacter(characters))
71+
return nullptr;
72+
73+
uint64_t key = StringEntry::makeKey(length + 2, index.hashBits);
74+
std::span<StringEntry, longStringWays> entries { std::span { m_longStrings }.subspan(index.set, longStringWays) };
75+
JSString* string = nullptr;
76+
if (length >= longStringSearchLength) {
77+
auto secondaryIndex = secondaryLongStringIndex(characters.data(), length);
78+
auto& secondary = m_secondaryLongStrings[secondaryIndex.set];
79+
uint64_t secondaryKey = StringEntry::makeKey(length + 2, secondaryIndex.hashBits);
80+
if (secondary.key() == secondaryKey && longStringMatches(secondary.string(), characters))
81+
string = secondary.string();
82+
else {
83+
string = jsNontrivialString(vm, String(characters));
84+
m_secondaryLongStrings[secondaryIndex.set] = { string, secondaryKey };
85+
}
86+
} else
87+
string = jsNontrivialString(vm, String(characters));
88+
insertLongString(entries, string, key);
89+
addString(source, length + 2, string);
90+
return &entries[0];
91+
}
92+
5393
template<unsigned size>
5494
template<unsigned ways>
5595
void JSONCache::NameTable<size>::insert(unsigned set, Structure* from, Structure* to, PropertyOffset offset, const NameText& text, unsigned textLength)

0 commit comments

Comments
 (0)