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

Linking with objective-c causes bus error on macOS #6337

Closed
schroffl opened this issue Sep 14, 2020 · 6 comments
Closed

Linking with objective-c causes bus error on macOS #6337

schroffl opened this issue Sep 14, 2020 · 6 comments
Labels
bug Observed behavior contradicts documented or intended behavior os-macos upstream An issue with a third party project that Zig uses.
Milestone

Comments

@schroffl
Copy link
Contributor

schroffl commented Sep 14, 2020

I'm trying to write some macOS-specific code in objective-c and include that in my Zig application. However, the following simple setup causes a crash when building.

build.zig

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

pub fn build(b: *Builder) void {
    var exe = b.addExecutable("zig-macos-objc", "src/main.zig");

    // Compiles the objective-c code into `./objc.o`
    var compile_objc = b.addSystemCommand(&[_][]const u8{
        "clang",
        "-c",
        "src/objc.m",
    });

    exe.addFrameworkDir("/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/");
    exe.linkFramework("Foundation");
    exe.addObjectFile("./objc.o");
    exe.step.dependOn(&compile_objc.step);

    // Everything from here on is as emitted by `zig init-exe`

    const target = b.standardTargetOptions(.{});
    const mode = b.standardReleaseOptions();

    exe.setTarget(target);
    exe.setBuildMode(mode);
    exe.install();

    const run_cmd = exe.run();
    run_cmd.step.dependOn(b.getInstallStep());

    const run_step = b.step("run", "Run the app");
    run_step.dependOn(&run_cmd.step);
}

src/objc.m

#import <Foundation/Foundation.h>

extern void my_objc_function() {
    NSLog(@"All your codebase are belong to us.");
}

src/main.zig

extern fn my_objc_function() void;

pub fn main() void {
    my_objc_function();
}

This is what caused the crash according to the macOS Console:

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   libsystem_platform.dylib      	0x00007fff70973470 _platform_memcmp + 208
1   zig                           	0x000000010c63301e lld::mach_o::normalized::MachOFileLayout::buildFileOffsets() + 894

Zig-Version: 0.6.0+c49435f76
macOS Version: 10.15.6

If any other information like the output fromzig build --verbose-link is needed I can add that as well.


Edit: By manually using ld I was able to link a working binary.

@andrewrk andrewrk added os-macos upstream An issue with a third party project that Zig uses. bug Observed behavior contradicts documented or intended behavior labels Oct 4, 2020
@andrewrk andrewrk added this to the 0.8.0 milestone Oct 4, 2020
@andrewrk
Copy link
Member

andrewrk commented Oct 4, 2020

#5828 (comment)

@andrewrk andrewrk modified the milestones: 0.8.0, 0.9.0 Nov 6, 2020
@fabioarnold
Copy link
Contributor

fabioarnold commented Dec 28, 2020

Just tried this with Zig version 0.7.1+f75d4cbe5 and it works. I'm on macOS 11.1 arm64. @kubkon can this issue be closed?

Edit:
Had to add -isysroot in build.zig

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

pub fn build(b: *Builder) void {
    var exe = b.addExecutable("zig-macos-objc", "src/main.zig");

    // Compiles the objective-c code into `./objc.o`
    var compile_objc = b.addSystemCommand(&[_][]const u8{
        "clang",
        "-isysroot", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk",
        "-c", "src/objc.m",
    });

    exe.addFrameworkDir("/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/");
    exe.linkFramework("Foundation");
    exe.addObjectFile("./objc.o");
    exe.step.dependOn(&compile_objc.step);

    // Everything from here on is as emitted by `zig init-exe`

    const target = b.standardTargetOptions(.{});
    const mode = b.standardReleaseOptions();

    exe.setTarget(target);
    exe.setBuildMode(mode);
    exe.install();

    const run_cmd = exe.run();
    run_cmd.step.dependOn(b.getInstallStep());

    const run_step = b.step("run", "Run the app");
    run_step.dependOn(&run_cmd.step);
}

@kubkon
Copy link
Member

kubkon commented Jan 1, 2021

Hmm, I'm surprised this works for you @fabioarnold. I get a linker error:

warning(link): unexpected LLD stderr:
ld64.lld: error: Unable to find framework for -framework Foundation

attempt to unwrap error: FileNotFound
/Users/kubkon/dev/zig/src/main.zig:2027:87: 0x1027caae3 in main.cmdTranslateC (zig1)
        const new_argv_with_sentinel = try arena.alloc(?[*:0]const u8, argv.items.len + 1);
                                                                                      ^
