rust - 改变不可变的局部变量是未定义的行为吗?

标签 rust immutability undefined-behavior

The Rust Reference似乎在说改变不可变的本地数据(不在 UnsafeCell 内)是未定义的行为:

Behavior considered undefined

  • Mutating immutable data. All data inside a const item is immutable. Moreover, all data reached through a shared reference or data owned by an immutable binding is immutable, unless that data is contained within an UnsafeCell<U>.

下面的代码通过将一个不可变的局部变量重新解释为 AtomicU32 来改变它.目前代码运行得很好并打印了预期的结果,但它的行为实际上是未定义的吗?
use std::sync::atomic::{AtomicU32, Ordering};

#[repr(C, align(4))]
struct Bytes([u8; 4]);

fn main() {
    let bytes = Bytes([11; 4]);
    let x = unsafe { &*(&bytes as *const Bytes as *const AtomicU32) };
    x.store(12345, Ordering::SeqCst);
    println!("{:?}", bytes.0); // [57, 48, 0, 0]
}
Miri 不会提示下面的代码示例,其中字节是可变的。由于这些字节是通过共享引用( &AtomicU32 )进行变异的,在我看来,根据 The Rust Reference,下面的代码也应该具有未定义的行为 - 鉴于“通过共享引用 [..] 到达的所有数据是不可变”和“改变不可变数据[被认为是未定义的行为]”。
use std::sync::atomic::{AtomicU32, Ordering};

#[repr(C, align(4))]
struct Bytes([u8; 4]);

fn main() {
    let mut bytes = Bytes([11; 4]);
    let x = unsafe { &*(&mut bytes as *mut Bytes as *const AtomicU32) };
    x.store(12345, Ordering::SeqCst);
    println!("{:?}", bytes.0); // [57, 48, 0, 0]
}

最佳答案

,根据美里的说法:

error: Undefined Behavior: trying to reborrow for SharedReadWrite at alloc1377, but parent tag <untagged> does not have an appropriate item in the borrow stack
 --> src/main.rs:8:22
  |
8 |     let x = unsafe { &*(&bytes as *const Bytes as *const AtomicU32) };
  |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ trying to reborrow for SharedReadWrite at alloc1377, but parent tag <untagged> does not have an appropriate item in the borrow stack
  |
  = help: this indicates a potential bug in the program: it performed an invalid operation, but the rules it violated are still experimental
  = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information
          
  = note: inside `main` at src/main.rs:8:22
  = note: inside `<fn() as std::ops::FnOnce<()>>::call_once - shim(fn())` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:227:5
  = note: inside `std::sys_common::backtrace::__rust_begin_short_backtrace::<fn(), ()>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/sys_common/backtrace.rs:125:18
  = note: inside closure at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/rt.rs:66:18
  = note: inside `std::ops::function::impls::<impl std::ops::FnOnce<()> for &dyn std::ops::Fn() -> i32 + std::marker::Sync + std::panic::RefUnwindSafe>::call_once` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:259:13
  = note: inside `std::panicking::r#try::do_call::<&dyn std::ops::Fn() -> i32 + std::marker::Sync + std::panic::RefUnwindSafe, i32>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/panicking.rs:379:40
  = note: inside `std::panicking::r#try::<i32, &dyn std::ops::Fn() -> i32 + std::marker::Sync + std::panic::RefUnwindSafe>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/panicking.rs:343:19
  = note: inside `std::panic::catch_unwind::<&dyn std::ops::Fn() -> i32 + std::marker::Sync + std::panic::RefUnwindSafe, i32>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/panic.rs:396:14
  = note: inside `std::rt::lang_start_internal` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/rt.rs:51:25
  = note: inside `std::rt::lang_start::<()>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/rt.rs:65:5
也可以看看:
  • Can an FFI function modify a variable that wasn't declared mutable?
  • Do aliasing mutable raw pointers (*mut T) cause undefined behaviour?

  • since those bytes are being mutated through a shared reference (&AtomicU32)


    AtomicU32 contains an UnsafeCell ,因此它符合您引用的豁免标准:
            pub struct $atomic_type {
                v: UnsafeCell<$int_type>,
            }
    
    这是 API 的一部分,如 AtomicU32::from_mut ,不需要 unsafe .

    关于rust - 改变不可变的局部变量是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65997647/

    相关文章:

    rust - 为什么 Rust 无法识别我在闭包内重新分配给移动的变量?

    javascript - 嵌套的纯函数还是纯函数吗?

    c# - 在 C# 中创建不可变类的最简洁方法是什么?

    c++ - 派生类没有额外的数据成员;将基对象静态向下转换为派生对象是否安全?

    erlang - Erlang 中的函数相等和排序

    rust - 对 Box 中结构字段的移动语义感到困惑

    rust - T <'a>: ' b 是 'a: ' b 的语法糖吗?

    rust - 使用迭代器作为来自一个向量的函数的参数多次

    java - 为什么可变字符串会导致安全问题?

    c++ - 左值引用是否隐藏了未定义的行为?