#重构 #c2rust #编程语言 #rust

nightly app crusts

CRustS - 从不安全的 C 到更安全的 Rust

2 个版本

0.0.2 2022 年 12 月 29 日
0.0.1 2022 年 12 月 28 日

#326编程语言

Apache-2.0

21KB
393

CRustS - 将不安全的 C 代码转换为更安全的 Rust 代码

Michael Ling, Yijun Yu, Haitao Wu, Yuan Wang, James R. Cordy, Ahmed E. Hassan
Trustworthiness Software Engineering & Open Source Lab
Huawei Technologies, Inc.

作为一种更安全的 C 替代品,Rust 是一种用于编写系统软件的语言,具有类型安全的编译器来检查其内存和并发安全性。为了促进现有项目从 C 到 Rust 的平滑过渡,并为 C 中现有功能的初始 Rust 重新实现打下坚实基础,拥有一种能够使用程序转换技术将程序从 C 转换为 Rust 的源到源转换器将大有裨益。然而,现有的 C 到 Rust 转换工具集存在缺点,即它们在很大程度上保留了 C 的不安全语义,同时在 Rust 语法中重新编写它们。因此,结果 Rust 程序的安全性仍然主要依赖于程序员,而不是 Rust 编译器。为了获得更多安全保证,在本演示中,我们介绍了 CRustS,这是一种系统性的源到源转换方法,通过放宽转换的语义保持约束,来提高代码通过 Rust 编译器安全检查的比例。我们的方法使用了 220 条 TXL 源到源转换规则,其中 198 条严格保持语义,22 条近似语义,从而减少了不安全表达式的范围,并提供了更多安全重构的机会。我们的方法已在开源和商业项目上进行了评估。我们的解决方案在转换后显著提高了安全代码比率,函数级安全代码比率与典型 Rust 项目的平均水平相当。

Laertes[OOPSLA’21] 相比,就其自己的基准测试而言,CRustS 获得的安全比率要高得多。

安装

# install c2rust
if [ $(uname -s) == "Darwin" ]; then
   git clone https://github.com/immunant/c2rust 
   cd c2rust
   scripts/provision_mac.sh
   cargo build --release
   cp target/release/c2rust $HOME/.cargo/bin
   cp target/release/c2rust-transpile $HOME/.cargo/bin
   cp target/release/c2rust-analyze $HOME/.cargo/bin
   cp target/release/c2rust-instrument $HOME/.cargo/bin
   cd -
   brew install bear
   export PATH=$HOME/.local/bin:$HOME/.cargo/bin:$PATH

   cargo install crusts

elif [ $(uname -s) == "Linux" ]; then
   apt install llvm cmake clang libclang-dev bear -y
   LLVM_LIB_DIR=/usr/lib/llvm-14/lib/ cargo install c2rust
   curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
   rustup override set nightly-2021-11-22-x86_64-unknown-linux-gnu
   rustup component add rustfmt --toolchain nightly-2021-11-22-x86_64-unknown-linux-gnu
   export PATH=$HOME/.local/bin:$HOME/.cargo/bin:$PATH

   cargo install crusts

else

   docker pull yijun/crusts

fi

用法

在包含 `Makefile` 的文件夹中运行 crusts

crusts [-v | -c2rust]

docker run -v $(pwd):/mnt -t yijun/crusts [-v | -c2rust]

因此,将从 C 代码生成 Rust 代码

src/*.rs -- contains transpiled and refactored Rust code from the C code;
Cargo.toml build.rs lib.rs -- contains the `cargo build` configurations;

选项

  • -v -- 版本信息

  • -c2rust -- 只运行 c2rust

参考文献

  • Michael Ling,Yijun Yu,Haitao Wu,Yuan Wang,James Cordy,Ahmed Hassan. "In Rust We Trust: A transpiler from Unsafe C to Safer Rust", In: Proceedings of ICSE, 2022.
  • 梅赫梅特·埃姆雷,莱恩·施罗德,凯尔·迪韦,本·哈德科普夫。2021。《将C语言翻译为更安全的Rust》。ACM程序语言会议论文集,OOPSLA,文章编号121(2021年10月),29页。(代码
  • TXL
  • C2Rust

更新

  • 与Laertes比较
  • 为Windows用户集成Docker
  • 添加开关-c2rust以关闭重构
  • 添加开关-v以显示版本信息
  • 错误修复:解引用指针,见test_unsafe
  • 错误修复:printf模式,见test_stdio

依赖项

~6–22MB
~328K SLoC