Closed Bug 2022627 Opened 8 months ago Closed 8 months ago

Type confusion between `JitScript*` and `ICScript*` in `BaselineInterpreterCodeGen::emitWarmUpCounterIncrement()`

Categories

(Core :: JavaScript Engine, defect)

defect

Tracking

()

RESOLVED DUPLICATE of bug 2022337
Tracking Status
firefox150 --- affected

People

(Reporter: jkratzer, Unassigned)

Details

(Keywords: ai-involved)

Attachments

(2 files)

Summary

Type confusion between JitScript* and ICScript* in BaselineInterpreterCodeGen::emitWarmUpCounterIncrement() at /firefox/js/src/jit/BaselineCodeGen.cpp:1808. The helper emitTrialInliningCheck() unconditionally reloads its register parameter as an ICScript* after a VM call (line 1618), but the Baseline Interpreter caller passes a register holding JitScript*. After the helper returns on the VM-call path, subsequent code at line 1870 writes the constant 0x3 (BaselineQueuedScriptPtr) through the type-confused pointer, corrupting the SingleLinkedList<BumpChunk> metadata inside ICScript::allocSitesSpace_ (a LifoAlloc). The corruption manifests as a crash dereferencing 0x3 during GC when LifoAlloc::transferFrom() walks the corrupted list.

Affected Code

File: /firefox/js/src/jit/BaselineCodeGen.cpp

The helper (lines 1593–1623) — reloads as ICScript*:

template <typename Handler>
bool BaselineCodeGen<Handler>::emitTrialInliningCheck(Register count,
                                                      Register icScript,
                                                      Register scratch) {
  ...
  masm.branch32(Assembler::NotEqual, count,
                Imm32(JitOptions.trialInliningWarmUpThreshold),
                &noTrialInlining);
  prepareVMCall();
  masm.PushBaselineFramePtr(FramePointer, scratch);
  using Fn = bool (*)(JSContext*, BaselineFrame*);
  if (!callVMNonOp<Fn, DoTrialInlining>()) {
    return false;
  }
  // Reload registers potentially clobbered by the call.
  Address warmUpCounterAddr(icScript, ICScript::offsetOfWarmUpCount());
  masm.loadPtr(frame.addressOfICScript(), icScript);   // line 1618: reloads as ICScript*
  masm.load32(warmUpCounterAddr, count);
  masm.bind(&noTrialInlining);
  return true;
}

