Three miscompilation bugs in Solana’s LLVM fork
We highlight three unique bugs that we found in the Solana LLVM fork: an invalid SelectionDAG optimization, a missing stack diagnostic and a stack overflow in the peephole optimizer.
Bugs
Building on the background and fuzzing techniques introduced in Part 1, we now present 3 bugs from different parts of LLVM. While the code review was focused on SBF-specific bugs, it turned out to be a relatively narrow scope as the fuzzer was also able to find a few bugs in generic LLVM backend code.
Bug 1
This is a recent DAGCombiner bug that was reported upstream, where the optimizer wants to replace DAG nodes of the form
SELECT cond, (LOAD p1), (LOAD p2)with
LOAD (SELECT cond, p1, p2)where SELECT chooses between its two inputs based on the condition, like a ternary operator. But this transformation turns out to be invalid in certain edge cases.
To understand why, we have to introduce the undef and poison values in LLVM IR. They are special values used to represent “deferred undefined behavior”. Unlike operations that trigger immediate undefined behavior such as division by zero, whose effects are visible right away, operations that trigger deferred UB create unpredictable results, but are otherwise safe to execute. Like many constructs in LLVM, deferred UB exists to facilitate optimizations such as speculative execution.
Specifically, the semantics of poison is relevant for this bug. It generally propagates across “pure” operations, so if one of the inputs (the condition of a SELECT for example) is poison, the output will also be poison. But attempting to use poison in a side-effecting operation like LOAD will trigger immediate UB. So in this example, if cond is poison, the output of the node before the transformation is poison, but afterwards it will trigger immediate UB, which makes the optimization invalid.
Bug 2
To detect if a function’s stack usage exceeds the limit, the SBF backend performs this check for each stack memory reference:
llvm/lib/Target/SBF/SBFRegisterInfo.cppif (StackGrowsUp && Offset > 0) { ShouldWarn = true;} else if (!StackGrowsUp && Offset < MaxOffset) { ShouldWarn = true;}In SBPFv3, StackGrowsUp is true, so this code is just checking if Offset, which is the offset of the start of the referenced object from the frame pointer, is positive. In other words, it only emits a warning if the start of the object is above the top of the current frame without taking into account the length of the object. As a result, it is still possible for parts of an object to overlap with the next frame even if it starts in the current frame, which is especially problematic for SBPFv3 because of the lack of stack frame gaps. This bug was reported to Solana and fixed in this PR.
As a proof of concept, this bug can affect an Anchor program that uses a large account struct. For each instruction entrypoint, Anchor generates a function that deserializes the account data before passing it to the user-defined handler:
lang/syn/src/codegen/program/handlers.rspub fn #ix_method_name<'info>( #program_id: &'info Pubkey, #account_infos: &'info [AccountInfo<'info>], #ix_data: &'info [u8],) -> anchor_lang::Result<()> { // ... let mut #deserialized_accounts = #accounts_struct_name::try_accounts( #program_id, &mut #remaining_accounts, #ix_data, &mut #bumps, &mut #reallocs, )?;
// ... // Invoke user defined handler. let #result = #program_name::#ix_method_name(..., &mut #deserialized_accounts, ...)?;
// ... // Exit routine. #deserialized_accounts.exit(#program_id)}If an instruction takes in an account that is defined like the following:
#[account]#[derive(InitSpace)]pub struct PoolState { pub reserve_a: u64, pub reserve_b: u64, pub price_history: [u64; 247],}then the size of this struct would be exactly right for the total stack frame usage of the generated function to exceed the 4096-byte limit. Specifically, the stack slot allocated for the program_id pointer, which is one of the function’s local variables, starts inside the frame but extends beyond the end of the frame, so no warnings would be issued during compilation. The user handler will overwrite the pointer with its own variables, causing a crash once the callee returns and the invalid pointer is used later on in the function.
Bug 3
This bug is different from the other ones I found in that it does not lead to a miscompilation. Instead, it causes LLVM itself to crash due to stack overflow. The bug is in LLVM’s generic peephole optimizer, which is an optional MachineIR pass, so it is not specific to the SBF backend. Interestingly, the fuzzer triggered this crash when it was running the compiler for x86 but not SBPF because the peephole optimizer pass is not enabled in the SBF backend.
The bug has to do with how the peephole optimizer handles “uncoalescable” copy instructions, which are like the ordinary register-to-register COPY instruction, but across different register classes. For example, a bitcast from i64 to double in x86 MachineIR is considered an uncoalescable copy even though the contents of the source and destination registers are exactly the same. This is because i64 values are stored in gr64 (general-purpose) registers while doubles have to be stored in fr64 (floating-point) registers like xmm0, so they cannot be used interchangeably or “coalesced”.
To try to eliminate these uncoalescable copies, the optimizer will follow a chain of copy-like instructions to find a source register with the same register class as the register of interest. For example, these are two bitcast instructions in x86 MachineIR:
%1:fr64 = MOV64toSDrr %0:gr64 ; bitcast i64 to double...%2:gr64 = MOVSDto64rr %1:fr64 ; bitcast double to i64When performing this optimization on the second bitcast, we are looking for a gr64 register with the same contents as %2. By searching up the copy chain, we will find that %0 is a suitable source, so the second bitcast will be removed and replaced with a regular COPY:
%1:fr64 = MOV64toSDrr %0:gr64...%2:gr64 = COPY %0:gr64The actual implementation is slightly more complicated. For each uncoalescable copy instruction, findNextSource first searches up the chain of copies and constructs a “rewrite map”, which maps the destination register of each copy-like instruction it encountered along the way to the source. In the previous example, the rewrite map would contain two entries: %2 -> %1 and %1 -> %0. If a PHI instruction is reached during the search, its rewrite map entry will map to several source registers, one from each predecessor of the PHI.
After this step, getNewSource performs a similar search over entries in the rewrite map to determine what the new source should be for a given register. For PHI instructions, getNewSource recurses into each source of the PHI and continues the search. However, this recursive algorithm is problematic if there is a cycle in the rewrite map involving a PHI instruction, like in the following IR:
define void @f(i32 %a, i64 %b) {start: %_38 = bitcast i64 %b to double br label %bb3
bb3: %_15.40.2 = phi double [ %_38, %start ], [ %_43, %bb5 ] %_39 = bitcast double %_15.40.2 to i64 ; [1] %insert.insert219 = add i64 %_39, 1 %_40 = bitcast i64 %insert.insert219 to double br label %bb5.outer
bb5.outer: %_15.40.4 = phi double [ %_38, %bb9 ], [ %_40, %bb3 ], [ %_43, %bb5 ] %_43 = freeze double %_15.40.4 br label %bb5
bb5: switch i32 %a, label %bb5 [ i32 0, label %bb5.outer i32 1, label %bb9 i32 2, label %bb3 ]
bb9: br label %bb5.outer}When constructing the rewrite map for the bitcast instruction at [1], we start from %_39 and follow the chain of copies to %_43 in bb5.outer. Here, a cycle is introduced as we process the freeze and phi instructions (freeze is also a copy-like instruction). Specifically, the rewrite map now contains %_43 -> %_15.40.4 and %_15.40.4 -> %_38, %_40, %_43, causing getNewSource to recurse infinitely as soon as the search reaches %_43.
Curiously, a very similar bug was reported back in 2018, but the underlying issue, which is the lack of proper handling for cycles in the rewrite map, was never addressed. However, it is not surprising that this crash was never hit when compiling real-world programs. Even though the bug was found with a MIR program generated by Rustlantis, I could not find any Rust code that would trigger it. Since MIR is a lot closer to LLVM IR, it is easier to craft MIR code that would be lowered to IR with a similar structure to the PoC, particularly control flow that introduces a rewrite map cycle, which is just not feasible with normal Rust.
Conclusion
Reflecting on the methodology used, I think that the combination of strategies was reasonably effective, although I definitely could have made heavier use of AI for tasks other than code review. For example, I could have leveraged AI to implement a second fuzzer based on the IR mutation idea to potentially catch more bugs.
In the process of finding these bugs, we also gained insight into the inner workings of LLVM backends, though we have really only scratched the surface of their complexity. And that’s just one part of the compiler: other components, like the middle-end optimizer, can introduce even more bugs. Compiler correctness is especially important for an environment like Solana smart contracts, but compilers are very often overlooked as a security-relevant component and trusted as a black box by developers. This is made more challenging by the high complexity of LLVM, so it is common for backend implementers to miss certain nuances and write code that breaks in edge cases.
Acknowledgments
I would like to thank my mentor mixy for his continued support during the project and the writing of this blog post.