用大模型自动替换C转Rust代码中的原始指针,提升安全性
Raw Pointer Rewriting with LLMs for Translating C to Safer Rust
- 通过决策树提示引导,将函数内原始指针升维为安全数据结构
- 在28个真实项目上消除18.57%的局部原始指针,编译与测试错误显著减少
- 适合关注C转Rust安全性的开发者和自动化重构研究者
由于Rust具备强内存与线程安全特性,将C代码转换为Rust正受到广泛关注。现有工具如C2RUST可实现语法引导的跨语言转换,生成语义等价的Rust代码。然而,生成的Rust程序仍大量依赖unsafe构造,尤其是原始指针,削弱了Rust的安全保障。本文提出一种原始指针重写技术PR2,旨在消除由C2RUST生成的Rust代码中的原始指针。PR2采用基于决策树的提示策略指导指针升维,并利用代码变更分析修复重写过程中引入的错误,有效解决编译失败与测试用例执行异常问题。我们在28个真实C项目上使用gpt-4o-mini实现并评估PR2,结果表明其成功消除18.57%的局部原始指针,显著提升代码安全性。平均每个项目转换耗时5.02小时,成本为1.13美元。
原文摘要 · Abstract (English)
There has been a growing interest in translating C code to Rust due to Rust's robust memory and thread safety guarantees. Tools such as C2RUST enable syntax-guided transpilation from C to semantically equivalent Rust code. However, the resulting Rust programs often rely heavily on unsafe constructs, particularly raw pointers, which undermines Rust's safety guarantees. This paper aims to improve the memory safety of Rust programs generated by C2RUST by eliminating raw pointers. Specifically, we propose a raw pointer rewriting technique that lifts raw pointers in individual functions to appropriate Rust data structures. Technically, PR2 employs decision-tree-based prompting to guide the pointer lifting process. It also leverages code change analysis to guide the repair of errors introduced during rewriting, effectively addressing errors encountered during compilation and test case execution. We implement PR2 and evaluate it using gpt-4o-mini on 28 real-world C projects. It is shown that PR2 successfully eliminates 18.57% of local raw pointers across these projects, significantly enhancing the safety of the translated Rust code. On average, PR2 completes the transformation of a project in 5.02 hours, at a cost of $1.13.
Thank you to arXiv for use of its open access interoperability. PaperDance 不是 arXiv 官方产品;中文卡片由大模型生成,请以原文为准。