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

incorrect handling of [repr(packed)] and [repr(align(n)] struct attributes #3260

Open
nobel-sh opened this issue Nov 22, 2024 · 0 comments
Open

Comments

@nobel-sh
Copy link
Contributor

In Rust, the #[repr(packed)] attribute is intended to remove padding between struct fields. Similarly, #[repr(align(n))] is used to adjust the alignment of a struct to n bytes. However, in the case of gccrs, it appears that these attributes are not fully respected.

// uncomment commented code to run with gccrs

// #![feature(intrinsics)]
// #[lang = "sized"]
// pub trait Sized {}

// extern "rust-intrinsic" {
//     fn size_of<T>() -> usize;
// }

extern "C"{
    fn printf(format: *const i8, ...);
}


#[repr(packed)]
struct StructPacked {
    flag: bool,
    number: i32,
    data: [u8; 16],
}

#[repr(align(16))]
struct StructAligned {
    flag: bool,
    number: i32,
    data: [u8; 16],
}

fn main(){
    let matrix = [[1.0; 4]; 4];
    let data = [0u8; 16];

    let struct_packed = StructPacked {
        flag: true,
        number: 42,
        data,
    };

    let struct_aligned = StructAligned {
        flag: true,
        number: 42,
        data,
    };

    println!("StructPacked: {}", size_of::<StructPacked>());
    println!("StructAligned: {}", size_of::<StructAligned>());

    // uncomment below for gccrs

    // unsafe{
    //     printf(
    //         "StructPacked: %zu\n\0" as *const str as *const i8,
    //         size_of::<StructPacked>(),
    //     );
    //     printf(
    //         "StructAligned: %zu\n\0" as *const str as *const i8,
    //         size_of::<StructAligned>(),
    //     );
    // }
}

rustc:

StructPacked: 21
StructAligned: 32

gccrs:

StructPacked: 24
StructAligned: 24

godbolt: https://godbolt.org/z/rornPra3c

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

No branches or pull requests

1 participant