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

packed struct can not handle arbitrary bit-width integers (more than 16 bit) correctly #5451

Closed
WoodyAtHome opened this issue May 27, 2020 · 4 comments

Comments

@WoodyAtHome
Copy link

@WoodyAtHome WoodyAtHome commented May 27, 2020

zig version 0.6.0+e1186c88e

const std = @import("std");

pub fn main() void {
    const Can = packed struct {
        const CR = packed struct {
            init: u1, lo: u1, mode: u3, reserved1: u3, reserved2: u17
        };
        cr: CR,
    };

    var can = Can{
        .cr = Can.CR{
            .init = 1,
            .lo = 0,
            .mode = 7,
            .reserved1 = 0,
            .reserved2 = 0,
        },
    };
    std.debug.warn("sizeOf(Can.CR) = {} bytes.\n", .{@sizeOf(Can.CR)});
}

Now play with the size of reserved2.

reserved2: u1..u16: Compiler and sizeOf output ok.

reserved2: u17..u23: strange compiler output and sizeOf(Can.CR) should be 4 bytes.

zig run main.zig 
<unknown>:0: error: invalid number of bytes
<unknown>:0: error: invalid number of bytes
sizeOf(Can.CR) = 5 bytes.

reserved2: u24: compiler crashes

zig run main.zig 
Assertion failed at /deps/zig/src/analyze.cpp:8386 in resolve_llvm_types_struct. This is a bug in the Zig compiler.
Unable to dump stack trace: debug info stripped

reserved2: u25:Compiler and sizeOf output ok.

@pixelherodev
Copy link
Contributor

@pixelherodev pixelherodev commented May 27, 2020

This is a known bug, I believe, though I do not remember the exact issue off-hand. If you search for "packed," you'll notice a number of bugs :(

@WoodyAtHome
Copy link
Author

@WoodyAtHome WoodyAtHome commented May 27, 2020

I couldn't find this bug I searched before.

@WoodyAtHome
Copy link
Author

@WoodyAtHome WoodyAtHome commented May 27, 2020

My workaround is now to use

reserved21: u8,
reserved22: u8,
reserved23: u8,

insteadof
reserved2: u24

@MasterQ32
Copy link
Contributor

@MasterQ32 MasterQ32 commented May 27, 2020

Yes this is a known issue, see #2627 and #3133

@Vexu Vexu closed this Jun 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants