Hunting miscompilations in Solana’s LLVM fork
A tour of Solana’s custom LLVM backend, the ISA that it targets and the differential fuzzing techniques we applied to help us expose miscompilation bugs.
Warning (Part 1 of 2)
This part explains how Solana’s LLVM backend and the SBPF instruction set work, then describes the differential fuzzer I built to test them. If you only want the bugs, skip to Part 2.
Introduction
The Solana LLVM fork is an important component of the Solana ecosystem, yet it has received relatively little attention from security auditors. Although parts of it have been audited by the OtterSec team, a full review was never really performed and was always put on the back burner, so we decided that it was finally time for a comprehensive review of this LLVM fork.
To find bugs in the backend implementation, I used a combination of strategies, mainly manual code review and fuzzing. I also used some AI to assist in the review process and to develop PoCs. In addition to bug-finding, we also wanted to deepen our understanding of how LLVM backends work, especially the parts that are specific to Solana.
Goals
My original goal was to look for end-to-end miscompilation bugs in the Solana toolchain, meaning that a Rust program would be compiled to incorrect assembly. The Solana toolchain is a fork of the standard Rust toolchain, whose main components are the Rust compiler (rustc) and LLVM. Because most of the Solana-specific code in the toolchain exists as a custom backend in its LLVM fork, I wanted to look for miscompilations that are specific to Solana and not present in upstream LLVM.
Motivation
A real miscompilation bug in the LLVM backend would be very impactful for the security of Solana smart contracts, because it could silently cause unexpected behavior or introduce vulnerabilities in deployed programs even if the program source code is well-formed.
But why does Solana need an LLVM fork in the first place? The full timeline is complicated, but in short, a fork of LLVM was created very early on, back in 2018 when Solana was still using C instead of Rust. Shortly after, Solana developers started working on adding BPF support to rustc using this LLVM fork, before any BPF support existed in upstream rustc1. Since then, more and more changes to the BPF instruction semantics and ABI were introduced to Solana, and around 2021 and 2022 the changes in the LLVM fork were moved to a completely separate backend called SBF to reflect the fact that Solana’s ISA has diverged significantly from BPF.
Prerequisite knowledge
Note
To prevent potential naming confusion between SBPF and SBF, in this blog post SBPF (Solana BPF) refers to the instruction set and SBF (Solana binary format) is the name of the LLVM backend.
What is an LLVM backend?
LLVM, like most modern compilers, is organized in three stages. The frontend takes the source code of a high-level language like Rust and produces LLVM IR. The generic middle-end (called opt in LLVM) is responsible for optimizing the IR, and the backend (called llc) takes the optimized IR and generates machine code from it, a process known as code generation or CodeGen.
The original plan was to review code that is specific to the SBF backend and look for bugs there. But in practice, to find meaningful bugs, it was not as simple as reading the SBF files in isolation. The SBF backend shares a lot, if not most, of its code with BPF, so I found it very helpful to compare the two in order to familiarize myself with how an LLVM backend is organized. Also, all backends are built around several core LLVM abstractions, so it is important for us to first understand what these abstractions do and how they interact with each other.
SelectionDAG
Even though LLVM has separate backends for each supported target, much of their code uses a shared framework called SelectionDAG2. It is a different way of representing IR instructions, and it is used by the backend when transforming LLVM IR into another IR form that is closer to machine code called MachineIR. This transformation is a multi-step process, of which legalization and instruction selection are particularly interesting to us because these stages require custom backend implementation to support each target instruction set.
First, one DAG (directed acyclic graph) is constructed for each basic block in the IR. Roughly speaking, each node in the graph corresponds to an IR instruction and the edges represent data-flow dependencies. This is an example of a basic block in LLVM IR and its corresponding DAG:
bb:%y = add i32 %a, 5%z = mul i32 %y, 3br label %joinThe edges go from a node that takes a value as its input to a node that produces the value as the output. CopyFromReg and CopyToReg are special nodes that represent “importing” and “exporting” a value in and out of the basic block. This is needed because the variable %a is not defined within the basic block, and similarly %z is used somewhere outside of the basic block. The blue edge is called a chain and it contains important information for scheduling, which takes the DAG and arranges it as a linear sequence of instructions. This chain is created during DAG construction to represent the fact that br must be scheduled after mul even though there is no explicit data dependency between them.
Legalization
We have now constructed a SelectionDAG from a basic block, but not every DAG node represents an operation that is supported by the target. For example, there exists a CTTZ (count trailing zeros) node, but there is no corresponding machine instruction for it in Solana’s instruction set. As a result, LLVM has to expand the node into the appropriate algorithm, introducing many additional nodes in the process. Fortunately, such expansions are the same across all targets, so a backend just needs to call the setOperationAction method with the Expand action and let the generic LLVM code handle the rest.
Some nodes, however, are inherently target-specific, so the backend has to implement custom legalization logic for them. One example is the CALL node, which requires the backend to handle calling convention details such as arguments and return values. Backends can implement these custom legalizers by providing a class that inherits from TargetLowering. For SBF, this is implemented in SBFISelLowering.cpp.
Instruction selection
After the legalization step ensures that every node in the DAG is legal, instruction selection converts generic DAG nodes into nodes that are backed by machine instructions (called MachineInstrs). Note that this representation differs from the instructions in the final assembly. In particular, their operands are represented abstractly as virtual registers instead of actual machine registers.
Instruction selection is performed by matching the DAG nodes against a set of patterns defined by the backend, usually in the TableGen format. TableGen is a flexible language that records high-level descriptions, and in the context of instruction selection it is used to automatically generate C++ matching code from the defined patterns. The instruction selection patterns of the SBF backend are defined in SBFInstrInfo.td.
llvm/lib/Target/SBF/SBFInstrInfo.tddef SBFcall : SDNode<"SBFISD::CALL", SDT_SBFCall, [SDNPHasChain, SDNPOptInGlue, SDNPOutGlue, SDNPVariadic]>;def : Pat<(SBFcall tglobaladdr:$dst), (JAL tglobaladdr:$dst)>;Above is a snippet of SBFInstrInfo.td that handles instruction selection for function calls. It defines a custom CALL SelectionDAG node and a pattern that maps these nodes to the JAL (aka call) machine instruction.
DAGCombiner
Even though IR-level optimizations are performed by the middle-end, SelectionDAG also implements many local optimizations on the DAG itself in a pass called DAGCombiner. If these optimizations are not done correctly, they can introduce subtle miscompilation bugs.
After SelectionDAG
The final step in the SelectionDAG pipeline is instruction scheduling, which arranges the nodes in the DAG as a linear sequence of MachineInstrs. However, a backend still has more work to do before emitting machine code. For the code review, I focused on the following passes with custom SBF implementations.
Pseudo expansion
It turns out that even after legalization, some MachineInstrs are still pseudo instructions that do not correspond directly to any machine instruction. One such example is the Select family of MachineInstrs, which has to be rewritten using comparison and branching instructions. The SBF backend handles the expansion of these pseudo instructions by providing the EmitInstrWithCustomInserter method.
Frame index handling
MachineInstr operands that are stack memory references are initially represented as frame indices, which are indices of the objects on the stack. The SBF backend implements the eliminateFrameIndex method, which converts the frame indices to concrete offsets from the frame pointer based on the computed object layout.
Linking
The Solana toolchain uses the standard LLVM linker, lld, to link together multiple object files into a binary3. For the SBF target, the linker is configured to produce ELFs for the appropriate SBPF version through a set of custom linker scripts, and the only addition to the linker source code is for handling SBPF-specific relocation types.
What is SBPF?
Now that we have an idea of the SBF backend’s overall structure, we also need to take a step back and learn about the SBPF instruction set itself. This is important because the ISA details are closely tied to how the backend is implemented and we want to verify that the compiler generates correct SBPF code.
SBPF is the instruction set for the Solana virtual machine. It is largely based on eBPF, but with modifications to address some of its limitations. For instance, eBPF only supports passing a maximum of 5 arguments in registers (r1-r5)4 for function calls and does not have an instruction for indirect calls. Many versions of the instruction set have been defined, namely SBPFv0 to SBPFv4, which are incompatible with each other due to differences in instruction semantics or ABI. The SBF backend supports all of these variants by mapping each SBPF version to a combination of different feature flags in SBFTargetFeatures.td.
For this project, I mainly focused on SBPFv0 and v3, since v0 is the current toolchain default and v3 is becoming the default in the near future. A main goal of SBPFv3 is to restore compatibility with standard eBPF and remove as many Solana-specific quirks as possible. There are two main differences between SBPFv0 and v3 that are particularly relevant to the SBF backend: stack and syscalls.
SBPF stack
Both SBPFv0 and v3 use fixed-size stack frames of 4096 bytes, which is inherited from the eBPF architecture. Dynamic stack frames, where each function allocates as much stack space as it needs, were introduced to Solana but are not currently used in v0 and v3. r10 is the frame pointer that points to the top of the frame. With fixed-size frames, r10 is a read-only register because incrementing and restoring it for each function call is the responsibility of the VM instead of the program.
SBPFv0
In SBPFv0, a function’s local variables are allocated starting from the top of the frame and grow downwards, which is the same behavior as eBPF. For functions with more than 5 arguments, Solana introduced a mechanism to pass additional arguments on the stack, where the outgoing stack arguments are placed at the bottom of the caller’s frame. For the callee to access these arguments, r5 is set to the value of the caller’s frame pointer5, which leaves only 4 registers (r1-r4) available for use.
SBPFv0 enables stack frame gaps by default6, which are 4096-byte regions between consecutive frames that are not mapped, so accessing it would trigger an access violation in the VM. They were introduced to catch memory corruption bugs that could happen if a function allocates large objects on the stack whose total size exceeds the maximum of 4096 bytes. This is possible because LLVM itself does not really have a concept of “fixed-size stack frames”; it will simply allocate as much space as the function requires. To mitigate this, the SBF backend checks for references to stack memory during the frame index elimination step and issues a warning (not an error!) if the computed stack offsets are outside the bounds of the current frame.
Even though stack frame gaps can turn this class of bugs into explicit crashes instead of silent memory corruption, they do not work in all cases. Because a function’s local variables and outgoing stack arguments are located on opposite ends of the same stack frame, if it calls another function that takes arguments on the stack, its local variables can overlap with the outgoing stack arguments even if the total size of these variables does not exceed the 4096-byte limit. This will cause some of its local variables to be corrupted after the function call even though these accesses are entirely within a valid memory region. This situation was previously missed by the stack usage diagnostic in the SBF backend, but it is now fixed.
SBPFv3
In SBPFv3, stack frame gaps are disabled and a function’s local variables are allocated from the bottom of its frame. Outgoing stack arguments are now placed at the bottom of the callee’s frame before any of the callee’s local variables. The callee also directly accesses the stack arguments from its r10 without having to use r5.
Below is a diagram showing the stack layout differences between SBPFv0 and v3:
SBPF syscalls
SBPFv0
In SBPFv0, invoking a syscall is just calling an external (extern "C") function with the same name as the syscall. Since no definition exists for these functions, a dynamic relocation of type R_SBF_64_32 will be emitted for each call instruction. When the SBPF VM processes this relocation during ELF loading, it patches the 32-bit immediate field (last 4 bytes) of the instruction with the murmur32 hash of the syscall name. The disassembly below shows the relocation entry for sol_log_ in an SBPF binary and the corresponding call instruction with a placeholder immediate of -1.
18: 85 10 00 00 ff ff ff ff call -0x1 0000000000000018: R_SBF_64_32 sol_log_SBPFv3
In SBPFv3, as part of the transition towards strict ELF loading, relocation processing is disabled in the VM. Instead, the SDK defines syscalls as calling a function pointer whose value is the hash of the syscall name using the following macro:
define-syscall/src/lib.rspub unsafe fn $name($($arg: $typ),*) -> $ret { // this enum is used to force the hash to be computed in a const context #[repr(usize)] enum Syscall { Code = $crate::sys_hash(stringify!($name)), }
let syscall: extern "C" fn($($arg: $typ),*) -> $ret = core::mem::transmute(Syscall::Code); syscall($($arg),*)}This is directly lowered to a call instruction with its immediate field set to the hash, which corresponds to the “helper call” semantics in eBPF.
18: 85 00 00 00 bd 59 75 20 call 0x207559bdNote the difference in the second byte of the instruction: a value of 0x10 indicates that the immediate encodes an offset, while 0 means that the immediate is a syscall hash.
ELF layout
In addition to the ISA-level differences between SBPFv0 and v3, there is also a significant change in the behavior of the ELF loader. In SBPFv0, the loader reads the section headers from the ELF to determine the base addresses of different parts of the binary like .text and .rodata. SBPFv3 uses a strict loader, which reads the program headers instead and verifies that each segment is at a specific predefined address. Specifically, it expects only 2 segments: read-only data at address 0 and bytecode at address 0x100000000. The linker handles these ELF differences using separate linker scripts for SBPFv0 and v3.
Fuzzing
In addition to manually reviewing the SBF backend code, I also tried to fuzz the compiler using a modified version of Rustlantis. It is a differential fuzzer for Rust compilation based on MIR (mid-level IR), an intermediate representation used internally by rustc. It first generates a random MIR program and then compares the execution results of the same program compiled in different ways. It has previously found multiple bugs in both rustc and LLVM, and I decided to use it for my project because its modular design makes it rather straightforward to add support for the SBF backend.
The differential fuzzing technique used by Rustlantis is very flexible and can be used to find miscompilation bugs in different parts of the compilation pipeline. For example, by comparing programs compiled with or without Rust MIR optimizations, we can find bugs in rustc’s MIR optimizer. Alternatively, to look for miscompilations introduced by the SBF backend, which is the goal for this project, we can compare programs compiled to different targets, for example native x86 and SBPF.
MIR generation
MIR is a lot simpler than normal Rust, so it is easier to generate random programs in it. However, it is also a lower-level language compared to Rust and allows unsafe operations with undefined behavior, which is bad because we want executions to be deterministic. To create a UB-free MIR program, Rustlantis needs to maintain information about the program as it is being generated. For example, MIR has a concept of “places”, which are basically lvalues or locations in memory, and “projections”, such as accessing a struct field or dereferencing a pointer, which connect one place to another. Rustlantis maintains a “place graph” as it generates the program to track where each pointer points as well as the set of possible runtime values of each place. This information is useful for avoiding UB. For example, Rustlantis will not generate a division unless the value chosen to be the divisor is known to be non-zero.
In terms of overall structure, the generated MIR program is comprised of multiple functions. Each function has many local variables with complex types and multiple basic blocks as its body. Starting from the first function, Rustlantis generates statements one basic block at a time and generation always follows the same path as program execution. If a Call statement is generated, the cursor will move to a new function and the process repeats until the preconfigured number of functions or basic blocks per function is reached. The input parameters to the first function, which are just random constants, are marked with black_box to prevent the compiler from propagating them through the entire program.
One important property of the program is that during execution, it is guaranteed to terminate and not contain any loops, but the compiler cannot always prove that this is the case because of how Rustlantis generates match statements. Similar to the switch instruction in LLVM IR, match is a terminator statement that occurs at the end of a basic block in MIR and chooses its successor based on some value. A generated match statement may look like this:
bb8 = { // MIR code omitted match _17.0 { 0 => bb6, 1 => bb2, 2 => bb3, 3 => bb4, 4 => bb5, 5 => bb9, 1053903587 => bb11, _ => bb10 }}Importantly, Rustlantis only generates a match on known values so that it can create a match arm for that specific value. Note that this value is not necessarily known to the compiler. This way, Rustlantis knows the exact match arm that will be taken at runtime and can choose its target such that the match does not loop back to a previous basic block. The other arms are called “decoy arms”, which will never actually be taken, so Rustlantis can choose an arbitrary target for them. In the example above, the arm with a value of 1053903587 is the actual runtime path and the rest are decoy arms. This match is at the end of bb8, so the targets of some of these decoy arms form backedges to previous basic blocks like bb2. This mechanism allows Rustlantis to create complex control-flow structures in the generated MIR code without actually introducing a loop in the program.
Differential testing
Once we have generated a random MIR program, we need to compile it, execute it and compare the states of program execution as the oracle for the fuzzer.
To compile the MIR program into an SBPF binary, we just need to use the standard Solana rustc with the custom MIR feature enabled, which allows us to embed MIR code in a Rust source file. I used a high optimization level (-C opt-level=3), which will enable optimization passes in both the LLVM middle-end and backend. But because LLVM aggressively inlines functions, the nested function calls in MIR will usually be reduced to a single function with a large number of local variables. This is a problem for SBPF because the total size of these variables will sometimes exceed the stack frame limit of 4096 bytes. I modified Rustlantis to handle this situation by capturing compiler output and skipping the program if the compiler emits a stack size warning while compiling it.
I also needed to add support to Rustlantis for executing SBPF binaries. I created a custom runner that loads and executes SBPF ELFs using the SBPF VM crate, the same one that is used by the Agave validator. It also implements some essential syscalls, such as memcpy and memset, that might be invoked from an optimized program.
To expose the program execution states to the fuzzer, the MIR generator randomly chooses some local variables in each function and generates code that writes their values to a global Hasher at the end of the function. Before the program exits, the final hash is printed out and read by the fuzzer. If the hash is different across executions of the same program, the fuzzer will treat it as a potential miscompilation.
Evaluation
After leaving the fuzzer running for some time, it was able to find a few bugs, including miscompilations, missing diagnostics and compiler crashes. Despite the results, this fuzzing setup is limited by its throughput, because a large program needs to be compiled and optimized on every iteration, which takes a considerable amount of time. Also, one detail that I missed in the initial fuzzing runs is a lack of function calls in the optimized code as a result of LLVM’s aggressive function inlining. This prevents the fuzzer from properly testing the call lowering implementation in the backend, so I had to disable function inlining explicitly.
I also looked into this work, which was used to verify LLVM’s aarch64 backend. It is based on the Alive2 toolkit, which can validate the correctness of transformations on LLVM IR using formal verification. To make this tool work for verifying IR-to-assembly lowering, the authors had to implement a lifter that converts aarch64 assembly back into the equivalent IR. I decided not to pursue this further because implementing a lifter for SBPF is likely a time-consuming and error-prone process. For this approach to work, the lifted IR must have exactly the same semantics as the original assembly, so subtle bugs in the lifter will render the verification results invalid. The authors had to implement their own lifter because they experienced bugs in many of the existing aarch64 lifters that they tried.
One component from the above project that I found interesting is its mutation engine called alive-mutate. To generate inputs for the fuzzer, alive-mutate makes targeted modifications to existing LLVM IR code while ensuring that it remains valid IR. The mutation engine is used with a corpus of IR source files, for example the LLVM test suite. A potential future improvement for my differential fuzzer is using alive-mutate to generate LLVM IR directly instead of having to go through Rust MIR.
For details on some of the bugs found by the fuzzer, continue to Part 2.
Footnotes
-
In 2020, BPF support was added to upstream rustc by alessandrod himself, but at that point Solana had already settled on using its own rustc and LLVM fork, so this was not really an option. ↩
-
There is a newer alternative to SelectionDAG called GlobalISel, but it is not currently used by the SBF backend. ↩
-
Interestingly enough,
llddoes not support eBPF at all because linking is not required when compiling kernel eBPF programs, which are usually just single C files. Linker support is necessary for Rust, however, because a typical Rust compilation always involves multiple object files. ↩ -
Support for stack arguments was recently added to the upstream eBPF backend in this PR, but it is implemented in a way that is completely incompatible with SBPF’s calling convention, which caused some trouble for people trying to use the eBPF backend to compile SBPF binaries. ↩
-
Actually there is nothing that prevents the callee from accessing the arguments in the caller’s frame using offsets from its own
r10, so I am not entirely sure whyr5is even needed in the first place. It seems like thisr5convention has been there ever since stack argument support was first added in this commit. ↩ -
Stack frame gaps for SBPFv0 will be disabled by SIMD-0460, partly because they were shown to cause poor performance in the VM during address translation. ↩