/Users/kubkon/dev/zig/src/main.zig:1787:31: 0x10272057b in main.buildOutputType (zig1)
            .no => break :blk .none,
                              ^
/Users/kubkon/dev/zig/src/main.zig:125:49: 0x1026f98d7 in main.mainArgs (zig1)
    if (std.process.can_execv and std.os.getenvZ("ZIG_IS_DETECTING_LIBC_PATHS") != null) {
                                                ^
/Users/kubkon/dev/zig/lib/std/heap.zig:142:46: 0x1026f6c63 in std.heap.CAllocator.resize (zig1)
            const full_len = alignedAllocSize(buf.ptr);
                                             ^
/Users/kubkon/dev/zig/lib/std/heap.zig:142:46: 0x1026f6c63 in std.heap.CAllocator.resize (zig1)
            const full_len = alignedAllocSize(buf.ptr);
                                             ^
/Users/kubkon/dev/zig/lib/std/heap.zig:142:46: 0x1026f6c63 in std.heap.CAllocator.resize (zig1)
            const full_len = alignedAllocSize(buf.ptr);
                                             ^
/Users/kubkon/dev/zig/lib/std/heap.zig:142:46: 0x1026f6c63 in std.heap.CAllocator.resize (zig1)
            const full_len = alignedAllocSize(buf.ptr);
                                             ^
/Users/kubkon/dev/zig/lib/std/array_list.zig:151:25: 0x10293536f in std.array_list.ArrayListAligned(std.dwarf.FileEntry,null).append (zig1)
            new_item_ptr.* = item;
                        ^
/Users/kubkon/dev/zig/lib/std/array_list.zig:393:0: 0x1028aa693 in std.array_list.ArrayListAlignedUnmanaged(u8,null).deinit (zig1)
        pub fn deinit(self: *Self, allocator: *Allocator) void {

/Users/kubkon/dev/zig/lib/std/crypto/sha2.zig:148:14: 0x1028aa3cb in std.crypto.sha2.Sha2x32((struct std.crypto.sha2.Sha2Params32 constant)).final (zig1)
            d.buf_len += 1;
             ^
/Users/kubkon/dev/zig/lib/std/crypto/sha2.zig:144:30: 0x1028aa35f in std.crypto.sha2.Sha2x32((struct std.crypto.sha2.Sha2Params32 constant)).final (zig1)
            mem.set(u8, d.buf[d.buf_len..], 0);
                             ^
/Users/kubkon/dev/zig/lib/std/base64.zig:54:23: 0x10287029b in std.base64.Base64Encoder.encode (zig1)
            out_index += 1;
                      ^
/Users/kubkon/dev/zig/lib/std/crypto/sha2.zig:272:185: 0x102a24fbb in std.crypto.sha2.Sha2x32((struct std.crypto.sha2.Sha2Params32 constant)).round (zig1)
                v[r.h] = v[r.h] +% (math.rotr(u32, v[r.a], @as(u32, 2)) ^ math.rotr(u32, v[r.a], @as(u32, 13)) ^ math.rotr(u32, v[r.a], @as(u32, 22))) +% ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c]));
                                                                                                                                                                                        ^
/Users/kubkon/dev/zig/src/link/MachO/CodeSignature.zig:163:32: 0x1028aa893 in link.MachO.CodeSignature.writeHeader (zig1)
    mem.writeIntBig(u32, buffer[8..12], self.inner.count);
                               ^
/Users/kubkon/dev/zig/lib/std/fmt.zig:360:13: 0x10282204b in std.fmt.format (zig1)
            writer,
            ^
/Users/kubkon/dev/zig/lib/std/heap.zig:142:46: 0x1026f6c63 in std.heap.CAllocator.resize (zig1)
            const full_len = alignedAllocSize(buf.ptr);
                                             ^
/Users/kubkon/dev/zig/lib/std/heap.zig:142:46: 0x1026f6c63 in std.heap.CAllocator.resize (zig1)
            const full_len = alignedAllocSize(buf.ptr);
                                             ^
/Users/kubkon/dev/zig/lib/std/heap.zig:142:46: 0x1026f6c63 in std.heap.CAllocator.resize (zig1)
            const full_len = alignedAllocSize(buf.ptr);
                                             ^
/Users/kubkon/dev/zig/lib/std/array_list.zig:151:25: 0x10293536f in std.array_list.ArrayListAligned(std.dwarf.FileEntry,null).append (zig1)
            new_item_ptr.* = item;
                        ^