The interpreter caller (lines 1795–1870) — passes JitScript*:

  Register scriptReg = R2.scratchReg();
  Register countReg = R0.scratchReg();

  // Load the JitScript* in scriptReg.
  loadScript(scriptReg);
  masm.loadJitScript(scriptReg, scriptReg);            // line 1800: scriptReg = JitScript*

  // Bump warm-up counter.
  Address warmUpCounterAddr(scriptReg, JitScript::offsetOfWarmUpCount());
  masm.load32(warmUpCounterAddr, countReg);
  masm.add32(Imm32(1), countReg);
  masm.store32(countReg, warmUpCounterAddr);

  if (!emitTrialInliningCheck(countReg, scriptReg, R1.scratchReg())) {  // line 1808: BUG — passes JitScript*, gets ICScript* back on VM-call path
    return false;
  }

  if (JitOptions.baselineBatching) {
    Register scratch = R1.scratchReg();
    Label done, compileBatch;
    Address baselineScriptAddr(scriptReg, JitScript::offsetOfBaselineScript());  // line 1815: type-confused Address
    ...
    masm.bind(&notCompiled);
    // First, mark the jitscript as queued.
    masm.storePtr(ImmPtr(BaselineQueuedScriptPtr), baselineScriptAddr);  // line 1870: CORRUPTING WRITE — 0x3 into ICScript's LifoAlloc

Why it's vulnerable: The helper's parameter is named icScript and its reload semantics assume the caller also uses ICScript*. The Baseline Compiler caller at line 1661 satisfies this (loads ICScript* at line 1653). The Baseline Interpreter caller at line 1808 does NOT — it loads JitScript* at line 1800. On the slow path where count == trialInliningWarmUpThreshold, the VM call clobbers registers and line 1618 reloads scriptReg with a different-typed pointer. Control returns to the caller with scriptReg silently retyped, and all subsequent Address(scriptReg, JitScript::offsetOf...) computations index the wrong struct.

Introduced by: Bug 1943901 "Do trial inlining from the baseline interpreter" (rev 41e146f0f8d0, Iain Ireland). The patch extracted the trial-inlining check into a helper from the Compiler path and added a call from the Interpreter path without accounting for the different register type.

Offset arithmetic (x86-64):

  • offsetof(JitScript, baselineScript_) ≈ 40 (after LinkedListElement {mNext 8, mPrev 8, mIsSentinel 1 → padded to 24} + profileString_ 8 + owningScript_ 8)
  • ICScript + 40 lands inside allocSitesSpace_ (starts at offset 16), at oversize_.last_ (chunks_ = 16 bytes, oversize_.head_ = 8 bytes → oversize_.last_ at offset 40)
  • The crash at LifoAlloc.cpp:391 (oversize_.prependAll(std::move(other->oversize_))) confirms oversize_ is the corrupted list

The non-batching path at lines 1919–1921 also performs a type-confused READ (branchTestPtr on [scriptReg + JitScript::offsetOfBaselineScript()]) but is incidentally benign — both branch outcomes lead to safe behavior (either skip compilation or call a VM function that ignores scriptReg).

Exploit Chain

  1. Attacker runs JavaScript in the Baseline Interpreter with a function whose loop drives the warmup counter upward.
  2. baselineBatching is enabled. The script gets queued for compilation at baselineJitWarmUpThreshold (e.g. 10 with --fast-warmup) but remains in the interpreter until the batch fires.
  3. On the iteration where warmup count equals trialInliningWarmUpThreshold exactly (14 with --fast-warmup), the branch at line 1606 falls through.
  4. DoTrialInlining VM call clobbers scriptReg. Line 1618 reloads it from frame.addressOfICScript() — now scriptReg holds ICScript*.
  5. Control returns to line 1812. countReg (14) > baselineJitWarmUpThreshold (10), so execution enters the batching block.
  6. Line 1823 reads [ICScript* + 40] = oversize_.last_ = nullptr (common case — no oversized alloc-site chunks). Low bit clear → notSpecial. Value ≤ 5 → notCompiled.
  7. Line 1870 writes 0x3 to [ICScript* + 40], overwriting allocSitesSpace_.oversize_.last_ in the live ICScript. SingleLinkedList invariant bool(head_) == bool(last_) is now violated (head_ = null, last_ = 0x3).
  8. Script continues executing. The corruption persists.
  9. GC fires (gc() or natural GC). JitScript::Destroy → JitScript::prepareForDestruction → ICScript::prepareForDestruction → queueAllLifoBlocksForFreeAfterMinorGC(&allocSitesSpace_) → LifoAlloc::transferFrom.
  10. At LifoAlloc.cpp:391: oversize_.prependAll(std::move(other->oversize_)) where other->oversize_.last_ = 0x3. prependAll calls appendAll on the corrupted list. empty() returns !last_ = !0x3 = false, so the list appears non-empty. Line 364 executes last_->next_ = std::move(list.head_) — dereferences (BumpChunk*)0x3 to write its next_ member. SEGV.

Security Impact

Severity: Moderate currently; High if baselineBatching ships enabled.

Attacker capability: JIT-emitted code performs an unchecked heap write of a fixed constant (0x3) to a fixed offset within a live ICScript heap allocation, corrupting LifoAlloc linked-list metadata. The corrupted object remains live between the write and GC, during which other code paths may interact with the corrupted LifoAlloc (e.g., getOrCreateAllocSite allocating into it). The written value 0x3 lands in the guard page in this build, but struct layout changes (different compiler, build flags, or #ifdef DEBUG variations) shift offsetof(JitScript, baselineScript_) and would corrupt a different ICScript field.

This is fundamentally distinct from a null-pointer-dereference DoS: the crash at 0x3 is the downstream effect of prior heap-write corruption, not the root cause. The root cause is JIT code writing a constant through a type-confused pointer into valid heap memory.

Preconditions:

  • JitOptions.baselineBatching = true — default false, settable only via JS shell --baseline-batching=on or env var JIT_OPTION_baselineBatching=true. No about:config pref exists. Not currently reachable from web content.
  • Script must reach trialInliningWarmUpThreshold while still executing in the Baseline Interpreter. With --fast-warmup (baseline=10, trial=14, eager-batch=20), this happens naturally. With defaults (baseline=100, trial=500, eager-batch=200), scripts normally exit the interpreter before warmup 500, though batch-compilation failures could theoretically widen the window.
  • JitOptions.disableInlining = false (default).

The feature is clearly under active development for eventual default enablement. Any future patch that flips baselineBatching on by default would promote this to a web-reachable heap-write primitive.

ASAN Report

rax = 0x3 is the corrupted last_ field loaded for the last_->next_ dereference at LifoAlloc.h:364. This is exactly BaselineQueuedScriptPtr = reinterpret_cast<BaselineScript*>(QueuedScript) where QueuedScript = 0x3 (/firefox/js/src/jit/JitScript.h:61,71).

Also reproduces with: /firefox/obj-x86_64-pc-linux-gnu/dist/bin/js --fuzzing-safe --fast-warmup --baseline-batching=on --no-ion poc.js

Suggested Fix

Reload scriptReg as JitScript* immediately after emitTrialInliningCheck in the interpreter specialization. This is two extra loads on a slow path already dominated by a VM call:

--- a/js/src/jit/BaselineCodeGen.cpp
+++ b/js/src/jit/BaselineCodeGen.cpp
@@ -1805,10 +1805,16 @@ bool BaselineInterpreterCodeGen::emitWarmUpCounterIncrement() {
   masm.add32(Imm32(1), countReg);
   masm.store32(countReg, warmUpCounterAddr);

   if (!emitTrialInliningCheck(countReg, scriptReg, R1.scratchReg())) {
     return false;
   }

+  // |emitTrialInliningCheck| reloads |scriptReg| as ICScript* on the slow
+  // path after the DoTrialInlining VM call. The code below addresses fields
+  // via JitScript offsets, so restore |scriptReg| to a JitScript* here.
+  loadScript(scriptReg);
+  masm.loadJitScript(scriptReg, scriptReg);
+
   if (JitOptions.baselineBatching) {
     Register scratch = R1.scratchReg();
     Label done, compileBatch;
     Address baselineScriptAddr(scriptReg, JitScript::offsetOfBaselineScript());

A defense-in-depth improvement: rename the helper parameter from icScript to something type-neutral, or add a static_assert + comment documenting that callers must NOT assume the register retains its input value or type.

Attached file poc.js —
Attached file crash_stack.txt —

This is a duplicate of bug 2022337, which Markus coincidentally opened yesterday. It is unreachable in the browser, because the baselineBatching jit option is not exposed. When baseline batching is enabled, this will deterministically overwrite a specific offset inside the ICScript with the value 3. Contrary to the analysis above, JitScript::offsetOfBaselineScript is 6 words in all builds (see the searchfox field layout here, which will always end up clobbering the same field in the LifoAlloc in ICScript. Because that field (oversize_.last_) is a pointer, writing the value 3 will always result in a near-null value that will crash safely when dereferenced, so this would not be exploitable even if it were reachable in the browser.

Group: javascript-core-security
Status: NEW → RESOLVED
Closed: 8 months ago
Duplicate of bug: 2022337
Resolution: --- → DUPLICATE
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Created:
Updated:
Size: