
Reproducing Solidity’s Yul Memory-Spilling Bug in Mutual Recursion
Solidity’s Yul optimizer could misclassify a function in an intersecting mutual-recursion cycle as non-recursive. The IR pipeline’s stack-to-memory mover could then place that function’s locals at fixed memory offsets, where a nested invocation overwrote values still needed by the outer invocation. The issue affects Solidity 0.7.2 through 0.8.35 when the relevant IR-pipeline conditions are met; it is fixed in 0.8.36. Reproduce it by compiling a carefully shaped call graph with viaIR, then compare output against a fixed compiler.
What the bug changes—and why recursion matters
The EVM exposes only the topmost 16 stack slots for direct access. When a function has too many simultaneously live values, Solidity’s IR pipeline can use a stack-to-memory transformation—also called the StackLimitEvader—to place some locals at fixed memory offsets. For a non-recursive function, those offsets can be reused safely: another activation of that function cannot overlap the current one.
That assumption fails for recursion. If a function is re-entered before its first invocation has finished, the nested activation can overwrite the fixed slots, corrupting values the outer invocation later reads. To avoid this, the mover must not spill locals in any function that belongs to a recursive call cycle.
The relevant compiler bug was in CallGraphGenerator’s cycle detection. Its path-based depth-first search could mark a function as visited after exploring one cycle, then short-circuit when another intersecting cycle reached that finished function. A function genuinely in the second cycle could consequently be reported as non-recursive. Solidity’s fix replaces this approach with Tarjan’s strongly connected components algorithm.
Environment and baseline specifications
The affected compiler range is Solidity 0.7.2 through 0.8.35, inclusive; the fix is in Solidity 0.8.36. This article’s example targets Solidity 0.8.35 as the vulnerable baseline and Solidity 0.8.36 as the fixed comparison. Use the IR pipeline explicitly with viaIR: true in Standard JSON or --via-ir on the command line. No OpenZeppelin dependency is needed: the defect is in compiler analysis, not a library API.
The IR pipeline was experimental before 0.8.13 and required experimental opt-in. On Solidity 0.8.20 and earlier, reaching the stack-to-memory mover requires optimization; from 0.8.21 onward, disabling the optimizer does not avoid the mover. Solidity 0.7.2 is the conservative start of the affected range, though the source report says its working reproducer was observed from 0.8.8 onward (or 0.8.10 through the experimental via-ir entry point). The 0.7.2–0.8.7 range is conservatively considered affected, not demonstrated by that reproducer.
Vulnerable call graph and minimal reproduction shape
The key is not just mutual recursion. The example needs intersecting cycles that share a function, plus a traversal order that causes the old analysis to miss one cycle member:
a -> b -> a
a -> c -> b -> a
All three functions are in one strongly connected component. In the failing traversal, the compiler explores a -> b first, marks b visited while closing b -> a, then explores a -> c. When c -> b reaches the already-visited b, traversal stops instead of discovering that the path through b -> a -> c closes another cycle. The old analysis can therefore label c non-recursive.
A source-level reproduction follows. The omitted locals are intentional: there must be enough simultaneously live values in c to induce spilling, and the values must remain live across the recursive call.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.35;
contract SpillRepro {
uint256[26] public seed;
function init() external {
for (uint256 i; i < 26; ++i) {
seed[i] = (i + 1) * 0x1111;
}
}
function trigger() external returns (uint256) {
a(3);
return seed[3];
}
function a(uint256 m) internal {
if (m == 0) return;
b(m);
c(m);
}
function b(uint256 m) internal {
if (m == 0) return;
a(m - 1);
}
function c(uint256 m) internal {
if (m == 0) return;
uint256 v1 = seed[0] ^ m;
uint256 v2 = seed[1] ^ m;
// Define v3 through v24 in the same form.
uint256 v25 = seed[24] ^ m;
b(m - 1);
// The outer activation expects its original m here.
seed[m] = m;
// Keeps v1..v25 live across b(m - 1).
seed[25] = v1 + v2 /* + ... */ + v25;
}
}
The source report’s full reproducer supplies the intervening locals and specific naming/order needed to trigger the bad classification. Treat this abbreviated listing as the call-graph and liveness shape to reproduce, not as a guarantee that every compiler build or renamed variant miscompiles. The old traversal’s outcome depends on callee visitation order, which is influenced by internal Yul function-name hashes. Renaming functions can change whether the bug appears without changing the high-level graph.
After initialization, seed[3] is 0x4444. Correct execution of trigger() should make c(3) write seed[3] = 3, so the returned value is 3. In the reported failing build, the spilled m is overwritten during nested recursion; the write targets the wrong index and seed[3] remains 0x4444. The compiler does not necessarily warn or revert: this is a silent miscompilation.
Production mitigation and compiler comparison
The production fix is to compile with Solidity 0.8.36 or later. The corrected analysis uses Tarjan’s algorithm to identify strongly connected components, so every function in a multi-function component is classified as recursive, regardless of traversal order. Direct self-calls are recursive as well.
If an affected compiler cannot yet be replaced, use a non-affected compilation route where feasible: the legacy evmasm pipeline is not affected by this bug. Alternatively, restructure the call graph to remove mutual recursion, or ensure that recursive functions do not require stack-to-memory relocation. These are temporary mitigations, not substitutes for upgrading and retesting: changing names or disabling optimization is not a reliable fix.
| Build or approach | Relevant conditions | Expected result | Security assessment |
|---|---|---|---|
Solidity 0.8.35, viaIR: true, optimizer enabled | Intersecting cycles; misclassified function spills locals | Reproducer may return 0x4444 instead of 3 | Vulnerable if all trigger conditions coincide |
Solidity 0.8.35, viaIR: true, optimizer disabled | Solidity 0.8.21–0.8.35 | Stack-to-memory mover can still run | Not a mitigation |
Solidity 0.8.20 or earlier, viaIR: true, optimizer disabled | Older IR pipeline behavior | Mover does not run in this configuration | Avoids this path, but is not a general compiler-security strategy |
Solidity 0.8.35, legacy evmasm | IR pipeline not used | This specific bug is not reached | Pipeline-specific mitigation |
Solidity 0.8.36+, viaIR: true | Tarjan SCC analysis | Recursive functions are identified correctly | Fixed for this bug |
Differential verification with Foundry
Pin compiler versions rather than relying on whichever solc is installed. A Foundry configuration can make the vulnerable and fixed builds explicit:
# foundry.toml
[profile.vulnerable]
src = "src"
test = "test"
solc = "0.8.35"
via_ir = true
optimizer = true
optimizer_runs = 200
[profile.fixed]
src = "src"
test = "test"
solc = "0.8.36"
via_ir = true
optimizer = true
optimizer_runs = 200
Write a regression test for the observable behavior, not an internal compiler detail:
function test_recursiveSpillResult() public {
SpillRepro target = new SpillRepro();
target.init();
assertEq(target.seed(3), 0x4444);
assertEq(target.trigger(), 3);
}
Run it under both profiles:
FOUNDRY_PROFILE=vulnerable forge test --match-test test_recursiveSpillResult -vv
FOUNDRY_PROFILE=fixed forge test --match-test test_recursiveSpillResult -vv
Use the full reproducer and exact source naming from the Solidity report when checking for the historical failure. A reduced or renamed test may change Yul names and visitation order, suppressing the misclassification. Record the compiler version, optimizer settings, viaIR setting, and EVM target alongside the test result. The result is compiler- and configuration-specific; a passing run on one build does not establish that another build is safe.
For a compiler-level comparison, generate Standard JSON input for each exact compiler version with identical source and settings, then compare the execution result and inspect generated IR:
solc-0.8.35 --version
solc-0.8.36 --version
solc-0.8.35 --standard-json < input.json > out-0835.json
solc-0.8.36 --standard-json < input.json > out-0836.json
solc-0.8.35 --via-ir --ir-optimized --yul-optimizations \
--optimize --optimize-runs 200 SpillRepro.sol
--ir-optimized inspection can help identify stack-to-memory transformations, but generated text alone is not a correctness proof. Run the behavioral regression against deployed bytecode from both builds. If your contract handles token deposits or shares, also verify that the corrupted result cannot distort balance accounting; the distinct risks around vault share calculations are covered in Preventing ERC-4626 Share Inflation Attacks in Solidity.
Production pitfalls and edge cases
Optimizer settings are version-sensitive. On 0.8.21 and later, turning off the optimizer does not disable the relevant stack-to-memory stage. On older affected versions, optimization is necessary to reach that stage, so a test that omits --optimize may fail to reproduce the issue without showing that the compiler is safe.
A recursive graph alone is not sufficient. The misclassified function must also be complex enough for the mover to relocate values, and an overwritten value must influence observable behavior. Simple recursion, or recursion where no relevant local remains live across the nested call, may produce correct results even with the faulty analysis.
Compiler version is part of the build artifact. Verify the compiler used in CI, local builds, and deployment—not just the version declared in a config file. Archive build metadata and bytecode hashes, then rerun regression tests after changing compiler versions or pipeline settings.
Do not treat a source scan as proof of safety. The source report’s Sourcify scan found 272 of roughly 207,000 viaIR contracts with a potentially misclassified function, but none of those identified contracts relocated variables inside that function. That finding is useful context, not a guarantee about unscanned code or future deployments. In a broader audit, inspect recursive internal call paths and the liveness of locals across recursive calls; also review any external input that influences recursion depth or stored indices.
When decoded or externally supplied data determines a call path, validate its shape independently; the compiler fix does not replace input validation. See Preventing Unsafe abi.decode Usage in Solidity. If the affected function participates in a payment or token-flow path, test the resulting state transitions and failed-call handling as well; Preventing Unchecked Low-Level Call Failures in Solidity covers that separate concern.
Frequently Asked Questions (FAQ)
Which Solidity versions are affected by the Yul memory-spilling bug?
Solidity 0.7.2 through 0.8.35 is the conservatively affected range, and Solidity 0.8.36 fixes the bug. It is specific to the IR pipeline; the legacy evmasm pipeline is not affected. Before 0.8.21, the optimizer must also be enabled for the relevant mover to run.
Does disabling the optimizer fix the bug in Solidity 0.8.35?
No. In Solidity 0.8.21 and later, the stack-to-memory mover is a distinct IR-pipeline stage and can run regardless of optimizer settings. Disabling optimization is therefore not a mitigation for Solidity 0.8.35 with viaIR enabled.
Why might the same reproducer work after renaming a Solidity function?
The old cycle-detection traversal’s callee order depended on internal Yul names, which are influenced by function-name hashes. A different order can cause the traversal to discover the cycle instead of short-circuiting at a previously visited function. Renaming may hide the symptom, but does not repair the compiler or provide a reliable security fix.