gpt4 book ai didi

rust - Release模式下安全 Rust 中的有符号整数溢出是否被视为未定义行为?

转载 作者:行者123 更新时间:2023-12-01 11:11:11 29 4
gpt4 key购买 nike

Rust 在调试和 Release模式下以不同的方式处理有符号整数溢出。当它发生时,Rust 在 Debug模式下会发生 panic ,而在 Release模式下默默地执行二进制补码包装。

据我所知,C/C++ 将有符号整数溢出视为未定义行为,部分原因是:

  • 在 C 标准化的那个时候,表示有符号整数的不同底层体系结构,例如补码,可能仍在某处使用。编译器无法假设硬件中如何处理溢出。
  • 后来的编译器因此做出假设,例如两个正整数之和也必须为正数才能生成优化的机器代码。

  • 因此,如果 Rust 编译器确实在有符号整数方面执行与 C/C++ 编译器相同类型的优化,那么为什么 The Rustonomicon 指出:

    No matter what, Safe Rust can't cause Undefined Behavior.



    或者即使 Rust 编译器不执行这样的优化,Rust 程序员仍然不希望看到有符号整数环绕。不能称为“未定义行为”吗?

    最佳答案

    Q: So if Rust compilers do perform the same kind of optimization as C/C++ compilers regarding signed integers



    rust 没有。因为,正如您所注意到的,它无法执行这些优化,因为整数溢出是明确定义的。

    对于 Release模式的添加,Rust 将发出以下 LLVM 指令(您可以查看 on Playground):

    add i32 %b, %a

    另一方面,clang 将发出以下 LLVM 指令(您可以通过 clang -S -emit-llvm add.c 查看):

    add nsw i32 %6, %8

    区别在于 nsw (无签名包装)标志。按照规定 in the LLVM reference about add :

    If the sum has unsigned overflow, the result returned is the mathematical result modulo 2n, where n is the bit width of the result.

    Because LLVM integers use a two’s complement representation, this instruction is appropriate for both signed and unsigned integers.

    nuw and nsw stand for “No Unsigned Wrap” and “No Signed Wrap”, respectively. If the nuw and/or nsw keywords are present, the result value of the add is a poison value if unsigned and/or signed overflow, respectively, occurs.



    毒值是导致未定义行为的原因。如果标志不存在,则结果很好地定义为 2 的补码包装。

    Q: Or even if Rust compilers do not perform such optimization, Rust programmers still do not anticipate seeing a signed integer wrapping around. Can't it be called "undefined behavior"?



    在此上下文中使用的“未定义行为”具有非常具体的含义,与这两个词的直观英文含义不同。 UB 在这里具体意味着编译器可以假设永远不会发生溢出,并且如果发生溢出,则允许任何程序行为。这不是 Rust 规定的。

    然而,通过算术运算符的整数溢出被认为是 Rust 中的一个错误。那是因为,正如你所说,它通常是无法预料的。如果你有意想要包装行为,可以使用诸如 i32::wrapping_add 之类的方法。 .

    一些额外的资源:
  • RFC 560指定关于 Rust 中整数溢出的所有内容。简而言之: Debug模式下的 panic , Release模式下的 2 的补码包装。
  • Myths and Legends about Integer Overflow in Rust .关于这个话题的好博文。
  • 关于rust - Release模式下安全 Rust 中的有符号整数溢出是否被视为未定义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60238060/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com