/Users/kubkon/dev/zig/lib/std/heap/arena_allocator.zig:73:42: 0x1027b4dcb in std.heap.arena_allocator.ArenaAllocator.alloc (zig1)
            const cur_buf = cur_node.data[@sizeOf(BufNode)..];
                                         ^
/Users/kubkon/dev/zig/lib/std/array_list.zig:151:25: 0x10293536f in std.array_list.ArrayListAligned(std.dwarf.FileEntry,null).append (zig1)
            new_item_ptr.* = item;
                        ^
/Users/kubkon/dev/zig/lib/std/heap.zig:142:46: 0x1026f6c63 in std.heap.CAllocator.resize (zig1)
            const full_len = alignedAllocSize(buf.ptr);
                                             ^
/Users/kubkon/dev/zig/lib/std/array_list.zig:151:25: 0x10293536f in std.array_list.ArrayListAligned(std.dwarf.FileEntry,null).append (zig1)
            new_item_ptr.* = item;
                        ^
/Users/kubkon/dev/zig/lib/std/heap.zig:142:46: 0x1026f6c63 in std.heap.CAllocator.resize (zig1)
            const full_len = alignedAllocSize(buf.ptr);
                                             ^
/Users/kubkon/dev/zig/lib/std/array_list.zig:151:25: 0x10293536f in std.array_list.ArrayListAligned(std.dwarf.FileEntry,null).append (zig1)
            new_item_ptr.* = item;
                        ^
/Users/kubkon/dev/zig/lib/std/Progress.zig:281:92: 0x1028f76cb in std.Progress.bufWrite (zig1)
fn bufWrite(self: *Progress, end: *usize, comptime format: []const u8, args: anytype) void {
                                                                                           ^
/Users/kubkon/dev/zig/lib/std/fs.zig:918:64: 0x10277facb in std.fs.Dir.createFileZ (zig1)
            _ = os.fcntl(fd, os.F_SETFL, fl_flags) catch |err| switch (err) {
                                                               ^
/Users/kubkon/dev/zig/lib/std/debug.zig:62:38: 0x102779f97 in std.debug.print (zig1)
    const held = stderr_mutex.acquire();
                                     ^
/Users/kubkon/dev/zig/src/link/MachO.zig:670:32: 0x102885faf in link.MachO.linkWithLLD (zig1)
                try argv.append("-rpath");
                               ^
/Users/kubkon/dev/zig/lib/std/fs.zig:1877:24: 0x10286d42f in std.fs.Dir.copyFile (zig1)
            const st = try in_file.stat();
                       ^
/Users/kubkon/dev/zig/src/Compilation.zig:1511:39: 0x1028292db in Compilation.performAllTheWork (zig1)
                            try module.failed_decls.ensureCapacity(module.gpa, module.failed_decls.items().len + 1);
                                      ^
/Users/kubkon/dev/zig/lib/std/fmt.zig:359:13: 0x1028228fb in std.fmt.format (zig1)
            options,
            ^
???:?:?: 0x1068ca3ab in ___zig_fail_unwrap (???)
/Users/kubkon/dev/zig/lib/std/debug.zig:0:13: 0x1026f9497 in std.debug.panicExtra (zig1)
???:?:?: 0x19cea4f33 in ??? (???)
Panicked during a panic. Aborting.

Are you using the system linker by any chance, i.e., have this var set ZIG_SYSTEM_LINKER_HACK=1?

@fabioarnold
Copy link
Contributor

fabioarnold commented Jan 1, 2021

You're right, sorry!
I had changed the line in my shell rc to export ZIG_SYSTEM_LINKER_HACK=0 and the linker hack was still enabled. Commenting out the line lead to the link error you mentioned.

@kubkon
Copy link
Member

kubkon commented Jan 1, 2021

Thanks for confirming @fabioarnold!

@andrewrk andrewrk modified the milestones: 0.9.0, 0.10.0 May 19, 2021
@kubkon
Copy link
Member

kubkon commented Jun 29, 2021

Fixed in #9229.

@kubkon kubkon closed this as completed Jun 29, 2021
@andrewrk andrewrk modified the milestones: 0.10.0, 0.9.0 Jun 29, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Observed behavior contradicts documented or intended behavior os-macos upstream An issue with a third party project that Zig uses.
Projects
None yet
Development

No branches or pull requests

4 participants