Skip to content

False positives from invalid_reference_casting #124685

Closed
@khuey

Description

@khuey
use std::ptr;

fn apply_mask(array: &mut [u8], offset: usize, mask: u64) {
    assert!(offset + 8 <= array.len());
    let a1 = &mut array[offset];
    let a2 = a1 as *mut u8;
    let a3 = a2 as *mut u64;
    unsafe {
        ptr::write_unaligned(a3, ptr::read_unaligned(a3) | mask);
    };
}

Starting with rustc 1.78.0 (because of #118983) this produces the following

error: casting references to a bigger memory layout than the backing allocation is undefined behavior, even if the reference is unused
 --> src/lib.rs:9:9
  |
5 |     let a1 = &mut array[offset];
  |                   ------------- backing allocation comes from here
6 |     let a2 = a1 as *mut u8;
7 |     let a3 = a2 as *mut u64;
  |              -------------- casting happend here
8 |     unsafe {
9 |         ptr::write_unaligned(a3, ptr::read_unaligned(a3) | mask);
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: casting from `u8` (1 bytes) to `u64` (8 bytes)
  = note: `#[deny(invalid_reference_casting)]` on by default

Perhaps I'm missing something but this is not undefined behavior as far as I can tell. The lint is wrong about the backing allocation and I suspect the false warning is downstream from that?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.C-bugCategory: This is a bug.D-papercutDiagnostics: An error or lint that needs small tweaks.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions