ziglang / zig

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

segfault when calling function from specific api #3297

Open slaide opened 5 years ago

slaide commented 5 years ago

for no apparent reason, a call to xcb_connect causes a segfault (on linux x86_64). exactly the same code succeeds in c++. i do include the same file, link to the same library, and open the file the same way (also built in the same environment, etc.). absolutely no clue what the problem is.

const xcb=@import("xcb.zig"); //also fails if imported from c, untranslated

pub fn main() anyerror!void {
    var connection= xcb.xcb_connect(null, null);
}

zig version: 0.4.0+c5716715

valgrind:

==18659== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==18659== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==18659== Command: zig-cache/bin/temp
==18659== 
==18659== Jump to the invalid address stated on the next line
==18659==    at 0x0: ???
==18659==    by 0x226A7A: std.special.callMain (start.zig:189)
==18659==    by 0x226A7A: std.special.callMainWithArgs (start.zig:158)
==18659==    by 0x226A7A: std.special.posixCallMainAndExit (start.zig:149)
==18659==    by 0x2268FE: _start (start.zig:87)
==18659==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==18659== 
Segmentation fault at address 0x0
Unable to dump stack trace: Unable to open debug info: MissingDebugInfo
andrewrk commented 4 years ago

Can I see xcb.zig and (gdb) disassemble after the segfault?

FireFox317 commented 4 years ago

When trying to reproduce this I found that this segfaults when the user forgets to link to libc (--library c).

Working command: zig build-exe main.zig -isystem /usr/include -L /usr/lib/ --library xcb --library c

Zig file (main.zig):

const xcb = @cImport(@cInclude("xcb/xcb.h"));

pub fn main() void {
    var connection = xcb.xcb_connect(null, null);
}

Edit: When doing zig translate-c /usr/include/xcb/xcb.h on the file without --library c it correctly gives an error about a <sys/types.h> file that cannot be found. However this error is not shown when doing the zig build-exe command without --library c

Edit2: The same fault happens when a user makes a build.zig file and only adds exe.linkSystemLibrary("xcb") and doesn't add exe.linkSystemLibrary("c"). One could imagine that the zig user doesn't know that they have to link to libc.

Vexu commented 1 year ago

I don't think there is a lot Zig can do here. Adding -lxcb also adds all the import directories needed for it so no error is produced. Same thing happens with translate-c if you add -lxcb.