[clang] [lldb] [llvm] [lldb] Support relocatable Mach-O DWARF sections (PR #239801)
Adrian Prantl via cfe-commits
cfe-commits at lists.llvm.org
Fri Nov 6 16:47:34 PST 2026
https://github.com/adrian-prantl updated https://github.com/llvm/llvm-project/pull/239801
>From 0031f7dab64d19d2c9c23c9953df83aefb32f722 Mon Sep 17 00:00:00 2001
From: Adrian Prantl <aprantl at apple.com>
Date: Thu, 5 Nov 2026 13:57:36 -0800
Subject: [PATCH 1/4] [MC][MachO] Add an option to relocate cross-section
offsets in DWARF
Mach-O objects store references from one DWARF section into another as
bare offsets rather than relocations. For comparison in ELF DWARF
references are relocations against sections that start at address
0. Because of this Mach-O DWARF sections cannot be concatenated by
tools such as ld -r. However, this would be useful for some niche
use-cases such as doing an incremental (ld -r) link and then creating
a static archive that is then distributed to another machine.
Add MCTargetOptions::MachORelocatableDwarf, exposed to tools as the
hidden -macho-relocatable-dwarf flag, which sets
DwarfUsesRelocationsAcrossSections for Darwin targets. When it is set,
every __DWARF section is assigned address 0, while the section data
keeps its layout in the file.
The option is off by default, so existing output does not change.
Assisted-by: Claude
---
llvm/include/llvm/MC/MCMachObjectWriter.h | 4 ++
llvm/include/llvm/MC/MCTargetOptions.h | 4 ++
.../llvm/MC/MCTargetOptionsCommandFlags.h | 2 +
llvm/lib/MC/MCAsmInfoDarwin.cpp | 3 +-
llvm/lib/MC/MCTargetOptionsCommandFlags.cpp | 8 +++
llvm/lib/MC/MachObjectWriter.cpp | 46 +++++++++++----
.../test/MC/MachO/AArch64/relocatable-dwarf.s | 57 +++++++++++++++++++
7 files changed, 113 insertions(+), 11 deletions(-)
create mode 100644 llvm/test/MC/MachO/AArch64/relocatable-dwarf.s
diff --git a/llvm/include/llvm/MC/MCMachObjectWriter.h b/llvm/include/llvm/MC/MCMachObjectWriter.h
index 125c45d34758b4..876259adb5087f 100644
--- a/llvm/include/llvm/MC/MCMachObjectWriter.h
+++ b/llvm/include/llvm/MC/MCMachObjectWriter.h
@@ -145,6 +145,10 @@ class LLVM_ABI MachObjectWriter final : public MCObjectWriter {
DenseMap<const MCSection *, uint64_t> SectionAddress;
+ // Offset of each section's data from the start of all section data. Equal to
+ // the section's address, unless relocatable DWARF numbers it from 0.
+ DenseMap<const MCSection *, uint64_t> SectionDataOffset;
+
// List of sections in layout order. Virtual sections are after non-virtual
// sections.
SmallVector<MCSection *, 0> SectionOrder;
diff --git a/llvm/include/llvm/MC/MCTargetOptions.h b/llvm/include/llvm/MC/MCTargetOptions.h
index 8414723cf6e0c8..f18c5c066fa455 100644
--- a/llvm/include/llvm/MC/MCTargetOptions.h
+++ b/llvm/include/llvm/MC/MCTargetOptions.h
@@ -69,6 +69,10 @@ class MCTargetOptions {
bool ImplicitMapSyms = false;
+ /// Use relocations for cross-section offsets in the __DWARF segment of
+ /// Mach-O objects.
+ bool MachORelocatableDwarf = false;
+
// If true, prefer R_X86_64_[REX_]GOTPCRELX to R_X86_64_GOTPCREL on x86-64
// ELF.
bool X86RelaxRelocations = true;
diff --git a/llvm/include/llvm/MC/MCTargetOptionsCommandFlags.h b/llvm/include/llvm/MC/MCTargetOptionsCommandFlags.h
index 136eb2567678dc..47ea7cabe68752 100644
--- a/llvm/include/llvm/MC/MCTargetOptionsCommandFlags.h
+++ b/llvm/include/llvm/MC/MCTargetOptionsCommandFlags.h
@@ -60,6 +60,8 @@ LLVM_ABI bool getCrel();
LLVM_ABI bool getImplicitMapSyms();
+LLVM_ABI bool getMachORelocatableDwarf();
+
LLVM_ABI bool getX86RelaxRelocations();
LLVM_ABI bool getX86Sse2Avx();
diff --git a/llvm/lib/MC/MCAsmInfoDarwin.cpp b/llvm/lib/MC/MCAsmInfoDarwin.cpp
index efd8eb022c27b7..b7277af5171df1 100644
--- a/llvm/lib/MC/MCAsmInfoDarwin.cpp
+++ b/llvm/lib/MC/MCAsmInfoDarwin.cpp
@@ -15,6 +15,7 @@
#include "llvm/BinaryFormat/MachO.h"
#include "llvm/MC/MCDirectives.h"
#include "llvm/MC/MCSectionMachO.h"
+#include "llvm/MC/MCTargetOptions.h"
using namespace llvm;
@@ -83,7 +84,7 @@ MCAsmInfoDarwin::MCAsmInfoDarwin(const MCTargetOptions &Options)
HasDotTypeDotSizeDirective = false;
HasNoDeadStrip = true;
- DwarfUsesRelocationsAcrossSections = false;
+ DwarfUsesRelocationsAcrossSections = Options.MachORelocatableDwarf;
SetDirectiveSuppressesReloc = true;
}
diff --git a/llvm/lib/MC/MCTargetOptionsCommandFlags.cpp b/llvm/lib/MC/MCTargetOptionsCommandFlags.cpp
index 65c550a998bfe3..59461918b562ef 100644
--- a/llvm/lib/MC/MCTargetOptionsCommandFlags.cpp
+++ b/llvm/lib/MC/MCTargetOptionsCommandFlags.cpp
@@ -57,6 +57,7 @@ MCOPT(bool, NoTypeCheck)
MCOPT(bool, SaveTempLabels)
MCOPT(bool, Crel)
MCOPT(bool, ImplicitMapSyms)
+MCOPT(bool, MachORelocatableDwarf)
MCOPT(bool, X86RelaxRelocations)
MCOPT(bool, X86Sse2Avx)
MCOPT(bool, DisableIntegratedAS)
@@ -161,6 +162,12 @@ llvm::mc::RegisterMCTargetOptionsFlags::RegisterMCTargetOptionsFlags() {
"object files using this option"));
MCBINDOPT(ImplicitMapSyms);
+ static cl::opt<bool> MachORelocatableDwarf(
+ "macho-relocatable-dwarf", cl::Hidden,
+ cl::desc(
+ "Use relocations for cross-section offsets in the __DWARF segment"));
+ MCBINDOPT(MachORelocatableDwarf);
+
static cl::opt<bool> X86RelaxRelocations(
"x86-relax-relocations",
cl::desc("Emit GOTPCRELX/REX_GOTPCRELX/CODE_4_GOTPCRELX instead of "
@@ -228,6 +235,7 @@ MCTargetOptions llvm::mc::InitMCTargetOptionsFromFlags() {
Options.MCSaveTempLabels = getSaveTempLabels();
Options.Crel = getCrel();
Options.ImplicitMapSyms = getImplicitMapSyms();
+ Options.MachORelocatableDwarf = getMachORelocatableDwarf();
Options.X86RelaxRelocations = getX86RelaxRelocations();
Options.X86Sse2Avx = getX86Sse2Avx();
Options.DisableIntegratedAS = getDisableIntegratedAS();
diff --git a/llvm/lib/MC/MachObjectWriter.cpp b/llvm/lib/MC/MachObjectWriter.cpp
index 790f7595807b95..f428a66975fbed 100644
--- a/llvm/lib/MC/MachObjectWriter.cpp
+++ b/llvm/lib/MC/MachObjectWriter.cpp
@@ -46,6 +46,7 @@ void MachObjectWriter::reset() {
IndirectSymbols.clear();
DataRegions.clear();
SectionAddress.clear();
+ SectionDataOffset.clear();
SectionOrder.clear();
StringTable.clear();
LocalSymbolData.clear();
@@ -125,7 +126,8 @@ uint64_t MachObjectWriter::getSymbolAddress(const MCSymbol &S) const {
uint64_t MachObjectWriter::getPaddingSize(const MCAssembler &Asm,
const MCSection *Sec) const {
- uint64_t EndAddr = getSectionAddress(Sec) + Asm.getSectionAddressSize(*Sec);
+ uint64_t EndOffset =
+ SectionDataOffset.lookup(Sec) + Asm.getSectionAddressSize(*Sec);
unsigned Next =
static_cast<const MCSectionMachO *>(Sec)->getLayoutOrder() + 1;
if (Next >= SectionOrder.size())
@@ -134,7 +136,7 @@ uint64_t MachObjectWriter::getPaddingSize(const MCAssembler &Asm,
const MCSection &NextSec = *SectionOrder[Next];
if (NextSec.isBssSection())
return 0;
- return offsetToAlignment(EndAddr, NextSec.getAlign());
+ return offsetToAlignment(EndOffset, NextSec.getAlign());
}
static bool isSymbolLinkerVisible(const MCSymbol &Symbol) {
@@ -701,16 +703,36 @@ void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm) {
}
}
- uint64_t StartAddress = 0;
+ uint64_t StartOffset = 0;
for (const MCSection *Sec : SectionOrder) {
- StartAddress = alignTo(StartAddress, Sec->getAlign());
- SectionAddress[Sec] = StartAddress;
- StartAddress += Asm.getSectionAddressSize(*Sec);
+ StartOffset = alignTo(StartOffset, Sec->getAlign());
+ SectionDataOffset[Sec] = StartOffset;
+ StartOffset += Asm.getSectionAddressSize(*Sec);
// Explicitly pad the section to match the alignment requirements of the
// following one. This is for 'gas' compatibility, it shouldn't
/// strictly be necessary.
- StartAddress += getPaddingSize(Asm, Sec);
+ StartOffset += getPaddingSize(Asm, Sec);
+ }
+
+ if (!getContext().getAsmInfo().doesDwarfUseRelocationsAcrossSections()) {
+ for (const MCSection *Sec : SectionOrder)
+ SectionAddress[Sec] = SectionDataOffset[Sec];
+ return;
+ }
+
+ // A relocated reference into a DWARF section has to hold an offset into
+ // that section, so every __DWARF section starts at address 0.
+ uint64_t StartAddress = 0;
+ for (const MCSection *Sec : SectionOrder) {
+ if (static_cast<const MCSectionMachO *>(Sec)->getSegmentName() ==
+ "__DWARF") {
+ SectionAddress[Sec] = 0;
+ continue;
+ }
+ StartAddress = alignTo(StartAddress, Sec->getAlign());
+ SectionAddress[Sec] = StartAddress;
+ StartAddress += Asm.getSectionAddressSize(*Sec);
}
}
@@ -895,6 +917,7 @@ uint64_t MachObjectWriter::writeObject() {
uint64_t VMSize = 0;
for (const MCSection &Sec : Asm) {
uint64_t Address = getSectionAddress(&Sec);
+ uint64_t Offset = SectionDataOffset.lookup(&Sec);
uint64_t Size = Asm.getSectionAddressSize(Sec);
uint64_t FileSize = Asm.getSectionFileSize(Sec);
FileSize += getPaddingSize(Asm, &Sec);
@@ -904,9 +927,12 @@ uint64_t MachObjectWriter::writeObject() {
if (Sec.isBssSection())
continue;
- SectionDataSize = std::max(SectionDataSize, Address + Size);
- SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
+ SectionDataSize = std::max(SectionDataSize, Offset + Size);
+ SectionDataFileSize = std::max(SectionDataFileSize, Offset + FileSize);
}
+ // A segment's file size can't exceed its VM size, even when sections at
+ // overlapping addresses take more space in the file than in memory.
+ VMSize = std::max(VMSize, SectionDataSize);
// The section data is padded to pointer size bytes.
//
@@ -929,7 +955,7 @@ uint64_t MachObjectWriter::writeObject() {
const auto &Sec = static_cast<const MCSectionMachO &>(Section);
std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
unsigned NumRelocs = Relocs.size();
- uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
+ uint64_t SectionStart = SectionDataStart + SectionDataOffset.lookup(&Sec);
unsigned Flags = Sec.getTypeAndAttributes();
if (Sec.hasInstructions())
Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
diff --git a/llvm/test/MC/MachO/AArch64/relocatable-dwarf.s b/llvm/test/MC/MachO/AArch64/relocatable-dwarf.s
new file mode 100644
index 00000000000000..f8e30f853529e2
--- /dev/null
+++ b/llvm/test/MC/MachO/AArch64/relocatable-dwarf.s
@@ -0,0 +1,57 @@
+// With -macho-relocatable-dwarf, a reference from one DWARF section into
+// another is a relocation, and every __DWARF section is numbered from address 0
+// so that the relocated field holds the DWARF offset. The section data keeps
+// its place in the file.
+
+// RUN: llvm-mc -triple arm64-apple-macos14 -filetype=obj %s -o %t.o
+// RUN: llvm-readobj --sections %t.o | FileCheck %s --check-prefix=PLAIN-SECT
+// RUN: llvm-objdump -s --section=__debug_info %t.o | FileCheck %s --check-prefix=PLAIN-FIELD
+
+// RUN: llvm-mc -triple arm64-apple-macos14 -filetype=obj -macho-relocatable-dwarf %s -o %t.reloc.o
+// RUN: llvm-readobj --sections %t.reloc.o | FileCheck %s --check-prefix=RELOC-SECT
+// RUN: llvm-objdump -r -s --section=__debug_info %t.reloc.o | FileCheck %s --check-prefix=RELOC-FIELD
+
+// PLAIN-SECT: Name: __debug_str
+// PLAIN-SECT-NEXT: Segment: __DWARF
+// PLAIN-SECT-NEXT: Address: 0x4
+// PLAIN-SECT: Name: __debug_info
+// PLAIN-SECT-NEXT: Segment: __DWARF
+// PLAIN-SECT-NEXT: Address: 0x11
+
+// Without relocatable DWARF, the field holds the address of "second".
+// PLAIN-FIELD: 0011 0a000000
+
+// RELOC-SECT: Name: __text
+// RELOC-SECT-NEXT: Segment: __TEXT
+// RELOC-SECT-NEXT: Address: 0x0
+// RELOC-SECT-NEXT: Size: 0x4
+// RELOC-SECT-NEXT: Offset: [[#TEXT:]]
+// RELOC-SECT: Name: __debug_str
+// RELOC-SECT-NEXT: Segment: __DWARF
+// RELOC-SECT-NEXT: Address: 0x0
+// RELOC-SECT-NEXT: Size: 0xD
+// RELOC-SECT-NEXT: Offset: [[#TEXT + 4]]
+// RELOC-SECT: Name: __debug_info
+// RELOC-SECT-NEXT: Segment: __DWARF
+// RELOC-SECT-NEXT: Address: 0x0
+// RELOC-SECT-NEXT: Size: 0x4
+// RELOC-SECT-NEXT: Offset: [[#TEXT + 17]]
+
+// With relocatable DWARF, it holds the offset of "second" in __debug_str.
+// RELOC-FIELD: RELOCATION RECORDS FOR [__debug_info]:
+// RELOC-FIELD-NEXT: OFFSET TYPE VALUE
+// RELOC-FIELD-NEXT: 0000000000000000 ARM64_RELOC_UNSIGNED __debug_str
+// RELOC-FIELD: 0000 06000000
+
+ .text
+ .globl _foo
+_foo:
+ ret
+
+ .section __DWARF,__debug_str,regular,debug
+ .asciz "first"
+Lsecond:
+ .asciz "second"
+
+ .section __DWARF,__debug_info,regular,debug
+ .long Lsecond
>From 6c6a82c2c7276d2e2f65849e0e231d174f545a09 Mon Sep 17 00:00:00 2001
From: Adrian Prantl <aprantl at apple.com>
Date: Fri, 6 Nov 2026 10:00:20 -0800
Subject: [PATCH 2/4] [clang] Relocate DWARF across sections on Mach-O firmware
targets
Change the Darwin Toolchain to pass -grelocatable-dwarf for embedded
Mach-O targets when emitting DWARF 5 or later.
Assisted-by: Claude
---
clang/include/clang/Basic/CodeGenOptions.def | 3 ++
clang/include/clang/Driver/CommonArgs.h | 4 ++
clang/include/clang/Options/Options.td | 4 ++
clang/lib/CodeGen/BackendUtil.cpp | 1 +
clang/lib/Driver/ToolChains/Clang.cpp | 4 ++
clang/lib/Driver/ToolChains/CommonArgs.cpp | 7 ++++
clang/lib/Driver/ToolChains/Darwin.cpp | 6 +++
.../DebugInfo/AArch64/relocatable-dwarf.c | 24 ++++++++++++
clang/test/Driver/relocatable-dwarf.c | 39 +++++++++++++++++++
clang/test/Misc/cc1as-relocatable-dwarf.s | 25 ++++++++++++
clang/tools/driver/cc1as_main.cpp | 5 +++
11 files changed, 122 insertions(+)
create mode 100644 clang/test/DebugInfo/AArch64/relocatable-dwarf.c
create mode 100644 clang/test/Driver/relocatable-dwarf.c
create mode 100644 clang/test/Misc/cc1as-relocatable-dwarf.s
diff --git a/clang/include/clang/Basic/CodeGenOptions.def b/clang/include/clang/Basic/CodeGenOptions.def
index ff33f5be424ecd..8c7974ae1664a1 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -129,6 +129,9 @@ CODEGENOPT(EmitCompactUnwindNonCanonical, 1, 0, Benign)
CODEGENOPT(EmitSFrameUnwind, 1, 0, Benign) ///< Set when -sframe is enabled.
+/// Set when -grelocatable-dwarf is enabled.
+CODEGENOPT(MachORelocatableDwarf, 1, 0, Benign)
+
///< Set when -fxray-always-emit-customevents is enabled.
CODEGENOPT(XRayAlwaysEmitCustomEvents , 1, 0, Benign)
diff --git a/clang/include/clang/Driver/CommonArgs.h b/clang/include/clang/Driver/CommonArgs.h
index 138e18f8641b90..f97776e622d0bf 100644
--- a/clang/include/clang/Driver/CommonArgs.h
+++ b/clang/include/clang/Driver/CommonArgs.h
@@ -54,6 +54,10 @@ void renderDebugInfoCompressionArgs(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs,
const Driver &D, const ToolChain &TC);
+/// Whether Mach-O objects for \p T with DWARF \p DwarfVersion relocate offsets
+/// between DWARF sections.
+bool useMachORelocatableDwarf(const llvm::Triple &T, unsigned DwarfVersion);
+
void claimNoWarnArgs(const llvm::opt::ArgList &Args);
bool addSanitizerRuntimes(const ToolChain &TC, const llvm::opt::ArgList &Args,
diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td
index 81f26bb4791416..616630e3d44d78 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -8177,6 +8177,10 @@ def reloc_section_sym : Joined<["--"], "reloc-section-sym=">,
NormalizedValuesScope<"llvm::RelocSectionSymType">,
NormalizedValues<["All", "Internal", "None"]>,
MarshallingInfoEnum<CodeGenOpts<"RelocSectionSym">, "All">;
+def grelocatable_dwarf : Flag<["-"], "grelocatable-dwarf">,
+ HelpText<"Relocate offsets from one DWARF section into another in Mach-O "
+ "object files">,
+ MarshallingInfoFlag<CodeGenOpts<"MachORelocatableDwarf">>;
// The leading 'g' is misleading. This is an unwind tables option, not
// a debug option. But uses this name for gnu compatibility.
def gsframe : Flag<["--"], "gsframe">,
diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp
index f226878f64f6f8..e817d354c256b5 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -486,6 +486,7 @@ static bool initTargetOptions(const CompilerInstance &CI,
Options.MCOptions.Crel = CodeGenOpts.Crel;
Options.MCOptions.RelocSectionSym = CodeGenOpts.getRelocSectionSym();
Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
+ Options.MCOptions.MachORelocatableDwarf = CodeGenOpts.MachORelocatableDwarf;
Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
Options.MCOptions.CompressDebugSections =
CodeGenOpts.getCompressDebugSections();
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index df8c9ccb1027bb..f2ae29434e5a9f 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5125,6 +5125,8 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
CmdArgs.push_back("-dwarf-explicit-import");
renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
+ if (useMachORelocatableDwarf(T, EffectiveDWARFVersion))
+ CmdArgs.push_back("-grelocatable-dwarf");
renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
// This controls whether or not we perform JustMyCode instrumentation.
@@ -9456,6 +9458,8 @@ void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
llvm::DebuggerKind::Default);
renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
+ if (useMachORelocatableDwarf(Triple, DwarfVersion))
+ CmdArgs.push_back("-grelocatable-dwarf");
renderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
// Handle -fPIC et al -- the relocation-model affects the assembler
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index db5250db329a9f..a53059230961e1 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -680,6 +680,13 @@ void tools::addLinkerCompressDebugSectionsOption(
}
}
+bool tools::useMachORelocatableDwarf(const llvm::Triple &T,
+ unsigned DwarfVersion) {
+ return T.isOSBinFormatMachO() && DwarfVersion >= 5 &&
+ !(T.isMacOSX() || T.isiOS() || T.isWatchOS() || T.isXROS() ||
+ T.isDriverKit());
+}
+
void tools::renderDebugInfoCompressionArgs(const ArgList &Args,
ArgStringList &CmdArgs,
const Driver &D,
diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp b/clang/lib/Driver/ToolChains/Darwin.cpp
index baefa8c8c52015..69ff4188dbaf9c 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -456,6 +456,12 @@ void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
CmdArgs.push_back("-disable-atexit-based-global-dtor-lowering");
}
+ if (useMachORelocatableDwarf(getToolChain().getTriple(),
+ getDwarfVersion(getToolChain(), Args))) {
+ CmdArgs.push_back("-mllvm");
+ CmdArgs.push_back("-macho-relocatable-dwarf");
+ }
+
Args.AddLastArg(CmdArgs, options::OPT_prebind);
Args.AddLastArg(CmdArgs, options::OPT_noprebind);
Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
diff --git a/clang/test/DebugInfo/AArch64/relocatable-dwarf.c b/clang/test/DebugInfo/AArch64/relocatable-dwarf.c
new file mode 100644
index 00000000000000..7e61494075ef40
--- /dev/null
+++ b/clang/test/DebugInfo/AArch64/relocatable-dwarf.c
@@ -0,0 +1,24 @@
+// -grelocatable-dwarf relocates offsets between DWARF sections in Mach-O
+// object files.
+
+// REQUIRES: aarch64-registered-target
+
+// RUN: %clang_cc1 -triple arm64-apple-macos15 -debug-info-kind=limited \
+// RUN: -dwarf-version=5 -emit-obj %s -o %t.o
+// RUN: llvm-objdump -r --section=__debug_info %t.o \
+// RUN: | FileCheck %s --check-prefix=PLAIN
+// RUN: %clang_cc1 -triple arm64-apple-macos15 -debug-info-kind=limited \
+// RUN: -dwarf-version=5 -grelocatable-dwarf -emit-obj %s -o %t.reloc.o
+// RUN: llvm-objdump -r --section=__debug_info %t.reloc.o \
+// RUN: | FileCheck %s --check-prefix=RELOC
+
+// PLAIN: file format mach-o arm64
+// PLAIN-NOT: __debug_
+
+// RELOC: RELOCATION RECORDS FOR [__debug_info]:
+// RELOC-DAG: ARM64_RELOC_UNSIGNED __debug_abbrev
+// RELOC-DAG: ARM64_RELOC_UNSIGNED __debug_line
+// RELOC-DAG: ARM64_RELOC_UNSIGNED __debug_str_offs
+// RELOC-DAG: ARM64_RELOC_UNSIGNED __debug_addr
+
+int g;
diff --git a/clang/test/Driver/relocatable-dwarf.c b/clang/test/Driver/relocatable-dwarf.c
new file mode 100644
index 00000000000000..d89fa4f80417dd
--- /dev/null
+++ b/clang/test/Driver/relocatable-dwarf.c
@@ -0,0 +1,39 @@
+// Mach-O objects with DWARF 5 or later relocate offsets between DWARF sections,
+// except for the Apple operating systems below. This applies to code
+// generation, the integrated assembler, and LTO code generation in the linker.
+
+// RUN: %clang -### --target=arm64-apple-none-macho -g -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CC1
+// RUN: %clang -### --target=arm64-apple-firmware -g -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CC1
+// RUN: %clang -### --target=arm64-apple-bridgeos9.0 -g -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CC1
+// RUN: %clang -### --target=arm64-apple-none-macho -g -c -x assembler %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CC1AS
+// RUN: %clang -### --target=arm64-apple-none-macho -flto %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=LINK
+
+// RUN: %clang -### --target=arm64-apple-none-macho -g -gdwarf-4 -flto %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=NONE
+// RUN: %clang -### --target=arm64-apple-none-macho -gdwarf-4 -c -x assembler %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=NONE
+// RUN: %clang -### --target=arm64-apple-macos15 -g -flto %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=NONE
+// RUN: %clang -### --target=arm64-apple-ios17 -g -flto %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=NONE
+// RUN: %clang -### --target=arm64-apple-tvos17 -g -flto %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=NONE
+// RUN: %clang -### --target=arm64-apple-watchos10 -g -flto %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=NONE
+// RUN: %clang -### --target=arm64-apple-xros1 -g -flto %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=NONE
+// RUN: %clang -### --target=arm64-apple-driverkit23 -g -flto %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=NONE
+// RUN: %clang -### --target=x86_64-linux-gnu -g -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=NONE
+
+// CC1: "-cc1" {{.*}}"-grelocatable-dwarf"
+// CC1AS: "-cc1as" {{.*}}"-grelocatable-dwarf"
+// LINK: {{/|\\\\}}ld{{(.exe)?}}" {{.*}}"-mllvm" "-macho-relocatable-dwarf"
+// NONE-NOT: "-grelocatable-dwarf"
+// NONE-NOT: "-macho-relocatable-dwarf"
diff --git a/clang/test/Misc/cc1as-relocatable-dwarf.s b/clang/test/Misc/cc1as-relocatable-dwarf.s
new file mode 100644
index 00000000000000..a2fcd35df60edb
--- /dev/null
+++ b/clang/test/Misc/cc1as-relocatable-dwarf.s
@@ -0,0 +1,25 @@
+// REQUIRES: aarch64-registered-target
+// RUN: %clang -cc1as -triple arm64-apple-macos14 -filetype obj %s -o %t.o
+// RUN: llvm-objdump -s --section=__debug_info %t.o \
+// RUN: | FileCheck %s --check-prefix=PLAIN
+// RUN: %clang -cc1as -triple arm64-apple-macos14 -filetype obj \
+// RUN: -grelocatable-dwarf %s -o %t.reloc.o
+// RUN: llvm-objdump -s --section=__debug_info %t.reloc.o \
+// RUN: | FileCheck %s --check-prefix=RELOC
+
+// The field holds the address of "second" by default, and its offset in
+// __debug_str with -grelocatable-dwarf.
+// PLAIN: 0011 0a000000
+// RELOC: 0000 06000000
+
+ .text
+_foo:
+ ret
+
+ .section __DWARF,__debug_str,regular,debug
+ .asciz "first"
+Lsecond:
+ .asciz "second"
+
+ .section __DWARF,__debug_info,regular,debug
+ .long Lsecond
diff --git a/clang/tools/driver/cc1as_main.cpp b/clang/tools/driver/cc1as_main.cpp
index 0d7bd90b0354ef..ded9e0d906df01 100644
--- a/clang/tools/driver/cc1as_main.cpp
+++ b/clang/tools/driver/cc1as_main.cpp
@@ -172,6 +172,8 @@ struct AssemblerInvocation {
unsigned Crel : 1;
LLVM_PREFERRED_TYPE(bool)
unsigned ImplicitMapsyms : 1;
+ LLVM_PREFERRED_TYPE(bool)
+ unsigned MachORelocatableDwarf : 1;
LLVM_PREFERRED_TYPE(bool)
unsigned X86RelaxRelocations : 1;
@@ -225,6 +227,7 @@ struct AssemblerInvocation {
EmitCompactUnwindNonCanonical = false;
Crel = false;
ImplicitMapsyms = 0;
+ MachORelocatableDwarf = 0;
X86RelaxRelocations = 0;
X86Sse2Avx = 0;
}
@@ -398,6 +401,7 @@ bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
Args.hasArg(OPT_femit_compact_unwind_non_canonical);
Opts.EmitSFrameUnwind = Args.hasArg(OPT_gsframe);
Opts.Crel = Args.hasArg(OPT_crel);
+ Opts.MachORelocatableDwarf = Args.hasArg(OPT_grelocatable_dwarf);
Opts.RelocSectionSym = RelocSectionSymType::All;
if (auto *A = Args.getLastArg(OPT_reloc_section_sym))
Opts.RelocSectionSym = StringSwitch<RelocSectionSymType>(A->getValue())
@@ -475,6 +479,7 @@ executeAssemblerImpl(const cl::LibraryOptionsContext &LibraryOptions,
MCOptions.Crel = Opts.Crel;
MCOptions.RelocSectionSym = Opts.RelocSectionSym;
MCOptions.ImplicitMapSyms = Opts.ImplicitMapsyms;
+ MCOptions.MachORelocatableDwarf = Opts.MachORelocatableDwarf;
MCOptions.X86RelaxRelocations = Opts.X86RelaxRelocations;
MCOptions.X86Sse2Avx = Opts.X86Sse2Avx;
MCOptions.MCNoExecStack = Opts.NoExecStack;
>From b8427de0e88d7594dac51623821e47f79ffe7b88 Mon Sep 17 00:00:00 2001
From: Adrian Prantl <aprantl at apple.com>
Date: Fri, 6 Nov 2026 10:37:10 -0800
Subject: [PATCH 3/4] [lldb] Support relocatable Mach-O DWARF sections
Symtab::InitAddressIndexes gives symbols without a size the distance
to the next symbol, capped at the end of the section that contains the
symbol's address.
With relocatable DWARF, every section in the __DWARF segment of a
Mach-O object starts at address 0, just like __text. That means the
lookup by address can incorrectly return a DWARF section instead of
__text. The last symbol in __text then gets a size that extends past
the end of __text.
Fix this by using the section the symbol is defined in, and fall back
to the lookup by address for symbols without one.
Assisted-by: Claude
rdar://192083461
---
lldb/source/Symbol/Symtab.cpp | 20 ++++++++++-----
.../MachO/symbol-size-shared-address.s | 25 +++++++++++++++++++
2 files changed, 39 insertions(+), 6 deletions(-)
create mode 100644 lldb/test/Shell/ObjectFile/MachO/symbol-size-shared-address.s
diff --git a/lldb/source/Symbol/Symtab.cpp b/lldb/source/Symbol/Symtab.cpp
index ce164a38b9c58b..9ae9391f9e87a0 100644
--- a/lldb/source/Symbol/Symtab.cpp
+++ b/lldb/source/Symbol/Symtab.cpp
@@ -943,15 +943,24 @@ void Symtab::InitAddressIndexes() {
m_file_addr_to_index.GetMutableEntryAtIndex(i);
if (entry->GetByteSize() == 0) {
addr_t curr_base_addr = entry->GetRangeBase();
- const RangeVector<addr_t, addr_t>::Entry *containing_section =
- section_ranges.FindEntryThatContains(curr_base_addr);
+ Symbol &symbol = m_symbols[entry->data];
- // Use the end of the section as the default max size of the symbol
+ // Use the end of the section as the default max size of the symbol.
+ // Sections of an object file can share addresses, so prefer the
+ // section the symbol is defined in over one found by its address.
addr_t sym_size = 0;
- if (containing_section) {
+ SectionSP symbol_section = symbol.GetAddressRef().GetSection();
+ if (symbol_section &&
+ symbol_section->ContainsFileAddress(curr_base_addr)) {
+ sym_size = symbol_section->GetFileAddress() +
+ symbol_section->GetByteSize() - curr_base_addr;
+ } else if (const RangeVector<addr_t, addr_t>::Entry
+ *containing_section =
+ section_ranges.FindEntryThatContains(
+ curr_base_addr)) {
sym_size =
containing_section->GetByteSize() -
- (entry->GetRangeBase() - containing_section->GetRangeBase());
+ (curr_base_addr - containing_section->GetRangeBase());
}
for (size_t j = i; j < num_entries; j++) {
@@ -972,7 +981,6 @@ void Symtab::InitAddressIndexes() {
if (sym_size > 0) {
entry->SetByteSize(sym_size);
- Symbol &symbol = m_symbols[entry->data];
symbol.SetByteSize(sym_size);
symbol.SetSizeIsSynthesized(true);
}
diff --git a/lldb/test/Shell/ObjectFile/MachO/symbol-size-shared-address.s b/lldb/test/Shell/ObjectFile/MachO/symbol-size-shared-address.s
new file mode 100644
index 00000000000000..74fd20bcaa13a2
--- /dev/null
+++ b/lldb/test/Shell/ObjectFile/MachO/symbol-size-shared-address.s
@@ -0,0 +1,25 @@
+# REQUIRES: x86
+
+# With relocatable DWARF, every __DWARF section of an object file starts at
+# address 0, like __text. A symbol without a size is still bounded by the end
+# of the section it is defined in.
+
+# RUN: llvm-mc -triple x86_64-apple-macosx -filetype=obj \
+# RUN: -macho-relocatable-dwarf %s -o %t.o
+# RUN: lldb-test symtab --find-symbols-by-regex='.*' %t.o | FileCheck %s
+
+# CHECK-DAG: Code 0x0000000000000000 0x0000000000000002 {{.*}} foo
+# CHECK-DAG: Code 0x0000000000000002 0x0000000000000002 {{.*}} bar
+
+ .text
+ .globl _foo
+_foo:
+ nop
+ ret
+ .globl _bar
+_bar:
+ nop
+ ret
+
+ .section __DWARF,__debug_str,regular,debug
+ .space 0x100
>From 16ef64476b0822a22779116209e1a8bb30751413 Mon Sep 17 00:00:00 2001
From: Adrian Prantl <aprantl at apple.com>
Date: Fri, 6 Nov 2026 16:45:37 -0800
Subject: [PATCH 4/4] fixup! [lldb] Support relocatable Mach-O DWARF sections
---
lldb/source/Symbol/Symtab.cpp | 24 +++++++------------
.../MachO/symbol-size-shared-address.s | 5 ++--
2 files changed, 12 insertions(+), 17 deletions(-)
diff --git a/lldb/source/Symbol/Symtab.cpp b/lldb/source/Symbol/Symtab.cpp
index 9ae9391f9e87a0..91e0dc3d9ae0cc 100644
--- a/lldb/source/Symbol/Symtab.cpp
+++ b/lldb/source/Symbol/Symtab.cpp
@@ -889,8 +889,10 @@ static void AddSectionsToRangeMap(SectionList *sectlist,
if (child_sectlist.GetNumSections(0) > 0) {
AddSectionsToRangeMap(&child_sectlist, section_ranges);
} else {
+ // Debug info sections can share addresses with the sections that
+ // symbols are defined in.
size_t size = sect_sp->GetByteSize();
- if (size > 0) {
+ if (size > 0 && !sect_sp->ContainsOnlyDebugInfo()) {
addr_t base_addr = sect_sp->GetFileAddress();
RangeVector<addr_t, addr_t>::Entry entry;
entry.SetRangeBase(base_addr);
@@ -943,24 +945,15 @@ void Symtab::InitAddressIndexes() {
m_file_addr_to_index.GetMutableEntryAtIndex(i);
if (entry->GetByteSize() == 0) {
addr_t curr_base_addr = entry->GetRangeBase();
- Symbol &symbol = m_symbols[entry->data];
+ const RangeVector<addr_t, addr_t>::Entry *containing_section =
+ section_ranges.FindEntryThatContains(curr_base_addr);
- // Use the end of the section as the default max size of the symbol.
- // Sections of an object file can share addresses, so prefer the
- // section the symbol is defined in over one found by its address.
+ // Use the end of the section as the default max size of the symbol
addr_t sym_size = 0;
- SectionSP symbol_section = symbol.GetAddressRef().GetSection();
- if (symbol_section &&
- symbol_section->ContainsFileAddress(curr_base_addr)) {
- sym_size = symbol_section->GetFileAddress() +
- symbol_section->GetByteSize() - curr_base_addr;
- } else if (const RangeVector<addr_t, addr_t>::Entry
- *containing_section =
- section_ranges.FindEntryThatContains(
- curr_base_addr)) {
+ if (containing_section) {
sym_size =
containing_section->GetByteSize() -
- (curr_base_addr - containing_section->GetRangeBase());
+ (entry->GetRangeBase() - containing_section->GetRangeBase());
}
for (size_t j = i; j < num_entries; j++) {
@@ -981,6 +974,7 @@ void Symtab::InitAddressIndexes() {
if (sym_size > 0) {
entry->SetByteSize(sym_size);
+ Symbol &symbol = m_symbols[entry->data];
symbol.SetByteSize(sym_size);
symbol.SetSizeIsSynthesized(true);
}
diff --git a/lldb/test/Shell/ObjectFile/MachO/symbol-size-shared-address.s b/lldb/test/Shell/ObjectFile/MachO/symbol-size-shared-address.s
index 74fd20bcaa13a2..13db52a394e3ff 100644
--- a/lldb/test/Shell/ObjectFile/MachO/symbol-size-shared-address.s
+++ b/lldb/test/Shell/ObjectFile/MachO/symbol-size-shared-address.s
@@ -8,12 +8,13 @@
# RUN: -macho-relocatable-dwarf %s -o %t.o
# RUN: lldb-test symtab --find-symbols-by-regex='.*' %t.o | FileCheck %s
-# CHECK-DAG: Code 0x0000000000000000 0x0000000000000002 {{.*}} foo
-# CHECK-DAG: Code 0x0000000000000002 0x0000000000000002 {{.*}} bar
+# CHECK-DAG: Code 0x0000000000000000 0x0000000000000003 {{.*}} foo
+# CHECK-DAG: Code 0x0000000000000003 0x0000000000000002 {{.*}} bar
.text
.globl _foo
_foo:
+ nop
nop
ret
.globl _bar
More information about the cfe-commits
mailing list