[lld] lld/MachO: support static executable metadata (PR #224995)
Tristan Ross via llvm-commits
llvm-commits at lists.llvm.org
Sun Sep 20 22:39:50 PDT 2026
https://github.com/RossComputerGuy updated https://github.com/llvm/llvm-project/pull/224995
>From e9a3052571c65f6a476a646a613ff8db24d9f0fb Mon Sep 17 00:00:00 2001
From: Tristan Ross <tristan.ross at determinate.systems>
Date: Sun, 20 Sep 2026 22:21:08 -0700
Subject: [PATCH 1/3] lld/MachO: support static executable metadata
---
lld/MachO/Driver.cpp | 14 ++++++++------
lld/MachO/Options.td | 1 -
lld/MachO/SyntheticSections.cpp | 9 ++++++---
lld/MachO/Writer.cpp | 17 ++++++++++-------
lld/test/MachO/static-link.s | 14 ++++++++++++++
5 files changed, 38 insertions(+), 17 deletions(-)
diff --git a/lld/MachO/Driver.cpp b/lld/MachO/Driver.cpp
index 5603dcba5a38a..ec347f726e1d6 100644
--- a/lld/MachO/Driver.cpp
+++ b/lld/MachO/Driver.cpp
@@ -1821,6 +1821,8 @@ bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
config = std::make_unique<Configuration>();
symtab = std::make_unique<SymbolTable>();
config->outputType = getOutputType(args);
+ if (const Arg *arg = args.getLastArg(OPT_static, OPT_dynamic))
+ config->staticLink = arg->getOption().matches(OPT_static);
target = createTargetInfo(args);
depTracker = std::make_unique<DependencyTracker>(
args.getLastArgValue(OPT_dependency_info));
@@ -2027,9 +2029,11 @@ bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
args.hasFlag(OPT_function_starts, OPT_no_function_starts, true);
config->emitDataInCodeInfo =
args.hasFlag(OPT_data_in_code_info, OPT_no_data_in_code_info, true);
- config->emitChainedFixups = shouldEmitChainedFixups(args);
+ config->emitChainedFixups =
+ !config->staticLink && shouldEmitChainedFixups(args);
config->emitInitOffsets =
- config->emitChainedFixups || args.hasArg(OPT_init_offsets);
+ !config->staticLink &&
+ (config->emitChainedFixups || args.hasArg(OPT_init_offsets));
config->emitRelativeMethodLists = shouldEmitRelativeMethodLists(args);
config->icfLevel = getICFLevel(args);
config->keepICFStabs = args.hasArg(OPT_keep_icf_stabs);
@@ -2226,9 +2230,6 @@ bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
config->markDeadStrippableDylib = true;
}
- if (const Arg *arg = args.getLastArg(OPT_static, OPT_dynamic))
- config->staticLink = (arg->getOption().getID() == OPT_static);
-
if (const Arg *arg =
args.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace))
config->namespaceKind = arg->getOption().getID() == OPT_twolevel_namespace
@@ -2375,7 +2376,8 @@ bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
config->adhocCodesign = args.hasFlag(
OPT_adhoc_codesign, OPT_no_adhoc_codesign,
- shouldAdhocSignByDefault(config->arch(), config->platform()));
+ !config->staticLink &&
+ shouldAdhocSignByDefault(config->arch(), config->platform()));
if (args.hasArg(OPT_v)) {
message(getLLDVersion(), ctx->e.errs());
diff --git a/lld/MachO/Options.td b/lld/MachO/Options.td
index 32b6ce0a64a07..043caa1ac7786 100644
--- a/lld/MachO/Options.td
+++ b/lld/MachO/Options.td
@@ -257,7 +257,6 @@ def dynamic : Flag<["-"], "dynamic">,
Group<grp_kind>;
def static : Flag<["-"], "static">,
HelpText<"Link statically">,
- Flags<[HelpHidden]>,
Group<grp_kind>;
def preload : Flag<["-"], "preload">,
HelpText<"Produce an unsegmented binary for embedded systems">,
diff --git a/lld/MachO/SyntheticSections.cpp b/lld/MachO/SyntheticSections.cpp
index 1f388b329aedf..022db2257e5e8 100644
--- a/lld/MachO/SyntheticSections.cpp
+++ b/lld/MachO/SyntheticSections.cpp
@@ -124,10 +124,13 @@ void MachHeaderSection::writeTo(uint8_t *buf) const {
hdr->filetype = config->outputType;
hdr->ncmds = loadCommands.size();
hdr->sizeofcmds = sizeOfCmds;
- hdr->flags = MH_DYLDLINK;
+ hdr->flags = config->staticLink ? 0 : MH_DYLDLINK;
- if (config->namespaceKind == NamespaceKind::twolevel)
- hdr->flags |= MH_NOUNDEFS | MH_TWOLEVEL;
+ if (config->namespaceKind == NamespaceKind::twolevel) {
+ hdr->flags |= MH_NOUNDEFS;
+ if (!config->staticLink)
+ hdr->flags |= MH_TWOLEVEL;
+ }
if (config->outputType == MH_DYLIB && !config->hasReexports)
hdr->flags |= MH_NO_REEXPORTED_DYLIBS;
diff --git a/lld/MachO/Writer.cpp b/lld/MachO/Writer.cpp
index 49415ccb70af8..35355495a7f0f 100644
--- a/lld/MachO/Writer.cpp
+++ b/lld/MachO/Writer.cpp
@@ -822,12 +822,14 @@ template <class LP> void Writer::createLoadCommands() {
seg->index = segIndex++;
}
- if (config->emitChainedFixups) {
- in.header->addLoadCommand(make<LCChainedFixups>(in.chainedFixups));
- in.header->addLoadCommand(make<LCExportsTrie>(in.exports));
- } else {
- in.header->addLoadCommand(make<LCDyldInfo>(
- in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports));
+ if (!config->staticLink) {
+ if (config->emitChainedFixups) {
+ in.header->addLoadCommand(make<LCChainedFixups>(in.chainedFixups));
+ in.header->addLoadCommand(make<LCExportsTrie>(in.exports));
+ } else {
+ in.header->addLoadCommand(make<LCDyldInfo>(
+ in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports));
+ }
}
in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection));
in.header->addLoadCommand(
@@ -841,7 +843,8 @@ template <class LP> void Writer::createLoadCommands() {
switch (config->outputType) {
case MH_EXECUTE:
- in.header->addLoadCommand(make<LCLoadDylinker>());
+ if (!config->staticLink)
+ in.header->addLoadCommand(make<LCLoadDylinker>());
break;
case MH_DYLIB:
in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName,
diff --git a/lld/test/MachO/static-link.s b/lld/test/MachO/static-link.s
index c3760f13af953..915a9fcb3419f 100644
--- a/lld/test/MachO/static-link.s
+++ b/lld/test/MachO/static-link.s
@@ -9,6 +9,10 @@
# RUN: %lld -o %t/test -L%t -lgoodbye %t/test.o
#
# RUN: llvm-objdump --syms -d -r %t/test | FileCheck %s
+# RUN: %no-arg-lld -arch x86_64 -platform_version macos 11.0 11.0 \
+# RUN: -static -no_pie -o %t/static -L%t -lgoodbye %t/test.o
+# RUN: llvm-objdump --macho --private-header %t/static | FileCheck %s --check-prefix=STATIC-HEADER
+# RUN: llvm-objdump --macho --all-headers %t/static | FileCheck %s --check-prefix=STATIC-LOADS
# CHECK: SYMBOL TABLE:
# CHECK: {{0+}}[[ADDR:[0-9a-f]+]] g O __TEXT,__cstring _goodbye_world
@@ -17,6 +21,16 @@
# CHECK-LABEL: <_main>:
# CHECK: leaq {{.*}}(%rip), %rsi ## 0x[[ADDR]] <_goodbye_world>
+# STATIC-HEADER: magic cputype cpusubtype caps filetype {{.*}} flags
+# STATIC-HEADER-NEXT: MH_MAGIC_64 X86_64 ALL {{.*}} EXECUTE {{.*}} NOUNDEFS{{$}}
+
+# STATIC-LOADS: cmd LC_SYMTAB
+# STATIC-LOADS-NOT: cmd LC_DYLD_INFO_ONLY
+# STATIC-LOADS-NOT: cmd LC_DYLD_CHAINED_FIXUPS
+# STATIC-LOADS-NOT: cmd LC_DYLD_EXPORTS_TRIE
+# STATIC-LOADS-NOT: cmd LC_LOAD_DYLINKER
+# STATIC-LOADS-NOT: cmd LC_CODE_SIGNATURE
+
.section __TEXT,__text
.global _main
>From a031443bf7474247771497cfddd89b39b370c184 Mon Sep 17 00:00:00 2001
From: Tristan Ross <tristan.ross at determinate.systems>
Date: Sun, 20 Sep 2026 22:24:14 -0700
Subject: [PATCH 2/3] lld/MachO: implement image_base and segaddr
---
lld/MachO/Config.h | 2 ++
lld/MachO/Driver.cpp | 28 +++++++++++++++++++++++
lld/MachO/Options.td | 2 --
lld/MachO/Writer.cpp | 19 +++++++++++++++-
lld/test/MachO/segment-addresses.s | 36 ++++++++++++++++++++++++++++++
5 files changed, 84 insertions(+), 3 deletions(-)
create mode 100644 lld/test/MachO/segment-addresses.s
diff --git a/lld/MachO/Config.h b/lld/MachO/Config.h
index a939d7789a758..25ea02bfd52b2 100644
--- a/lld/MachO/Config.h
+++ b/lld/MachO/Config.h
@@ -157,6 +157,7 @@ struct Configuration {
uint32_t timeTraceGranularity = 500;
unsigned optimize;
std::string progName;
+ uint64_t imageBase = 0;
// For `clang -arch arm64 -arch x86_64`, clang will:
// 1. invoke the linker twice, to write one temporary output per arch
@@ -217,6 +218,7 @@ struct Configuration {
// so use a vector instead of a map.
std::vector<SectionAlign> sectionAlignments;
std::vector<SegmentProtection> segmentProtections;
+ llvm::DenseMap<llvm::StringRef, uint64_t> segmentAddresses;
bool ltoDebugPassManager = false;
bool emitLLVM = false;
llvm::StringRef codegenDataGeneratePath;
diff --git a/lld/MachO/Driver.cpp b/lld/MachO/Driver.cpp
index ec347f726e1d6..0caf231bfb412 100644
--- a/lld/MachO/Driver.cpp
+++ b/lld/MachO/Driver.cpp
@@ -2279,6 +2279,34 @@ bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
validName(arg->getValue(1));
}
+ auto parseAddress = [&](const Arg *arg, unsigned valueIndex) {
+ uint64_t address = 0;
+ StringRef value = arg->getValue(valueIndex);
+ if (!llvm::to_integer(value, address, 0))
+ error(arg->getSpelling() + ": failed to parse '" + value +
+ "' as an address");
+ return address;
+ };
+
+ if (const Arg *arg = args.getLastArg(OPT_image_base)) {
+ config->imageBase = parseAddress(arg, 0);
+ uint64_t aligned = alignTo(config->imageBase, target->getPageSize());
+ if (aligned != config->imageBase) {
+ warn("-image_base: address is not page aligned; rounding up to 0x" +
+ Twine::utohexstr(aligned));
+ config->imageBase = aligned;
+ }
+ }
+
+ for (const Arg *arg : args.filtered(OPT_segaddr)) {
+ StringRef segName = validName(arg->getValue(0));
+ uint64_t address = parseAddress(arg, 1);
+ if (!isAligned(Align(4096), address))
+ error("-segaddr: address for segment " + segName +
+ " is not 4KiB aligned");
+ config->segmentAddresses[segName] = address;
+ }
+
config->sectionAlignments = parseSectAlign(args);
for (const Arg *arg : args.filtered(OPT_segprot)) {
diff --git a/lld/MachO/Options.td b/lld/MachO/Options.td
index 043caa1ac7786..4cc63be36f182 100644
--- a/lld/MachO/Options.td
+++ b/lld/MachO/Options.td
@@ -429,7 +429,6 @@ def no_order_data : Flag<["-"], "no_order_data">,
def image_base : Separate<["-"], "image_base">,
MetaVarName<"<address>">,
HelpText<"Preferred hex load address for a dylib or bundle.">,
- Flags<[HelpHidden]>,
Group<grp_opts>;
def seg1addr : Separate<["-"], "seg1addr">,
MetaVarName<"<address>">,
@@ -973,7 +972,6 @@ def segs_read_only_addr : Separate<["-"], "segs_read_only_addr">,
def segaddr : MultiArg<["-"], "segaddr", 2>,
MetaVarName<"<segment> <address>">,
HelpText<"Specify the starting hex <address> at a 4KiB page boundary for <segment>">,
- Flags<[HelpHidden]>,
Group<grp_rare>;
def seg_page_size : MultiArg<["-"], "seg_page_size", 2>,
MetaVarName<"<segment> <size>">,
diff --git a/lld/MachO/Writer.cpp b/lld/MachO/Writer.cpp
index 35355495a7f0f..beacbc5eaad9b 100644
--- a/lld/MachO/Writer.cpp
+++ b/lld/MachO/Writer.cpp
@@ -45,7 +45,7 @@ class LCUuid;
class Writer {
public:
- Writer() : buffer(errorHandler().outputBuffer) {}
+ Writer() : buffer(errorHandler().outputBuffer), addr(config->imageBase) {}
void treatSpecialUndefineds();
void scanRelocations();
@@ -1170,9 +1170,19 @@ void Writer::finalizeAddresses() {
// Note that at this point, __LINKEDIT sections are empty, but we need to
// determine addresses of other segments/sections before generating its
// contents.
+ uint64_t floatingAddr = addr;
for (OutputSegment *seg : outputSegments) {
if (seg == linkEditSegment)
continue;
+ auto fixedAddr = config->segmentAddresses.find(seg->name);
+ bool isPageZero = seg->name == segment_names::pageZero;
+ bool hasFixedAddr = fixedAddr != config->segmentAddresses.end();
+ if (hasFixedAddr)
+ addr = fixedAddr->second;
+ else if (isPageZero && config->imageBase != 0)
+ addr = 0;
+ else
+ addr = floatingAddr;
seg->addr = addr;
assignAddresses(seg);
// codesign / libstuff checks for segment ordering by verifying that
@@ -1185,7 +1195,14 @@ void Writer::finalizeAddresses() {
seg->vmSize = addr - seg->addr;
seg->fileSize = fileOff - seg->fileOff;
seg->assignAddressesToStartEndSymbols();
+
+ // A fixed address below the normal layout does not move later segments
+ // backwards. A fixed address above it advances the layout to avoid
+ // overlapping a subsequent segment.
+ if (!isPageZero || config->imageBase == 0)
+ floatingAddr = std::max(floatingAddr, addr);
}
+ addr = floatingAddr;
}
void Writer::finalizeLinkEditSegment() {
diff --git a/lld/test/MachO/segment-addresses.s b/lld/test/MachO/segment-addresses.s
new file mode 100644
index 0000000000000..26d2b6d163308
--- /dev/null
+++ b/lld/test/MachO/segment-addresses.s
@@ -0,0 +1,36 @@
+# REQUIRES: x86
+# RUN: rm -rf %t && mkdir -p %t
+# RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %s -o %t/test.o
+# RUN: %no-arg-lld -arch x86_64 -platform_version macos 11.0 11.0 \
+# RUN: -static -no_pie -pagezero_size 0 -image_base 0x100000 \
+# RUN: -segaddr __FIXED 0x400000 -o %t/out %t/test.o
+# RUN: llvm-objdump --macho --private-headers %t/out | FileCheck %s
+# RUN: not %no-arg-lld -arch x86_64 -platform_version macos 11.0 11.0 \
+# RUN: -static -image_base invalid -o /dev/null %t/test.o 2>&1 | \
+# RUN: FileCheck %s --check-prefix=BAD-BASE
+# RUN: not %no-arg-lld -arch x86_64 -platform_version macos 11.0 11.0 \
+# RUN: -static -segaddr __FIXED 0x400001 -o /dev/null %t/test.o 2>&1 | \
+# RUN: FileCheck %s --check-prefix=BAD-SEGADDR
+
+# CHECK: segname __TEXT
+# CHECK-NEXT: vmaddr 0x0000000000100000
+# CHECK: segname __DATA
+# CHECK-NEXT: vmaddr 0x0000000000101000
+# CHECK: segname __FIXED
+# CHECK-NEXT: vmaddr 0x0000000000400000
+# CHECK: segname __LINKEDIT
+# CHECK-NEXT: vmaddr 0x0000000000401000
+
+# BAD-BASE: error: -image_base: failed to parse 'invalid' as an address
+# BAD-SEGADDR: error: -segaddr: address for segment __FIXED is not 4KiB aligned
+
+.text
+.globl _main
+_main:
+ retq
+
+.data
+.quad 0
+
+.section __FIXED,__fixed
+.quad 0
>From cbec4f8b03675cbee802ad994b182689d6673331 Mon Sep 17 00:00:00 2001
From: Tristan Ross <tristan.ross at determinate.systems>
Date: Sun, 20 Sep 2026 22:25:43 -0700
Subject: [PATCH 3/3] lld/MachO: implement segment_order
---
lld/MachO/Config.h | 1 +
lld/MachO/Driver.cpp | 12 +++++++++++
lld/MachO/Options.td | 1 -
lld/MachO/OutputSegment.cpp | 15 ++++++++++++++
lld/test/MachO/segment-order.s | 37 ++++++++++++++++++++++++++++++++++
5 files changed, 65 insertions(+), 1 deletion(-)
create mode 100644 lld/test/MachO/segment-order.s
diff --git a/lld/MachO/Config.h b/lld/MachO/Config.h
index 25ea02bfd52b2..023965dfbf777 100644
--- a/lld/MachO/Config.h
+++ b/lld/MachO/Config.h
@@ -219,6 +219,7 @@ struct Configuration {
std::vector<SectionAlign> sectionAlignments;
std::vector<SegmentProtection> segmentProtections;
llvm::DenseMap<llvm::StringRef, uint64_t> segmentAddresses;
+ llvm::SmallVector<llvm::StringRef, 0> segmentOrder;
bool ltoDebugPassManager = false;
bool emitLLVM = false;
llvm::StringRef codegenDataGeneratePath;
diff --git a/lld/MachO/Driver.cpp b/lld/MachO/Driver.cpp
index 0caf231bfb412..20800f55f3db8 100644
--- a/lld/MachO/Driver.cpp
+++ b/lld/MachO/Driver.cpp
@@ -2307,6 +2307,18 @@ bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
config->segmentAddresses[segName] = address;
}
+ if (const Arg *arg = args.getLastArg(OPT_segment_order)) {
+ StringRef(arg->getValue())
+ .split(config->segmentOrder, ':', -1,
+ /*KeepEmpty=*/false);
+ DenseSet<StringRef> seen;
+ for (StringRef segName : config->segmentOrder) {
+ validName(segName);
+ if (!seen.insert(segName).second)
+ error("-segment_order: duplicate segment " + segName);
+ }
+ }
+
config->sectionAlignments = parseSectAlign(args);
for (const Arg *arg : args.filtered(OPT_segprot)) {
diff --git a/lld/MachO/Options.td b/lld/MachO/Options.td
index 4cc63be36f182..664d173baa534 100644
--- a/lld/MachO/Options.td
+++ b/lld/MachO/Options.td
@@ -835,7 +835,6 @@ def section_order : MultiArg<["-"], "section_order", 2>,
def segment_order : Separate<["-"], "segment_order">,
MetaVarName<"<colon_separated_segment_list>">,
HelpText<"With -preload, specify layout sequence of colon-separated <segments>">,
- Flags<[HelpHidden]>,
Group<grp_rare>;
def allow_heap_execute : Flag<["-"], "allow_heap_execute">,
HelpText<"On i386, allow any page to execute code">,
diff --git a/lld/MachO/OutputSegment.cpp b/lld/MachO/OutputSegment.cpp
index 5824b5c7772b3..dcc75972166c2 100644
--- a/lld/MachO/OutputSegment.cpp
+++ b/lld/MachO/OutputSegment.cpp
@@ -79,6 +79,21 @@ template <typename T, typename F> static auto compareByOrder(F ord) {
}
static int segmentOrder(OutputSegment *seg) {
+ // __LINKEDIT contents are finalized after all regular sections, so it must
+ // remain last in file and VM order. Honor the requested order for every
+ // other segment; stable_sort preserves input order for names omitted from
+ // the list.
+ if (!config->segmentOrder.empty()) {
+ if (seg->name == segment_names::pageZero)
+ return -1;
+ if (seg->name == segment_names::linkEdit)
+ return std::numeric_limits<int>::max();
+ auto it = llvm::find(config->segmentOrder, seg->name);
+ if (it != config->segmentOrder.end())
+ return std::distance(config->segmentOrder.begin(), it);
+ return config->segmentOrder.size();
+ }
+
return StringSwitch<int>(seg->name)
.Case(segment_names::pageZero, -4)
.Case(segment_names::text, -3)
diff --git a/lld/test/MachO/segment-order.s b/lld/test/MachO/segment-order.s
new file mode 100644
index 0000000000000..636ac426b8bc7
--- /dev/null
+++ b/lld/test/MachO/segment-order.s
@@ -0,0 +1,37 @@
+# REQUIRES: x86
+# RUN: rm -rf %t && mkdir -p %t
+# RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %s -o %t/test.o
+# RUN: %no-arg-lld -arch x86_64 -platform_version macos 11.0 11.0 \
+# RUN: -static -no_pie -pagezero_size 0 \
+# RUN: -segment_order __TEXT:__THIRD:__FIRST:__SECOND:__LINKEDIT \
+# RUN: -o %t/out %t/test.o
+# RUN: llvm-objdump --macho --private-headers %t/out | FileCheck %s
+# RUN: not %no-arg-lld -arch x86_64 -platform_version macos 11.0 11.0 \
+# RUN: -static -segment_order __TEXT:__TEXT -o /dev/null %t/test.o 2>&1 | \
+# RUN: FileCheck %s --check-prefix=DUPLICATE
+
+# CHECK: segname __TEXT
+# CHECK: segname __THIRD
+# CHECK: segname __FIRST
+# CHECK: segname __SECOND
+# CHECK: segname __UNLISTED
+# CHECK: segname __LINKEDIT
+
+# DUPLICATE: error: -segment_order: duplicate segment __TEXT
+
+.text
+.globl _main
+_main:
+ retq
+
+.section __FIRST,__first
+.quad 0
+
+.section __SECOND,__second
+.quad 0
+
+.section __THIRD,__third
+.quad 0
+
+.section __UNLISTED,__unlisted
+.quad 0
More information about the llvm-commits
mailing list