Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

We are computing the wrong offsets for unsized packed structs #3200

Closed
RalfJung opened this issue Dec 2, 2023 · 1 comment · Fixed by rust-lang/rust#118540
Closed

We are computing the wrong offsets for unsized packed structs #3200

RalfJung opened this issue Dec 2, 2023 · 1 comment · Fixed by rust-lang/rust#118540

Comments

@RalfJung
Copy link
Member

RalfJung commented Dec 2, 2023

This assertion passes with rustc but not with Miri:

use std::mem;

#[repr(packed, C)]
struct PackedSized {
    f: u8,
    d: [u32; 4],
}

#[repr(packed, C)]
struct PackedUnsized {
    f: u8,
    d: [u32],
}

impl PackedSized {
    fn unsize(&self) -> &PackedUnsized {
        // We can't unsize via a generic type since then we get the error
        // that packed structs with unsized tail don't work if the tail
        // might need dropping.
        let len = 4usize;
        unsafe { mem::transmute((self, len)) }
    }
}

fn main() { unsafe {
    let p = PackedSized { f: 0, d: [1, 2, 3, 4] };
    let p = p.unsize() as *const PackedUnsized;
    let d = std::ptr::addr_of!((*p).d);
    assert_eq!(d.cast::<u32>().read_unaligned(), 1);
} }
@RalfJung
Copy link
Member Author

RalfJung commented Dec 2, 2023

rustc has the same issue when we change the code a bit: rust-lang/rust#118537.

rust-timer added a commit to rust-lang-ci/rust that referenced this issue Dec 4, 2023
Rollup merge of rust-lang#118540 - RalfJung:unsized-packed-offset, r=TaKO8Ki

codegen, miri: fix computing the offset of an unsized field in a packed struct

`#[repr(packed)]`  strikes again.

Fixes rust-lang#118537
Fixes rust-lang/miri#3200

`@bjorn3` I assume cranelift needs the same fix.
github-actions bot pushed a commit that referenced this issue Dec 5, 2023
codegen, miri: fix computing the offset of an unsized field in a packed struct

`#[repr(packed)]`  strikes again.

Fixes rust-lang/rust#118537
Fixes #3200

`@bjorn3` I assume cranelift needs the same fix.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant