ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
33.71k stars 2.47k forks source link

Packed struct bug. #20938

Open fubark opened 1 month ago

fubark commented 1 month ago

Zig Version

0.14.0-dev.839+a931bfada

Steps to Reproduce and Observed Behavior

const std = @import("std");

pub const Foo = packed struct {
    a: u31,
    b: bool,

    pub fn init() Foo {
        return .{ .a = undefined, .b = true };
    }
};

pub fn foo(a: Foo) void {
    std.debug.print("{} {b}\n", .{a.b, @as(u32, @bitCast(a))});
    // Expected "true", and a non zero value
    // Found "false", 0
}

pub fn main() !void {
    const a = Foo.init();
    foo(a);
}

Expected Behavior

There seems to be an issue with passing a packed struct into a function when the first field is initialized as undefined.

sno2 commented 1 month ago

I am able to reproduce this on windows without the foo function:

const std = @import("std");

pub const Foo = packed struct {
    a: u31,
    b: bool,

    pub fn init() Foo {
        return .{ .a = undefined, .b = true };
    }
};

pub fn main() !void {
    const a = Foo.init();
    std.debug.print("{} {b}\n", .{a.b, @as(u32, @bitCast(a))});
    // Expected "true", and a non zero value
    // Found "false", 0
}
$ zig run foo.zig
true 10111000111110011110110010010000
$ zig run foo.zig
false 10111010011011010010010110000
Vexu commented 1 month ago

Duplicate of #20095

sno2 commented 1 month ago

@Vexu I don't believe this is a duplicate. #20095 is about reading undefined fields, but we are reading a field that has been set to true and seeing undefined behavior.

sno2 commented 1 month ago

I believe this issue is only in the llvm backend:

    const exe = b.addExecutable(.{
        .name = "foo2",
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
        .use_llvm = false,
    });
true 10000000000000000000000000000000
true 10000000000000000000000000000000
true 10000000000000000000000000000000
true 10000000000000000000000000000000
Vexu commented 1 month ago

I'd expect it to be caused by the same issue but we can keep this open too.