How do programmers use unsafe rust?

How do programmers use unsafe rust?
复制标题

程序员如何使用不安全的 Rust?

DOI:
--
复制
发表时间:
2020
期刊:
Proc. ACM Program. Lang.
影响因子:
--
通讯作者:
Alexander J. Summers
Alexander J. Summers
中科院分区:
--
文献类型:
--
作者:
Vytautas Astrauskas;Christoph Matheja;F. Poli;Peter Müller;Alexander J. Summers

文献摘要

被引文献

相似文献

Rust 的所有权类型系统对如何访问和共享内存位置强制执行严格的规则。这一规则允许编译器静态地防止内存错误、数据争用、别名造成的无意副作用以及传统命令式程序中经常发生的其他错误。然而,Rust 类型系统施加的限制使得某些设计难以或不可能实现,例如需要别名的数据结构(例如双向链表和共享缓存)。为了解决这个限制,Rust 允许将代码块声明为不安全,从而免除类型系统的某些限制,例如操作 C 风格的原始指针。确保不安全代码的安全是程序员的责任。然而,Rust 语言的一个重要假设,我们称之为 Rust 假设,是程序员通过遵循三个主要原则来使用 Rust:谨慎使用不安全代码,使其易于审查,并将其隐藏在安全抽象后面,以便可以用安全 Rust 编写客户端代码。了解 Rust 程序员如何使用不安全代码,特别是 Rust 假设是否成立,对于 Rust 开发人员和测试人员、语言和库设计人员以及工具开发人员至关重要。本文通过分析大量 Rust 项目来实证研究不安全代码在实践中的使用情况,以评估 Rust 假设的有效性并对不安全代码的目的进行分类。我们通过自动检查程序的源代码、其中间表示 MIR 以及 Rust 编译器提供的类型信息来识别可以回答的查询;我们通过手动代码检查来补充结果。我们的研究部分支持 Rust 假设:虽然大多数不安全代码都很简单且封装良好,但不安全功能被广泛使用,尤其是与其他语言的互操作性。
Rust’s ownership type system enforces a strict discipline on how memory locations are accessed and shared. This discipline allows the compiler to statically prevent memory errors, data races, inadvertent side effects through aliasing, and other errors that frequently occur in conventional imperative programs. However, the restrictions imposed by Rust’s type system make it difficult or impossible to implement certain designs, such as data structures that require aliasing (e.g. doubly-linked lists and shared caches). To work around this limitation, Rust allows code blocks to be declared as unsafe and thereby exempted from certain restrictions of the type system, for instance, to manipulate C-style raw pointers. Ensuring the safety of unsafe code is the responsibility of the programmer. However, an important assumption of the Rust language, which we dub the Rust hypothesis, is that programmers use Rust by following three main principles: use unsafe code sparingly, make it easy to review, and hide it behind a safe abstraction such that client code can be written in safe Rust. Understanding how Rust programmers use unsafe code and, in particular, whether the Rust hypothesis holds is essential for Rust developers and testers, language and library designers, as well as tool developers. This paper studies empirically how unsafe code is used in practice by analysing a large corpus of Rust projects to assess the validity of the Rust hypothesis and to classify the purpose of unsafe code. We identify queries that can be answered by automatically inspecting the program’s source code, its intermediate representation MIR, as well as type information provided by the Rust compiler; we complement the results by manual code inspection. Our study supports the Rust hypothesis partially: While most unsafe code is simple and well-encapsulated, unsafe features are used extensively, especially for interoperability with other languages.