BUG: Wrong segment ordering for macOS using the non-LLVM ARM64 backend

When using the non-LLVM ARM64 backend (-fno-llvm -fno-lld) on macOS, binaries fail to run with:

dyld: segment '__CONST_ZIG' vm address out of order

macOS dyld requires Mach-O segments to appear in ascending VM address order.
The ZIG segments were all assigned the same rank (0xe) in getSegmentRank(), causing segmentLessThan() to fall back to alphabetical ordering:

Before (wrong - alphabetical):

__BSS_ZIG
__CONST_ZIG
__DATA_ZIG
__TEXT_ZIG

After (correct - VM address order):

__TEXT_ZIG
__CONST_ZIG
__DATA_ZIG
__BSS_ZIG

Fix

Assign each ZIG segment a unique rank in getSegmentRank():

if (mem.eql(u8, segname, "__TEXT_ZIG")) return 0xa;
if (mem.eql(u8, segname, "__CONST_ZIG")) return 0xb;
if (mem.eql(u8, segname, "__DATA_ZIG")) return 0xc;
if (mem.eql(u8, segname, "__BSS_ZIG")) return 0xd;

Test

$ zig build-exe -fno-llvm -fno-lld test.zig -femit-bin=test_bin
$ ./test_bin
$ echo $?
42

I put the fix here since I can’t open issues or PRs in the Zig Github repo.

How do I know?

Before fix (upstream master)

$ /Users/joel/Work/zig/master/out-llvm/bin/zig build-exe -fno-llvm -fno-lld /tmp/test_arm64_macos.zig -femit-bin=/tmp/test_unfixed

$ /tmp/test_unfixed
dyld[78487]: segment '__CONST_ZIG' vm address out of order in /private/tmp/test_unfixed
dyld[78487]: segment '__CONST_ZIG' vm address out of order

$ echo $?
134

$ otool -l /tmp/test_unfixed | grep "segname" | uniq
  segname __PAGEZERO
  segname __TEXT
  segname __DATA_CONST
  segname __DATA
  segname __BSS_ZIG
  segname __CONST_ZIG
  segname __DATA_ZIG
  segname __TEXT_ZIG
  segname __LINKEDIT

After fix

$ /Users/joel/Work/zig/claude/zig-out/bin/zig build-exe -fno-llvm -fno-lld /tmp/test_arm64_macos.zig -femit-bin=/tmp/test_fixed

$ /tmp/test_fixed

$ echo $?
42

$ otool -l /tmp/test_fixed | grep "segname" | uniq
  segname __PAGEZERO
  segname __TEXT
  segname __DATA_CONST
  segname __DATA
  segname __TEXT_ZIG
  segname __CONST_ZIG
  segname __DATA_ZIG
  segname __BSS_ZIG
  segname __LINKEDIT

Looks like there might be a tracking issue for this: https://github.com/ziglang/zig/issues/25521

I’m on Apple Silicon. Could you update that issue with the link to my PR, please? I think the solution might be universal.

I won’t, sorry. You’ve been warned about breaking Zig’s strict AI policy on Zig’s github before, and this PR also reeks of LLM.

1 Like

I’ve unlisted the topic since its only purpose is to promote a compiler bugfix from an untrusted contributor.

1 Like

I explained what the bug is.

I gave a solution and tests for it.

Not much else I can do.