TL;DR
Translating legacy C code into memory-safe, idiomatic Rust is notoriously difficult because existing transpilers rely heavily on unsafe blocks, while naive LLM translations introduce hallucinations and compile errors. SACTOR bridges this gap using a two-step translation pipeline guided by static analysis and verified incrementally via Foreign Function Interface (FFI) test harnesses. Across 200 programs, SACTOR produced 100% unsafe-free idiomatic Rust, with reasoning models like DeepSeek-R1 achieving up to a 93% translation success rate.
What Problem Does This Paper Address?
Decades of critical infrastructure remain written in C, leaving systems exposed to memory safety exploits like buffer overflows and use-after-free bugs. Rust provides modern, compile-time memory safety without performance penalties, making C-to-Rust migration highly desirable.
However, automated migration is fundamentally difficult:
- Rule-based transpilers (e.g., C2Rust) produce direct syntactic mappings wrapped in Rust’s
unsafeblocks, failing to leverage Rust's core safety features (ownership, borrowing, lifetimes). - Pure LLM approaches can generate idiomatic Rust, but they struggle with complex control flow, hallucinate pointer behaviors, and lack formal correctness guarantees.
- Formal verification techniques (such as symbolic execution or fuzzing) struggle to scale to non-trivial C code due to compiler-inserted checks and standard library mismatches.
Methods
SACTOR (Structure-Aware C-to-Rust Translator) divides the translation and verification process into modular steps:
- Dependency Analysis & Task Division: A custom static analysis tool based on
libclangparses the C code, extracts semantic dependencies (types, globals, and functions), and orders translation tasks topologically using depth-first search for circular dependencies. - Step 1: C to Unidiomatic Rust: Translates C to syntactically equivalent Rust that retains C-like semantics, raw pointers, and
unsafeblocks. Data types are transpiled using C2Rust, while functions are translated by the LLM using extracted dependency signatures. - Step 2: Unidiomatic to Idiomatic Rust: Refines unidiomatic Rust into safe, idiomatic Rust. To replace raw pointers with safe types (
Box, references, slices), SACTOR incorporates ownership, fatness, and mutability hints from Crown, a static pointer ownership analysis tool. - FFI-based "Soft Equivalence" Verification: Rather than running heavy symbolic execution, SACTOR checks functional correctness via end-to-end (E2E) execution.
- For unidiomatic code, functions share the C ABI and are dynamically linked directly against the original C binary.
- For idiomatic code (where types and signatures diverge), SACTOR prompts the LLM to synthesize a bidirectional test harness that marshals data between C and Rust representations before calling the target function.
- Iterative Feedback Mechanism: If compilation or test execution fails, compiler diagnostics and runtime I/O logs (injected via a Rust procedural macro) are fed back into the prompt for up to 6 retry attempts.
+-----------+ libclang +-----------------+ C2Rust / LLM +------------------+
| C Code | --------------> | Fragment Order | ---------------> | Unidiomatic Rust |
+-----------+ +-----------------+ +------------------+
|
Crown | Static Hints
v
+------------------+ FFI Harness +------------------------------------+
| Idiomatic Rust | <-------------------------- | Idiomatic Refinement & E2E Testing |
| (100% Safe Rust) | (Compiler/Log Feedback) +------------------------------------+
+------------------+
Datasets
The authors evaluated SACTOR across two benchmark suites (100 C programs each) and two real-world C projects:
- TransCoder-IR: 100 long-form C programs filtered to remove existing Rust translations, compilation errors, and memory leaks (verified using Valgrind). Includes existing E2E tests.
- Project CodeNet: 100 programs that accept command-line inputs (
argc/argv). Test cases were automatically synthesized using a custom SACTOR test generator. - Real-World Projects:
avl-tree(~1,000 LOC) – an AVL tree implementation with 12 unit/E2E test suites.urlparser(~500 LOC) – an RFC-compliant URL parser evaluated using 10 E2E tests.
Key Insights and Ideas
- Decoupling Syntax from Idiomatic Semantics: Forcing an LLM to simultaneously translate C syntax and redesign ownership semantics in a single step leads to frequent failures. Splitting the problem into C $\to$ Unidiomatic Rust and Unidiomatic $\to$ Idiomatic Rust significantly lowers cognitive load for the model.
- Static Analysis as Prompt Guidance: LLMs struggle to infer whether a C pointer represents a single value, a dynamically sized array, an owned resource, or a borrowed reference. Injecting static ownership annotations from Crown eliminates this ambiguity.
- The "Harness Bottleneck" in FFI Verification: When testing safe Rust code against legacy C drivers, the LLM must generate bridging harnesses to convert types (e.g.,
*const c_char$\leftrightarrow$&str). Translation failures in larger projects often stemmed not from the translated algorithm itself, but from the LLM failing to construct valid type-marshalling wrappers. - Reasoning Models Outperform on Complex Logic: Models with reasoning chains (DeepSeek-R1) handled string conversions and complex pointer-arithmetic bounds far better than non-reasoning models (Claude 3.5, GPT-4o).
Key Results
- Correctness & Success Rates:
- DeepSeek-R1 achieved the highest overall success rate: 93% on TransCoder-IR and 84% on CodeNet.
- GPT-4o followed with 80% and 79%, while Claude 3.5 Sonnet achieved 54% and 83% (struggling significantly with C-string semantics in TransCoder-IR).
- Elimination of Unsafe Code:
- While baseline tools like C2Rust, Crown, and C2SaferRust left substantial
unsafecode (average unsafe fraction between 10.8% and 100%), SACTOR achieved 100% Unsafe-Free code across all successfully translated idiomatic programs. - Reduced Clippy lint alerts by up to $7\times$ compared to C2Rust and Crown.
- Feedback Loop Impact: Iterative feedback dramatically aided weaker models (boosting Llama 3.3 70B's success rate by 17–21 percentage points), whereas high-tier models like GPT-4o saw minimal benefit.
- Cost & Efficiency: GPT-4o and Gemini 2.0 Flash proved most token-efficient (~2,500–3,300 tokens/task). DeepSeek-R1 required $5\text{–}7\times$ more tokens (~13,500–17,900 tokens/task) due to its internal chain-of-thought generation.
Limitations and Future Work
- Test Suite Dependency: SACTOR’s validation relies entirely on test coverage; subtle edge cases omitted from E2E test suites can slip through undetected.
- Complex Language Features: The current tool struggles with:
- Function pointers taking generic/
void*arguments (Rust generics cannot easily be passed across an FFI boundary without raw pointers). - Complex preprocessor macros, inline assembly, and mutable global state.
- Harness Synthesis Failures: In complex codebases like
avl-treeandurlparser, valid idiomatic code was sometimes rejected purely because the LLM could not synthesize a working FFI bridging harness. Future extensions could integrate automated property-based fuzzing and formal verification to alleviate harness generation bottlenecks.
Summary updated