一句话:提出静态分析技术,在 C 到 Rust 翻译中识别 tag 字段并将 C union 替换为 Rust 的 tagged union,以消除不安全特性。
自动将 C 翻译为 Rust 是提升遗留系统软件可靠性的有前景途径,但工业级翻译器 C2Rust 会生成包含 unsafe 特性的 Rust 代码,削弱了翻译目标。现有去除 unsafe 特性的工作仅覆盖有限子集,其中 union(多个字段共享同一内存存储的类型)尚未被处理:程序员常把 union 与 tag 字段放在 struct 中以记录最后写入的字段,但仍可能访问错误的字段;而 Rust 的 tagged union 在语言层面把 tag 与 union 结合,保证值访问的正确性。本文提出在 C 到 Rust 翻译期间用 tagged union 替换 union 的技术,其核心是一个静态分析:通过 must-points-to 分析计算 struct 字段值,并用启发式规则解释结果,从而识别 tag 字段及其对应的 tag 值。为提升效率,采用过程内按函数分析,支持对函数的选择性分析。在 36 个真实 C 程序上的评估表明:该方法精确,识别出 74 个 tag 字段,无误报、仅 5 个漏报;基本正确,23 个程序中有 17 个在转换后通过测试;且高效,可在 4910 秒内分析并转换 141k 行代码。
Automatic C-to-Rust translation is a promising way to enhance the reliability of legacy system software. However, C2Rust, an industrially developed translator, generates Rust code with unsafe features, undermining the translation's objective. While researchers have proposed techniques to remove unsafe features in C2Rust-generated code, these efforts have targeted only a limited subset of unsafe features. One important unsafe feature remaining unaddressed is a union, a type consisting of multiple fields sharing the same memory storage. Programmers often place a union with a tag in a struct to record the last-written field, but they can still access wrong fields. In contrast, Rust's tagged unions combine tags and unions at the language level, ensuring correct value access. In this work, we propose techniques to replace unions with tagged unions during C-to-Rust translation. We develop a static analysis that facilitates such replacement by identifying tag fields and the corresponding tag values. The analysis involves a must-points-to analysis computing struct field values and a heuristic interpreting these results. To enhance efficiency, we adopt intraprocedural function-wise analysis, allowing selective analysis of functions. Our evaluation on 36 real-world C programs shows that the proposed approach is (1) precise, identifying 74 tag fields with no false positives and only five false negatives, (2) mostly correct, with 17 out of 23 programs passing tests post-transformation, and (3) efficient, capable of analyzing and transforming 141k LOC in 4,910 seconds.