ziglang / zig

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

Unreachable at zig-0.8.0/src/stage1/ir.cpp:22346 in buf_write_value_bytes #9401

Open toffaletti opened 3 years ago

toffaletti commented 3 years ago

Given this code in a file named ptr_cast_crasher.zig:

const std = @import("std");
const assert = std.debug.assert;

const Header = packed struct {
    a: u32,
    b: u32,
};

const data = @embedFile("./ptr_cast_crasher.zig");

pub fn main() void {
    const hdr = @ptrCast(*const Header, &data[0..8]);
    assert(hdr.a != 0x1020020);
}
% zig build-exe ./ptr_cast_crasher.zig
Unreachable at /tmp/zig-20210605-55791-tdqqwr/zig-0.8.0/src/stage1/ir.cpp:22346 in buf_write_value_bytes. This is a bug in the Zig compiler.thread 1156087 panic: 
Unable to dump stack trace: debug info stripped
zsh: abort      zig build-exe ./ptr_cast_crasher.zig

This code can be modified to crash in other ways as well, for example, if we change &data[0..8] to data[0..8]:

const std = @import("std");
const assert = std.debug.assert;

const Header = packed struct {
    a: u32,
    b: u32,
};

const data = @embedFile("./ptr_cast_crasher.zig");

pub fn main() void {
    const hdr = @ptrCast(*const Header, data[0..8]);
    assert(hdr.a != 0x1020020);
}
% zig build-exe ./ptr_cast_crasher.zig
zsh: segmentation fault  zig build-exe ./ptr_cast_crasher.zig
toffaletti commented 3 years ago

I suspect this might be related to https://github.com/ziglang/zig/issues/4680

tau-dev commented 3 years ago

I suspect I'm encountering the same or a closely related issue, without even using @embedFile (which might suggest it's not closely tied to #4680):

pub fn main() anyerror!void {
    _ = length_codes[0];
}

const length_codes = blk: {
    var codes: [2]SomeStruct = undefined;
    for (codes[0..1]) |_| {
    }
    break :blk codes;
};

const SomeStruct = struct {
    val: u64,
};
$ zig version
0.9.0-dev.1679+6cf8a49bb
$ zig build-exe src/main.zig
Unreachable at /home/tau/foreign/zig/src/stage1/ir.cpp:22940 in buf_write_value_bytes. This is a bug in the Zig compiler.

This occurs whether I set the array to undefined or initialize it explicitly, but only if its length is greater than 1. Does anyone have a workaround for the issue?

[EDIT 2021-11-19: still broken on current master.]

toffaletti commented 2 years ago

~For what its worth, I no longer encounter this in 0.8.1 on an M1 Mac.~ I spoke too soon. I found a case where removing my work around triggers it still.

RetroDev256 commented 3 days ago

This looks like the same bug as #10024