如果您只是将数据视为字节,那么使用 Rust 的 memmap 是否安全?

Is Rust's memmap safe to use if you're just treating the data as bytes?

Rust 的 memmap crateunsafe 方法。

我能理解返回的地址 space 传递给可能会验证其内容然后继续使用它的构造函数是不安全的。

我正在编写一个二进制差异工具,它只将返回的地址 space 视为包含字节(任何值)并且不验证地址 space 的内容。

在这种情况下,我可以避免传播 unsafe 吗?

遗憾的是 memmap 没有记录其安全契约。确实在这一点上有an open issue from 2017

我关注了 this discussion in the RustSec/advisory-db repo re the crate's apparent abandonment to this safety documentation in the forked mapr crate,其中指出:

All file-backed memory map constructors are marked unsafe because of the potential for Undefined Behavior (UB) using the map if the underlying file is subsequently modified, in or out of process. Applications must consider the risk and take appropriate precautions when using file-backed maps. Solutions such as file permissions, locks or process-private (e.g. unlinked) files exist but are platform specific and limited.

这个安全问题显然也应该与 memmap 相关。

正确使用 unsafe 的主要原则之一是您有责任确保所有受影响代码的健全性 - 包括它周围的 safe 代码。

如果您要在库 crate 中公开此函数,则应将其标记为 unsafe;您图书馆的用户需要了解 UB 的产生位置,并自行做出有关安全的决定。

在应用程序箱中,您可以控制所有代码,并且永远不要将字节取消引用为任何其他内容。如果你这样做,将 unsafe 代码限制在你直接与内存映射交互的地方是完全可以接受的,包装在安全函数中。事实上,将所有东西包裹在unsafe中会适得其反,因为它会不清楚危险在哪里。