【问题标题】:Is it undefined behavior to mutate an immutable local variable?改变不可变的局部变量是未定义的行为吗?
【发布时间】:2021-02-01 17:48:26
【问题描述】:

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

行为被视为未定义

  • 改变不可变数据。 const 项内的所有数据都是不可变的。此外,通过共享引用获得的所有数据或不可变绑定拥有的数据都是不可变的,除非该数据包含在 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]
}

【问题讨论】:

  • 您正在通过不可变引用&bytes 来改变bytes,您问题中的引用很清楚地表明这是未定义的行为。你还能期待什么?
  • 我只是在寻找对参考文本的确认。你对我的后续代码示例有什么想法吗?
  • 后面的例子很好,因为&AtomicU32是从&mut Bytes派生的。即使bytes 本身被标记为可变,&*(&bytes as *const AtomicU32) 也将是不健全的,因为指针的 provenance 对你可以用它做什么很重要。另请参阅Temporarily opt-in to shared mutation,使用Cell 但不使用unsafe 基本相同。 (不幸的是,Atomics 没有稳定的等价物)

标签: rust immutability undefined-behavior


【解决方案1】:

是的,根据 Miri 的说法:

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

另见:


因为这些字节正在通过共享引用 (&amp;AtomicU32) 进行变异

AtomicU32 contains an UnsafeCell,因此它符合您引用的豁免标准:

        pub struct $atomic_type {
            v: UnsafeCell<$int_type>,
        }

这是作为AtomicU32::from_mut 的API 的一部分,不需要unsafe

【讨论】:

  • 感谢您向我指出一个有用的工具(Miri)。您对我添加到问题中的后续代码示例是否有未定义的行为有任何想法?
猜你喜欢
  • 2019-10-01
  • 2013-04-29
  • 2013-04-24
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-29
  • 1970-01-01
相关资源
最近更新 更多