Skip to content

ELF exe missing interpreter when linking to locally defined shared library in build.zig #6368

@marler8997

Description

@marler8997

The following files reproduce an issue where I have both a shared library and an executable in the same build.zig file with the exe linking to the shared library, but the resulting ELF executable is missing an interpreter/loader. However, the exe is specifically linking to the LibExeObjStep that was created with addSharedLibrary, so build.zig should know that the exe needs a loader. Running the resulting exe creates a seg fault with an "InvalidExe" error when it is unwrapped. Note that if I link a system library like exe.linkSystemLibrary("c"), then Zig now knows the exe needs to be dynamic and it works correctly.

build.zig:

const std = @import("std");
const Builder = std.build.Builder;

pub fn build(b: *Builder) !void {
    const mode = b.standardReleaseOptions();
    const target = b.standardTargetOptions(.{});
    const lib = b.addSharedLibrary("foo", "foo.zig", b.version(0, 0, 0));
    lib.setBuildMode(mode);
    lib.setTarget(target);
    lib.install();

    const exe = b.addExecutable("app", "app.zig");
    exe.setBuildMode(mode);
    exe.setTarget(target);
    exe.linkLibrary(lib);
    // uncomment this line to show it works around the issue
    //exe.linkSystemLibrary("c");
    exe.install();
}

foo.zig:

export fn foopassthru(x: i32) i32 {
    return x;
}

app.zig:

const std = @import("std");

extern fn foopassthru(i32) i32;

pub fn main() void {
    std.debug.warn("in main\n", .{});
    std.debug.warn("foopassthru(1234) = {}\n", .{foopassthru(1234)});
    std.debug.warn("Success\n", .{});
}
$ zig build
$ ./zig-cache/bin/app
in main
Segmentation fault at address 0x0
attempt to unwrap error: InvalidExe
Panicked during a panic. Aborting.
Aborted (core dumped)
$ patchelf --print-interpreter zig-cache/bin/app
cannot find section .interp

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behavior

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions