一句话:实证研究 Rust unsafe 代码的必要性,发现大量非必要使用,并设计 IDE 插件自动建议安全替代方案。
Rust 的 unsafe 块允许底层控制但放弃安全保证,原则上应仅在必要时使用,但已有迹象表明实际并非如此。本文对 140 个流行库和应用中的 5946 个 unsafe 块进行人工审查,判断其是否存在安全替代,从而评估使用的必要性。研究发现数百个不必要的 unsafe 实例,并给出分类体系与详细分析。基于此,作者总结九类常见的不必要 unsafe 模式,设计 IDE 插件自动推荐安全替代方案。将该插件应用于 RustSec Advisory Database 中 140 个有缺陷的 unsafe 块,在 28.6% 的案例中识别并提供可消除缺陷的安全版本。
Rust offers both safety guarantees and high performance. Thus, it has gained significant popularity in the industry. To extend its capability as a system programming language, Rust allows unsafe blocks where the execution has low-level controls but loses the safety guarantees. In principle, unsafe blocks should only be used when necessary. However, preliminary evidence shows a different situation. This paper aims to establish a deeper view of this matter and bring endeavors toward improvement. We first present a study on the use of unsafe Rust in practice. We manually inspected 5946 unsafe blocks from 140 popular libraries and applications, focusing on whether the use of unsafe code is necessary (precisely, whether they have safe alternatives). The study unveils hundreds of instances of unnecessary unsafe Rust code and provides a taxonomy together with detailed analyses. These results complement our understanding and offer insights for the community to make a change. Following the study, we further summarize nine popular patterns of unnecessary unsafe blocks and design an IDE plugin to auto-suggest their safe alternatives. Applied to 140 buggy unsafe blocks from the RustSec Advisory Database, the plugin identifies and offers safe versions to remove the bug for 28.6% of all cases.