Inappropriate implementation in V8 (CVE-2024-7972)
Turbofan incorrectly optimises 64-bit BigInt shifts, producing a constant 0 instead of the correct -1 for a right shift of -1n by a large BigInt. An attacker could cause a mismatch between the interpreter and optimised code, but the report states exploitability is unclear.
Originally disclosed on Chrome VRP
- Fix shipped in 3 months
VULNERABILITY DETAILS
Turbofan incorrectly optimizes 64 bit bigint shifts.
In src/compiler/simplified-lowering.cc "VisitNode(Node* node, Truncation truncation, SimplifiedLowering* lowering)" we try to optimize bigint (left and right) shifts:
case IrOpcode::kSpeculativeBigIntShiftLeft:
case IrOpcode::kSpeculativeBigIntShiftRight: {
if (truncation.IsUnused() && BothInputsAre(node, Type::BigInt())) {
VisitUnused<T>(node);
return;
}
if (truncation.IsUsedAsWord64()) { // #1
Type input_type = GetUpperBound(node->InputAt(0));
Type shift_amount_type = GetUpperBound(node->InputAt(1));
if (shift_amount_type.IsHeapConstant()) { // #2
HeapObjectRef ref = shift_amount_type.AsHeapConstant()->Ref();
if (ref.IsBigInt()) { // #3
We first check if the result is truncated to a word64 (#1), the shift amount is a heap constant (#2) and if it is a BigInt (#3). If all of these conditions are met, we continue with the optimization:
BigIntRef bigint = ref.AsBigInt();
bool lossless = false;
int64_t shift_amount = bigint.AsInt64(&lossless); // #4
// Canonicalize {shift_amount}.
bool is_shift_left =
node->opcode() == IrOpcode::kSpeculativeBigIntShiftLeft;
if (shift_amount < 0) { // #5
is_shift_left = !is_shift_left;
shift_amount = -shift_amount;
}
DCHECK_GE(shift_amount, 0);
We convert the BigInt to an int64_t (#4) and check if the shift amount is negative. If it is, we negate it and invert the shift op (#5). When converting the BigInt to an int64_t, we can lose information. lossless is true if the value represented by the bigint fits into an int64_t, i.e., is not too big and the sign of the bigint and the int64_t are the same.
A bigint is basically a number of digits that are stored effectively as one's complement with the sign stored separately. When negating a bigint, we can therefore just negate the sign and leave the digits as they are. However, the spec [0] also says this:
For binary operations, BigInts act as two's complement binary strings, with negative numbers treated as having bits set infinitely to the left.
With this out of the way, let's explain where the issue is. For this we have this poc:
y = BigInt("0xffffffffffffffff") // #6
function b() {
let x = BigInt.asIntN(64, -1n);
console.log("x: ", x);
console.log("y: ", y);
let lol = x >> (y);
return BigInt.asIntN(64, lol); // #7
}
console.log("lol: ", b());
console.log("lol: ", b());
% OptimizeFunctionOnNextCall(b)
console.log("lol: ", b());
We create a bigint y (#6) and a function b that shifts -1n right by y. We then call b three times. The first two calls print lol: -1, but the third call prints lol: 0.
We pass (#1), because (#7) truncated the result to a word64. We pass (#2) because y is a heap constant. We pass (#3) because y is a BigInt. We then convert y to an int64_t (#4). The value of shift_amount is -1. We therefore negate it and change the opcode to a left shift. lossless is false, because y is signed and 0xffffffffffffffff does not fit into an int64_t without changing the sign.
// If the operation is a *real* left shift, propagate truncation.
// If it is a *real* right shift, the output representation is
// word64 only if we know the input type is BigInt64.
// Otherwise, fall through to using BigIntOperationHint.
if (is_shift_left) {
VisitBinop<T>(
node,
UseInfo::CheckedBigIntTruncatingWord64(FeedbackSource{}),
UseInfo::Any(), MachineRepresentation::kWord64);
if (lower<T>()) {
if (!lossless || shift_amount > 63) {
DeferReplacement(node, jsgraph_->Int64Constant(0)); // #8
} else if (shift_amount == 0) {
DeferReplacement(node, node->InputAt(0));
} else {
DCHECK_GE(shift_amount, 1);
DCHECK_LE(shift_amount, 63);
ReplaceWithPureNode(
node,
graph()->NewNode(
lowering->machine()->Word64Shl(), node->InputAt(0),
jsgraph_->Int64Constant(shift_amount)));
}
}
return;
After some iterations of the fix-point iteration, we reach (#8), because lossless is false and shift_amount is 1. We replace the node with a constant 0.
This is wrong.
Why is this wrong?
Our code is:
-1n >> 0xffffffffffffffffn
and the result should be -1n [1].
But V8 treats it as if -1n was not a negative number where bits are treated as being set infinitely to the left.
I.e. V8 treats -1n as a 64-bit number, where this optimization would be correct.
I believe, the optimization at hand is only correct for positive numbers.
I guess that the thinking is that we can convert all right shift operations to left shift operations, if the right shift amount is negative. The developers probably correctly realized, that the shift amount can appear to be negative if the value is too big to fit into an int64_t. In this case, they concluded that all such spurious left shifts are actually right shifts where the shift amount is actually a very, very big number. For 0n >> very_big_number the result is 0, but not for -1n >> very_big_number.
IMPACT
Mismatch between interpreter and turbofan.
Interpreter (-1. Can be converted to very big value, by using BigInt.asUintN()) is correct, turbofan (0) is wrong.
EXPLOITABILITY It's unclear whether this is exploitable to me. Always getting a constant 0 appears to not be very helpful. There have been similiar issues in SimplifiedLowering in the past [2], [3], but again it's probably not exploitable as is and would require another bug.
REFERENCES [0] https://tc39.es/ecma262/multipage/ecmascript-data-types-and-values.html#sec-ecmascript-language-types-bigint-type [1] https://tc39.es/ecma262/multipage/ecmascript-data-types-and-values.html#sec-numeric-types-bigint-signedRightShift [2] https://faraz.faith/2021-01-07-cve-2020-16040-analysis/ [3] https://www.thezdi.com/blog/2021/12/8/understanding-the-root-cause-of-cve-2021-21220-a-chrome-bug-from-pwn2own-2021
VERSION
V8 Version: 258701f221f3966f70abb74ddc88925b9772cc62
Operating System: Linux debian 6.1.0-21-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.90-1 (2024-05-03) x86_64 GNU/Linux
REPRODUCTION CASE
- run poc.js with
d8 --jit-fuzzing --allow-natives-syntax poc.js
CREDIT INFORMATION The writeup has been written by Simon Gerst (intrigus-lgtm) based on a testcase originally found by Liam Wachter & Julian Gremminger.
Context
V8 is Chrome's JavaScript engine, and Turbofan is its optimising compiler. Turbofan builds a graph of nodes and lowers them through several phases; SimplifiedLowering is the phase that decides machine representations and replaces nodes with cheaper equivalents when it can prove the replacement is safe. This report is about a wrong replacement in that phase, specifically for 64-bit BigInt shift operations.
The bug was reported through the Chrome VRP by Simon Gerst (intrigus-lgtm), based on a testcase originally found by Liam Wachter and Julian Gremminger. It was rated medium severity, tracked as CVE-2024-7972, and disclosed on 9 September 2024 with a bounty of 11,000 USD.
Setup
The researcher worked against V8 at commit [redacted], on Linux (Debian, kernel 6.1.0-21-amd64, x86_64). The reproduction uses the d8 shell with two flags: --jit-fuzzing and --allow-natives-syntax. The latter is needed for the %OptimizeFunctionOnNextCall intrinsic used in the proof of concept.
Finding it
The starting point is the code in src/compiler/simplified-lowering.cc, in VisitNode(Node* node, Truncation truncation, SimplifiedLowering* lowering), which tries to optimise BigInt left and right shifts:
case IrOpcode::kSpeculativeBigIntShiftLeft:
case IrOpcode::kSpeculativeBigIntShiftRight: {
if (truncation.IsUnused() && BothInputsAre(node, Type::BigInt())) {
VisitUnused<T>(node);
return;
}
if (truncation.IsUsedAsWord64()) { // #1
Type input_type = GetUpperBound(node->InputAt(0));
Type shift_amount_type = GetUpperBound(node->InputAt(1));
if (shift_amount_type.IsHeapConstant()) { // #2
HeapObjectRef ref = shift_amount_type.AsHeapConstant()->Ref();
if (ref.IsBigInt()) { // #3
The optimisation only applies when three conditions hold: the result is truncated to a word64 (#1), the shift amount is a heap constant (#2), and that constant is a BigInt (#3). When all three hold, the code continues:
BigIntRef bigint = ref.AsBigInt();
bool lossless = false;
int64_t shift_amount = bigint.AsInt64(&lossless); // #4
// Canonicalize {shift_amount}.
bool is_shift_left =
node->opcode() == IrOpcode::kSpeculativeBigIntShiftLeft;
if (shift_amount < 0) { // #5
is_shift_left = !is_shift_left;
shift_amount = -shift_amount;
}
DCHECK_GE(shift_amount, 0);
The BigInt shift amount is converted to an int64_t (#4), and if it comes out negative the code negates it and flips the direction of the shift (#5). The lossless flag is set to true only when the value represented by the BigInt fits into an int64_t, that is, it is not too big and the sign of the BigInt matches the sign of the int64_t.
The researcher's explanation of why this is unsound rests on how BigInts are represented and specified. A BigInt is stored as a number of digits, effectively in one's complement with the sign kept separately, so negating a BigInt can be done by negating the sign and leaving the digits alone. But the specification also says:
For binary operations, BigInts act as two's complement binary strings, with negative numbers treated as having bits set infinitely to the left.
That difference between the storage model and the specified semantics is what the optimisation ignores.
Exploitation
Step 1: the proof of concept
The researcher's PoC is:
y = BigInt("0xffffffffffffffff") // #6
function b() {
let x = BigInt.asIntN(64, -1n);
console.log("x: ", x);
console.log("y: ", y);
let lol = x >> (y);
return BigInt.asIntN(64, lol); // #7
}
console.log("lol: ", b());
console.log("lol: ", b());
% OptimizeFunctionOnNextCall(b)
console.log("lol: ", b());
A BigInt y is created from 0xffffffffffffffff (#6). The function b shifts -1n right by y and truncates the result to a word64 with BigInt.asIntN(64, ...) (#7). The function is called three times, with the third call forced to run optimised code via %OptimizeFunctionOnNextCall(b).
The first two calls print lol: -1, but the third call prints lol: 0. The interpreter and Turbofan disagree.
Step 2: how the PoC satisfies the guards
The PoC passes (#1) because (#7) truncates the result to a word64. It passes (#2) because y is a heap constant. It passes (#3) because y is a BigInt. The conversion at (#4) then produces shift_amount equal to -1. The code negates it and changes the opcode to a left shift. lossless is false, because y is signed and 0xffffffffffffffff does not fit into an int64_t without changing the sign.
Step 3: the replacement
After some iterations of the fix-point iteration, the lowering reaches this code:
// If the operation is a *real* left shift, propagate truncation.
// If it is a *real* right shift, the output representation is
// word64 only if we know the input type is BigInt64.
// Otherwise, fall through to using BigIntOperationHint.
if (is_shift_left) {
VisitBinop<T>(
node,
UseInfo::CheckedBigIntTruncatingWord64(FeedbackSource{}),
UseInfo::Any(), MachineRepresentation::kWord64);
if (lower<T>()) {
if (!lossless || shift_amount > 63) {
DeferReplacement(node, jsgraph_->Int64Constant(0)); // #8
} else if (shift_amount == 0) {
DeferReplacement(node, node->InputAt(0));
} else {
DCHECK_GE(shift_amount, 1);
DCHECK_LE(shift_amount, 63);
ReplaceWithPureNode(
node,
graph()->NewNode(
lowering->machine()->Word64Shl(), node->InputAt(0),
jsgraph_->Int64Constant(shift_amount)));
}
}
return;
Because lossless is false and shift_amount is 1, the node is replaced with the constant 0 at (#8).
Step 4: why the result is wrong
The original expression is:
-1n >> 0xffffffffffffffffn
and the result should be -1n. V8 instead treats -1n as if it were not a negative number whose bits are set infinitely to the left, that is, as if it were a 64-bit number, for which the optimisation would be correct. The researcher's conclusion is that the optimisation is only correct for positive numbers.
The reasoning behind the flawed code, as the researcher reconstructs it, is that all right shifts with a negative amount can be turned into left shifts. The developers likely realised that the shift amount can appear to be negative when the value is too big to fit into an int64_t, and concluded that such spurious left shifts are really right shifts by a very, very large amount. For 0n >> very_big_number the result is indeed 0, but not for -1n >> very_big_number.
Root cause
The conversion of the BigInt shift amount to int64_t at (#4) can lose information, and the code records that in lossless. The canonicalisation at (#5) then flips a right shift into a left shift based on the truncated value. When the shift is treated as a left shift and lossless is false, the lowering replaces the whole operation with the constant 0 at (#8). That replacement is valid for a non-negative input, where shifting by a very large amount yields 0, but not for a negative input, whose bits are set infinitely to the left under the BigInt specification. The lossless flag is false here, and the code then replaces the node with the constant 0 at (#8).
Impact
The report describes the impact as a mismatch between the interpreter and Turbofan. The interpreter returns -1, which can be converted to a very big value using BigInt.asUintN(), and is correct; Turbofan returns 0, which is wrong. On exploitability the researcher is explicit that it is unclear whether the bug is exploitable: always getting a constant 0 does not appear to be very helpful. Similar issues in SimplifiedLowering have occurred in the past, but this one is probably not exploitable as is and would likely require another bug.
Fix
The report does not describe the fix that was applied.
- Other negative BigInt inputs with a shift amount that does not fit losslessly into an
int64_t, for example values built withBigInt.asIntNaround-1n. A positive result is an optimised call returning a different value from the interpreter. - Shift amounts whose sign differs from the truncated
int64_t, so thatlosslessis false and the direction is flipped. A positive result is the same interpreter/Turbofan mismatch after%OptimizeFunctionOnNextCall. - The same pattern with
BigInt.asUintNon the result, to see whether the wrong constant can be turned into a large value. A positive result is a value that differs between interpreted and optimised execution. - Other
SimplifiedLoweringpaths that uselosslessfromBigIntRef::AsInt64, checking whether any of them also treat a lossy conversion as a licence to fold. A positive result is a fold that is correct for non-negative inputs but wrong for negative ones.
What happened, in plain words
Chrome runs JavaScript using a program inside it called V8. V8 has two ways of running your code: a slow, careful mode that follows the rules exactly (the interpreter), and a fast mode that rewrites your code to run quicker (the optimising compiler, called Turbofan). The fast mode is only allowed to do this if the rewritten code gives exactly the same answers as the careful mode. If it does not, that is a bug.
This report is about one such bug. When a JavaScript program shifts a particular kind of number called a BigInt, Turbofan sometimes decides the answer is always zero and hard-codes that zero into the program. For negative numbers that is wrong: the correct answer is not zero. The person who found it showed a tiny program where the first two runs print -1 and the third run, after the fast compiler kicks in, prints 0.
The bug was reported through the Chrome VRP (Chrome's Vulnerability Reward Program, which pays people for finding security bugs in Chrome) by Simon Gerst (intrigus-lgtm), based on a testcase originally found by Liam Wachter and Julian Gremminger. It was rated medium severity, tracked as CVE-2024-7972 (the public ID number given to a known security flaw), and disclosed on 9 September 2024 with a bounty of 11,000 USD.
Background: the pieces involved
Before the details make sense, here are the pieces, explained from scratch.
JavaScript engine. A browser cannot run JavaScript directly; it needs a program that reads the JavaScript and executes it. That program is the engine. V8 is Chrome's engine.
Interpreter and optimising compiler. Running JavaScript by reading it line by line is simple but slow. So engines watch which functions run often, and once a function is used enough, a compiler translates it into much faster machine code. The interpreter is the careful, always-correct path. The compiler (Turbofan in V8) is the fast path. The fast path must produce the same results as the slow path, always. When they disagree, you have a correctness bug.
BigInt. Ordinary JavaScript numbers cannot hold arbitrarily large whole numbers exactly. BigInt is a separate type for whole numbers of any size, written with an n at the end, like -1n or 0xffffffffffffffffn. BigInts can be positive or negative and can be enormous.
Bit shift. A shift moves the binary digits (bits) of a number left or right. x >> y shifts x right by y places; x << y shifts it left. Shifting right by a large amount makes a positive number become zero, because all its 1 bits fall off the end.
Two's complement. Computers store negative numbers in a scheme called two's complement. The JavaScript specification says that for binary operations, BigInts behave as if negative numbers have 1 bits stretching infinitely to the left. So -1n is not just a 64-bit pattern of ones; conceptually it has infinitely many 1 bits. Shifting it right any number of places still leaves 1 bits, so the answer stays -1n.
Heap constant. When the compiler looks at your code, a value that never changes, like a number stored in a variable that is set once, can be treated as a fixed constant known at compile time. The compiler calls this a heap constant.
Truncation. Cutting a number down to a fixed width, for example keeping only the low 64 bits, is called truncation. BigInt.asIntN(64, x) does exactly this: it takes a BigInt and returns the value that fits in 64 bits, interpreted as a signed number.
Word64 and int64_t. A word64 is a 64-bit chunk of memory. int64_t is the C++ name for a signed 64-bit integer. A signed 64-bit integer can hold values from about minus nine quintillion to plus nine quintillion; anything outside that range does not fit.
Lossless conversion. Converting a BigInt to an int64_t can lose information if the BigInt is too big, or if its sign does not match. The code tracks this with a flag called lossless, which is true only when nothing was lost.
SimplifiedLowering. This is a phase inside Turbofan. The compiler first builds a graph of nodes (each node is an operation, like a shift), then SimplifiedLowering decides how each node should be represented in machine terms and replaces nodes with cheaper equivalents when it can prove the replacement is safe. This report is about one replacement that was not safe.
Setup
The researcher worked against V8 at commit [redacted], on Linux (Debian, kernel 6.1.0-21-amd64, x86_64). A commit is a specific saved version of the source code, identified by a long hash, so anyone can check out exactly the same code.
The reproduction uses the d8 shell. d8 is a small command-line program that runs JavaScript using V8 without a browser around it, which makes testing engine behaviour much easier. Two flags are passed:
--jit-fuzzingturns on settings useful for testing the just-in-time compiler (the part that compiles code while it runs).--allow-natives-syntaxallows special internal commands in the JavaScript, which is needed for the%OptimizeFunctionOnNextCallintrinsic used in the proof of concept. An intrinsic here is a built-in command that reaches into the engine; it is not normal JavaScript and only works with this flag.
Finding it
The starting point is code in src/compiler/simplified-lowering.cc, inside a function called VisitNode(Node* node, Truncation truncation, SimplifiedLowering* lowering). That function tries to optimise BigInt left and right shifts. Here is the first part:
case IrOpcode::kSpeculativeBigIntShiftLeft:
case IrOpcode::kSpeculativeBigIntShiftRight: {
if (truncation.IsUnused() && BothInputsAre(node, Type::BigInt())) {
VisitUnused<T>(node);
return;
}
if (truncation.IsUsedAsWord64()) { // #1
Type input_type = GetUpperBound(node->InputAt(0));
Type shift_amount_type = GetUpperBound(node->InputAt(1));
if (shift_amount_type.IsHeapConstant()) { // #2
HeapObjectRef ref = shift_amount_type.AsHeapConstant()->Ref();
if (ref.IsBigInt()) { // #3
Line by line:
case IrOpcode::kSpeculativeBigIntShiftLeft:andcase IrOpcode::kSpeculativeBigIntShiftRight:select the two kinds of node this code handles: a BigInt shift left and a BigInt shift right. The word speculative means the compiler is guessing about the types and will check them at runtime.if (truncation.IsUnused() && BothInputsAre(node, Type::BigInt()))handles the easy case: if the result is never used and both inputs are BigInts, the node is simply marked unused and the function returns. Nothing to optimise.if (truncation.IsUsedAsWord64()) { // #1is the first condition for the optimisation: the result is being cut down to a 64-bit word. The comment#1is a label the researcher uses later to refer back to this check.Type input_type = GetUpperBound(node->InputAt(0));andType shift_amount_type = GetUpperBound(node->InputAt(1));ask the compiler what it knows about the two inputs: the value being shifted and the amount to shift by.if (shift_amount_type.IsHeapConstant()) { // #2is the second condition: the shift amount must be a fixed constant known at compile time.HeapObjectRef ref = shift_amount_type.AsHeapConstant()->Ref();fetches that constant.if (ref.IsBigInt()) { // #3is the third condition: the constant must be a BigInt.
So the optimisation only applies when three conditions hold: the result is truncated to a word64 (#1), the shift amount is a heap constant (#2), and that constant is a BigInt (#3). When all three hold, the code continues:
BigIntRef bigint = ref.AsBigInt();
bool lossless = false;
int64_t shift_amount = bigint.AsInt64(&lossless); // #4
// Canonicalize {shift_amount}.
bool is_shift_left =
node->opcode() == IrOpcode::kSpeculativeBigIntShiftLeft;
if (shift_amount < 0) { // #5
is_shift_left = !is_shift_left;
shift_amount = -shift_amount;
}
DCHECK_GE(shift_amount, 0);
Line by line:
BigIntRef bigint = ref.AsBigInt();gets the BigInt value out of the constant.bool lossless = false;prepares a flag that will say whether the conversion lost information.int64_t shift_amount = bigint.AsInt64(&lossless); // #4converts the BigInt shift amount into a signed 64-bit integer, and stores inlosslesswhether that conversion was exact.bool is_shift_left = node->opcode() == IrOpcode::kSpeculativeBigIntShiftLeft;records whether the original operation was a left shift.if (shift_amount < 0) { // #5checks whether the converted shift amount came out negative.is_shift_left = !is_shift_left;andshift_amount = -shift_amount;flip the direction of the shift and make the amount positive. The idea is that shifting right by a negative amount is the same as shifting left by the positive amount, and vice versa.DCHECK_GE(shift_amount, 0);is a debug-only assertion that the amount is now non-negative.
The lossless flag is set to true only when the value represented by the BigInt fits into an int64_t, that is, it is not too big and the sign of the BigInt matches the sign of the int64_t.
The researcher's explanation of why this is unsound rests on how BigInts are represented and specified. A BigInt is stored as a number of digits, effectively in one's complement with the sign kept separately, so negating a BigInt can be done by negating the sign and leaving the digits alone. But the specification also says:
For binary operations, BigInts act as two's complement binary strings, with negative numbers treated as having bits set infinitely to the left.
That difference between the storage model and the specified semantics is what the optimisation ignores. In storage, flipping the sign is cheap and the digits stay put. In the specified behaviour, a negative number is an infinite string of 1 bits, so shifting it right never runs out of 1 bits and never becomes zero.
Exploitation
Step 1: the proof of concept
The researcher's PoC (proof of concept, a small program that demonstrates the bug) is:
y = BigInt("0xffffffffffffffff") // #6
function b() {
let x = BigInt.asIntN(64, -1n);
console.log("x: ", x);
console.log("y: ", y);
let lol = x >> (y);
return BigInt.asIntN(64, lol); // #7
}
console.log("lol: ", b());
console.log("lol: ", b());
% OptimizeFunctionOnNextCall(b)
console.log("lol: ", b());
Line by line:
y = BigInt("0xffffffffffffffff") // #6creates a BigInt from the hexadecimal string0xffffffffffffffff, which is sixteen f digits, that is, 64 bits all set to 1. This is the shift amount.function b() {starts a function that will be called several times.let x = BigInt.asIntN(64, -1n);setsxto-1ncut down to 64 bits as a signed number, which is still-1n.console.log("x: ", x);andconsole.log("y: ", y);print the two values so you can see them.let lol = x >> (y);shiftsxright byy. This is the operation under test.return BigInt.asIntN(64, lol); // #7cuts the result down to 64 bits and returns it. This is what satisfies condition #1: the result is truncated to a word64.console.log("lol: ", b());callsband prints the result. This happens twice.% OptimizeFunctionOnNextCall(b)is an internal command that tells V8: the next timebis called, use the optimised compiled version. This is why the--allow-natives-syntaxflag is needed.console.log("lol: ", b());callsba third time, now running the optimised code.
The first two calls print lol: -1, but the third call prints lol: 0. The interpreter and Turbofan disagree. The first two calls are the careful path; the third is the fast path, and the fast path is wrong.
Step 2: how the PoC satisfies the guards
The PoC passes (#1) because (#7) truncates the result to a word64. It passes (#2) because y is a heap constant: it is set once and never changed, so the compiler can treat it as a fixed value. It passes (#3) because y is a BigInt. The conversion at (#4) then produces shift_amount equal to -1. The code negates it and changes the opcode to a left shift. lossless is false, because y is signed and 0xffffffffffffffff does not fit into an int64_t without changing the sign. In other words, the conversion at (#4) produced -1 and set lossless to false, because y is signed and does not fit into an int64_t without changing the sign.
Step 3: the replacement
After some iterations of the fix-point iteration (a process where the compiler repeatedly revisits nodes until nothing more changes), the lowering reaches this code:
// If the operation is a *real* left shift, propagate truncation.
// If it is a *real* right shift, the output representation is
// word64 only if we know the input type is BigInt64.
// Otherwise, fall through to using BigIntOperationHint.
if (is_shift_left) {
VisitBinop<T>(
node,
UseInfo::CheckedBigIntTruncatingWord64(FeedbackSource{}),
UseInfo::Any(), MachineRepresentation::kWord64);
if (lower<T>()) {
if (!lossless || shift_amount > 63) {
DeferReplacement(node, jsgraph_->Int64Constant(0)); // #8
} else if (shift_amount == 0) {
DeferReplacement(node, node->InputAt(0));
} else {
DCHECK_GE(shift_amount, 1);
DCHECK_LE(shift_amount, 63);
ReplaceWithPureNode(
node,
graph()->NewNode(
lowering->machine()->Word64Shl(), node->InputAt(0),
jsgraph_->Int64Constant(shift_amount)));
}
}
return;
Line by line:
- The comment explains the intent: if the operation is a real left shift, the truncation can be passed through; if it is a real right shift, the result can only be treated as a word64 when the input is known to be a BigInt64; otherwise the code falls back to a general BigInt operation.
if (is_shift_left) {enters this branch when the operation has been turned into a left shift (which is what happened to our right shift, because the shift amount was negative).VisitBinop<T>(...)visits the two inputs with the given use information, telling the compiler how the inputs will be used.if (lower<T>()) {runs the actual replacement only during the lowering pass.if (!lossless || shift_amount > 63) {is the key check: if the conversion was not lossless, or the shift amount is larger than 63, then...DeferReplacement(node, jsgraph_->Int64Constant(0)); // #8...replace the whole node with the constant 0.} else if (shift_amount == 0) {otherwise, if the shift amount is zero, the result is just the input unchanged, soDeferReplacement(node, node->InputAt(0));replaces the node with its first input.} else {in all remaining cases the shift amount is between 1 and 63, checked by the twoDCHECKlines, and the node is replaced with a real 64-bit left shift by that amount, built withWord64Shl.return;ends the handling of this node.
Because lossless is false and shift_amount is 1, the node is replaced with the constant 0 at (#8). The compiler has decided, permanently, that this shift always produces zero.
Step 4: why the result is wrong
The original expression is:
-1n >> 0xffffffffffffffffn
and the result should be -1n. Under the BigInt rules, -1n has infinitely many 1 bits to the left, so shifting it right by any amount still leaves 1 bits and the answer stays -1n. V8 instead treats -1n as if it were not a negative number whose bits are set infinitely to the left, that is, as if it were a 64-bit number, for which the optimisation would be correct. For a 64-bit number made of all 1 bits, shifting right by a huge amount would indeed give zero. The researcher's conclusion is that the optimisation is only correct for positive numbers.
The reasoning behind the flawed code, as the researcher reconstructs it, is that all right shifts with a negative amount can be turned into left shifts. The developers likely realised that the shift amount can appear to be negative when the value is too big to fit into an int64_t, and concluded that such spurious left shifts are really right shifts by a very, very large amount. For 0n >> very_big_number the result is indeed 0, but not for -1n >> very_big_number.
Root cause
The conversion of the BigInt shift amount to int64_t at (#4) can lose information, and the code records that in lossless. The canonicalisation at (#5) then flips a right shift into a left shift based on the truncated value. When the shift is treated as a left shift and lossless is false, the lowering replaces the whole operation with the constant 0 at (#8). That replacement is valid for a non-negative input, where shifting by a very large amount yields 0, but not for a negative input, whose bits are set infinitely to the left under the BigInt specification. The lossless flag is false here, and the code then replaces the node with the constant 0 at (#8).
Impact
The report describes the impact as a mismatch between the interpreter and Turbofan. The interpreter returns -1, which can be converted to a very big value using BigInt.asUintN(), and is correct; Turbofan returns 0, which is wrong. BigInt.asUintN() is the unsigned counterpart of BigInt.asIntN(): it cuts a BigInt down to a fixed width but interprets the bits as a non-negative number, so a pattern of all 1 bits becomes a very large positive value instead of -1.
On exploitability the researcher is explicit that it is unclear whether the bug is exploitable: always getting a constant 0 does not appear to be very helpful. Similar issues in SimplifiedLowering have occurred in the past, but this one is probably not exploitable as is and would likely require another bug. In other words, the wrong answer alone is a correctness bug; turning it into a security problem would need a second flaw to build on.
Fix
The report does not describe the fix that was applied.
- Other negative BigInt inputs with a shift amount that does not fit losslessly into an
int64_t, for example values built withBigInt.asIntNaround-1n. A positive result is an optimised call returning a different value from the interpreter. - Shift amounts whose sign differs from the truncated
int64_t, so thatlosslessis false and the direction is flipped. A positive result is the same interpreter/Turbofan mismatch after%OptimizeFunctionOnNextCall. - The same pattern with
BigInt.asUintNon the result, to see whether the wrong constant can be turned into a large value. A positive result is a value that differs between interpreted and optimised execution. - Other
SimplifiedLoweringpaths that uselosslessfromBigIntRef::AsInt64, checking whether any of them also treat a lossy conversion as a licence to fold. A positive result is a fold that is correct for non-negative inputs but wrong for negative ones.
Glossary
- BigInt: a JavaScript type for whole numbers of any size, written with an
nsuffix such as-1n. - Bit shift: an operation that moves the binary digits of a number left or right by a given number of places.
- Bounty: money paid by a company to someone who reports a valid security bug.
- Chrome VRP: Chrome's Vulnerability Reward Program, the scheme that pays researchers for security bugs in Chrome.
- Commit: a specific saved version of source code, identified by a long hash.
- CVE: a public identifier assigned to a known security vulnerability, here CVE-2024-7972.
- d8: a command-line program that runs JavaScript with V8 without a browser.
- Fix-point iteration: a process where the compiler repeatedly revisits nodes until nothing more changes.
- Heap constant: a value the compiler knows at compile time because it never changes, such as a variable set once.
- Interpreter: the part of an engine that runs code carefully, line by line, without compiling it.
- int64_t: the C++ name for a signed 64-bit integer.
- Intrinsic: a built-in engine command reachable from JavaScript, such as
%OptimizeFunctionOnNextCall, only available with a special flag. - JIT (just-in-time) compiler: a compiler that translates code into fast machine code while the program is running.
- Lossless: here, a flag saying whether converting a BigInt to an
int64_tkept the exact value and sign. - One's complement: a way of storing negative numbers by flipping the bits, with the sign kept separately.
- Proof of concept (PoC): a small program that demonstrates a bug.
- SimplifiedLowering: a phase in Turbofan that decides machine representations and replaces nodes with cheaper equivalents.
- Truncation: cutting a number down to a fixed width, for example keeping only the low 64 bits.
- Turbofan: V8's optimising compiler.
- Two's complement: the standard way computers store negative numbers, where negative values behave as if they have infinitely many 1 bits to the left.
- V8: Chrome's JavaScript engine.
- Word64: a 64-bit chunk of memory.