Rollup merge of #92704 - 5225225:std_mem_transmute_ref_t_mut_t, r=michaelwoerister

Change lint message to be stronger for &T -> &mut T transmute

The old message implied that it's only UB if you use the reference to mutate, which (as far as I know) is not true. As in, the following program has UB, and a &T -> &mut T transmute is effectively an `unreachable_unchecked`.

```rust
fn main() {
    #[allow(mutable_transmutes)]
    unsafe {
        let _ = std::mem::transmute::<&i32, &mut i32>(&0);
    }
}
```

In the future, it might be a good idea to use the edition system to make this a hard error, since I don't think it is *ever* defined behaviour? Unless we rule that `&UnsafeCell<i32> -> &mut i32` is fine. (That, and you always could just use `.get()`, so you're not losing anything)
This commit is contained in:
Matthias Krüger 2022-01-20 17:10:37 +01:00 committed by GitHub
commit 5c10dbd85f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 5 additions and 5 deletions

View file

@ -1247,7 +1247,7 @@ declare_lint! {
/// [`UnsafeCell`]: https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html
MUTABLE_TRANSMUTES,
Deny,
"mutating transmuted &mut T from &T may cause undefined behavior"
"transmuting &T to &mut T is undefined behavior, even if the reference is unused"
}
declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
@ -1259,8 +1259,8 @@ impl<'tcx> LateLintPass<'tcx> for MutableTransmutes {
get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (ty1.kind(), ty2.kind()))
{
if to_mt == hir::Mutability::Mut && from_mt == hir::Mutability::Not {
let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
consider instead using an UnsafeCell";
let msg = "transmuting &T to &mut T is undefined behavior, \
even if the reference is unused, consider instead using an UnsafeCell";
cx.struct_span_lint(MUTABLE_TRANSMUTES, expr.span, |lint| lint.build(msg).emit());
}
}

View file

@ -4,5 +4,5 @@ use std::mem::transmute;
fn main() {
let _a: &mut u8 = unsafe { transmute(&1u8) };
//~^ ERROR mutating transmuted &mut T from &T may cause undefined behavior
//~^ ERROR transmuting &T to &mut T is undefined behavior, even if the reference is unused, consider instead using an UnsafeCell
}

View file

@ -1,4 +1,4 @@
error: mutating transmuted &mut T from &T may cause undefined behavior, consider instead using an UnsafeCell
error: transmuting &T to &mut T is undefined behavior, even if the reference is unused, consider instead using an UnsafeCell
--> $DIR/transmute-imut-to-mut.rs:6:32
|
LL | let _a: &mut u8 = unsafe { transmute(&1u8) };