1 //===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "DwarfLinker.h"
10 #include "BinaryHolder.h"
12 #include "DeclContext.h"
13 #include "DwarfStreamer.h"
14 #include "MachOUtils.h"
15 #include "NonRelocatableStringpool.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/DenseMapInfo.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/Hashing.h"
24 #include "llvm/ADT/IntervalMap.h"
25 #include "llvm/ADT/None.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/PointerIntPair.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/ADT/Triple.h"
33 #include "llvm/ADT/Twine.h"
34 #include "llvm/BinaryFormat/Dwarf.h"
35 #include "llvm/BinaryFormat/MachO.h"
36 #include "llvm/CodeGen/AccelTable.h"
37 #include "llvm/CodeGen/AsmPrinter.h"
38 #include "llvm/CodeGen/DIE.h"
39 #include "llvm/Config/config.h"
40 #include "llvm/DebugInfo/DIContext.h"
41 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
42 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
43 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
44 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
45 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
46 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
47 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
48 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
49 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
50 #include "llvm/MC/MCAsmBackend.h"
51 #include "llvm/MC/MCAsmInfo.h"
52 #include "llvm/MC/MCCodeEmitter.h"
53 #include "llvm/MC/MCContext.h"
54 #include "llvm/MC/MCDwarf.h"
55 #include "llvm/MC/MCInstrInfo.h"
56 #include "llvm/MC/MCObjectFileInfo.h"
57 #include "llvm/MC/MCObjectWriter.h"
58 #include "llvm/MC/MCRegisterInfo.h"
59 #include "llvm/MC/MCSection.h"
60 #include "llvm/MC/MCStreamer.h"
61 #include "llvm/MC/MCSubtargetInfo.h"
62 #include "llvm/MC/MCTargetOptions.h"
63 #include "llvm/Object/MachO.h"
64 #include "llvm/Object/ObjectFile.h"
65 #include "llvm/Object/SymbolicFile.h"
66 #include "llvm/Support/Allocator.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/DJB.h"
70 #include "llvm/Support/DataExtractor.h"
71 #include "llvm/Support/Error.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/ErrorOr.h"
74 #include "llvm/Support/FileSystem.h"
75 #include "llvm/Support/Format.h"
76 #include "llvm/Support/LEB128.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Support/MemoryBuffer.h"
79 #include "llvm/Support/Path.h"
80 #include "llvm/Support/TargetRegistry.h"
81 #include "llvm/Support/ThreadPool.h"
82 #include "llvm/Support/ToolOutputFile.h"
83 #include "llvm/Support/WithColor.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetMachine.h"
86 #include "llvm/Target/TargetOptions.h"
98 #include <system_error>
106 /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
107 /// CompileUnit object instead.
108 static CompileUnit
*getUnitForOffset(const UnitListTy
&Units
, uint64_t Offset
) {
109 auto CU
= std::upper_bound(
110 Units
.begin(), Units
.end(), Offset
,
111 [](uint64_t LHS
, const std::unique_ptr
<CompileUnit
> &RHS
) {
112 return LHS
< RHS
->getOrigUnit().getNextUnitOffset();
114 return CU
!= Units
.end() ? CU
->get() : nullptr;
117 /// Resolve the DIE attribute reference that has been extracted in \p RefValue.
118 /// The resulting DIE might be in another CompileUnit which is stored into \p
119 /// ReferencedCU. \returns null if resolving fails for any reason.
120 static DWARFDie
resolveDIEReference(const DwarfLinker
&Linker
,
121 const DebugMapObject
&DMO
,
122 const UnitListTy
&Units
,
123 const DWARFFormValue
&RefValue
,
124 const DWARFDie
&DIE
, CompileUnit
*&RefCU
) {
125 assert(RefValue
.isFormClass(DWARFFormValue::FC_Reference
));
126 uint64_t RefOffset
= *RefValue
.getAsReference();
127 if ((RefCU
= getUnitForOffset(Units
, RefOffset
)))
128 if (const auto RefDie
= RefCU
->getOrigUnit().getDIEForOffset(RefOffset
)) {
129 // In a file with broken references, an attribute might point to a NULL
131 if (!RefDie
.isNULL())
135 Linker
.reportWarning("could not find referenced DIE", DMO
, &DIE
);
139 /// \returns whether the passed \a Attr type might contain a DIE reference
140 /// suitable for ODR uniquing.
141 static bool isODRAttribute(uint16_t Attr
) {
145 case dwarf::DW_AT_type
:
146 case dwarf::DW_AT_containing_type
:
147 case dwarf::DW_AT_specification
:
148 case dwarf::DW_AT_abstract_origin
:
149 case dwarf::DW_AT_import
:
152 llvm_unreachable("Improper attribute.");
155 static bool isTypeTag(uint16_t Tag
) {
157 case dwarf::DW_TAG_array_type
:
158 case dwarf::DW_TAG_class_type
:
159 case dwarf::DW_TAG_enumeration_type
:
160 case dwarf::DW_TAG_pointer_type
:
161 case dwarf::DW_TAG_reference_type
:
162 case dwarf::DW_TAG_string_type
:
163 case dwarf::DW_TAG_structure_type
:
164 case dwarf::DW_TAG_subroutine_type
:
165 case dwarf::DW_TAG_typedef
:
166 case dwarf::DW_TAG_union_type
:
167 case dwarf::DW_TAG_ptr_to_member_type
:
168 case dwarf::DW_TAG_set_type
:
169 case dwarf::DW_TAG_subrange_type
:
170 case dwarf::DW_TAG_base_type
:
171 case dwarf::DW_TAG_const_type
:
172 case dwarf::DW_TAG_constant
:
173 case dwarf::DW_TAG_file_type
:
174 case dwarf::DW_TAG_namelist
:
175 case dwarf::DW_TAG_packed_type
:
176 case dwarf::DW_TAG_volatile_type
:
177 case dwarf::DW_TAG_restrict_type
:
178 case dwarf::DW_TAG_atomic_type
:
179 case dwarf::DW_TAG_interface_type
:
180 case dwarf::DW_TAG_unspecified_type
:
181 case dwarf::DW_TAG_shared_type
:
189 bool DwarfLinker::DIECloner::getDIENames(const DWARFDie
&Die
,
190 AttributesInfo
&Info
,
191 OffsetsStringPool
&StringPool
,
192 bool StripTemplate
) {
193 // This function will be called on DIEs having low_pcs and
194 // ranges. As getting the name might be more expansive, filter out
196 if (Die
.getTag() == dwarf::DW_TAG_lexical_block
)
199 // FIXME: a bit wasteful as the first getName might return the
201 if (!Info
.MangledName
)
202 if (const char *MangledName
= Die
.getName(DINameKind::LinkageName
))
203 Info
.MangledName
= StringPool
.getEntry(MangledName
);
206 if (const char *Name
= Die
.getName(DINameKind::ShortName
))
207 Info
.Name
= StringPool
.getEntry(Name
);
209 if (StripTemplate
&& Info
.Name
&& Info
.MangledName
!= Info
.Name
) {
210 // FIXME: dsymutil compatibility. This is wrong for operator<
211 auto Split
= Info
.Name
.getString().split('<');
212 if (!Split
.second
.empty())
213 Info
.NameWithoutTemplate
= StringPool
.getEntry(Split
.first
);
216 return Info
.Name
|| Info
.MangledName
;
219 /// Report a warning to the user, optionally including information about a
220 /// specific \p DIE related to the warning.
221 void DwarfLinker::reportWarning(const Twine
&Warning
, const DebugMapObject
&DMO
,
222 const DWARFDie
*DIE
) const {
223 StringRef Context
= DMO
.getObjectFilename();
224 warn(Warning
, Context
);
226 if (!Options
.Verbose
|| !DIE
)
229 DIDumpOptions DumpOpts
;
230 DumpOpts
.ChildRecurseDepth
= 0;
231 DumpOpts
.Verbose
= Options
.Verbose
;
233 WithColor::note() << " in DIE:\n";
234 DIE
->dump(errs(), 6 /* Indent */, DumpOpts
);
237 bool DwarfLinker::createStreamer(const Triple
&TheTriple
,
238 raw_fd_ostream
&OutFile
) {
239 if (Options
.NoOutput
)
242 Streamer
= std::make_unique
<DwarfStreamer
>(OutFile
, Options
);
243 return Streamer
->init(TheTriple
);
246 /// Resolve the relative path to a build artifact referenced by DWARF by
247 /// applying DW_AT_comp_dir.
248 static void resolveRelativeObjectPath(SmallVectorImpl
<char> &Buf
, DWARFDie CU
) {
249 sys::path::append(Buf
, dwarf::toString(CU
.find(dwarf::DW_AT_comp_dir
), ""));
252 /// Collect references to parseable Swift interfaces in imported
253 /// DW_TAG_module blocks.
254 static void analyzeImportedModule(
255 const DWARFDie
&DIE
, CompileUnit
&CU
,
256 std::map
<std::string
, std::string
> &ParseableSwiftInterfaces
,
257 std::function
<void(const Twine
&, const DWARFDie
&)> ReportWarning
) {
258 if (CU
.getLanguage() != dwarf::DW_LANG_Swift
)
261 StringRef Path
= dwarf::toStringRef(DIE
.find(dwarf::DW_AT_LLVM_include_path
));
262 if (!Path
.endswith(".swiftinterface"))
264 if (Optional
<DWARFFormValue
> Val
= DIE
.find(dwarf::DW_AT_name
))
265 if (Optional
<const char *> Name
= Val
->getAsCString()) {
266 auto &Entry
= ParseableSwiftInterfaces
[*Name
];
267 // The prepend path is applied later when copying.
268 DWARFDie CUDie
= CU
.getOrigUnit().getUnitDIE();
269 SmallString
<128> ResolvedPath
;
270 if (sys::path::is_relative(Path
))
271 resolveRelativeObjectPath(ResolvedPath
, CUDie
);
272 sys::path::append(ResolvedPath
, Path
);
273 if (!Entry
.empty() && Entry
!= ResolvedPath
)
275 Twine("Conflicting parseable interfaces for Swift Module ") +
276 *Name
+ ": " + Entry
+ " and " + Path
,
278 Entry
= ResolvedPath
.str();
282 /// Recursive helper to build the global DeclContext information and
283 /// gather the child->parent relationships in the original compile unit.
285 /// \return true when this DIE and all of its children are only
286 /// forward declarations to types defined in external clang modules
287 /// (i.e., forward declarations that are children of a DW_TAG_module).
288 static bool analyzeContextInfo(
289 const DWARFDie
&DIE
, unsigned ParentIdx
, CompileUnit
&CU
,
290 DeclContext
*CurrentDeclContext
, UniquingStringPool
&StringPool
,
291 DeclContextTree
&Contexts
, uint64_t ModulesEndOffset
,
292 std::map
<std::string
, std::string
> &ParseableSwiftInterfaces
,
293 std::function
<void(const Twine
&, const DWARFDie
&)> ReportWarning
,
294 bool InImportedModule
= false) {
295 unsigned MyIdx
= CU
.getOrigUnit().getDIEIndex(DIE
);
296 CompileUnit::DIEInfo
&Info
= CU
.getInfo(MyIdx
);
298 // Clang imposes an ODR on modules(!) regardless of the language:
299 // "The module-id should consist of only a single identifier,
300 // which provides the name of the module being defined. Each
301 // module shall have a single definition."
303 // This does not extend to the types inside the modules:
304 // "[I]n C, this implies that if two structs are defined in
305 // different submodules with the same name, those two types are
306 // distinct types (but may be compatible types if their
307 // definitions match)."
309 // We treat non-C++ modules like namespaces for this reason.
310 if (DIE
.getTag() == dwarf::DW_TAG_module
&& ParentIdx
== 0 &&
311 dwarf::toString(DIE
.find(dwarf::DW_AT_name
), "") !=
312 CU
.getClangModuleName()) {
313 InImportedModule
= true;
314 analyzeImportedModule(DIE
, CU
, ParseableSwiftInterfaces
, ReportWarning
);
317 Info
.ParentIdx
= ParentIdx
;
318 bool InClangModule
= CU
.isClangModule() || InImportedModule
;
319 if (CU
.hasODR() || InClangModule
) {
320 if (CurrentDeclContext
) {
321 auto PtrInvalidPair
= Contexts
.getChildDeclContext(
322 *CurrentDeclContext
, DIE
, CU
, StringPool
, InClangModule
);
323 CurrentDeclContext
= PtrInvalidPair
.getPointer();
325 PtrInvalidPair
.getInt() ? nullptr : PtrInvalidPair
.getPointer();
327 Info
.Ctxt
->setDefinedInClangModule(InClangModule
);
329 Info
.Ctxt
= CurrentDeclContext
= nullptr;
332 Info
.Prune
= InImportedModule
;
333 if (DIE
.hasChildren())
334 for (auto Child
: DIE
.children())
335 Info
.Prune
&= analyzeContextInfo(Child
, MyIdx
, CU
, CurrentDeclContext
,
336 StringPool
, Contexts
, ModulesEndOffset
,
337 ParseableSwiftInterfaces
, ReportWarning
,
340 // Prune this DIE if it is either a forward declaration inside a
341 // DW_TAG_module or a DW_TAG_module that contains nothing but
342 // forward declarations.
343 Info
.Prune
&= (DIE
.getTag() == dwarf::DW_TAG_module
) ||
344 (isTypeTag(DIE
.getTag()) &&
345 dwarf::toUnsigned(DIE
.find(dwarf::DW_AT_declaration
), 0));
347 // Only prune forward declarations inside a DW_TAG_module for which a
348 // definition exists elsewhere.
349 if (ModulesEndOffset
== 0)
350 Info
.Prune
&= Info
.Ctxt
&& Info
.Ctxt
->getCanonicalDIEOffset();
352 Info
.Prune
&= Info
.Ctxt
&& Info
.Ctxt
->getCanonicalDIEOffset() > 0 &&
353 Info
.Ctxt
->getCanonicalDIEOffset() <= ModulesEndOffset
;
356 } // namespace dsymutil
358 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag
) {
362 case dwarf::DW_TAG_subprogram
:
363 case dwarf::DW_TAG_lexical_block
:
364 case dwarf::DW_TAG_subroutine_type
:
365 case dwarf::DW_TAG_structure_type
:
366 case dwarf::DW_TAG_class_type
:
367 case dwarf::DW_TAG_union_type
:
370 llvm_unreachable("Invalid Tag");
373 void DwarfLinker::startDebugObject(LinkContext
&Context
) {
374 // Iterate over the debug map entries and put all the ones that are
375 // functions (because they have a size) into the Ranges map. This map is
376 // very similar to the FunctionRanges that are stored in each unit, with 2
377 // notable differences:
379 // 1. Obviously this one is global, while the other ones are per-unit.
381 // 2. This one contains not only the functions described in the DIE
382 // tree, but also the ones that are only in the debug map.
384 // The latter information is required to reproduce dsymutil's logic while
385 // linking line tables. The cases where this information matters look like
386 // bugs that need to be investigated, but for now we need to reproduce
387 // dsymutil's behavior.
388 // FIXME: Once we understood exactly if that information is needed,
389 // maybe totally remove this (or try to use it to do a real
390 // -gline-tables-only on Darwin.
391 for (const auto &Entry
: Context
.DMO
.symbols()) {
392 const auto &Mapping
= Entry
.getValue();
393 if (Mapping
.Size
&& Mapping
.ObjectAddress
)
394 Context
.Ranges
[*Mapping
.ObjectAddress
] = DebugMapObjectRange(
395 *Mapping
.ObjectAddress
+ Mapping
.Size
,
396 int64_t(Mapping
.BinaryAddress
) - *Mapping
.ObjectAddress
);
400 void DwarfLinker::endDebugObject(LinkContext
&Context
) {
403 for (auto I
= DIEBlocks
.begin(), E
= DIEBlocks
.end(); I
!= E
; ++I
)
405 for (auto I
= DIELocs
.begin(), E
= DIELocs
.end(); I
!= E
; ++I
)
413 static bool isMachOPairedReloc(uint64_t RelocType
, uint64_t Arch
) {
416 return RelocType
== MachO::GENERIC_RELOC_SECTDIFF
||
417 RelocType
== MachO::GENERIC_RELOC_LOCAL_SECTDIFF
;
419 return RelocType
== MachO::X86_64_RELOC_SUBTRACTOR
;
422 return RelocType
== MachO::ARM_RELOC_SECTDIFF
||
423 RelocType
== MachO::ARM_RELOC_LOCAL_SECTDIFF
||
424 RelocType
== MachO::ARM_RELOC_HALF
||
425 RelocType
== MachO::ARM_RELOC_HALF_SECTDIFF
;
426 case Triple::aarch64
:
427 return RelocType
== MachO::ARM64_RELOC_SUBTRACTOR
;
433 /// Iterate over the relocations of the given \p Section and
434 /// store the ones that correspond to debug map entries into the
435 /// ValidRelocs array.
436 void DwarfLinker::RelocationManager::findValidRelocsMachO(
437 const object::SectionRef
&Section
, const object::MachOObjectFile
&Obj
,
438 const DebugMapObject
&DMO
) {
439 Expected
<StringRef
> ContentsOrErr
= Section
.getContents();
440 if (!ContentsOrErr
) {
441 consumeError(ContentsOrErr
.takeError());
442 Linker
.reportWarning("error reading section", DMO
);
445 DataExtractor
Data(*ContentsOrErr
, Obj
.isLittleEndian(), 0);
446 bool SkipNext
= false;
448 for (const object::RelocationRef
&Reloc
: Section
.relocations()) {
454 object::DataRefImpl RelocDataRef
= Reloc
.getRawDataRefImpl();
455 MachO::any_relocation_info MachOReloc
= Obj
.getRelocation(RelocDataRef
);
457 if (isMachOPairedReloc(Obj
.getAnyRelocationType(MachOReloc
),
460 Linker
.reportWarning("unsupported relocation in debug_info section.",
465 unsigned RelocSize
= 1 << Obj
.getAnyRelocationLength(MachOReloc
);
466 uint64_t Offset64
= Reloc
.getOffset();
467 if ((RelocSize
!= 4 && RelocSize
!= 8)) {
468 Linker
.reportWarning("unsupported relocation in debug_info section.",
472 uint64_t OffsetCopy
= Offset64
;
473 // Mach-o uses REL relocations, the addend is at the relocation offset.
474 uint64_t Addend
= Data
.getUnsigned(&OffsetCopy
, RelocSize
);
478 if (Obj
.isRelocationScattered(MachOReloc
)) {
479 // The address of the base symbol for scattered relocations is
480 // stored in the reloc itself. The actual addend will store the
481 // base address plus the offset.
482 SymAddress
= Obj
.getScatteredRelocationValue(MachOReloc
);
483 SymOffset
= int64_t(Addend
) - SymAddress
;
489 auto Sym
= Reloc
.getSymbol();
490 if (Sym
!= Obj
.symbol_end()) {
491 Expected
<StringRef
> SymbolName
= Sym
->getName();
493 consumeError(SymbolName
.takeError());
494 Linker
.reportWarning("error getting relocation symbol name.", DMO
);
497 if (const auto *Mapping
= DMO
.lookupSymbol(*SymbolName
))
498 ValidRelocs
.emplace_back(Offset64
, RelocSize
, Addend
, Mapping
);
499 } else if (const auto *Mapping
= DMO
.lookupObjectAddress(SymAddress
)) {
500 // Do not store the addend. The addend was the address of the symbol in
501 // the object file, the address in the binary that is stored in the debug
502 // map doesn't need to be offset.
503 ValidRelocs
.emplace_back(Offset64
, RelocSize
, SymOffset
, Mapping
);
508 /// Dispatch the valid relocation finding logic to the
509 /// appropriate handler depending on the object file format.
510 bool DwarfLinker::RelocationManager::findValidRelocs(
511 const object::SectionRef
&Section
, const object::ObjectFile
&Obj
,
512 const DebugMapObject
&DMO
) {
513 // Dispatch to the right handler depending on the file type.
514 if (auto *MachOObj
= dyn_cast
<object::MachOObjectFile
>(&Obj
))
515 findValidRelocsMachO(Section
, *MachOObj
, DMO
);
517 Linker
.reportWarning(
518 Twine("unsupported object file type: ") + Obj
.getFileName(), DMO
);
520 if (ValidRelocs
.empty())
523 // Sort the relocations by offset. We will walk the DIEs linearly in
524 // the file, this allows us to just keep an index in the relocation
525 // array that we advance during our walk, rather than resorting to
526 // some associative container. See DwarfLinker::NextValidReloc.
527 llvm::sort(ValidRelocs
);
531 /// Look for relocations in the debug_info section that match
532 /// entries in the debug map. These relocations will drive the Dwarf
533 /// link by indicating which DIEs refer to symbols present in the
535 /// \returns whether there are any valid relocations in the debug info.
536 bool DwarfLinker::RelocationManager::findValidRelocsInDebugInfo(
537 const object::ObjectFile
&Obj
, const DebugMapObject
&DMO
) {
538 // Find the debug_info section.
539 for (const object::SectionRef
&Section
: Obj
.sections()) {
540 StringRef SectionName
;
541 if (Expected
<StringRef
> NameOrErr
= Section
.getName())
542 SectionName
= *NameOrErr
;
544 consumeError(NameOrErr
.takeError());
546 SectionName
= SectionName
.substr(SectionName
.find_first_not_of("._"));
547 if (SectionName
!= "debug_info")
549 return findValidRelocs(Section
, Obj
, DMO
);
554 /// Checks that there is a relocation against an actual debug
555 /// map entry between \p StartOffset and \p NextOffset.
557 /// This function must be called with offsets in strictly ascending
558 /// order because it never looks back at relocations it already 'went past'.
559 /// \returns true and sets Info.InDebugMap if it is the case.
560 bool DwarfLinker::RelocationManager::hasValidRelocation(
561 uint64_t StartOffset
, uint64_t EndOffset
, CompileUnit::DIEInfo
&Info
) {
562 assert(NextValidReloc
== 0 ||
563 StartOffset
> ValidRelocs
[NextValidReloc
- 1].Offset
);
564 if (NextValidReloc
>= ValidRelocs
.size())
567 uint64_t RelocOffset
= ValidRelocs
[NextValidReloc
].Offset
;
569 // We might need to skip some relocs that we didn't consider. For
570 // example the high_pc of a discarded DIE might contain a reloc that
571 // is in the list because it actually corresponds to the start of a
572 // function that is in the debug map.
573 while (RelocOffset
< StartOffset
&& NextValidReloc
< ValidRelocs
.size() - 1)
574 RelocOffset
= ValidRelocs
[++NextValidReloc
].Offset
;
576 if (RelocOffset
< StartOffset
|| RelocOffset
>= EndOffset
)
579 const auto &ValidReloc
= ValidRelocs
[NextValidReloc
++];
580 const auto &Mapping
= ValidReloc
.Mapping
->getValue();
581 uint64_t ObjectAddress
= Mapping
.ObjectAddress
582 ? uint64_t(*Mapping
.ObjectAddress
)
583 : std::numeric_limits
<uint64_t>::max();
584 if (Linker
.Options
.Verbose
)
585 outs() << "Found valid debug map entry: " << ValidReloc
.Mapping
->getKey()
587 << format("\t%016" PRIx64
" => %016" PRIx64
, ObjectAddress
,
588 uint64_t(Mapping
.BinaryAddress
));
590 Info
.AddrAdjust
= int64_t(Mapping
.BinaryAddress
) + ValidReloc
.Addend
;
591 if (Mapping
.ObjectAddress
)
592 Info
.AddrAdjust
-= ObjectAddress
;
593 Info
.InDebugMap
= true;
597 /// Get the starting and ending (exclusive) offset for the
598 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
599 /// supposed to point to the position of the first attribute described
601 /// \return [StartOffset, EndOffset) as a pair.
602 static std::pair
<uint64_t, uint64_t>
603 getAttributeOffsets(const DWARFAbbreviationDeclaration
*Abbrev
, unsigned Idx
,
604 uint64_t Offset
, const DWARFUnit
&Unit
) {
605 DataExtractor Data
= Unit
.getDebugInfoExtractor();
607 for (unsigned i
= 0; i
< Idx
; ++i
)
608 DWARFFormValue::skipValue(Abbrev
->getFormByIndex(i
), Data
, &Offset
,
609 Unit
.getFormParams());
611 uint64_t End
= Offset
;
612 DWARFFormValue::skipValue(Abbrev
->getFormByIndex(Idx
), Data
, &End
,
613 Unit
.getFormParams());
615 return std::make_pair(Offset
, End
);
618 /// Check if a variable describing DIE should be kept.
619 /// \returns updated TraversalFlags.
620 unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager
&RelocMgr
,
623 CompileUnit::DIEInfo
&MyInfo
,
625 const auto *Abbrev
= DIE
.getAbbreviationDeclarationPtr();
627 // Global variables with constant value can always be kept.
628 if (!(Flags
& TF_InFunctionScope
) &&
629 Abbrev
->findAttributeIndex(dwarf::DW_AT_const_value
)) {
630 MyInfo
.InDebugMap
= true;
631 return Flags
| TF_Keep
;
634 Optional
<uint32_t> LocationIdx
=
635 Abbrev
->findAttributeIndex(dwarf::DW_AT_location
);
639 uint64_t Offset
= DIE
.getOffset() + getULEB128Size(Abbrev
->getCode());
640 const DWARFUnit
&OrigUnit
= Unit
.getOrigUnit();
641 uint64_t LocationOffset
, LocationEndOffset
;
642 std::tie(LocationOffset
, LocationEndOffset
) =
643 getAttributeOffsets(Abbrev
, *LocationIdx
, Offset
, OrigUnit
);
645 // See if there is a relocation to a valid debug map entry inside
646 // this variable's location. The order is important here. We want to
647 // always check in the variable has a valid relocation, so that the
648 // DIEInfo is filled. However, we don't want a static variable in a
649 // function to force us to keep the enclosing function.
650 if (!RelocMgr
.hasValidRelocation(LocationOffset
, LocationEndOffset
, MyInfo
) ||
651 (Flags
& TF_InFunctionScope
))
654 if (Options
.Verbose
) {
655 DIDumpOptions DumpOpts
;
656 DumpOpts
.ChildRecurseDepth
= 0;
657 DumpOpts
.Verbose
= Options
.Verbose
;
658 DIE
.dump(outs(), 8 /* Indent */, DumpOpts
);
661 return Flags
| TF_Keep
;
664 /// Check if a function describing DIE should be kept.
665 /// \returns updated TraversalFlags.
666 unsigned DwarfLinker::shouldKeepSubprogramDIE(
667 RelocationManager
&RelocMgr
, RangesTy
&Ranges
, const DWARFDie
&DIE
,
668 const DebugMapObject
&DMO
, CompileUnit
&Unit
, CompileUnit::DIEInfo
&MyInfo
,
670 const auto *Abbrev
= DIE
.getAbbreviationDeclarationPtr();
672 Flags
|= TF_InFunctionScope
;
674 Optional
<uint32_t> LowPcIdx
= Abbrev
->findAttributeIndex(dwarf::DW_AT_low_pc
);
678 uint64_t Offset
= DIE
.getOffset() + getULEB128Size(Abbrev
->getCode());
679 DWARFUnit
&OrigUnit
= Unit
.getOrigUnit();
680 uint64_t LowPcOffset
, LowPcEndOffset
;
681 std::tie(LowPcOffset
, LowPcEndOffset
) =
682 getAttributeOffsets(Abbrev
, *LowPcIdx
, Offset
, OrigUnit
);
684 auto LowPc
= dwarf::toAddress(DIE
.find(dwarf::DW_AT_low_pc
));
685 assert(LowPc
.hasValue() && "low_pc attribute is not an address.");
687 !RelocMgr
.hasValidRelocation(LowPcOffset
, LowPcEndOffset
, MyInfo
))
690 if (Options
.Verbose
) {
691 DIDumpOptions DumpOpts
;
692 DumpOpts
.ChildRecurseDepth
= 0;
693 DumpOpts
.Verbose
= Options
.Verbose
;
694 DIE
.dump(outs(), 8 /* Indent */, DumpOpts
);
697 if (DIE
.getTag() == dwarf::DW_TAG_label
) {
698 if (Unit
.hasLabelAt(*LowPc
))
700 // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
701 // that don't fall into the CU's aranges. This is wrong IMO. Debug info
702 // generation bugs aside, this is really wrong in the case of labels, where
703 // a label marking the end of a function will have a PC == CU's high_pc.
704 if (dwarf::toAddress(OrigUnit
.getUnitDIE().find(dwarf::DW_AT_high_pc
))
705 .getValueOr(UINT64_MAX
) <= LowPc
)
707 Unit
.addLabelLowPc(*LowPc
, MyInfo
.AddrAdjust
);
708 return Flags
| TF_Keep
;
713 Optional
<uint64_t> HighPc
= DIE
.getHighPC(*LowPc
);
715 reportWarning("Function without high_pc. Range will be discarded.\n", DMO
,
720 // Replace the debug map range with a more accurate one.
721 Ranges
[*LowPc
] = DebugMapObjectRange(*HighPc
, MyInfo
.AddrAdjust
);
722 Unit
.addFunctionRange(*LowPc
, *HighPc
, MyInfo
.AddrAdjust
);
726 /// Check if a DIE should be kept.
727 /// \returns updated TraversalFlags.
728 unsigned DwarfLinker::shouldKeepDIE(RelocationManager
&RelocMgr
,
729 RangesTy
&Ranges
, const DWARFDie
&DIE
,
730 const DebugMapObject
&DMO
,
732 CompileUnit::DIEInfo
&MyInfo
,
734 switch (DIE
.getTag()) {
735 case dwarf::DW_TAG_constant
:
736 case dwarf::DW_TAG_variable
:
737 return shouldKeepVariableDIE(RelocMgr
, DIE
, Unit
, MyInfo
, Flags
);
738 case dwarf::DW_TAG_subprogram
:
739 case dwarf::DW_TAG_label
:
740 return shouldKeepSubprogramDIE(RelocMgr
, Ranges
, DIE
, DMO
, Unit
, MyInfo
,
742 case dwarf::DW_TAG_base_type
:
743 // DWARF Expressions may reference basic types, but scanning them
744 // is expensive. Basic types are tiny, so just keep all of them.
745 case dwarf::DW_TAG_imported_module
:
746 case dwarf::DW_TAG_imported_declaration
:
747 case dwarf::DW_TAG_imported_unit
:
748 // We always want to keep these.
749 return Flags
| TF_Keep
;
757 /// Mark the passed DIE as well as all the ones it depends on
760 /// This function is called by lookForDIEsToKeep on DIEs that are
761 /// newly discovered to be needed in the link. It recursively calls
762 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
763 /// TraversalFlags to inform it that it's not doing the primary DIE
765 void DwarfLinker::keepDIEAndDependencies(
766 RelocationManager
&RelocMgr
, RangesTy
&Ranges
, const UnitListTy
&Units
,
767 const DWARFDie
&Die
, CompileUnit::DIEInfo
&MyInfo
,
768 const DebugMapObject
&DMO
, CompileUnit
&CU
, bool UseODR
) {
769 DWARFUnit
&Unit
= CU
.getOrigUnit();
772 // We're looking for incomplete types.
773 MyInfo
.Incomplete
= Die
.getTag() != dwarf::DW_TAG_subprogram
&&
774 Die
.getTag() != dwarf::DW_TAG_member
&&
775 dwarf::toUnsigned(Die
.find(dwarf::DW_AT_declaration
), 0);
777 // First mark all the parent chain as kept.
778 unsigned AncestorIdx
= MyInfo
.ParentIdx
;
779 while (!CU
.getInfo(AncestorIdx
).Keep
) {
780 unsigned ODRFlag
= UseODR
? TF_ODR
: 0;
781 lookForDIEsToKeep(RelocMgr
, Ranges
, Units
, Unit
.getDIEAtIndex(AncestorIdx
),
783 TF_ParentWalk
| TF_Keep
| TF_DependencyWalk
| ODRFlag
);
784 AncestorIdx
= CU
.getInfo(AncestorIdx
).ParentIdx
;
787 // Then we need to mark all the DIEs referenced by this DIE's
788 // attributes as kept.
789 DWARFDataExtractor Data
= Unit
.getDebugInfoExtractor();
790 const auto *Abbrev
= Die
.getAbbreviationDeclarationPtr();
791 uint64_t Offset
= Die
.getOffset() + getULEB128Size(Abbrev
->getCode());
793 // Mark all DIEs referenced through attributes as kept.
794 for (const auto &AttrSpec
: Abbrev
->attributes()) {
795 DWARFFormValue
Val(AttrSpec
.Form
);
796 if (!Val
.isFormClass(DWARFFormValue::FC_Reference
) ||
797 AttrSpec
.Attr
== dwarf::DW_AT_sibling
) {
798 DWARFFormValue::skipValue(AttrSpec
.Form
, Data
, &Offset
,
799 Unit
.getFormParams());
803 Val
.extractValue(Data
, &Offset
, Unit
.getFormParams(), &Unit
);
804 CompileUnit
*ReferencedCU
;
806 resolveDIEReference(*this, DMO
, Units
, Val
, Die
, ReferencedCU
)) {
807 uint32_t RefIdx
= ReferencedCU
->getOrigUnit().getDIEIndex(RefDie
);
808 CompileUnit::DIEInfo
&Info
= ReferencedCU
->getInfo(RefIdx
);
809 bool IsModuleRef
= Info
.Ctxt
&& Info
.Ctxt
->getCanonicalDIEOffset() &&
810 Info
.Ctxt
->isDefinedInClangModule();
811 // If the referenced DIE has a DeclContext that has already been
812 // emitted, then do not keep the one in this CU. We'll link to
813 // the canonical DIE in cloneDieReferenceAttribute.
814 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
815 // be necessary and could be advantageously replaced by
816 // ReferencedCU->hasODR() && CU.hasODR().
817 // FIXME: compatibility with dsymutil-classic. There is no
818 // reason not to unique ref_addr references.
819 if (AttrSpec
.Form
!= dwarf::DW_FORM_ref_addr
&& (UseODR
|| IsModuleRef
) &&
821 Info
.Ctxt
!= ReferencedCU
->getInfo(Info
.ParentIdx
).Ctxt
&&
822 Info
.Ctxt
->getCanonicalDIEOffset() && isODRAttribute(AttrSpec
.Attr
))
825 // Keep a module forward declaration if there is no definition.
826 if (!(isODRAttribute(AttrSpec
.Attr
) && Info
.Ctxt
&&
827 Info
.Ctxt
->getCanonicalDIEOffset()))
830 unsigned ODRFlag
= UseODR
? TF_ODR
: 0;
831 lookForDIEsToKeep(RelocMgr
, Ranges
, Units
, RefDie
, DMO
, *ReferencedCU
,
832 TF_Keep
| TF_DependencyWalk
| ODRFlag
);
834 // The incomplete property is propagated if the current DIE is complete
835 // but references an incomplete DIE.
836 if (Info
.Incomplete
&& !MyInfo
.Incomplete
&&
837 (Die
.getTag() == dwarf::DW_TAG_typedef
||
838 Die
.getTag() == dwarf::DW_TAG_member
||
839 Die
.getTag() == dwarf::DW_TAG_reference_type
||
840 Die
.getTag() == dwarf::DW_TAG_ptr_to_member_type
||
841 Die
.getTag() == dwarf::DW_TAG_pointer_type
))
842 MyInfo
.Incomplete
= true;
848 /// This class represents an item in the work list. In addition to it's obvious
849 /// purpose of representing the state associated with a particular run of the
850 /// work loop, it also serves as a marker to indicate that we should run the
851 /// "continuation" code.
853 /// Originally, the latter was lambda which allowed arbitrary code to be run.
854 /// Because we always need to run the exact same code, it made more sense to
855 /// use a boolean and repurpose the already existing DIE field.
856 struct WorklistItem
{
860 CompileUnit::DIEInfo
*ChildInfo
= nullptr;
862 /// Construct a classic worklist item.
863 WorklistItem(DWARFDie Die
, unsigned Flags
)
864 : Die(Die
), Flags(Flags
), IsContinuation(false){};
866 /// Creates a continuation marker.
867 WorklistItem(DWARFDie Die
) : Die(Die
), IsContinuation(true){};
871 // Helper that updates the completeness of the current DIE. It depends on the
872 // fact that the incompletness of its children is already computed.
873 static void updateIncompleteness(const DWARFDie
&Die
,
874 CompileUnit::DIEInfo
&ChildInfo
,
876 // Only propagate incomplete members.
877 if (Die
.getTag() != dwarf::DW_TAG_structure_type
&&
878 Die
.getTag() != dwarf::DW_TAG_class_type
)
881 unsigned Idx
= CU
.getOrigUnit().getDIEIndex(Die
);
882 CompileUnit::DIEInfo
&MyInfo
= CU
.getInfo(Idx
);
884 if (MyInfo
.Incomplete
)
887 if (ChildInfo
.Incomplete
|| ChildInfo
.Prune
)
888 MyInfo
.Incomplete
= true;
891 /// Recursively walk the \p DIE tree and look for DIEs to
892 /// keep. Store that information in \p CU's DIEInfo.
894 /// This function is the entry point of the DIE selection
895 /// algorithm. It is expected to walk the DIE tree in file order and
896 /// (though the mediation of its helper) call hasValidRelocation() on
897 /// each DIE that might be a 'root DIE' (See DwarfLinker class
899 /// While walking the dependencies of root DIEs, this function is
900 /// also called, but during these dependency walks the file order is
901 /// not respected. The TF_DependencyWalk flag tells us which kind of
902 /// traversal we are currently doing.
904 /// The return value indicates whether the DIE is incomplete.
905 void DwarfLinker::lookForDIEsToKeep(RelocationManager
&RelocMgr
,
906 RangesTy
&Ranges
, const UnitListTy
&Units
,
908 const DebugMapObject
&DMO
, CompileUnit
&CU
,
911 SmallVector
<WorklistItem
, 4> Worklist
;
912 Worklist
.emplace_back(Die
, Flags
);
914 while (!Worklist
.empty()) {
915 WorklistItem Current
= Worklist
.back();
918 if (Current
.IsContinuation
) {
919 updateIncompleteness(Current
.Die
, *Current
.ChildInfo
, CU
);
923 unsigned Idx
= CU
.getOrigUnit().getDIEIndex(Current
.Die
);
924 CompileUnit::DIEInfo
&MyInfo
= CU
.getInfo(Idx
);
926 // At this point we are guaranteed to have a continuation marker before us
927 // in the worklist, except for the last DIE.
928 if (!Worklist
.empty())
929 Worklist
.back().ChildInfo
= &MyInfo
;
934 // If the Keep flag is set, we are marking a required DIE's dependencies.
935 // If our target is already marked as kept, we're all set.
936 bool AlreadyKept
= MyInfo
.Keep
;
937 if ((Current
.Flags
& TF_DependencyWalk
) && AlreadyKept
)
940 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
941 // because it would screw up the relocation finding logic.
942 if (!(Current
.Flags
& TF_DependencyWalk
))
943 Current
.Flags
= shouldKeepDIE(RelocMgr
, Ranges
, Current
.Die
, DMO
, CU
,
944 MyInfo
, Current
.Flags
);
946 // If it is a newly kept DIE mark it as well as all its dependencies as
948 if (!AlreadyKept
&& (Current
.Flags
& TF_Keep
)) {
949 bool UseOdr
= (Current
.Flags
& TF_DependencyWalk
)
950 ? (Current
.Flags
& TF_ODR
)
952 keepDIEAndDependencies(RelocMgr
, Ranges
, Units
, Current
.Die
, MyInfo
, DMO
,
956 // The TF_ParentWalk flag tells us that we are currently walking up
957 // the parent chain of a required DIE, and we don't want to mark all
958 // the children of the parents as kept (consider for example a
959 // DW_TAG_namespace node in the parent chain). There are however a
960 // set of DIE types for which we want to ignore that directive and still
961 // walk their children.
962 if (dieNeedsChildrenToBeMeaningful(Current
.Die
.getTag()))
963 Current
.Flags
&= ~TF_ParentWalk
;
965 if (!Current
.Die
.hasChildren() || (Current
.Flags
& TF_ParentWalk
))
968 // Add children in reverse order to the worklist to effectively process
970 for (auto Child
: reverse(Current
.Die
.children())) {
971 // Add continuation marker before every child to calculate incompleteness
972 // after the last child is processed. We can't store this information in
973 // the same item because we might have to process other continuations
975 Worklist
.emplace_back(Current
.Die
);
976 Worklist
.emplace_back(Child
, Current
.Flags
);
981 /// Assign an abbreviation number to \p Abbrev.
983 /// Our DIEs get freed after every DebugMapObject has been processed,
984 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
985 /// the instances hold by the DIEs. When we encounter an abbreviation
986 /// that we don't know, we create a permanent copy of it.
987 void DwarfLinker::AssignAbbrev(DIEAbbrev
&Abbrev
) {
988 // Check the set for priors.
992 DIEAbbrev
*InSet
= AbbreviationsSet
.FindNodeOrInsertPos(ID
, InsertToken
);
994 // If it's newly added.
996 // Assign existing abbreviation number.
997 Abbrev
.setNumber(InSet
->getNumber());
999 // Add to abbreviation list.
1000 Abbreviations
.push_back(
1001 std::make_unique
<DIEAbbrev
>(Abbrev
.getTag(), Abbrev
.hasChildren()));
1002 for (const auto &Attr
: Abbrev
.getData())
1003 Abbreviations
.back()->AddAttribute(Attr
.getAttribute(), Attr
.getForm());
1004 AbbreviationsSet
.InsertNode(Abbreviations
.back().get(), InsertToken
);
1005 // Assign the unique abbreviation number.
1006 Abbrev
.setNumber(Abbreviations
.size());
1007 Abbreviations
.back()->setNumber(Abbreviations
.size());
1011 unsigned DwarfLinker::DIECloner::cloneStringAttribute(
1012 DIE
&Die
, AttributeSpec AttrSpec
, const DWARFFormValue
&Val
,
1013 const DWARFUnit
&U
, OffsetsStringPool
&StringPool
, AttributesInfo
&Info
) {
1014 // Switch everything to out of line strings.
1015 const char *String
= *Val
.getAsCString();
1016 auto StringEntry
= StringPool
.getEntry(String
);
1018 // Update attributes info.
1019 if (AttrSpec
.Attr
== dwarf::DW_AT_name
)
1020 Info
.Name
= StringEntry
;
1021 else if (AttrSpec
.Attr
== dwarf::DW_AT_MIPS_linkage_name
||
1022 AttrSpec
.Attr
== dwarf::DW_AT_linkage_name
)
1023 Info
.MangledName
= StringEntry
;
1025 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
), dwarf::DW_FORM_strp
,
1026 DIEInteger(StringEntry
.getOffset()));
1031 unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
1032 DIE
&Die
, const DWARFDie
&InputDIE
, AttributeSpec AttrSpec
,
1033 unsigned AttrSize
, const DWARFFormValue
&Val
, const DebugMapObject
&DMO
,
1034 CompileUnit
&Unit
) {
1035 const DWARFUnit
&U
= Unit
.getOrigUnit();
1036 uint64_t Ref
= *Val
.getAsReference();
1037 DIE
*NewRefDie
= nullptr;
1038 CompileUnit
*RefUnit
= nullptr;
1039 DeclContext
*Ctxt
= nullptr;
1042 resolveDIEReference(Linker
, DMO
, CompileUnits
, Val
, InputDIE
, RefUnit
);
1044 // If the referenced DIE is not found, drop the attribute.
1045 if (!RefDie
|| AttrSpec
.Attr
== dwarf::DW_AT_sibling
)
1048 unsigned Idx
= RefUnit
->getOrigUnit().getDIEIndex(RefDie
);
1049 CompileUnit::DIEInfo
&RefInfo
= RefUnit
->getInfo(Idx
);
1051 // If we already have emitted an equivalent DeclContext, just point
1053 if (isODRAttribute(AttrSpec
.Attr
)) {
1054 Ctxt
= RefInfo
.Ctxt
;
1055 if (Ctxt
&& Ctxt
->getCanonicalDIEOffset()) {
1056 DIEInteger
Attr(Ctxt
->getCanonicalDIEOffset());
1057 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1058 dwarf::DW_FORM_ref_addr
, Attr
);
1059 return U
.getRefAddrByteSize();
1063 if (!RefInfo
.Clone
) {
1064 assert(Ref
> InputDIE
.getOffset());
1065 // We haven't cloned this DIE yet. Just create an empty one and
1066 // store it. It'll get really cloned when we process it.
1067 RefInfo
.Clone
= DIE::get(DIEAlloc
, dwarf::Tag(RefDie
.getTag()));
1069 NewRefDie
= RefInfo
.Clone
;
1071 if (AttrSpec
.Form
== dwarf::DW_FORM_ref_addr
||
1072 (Unit
.hasODR() && isODRAttribute(AttrSpec
.Attr
))) {
1073 // We cannot currently rely on a DIEEntry to emit ref_addr
1074 // references, because the implementation calls back to DwarfDebug
1075 // to find the unit offset. (We don't have a DwarfDebug)
1076 // FIXME: we should be able to design DIEEntry reliance on
1079 if (Ref
< InputDIE
.getOffset()) {
1080 // We must have already cloned that DIE.
1081 uint32_t NewRefOffset
=
1082 RefUnit
->getStartOffset() + NewRefDie
->getOffset();
1083 Attr
= NewRefOffset
;
1084 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1085 dwarf::DW_FORM_ref_addr
, DIEInteger(Attr
));
1087 // A forward reference. Note and fixup later.
1089 Unit
.noteForwardReference(
1090 NewRefDie
, RefUnit
, Ctxt
,
1091 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1092 dwarf::DW_FORM_ref_addr
, DIEInteger(Attr
)));
1094 return U
.getRefAddrByteSize();
1097 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1098 dwarf::Form(AttrSpec
.Form
), DIEEntry(*NewRefDie
));
1102 void DwarfLinker::DIECloner::cloneExpression(
1103 DataExtractor
&Data
, DWARFExpression Expression
, const DebugMapObject
&DMO
,
1104 CompileUnit
&Unit
, SmallVectorImpl
<uint8_t> &OutputBuffer
) {
1105 using Encoding
= DWARFExpression::Operation::Encoding
;
1107 uint64_t OpOffset
= 0;
1108 for (auto &Op
: Expression
) {
1109 auto Description
= Op
.getDescription();
1110 // DW_OP_const_type is variable-length and has 3
1111 // operands. DWARFExpression thus far only supports 2.
1112 auto Op0
= Description
.Op
[0];
1113 auto Op1
= Description
.Op
[1];
1114 if ((Op0
== Encoding::BaseTypeRef
&& Op1
!= Encoding::SizeNA
) ||
1115 (Op1
== Encoding::BaseTypeRef
&& Op0
!= Encoding::Size1
))
1116 Linker
.reportWarning("Unsupported DW_OP encoding.", DMO
);
1118 if ((Op0
== Encoding::BaseTypeRef
&& Op1
== Encoding::SizeNA
) ||
1119 (Op1
== Encoding::BaseTypeRef
&& Op0
== Encoding::Size1
)) {
1120 // This code assumes that the other non-typeref operand fits into 1 byte.
1121 assert(OpOffset
< Op
.getEndOffset());
1122 uint32_t ULEBsize
= Op
.getEndOffset() - OpOffset
- 1;
1123 assert(ULEBsize
<= 16);
1125 // Copy over the operation.
1126 OutputBuffer
.push_back(Op
.getCode());
1128 if (Op1
== Encoding::SizeNA
) {
1129 RefOffset
= Op
.getRawOperand(0);
1131 OutputBuffer
.push_back(Op
.getRawOperand(0));
1132 RefOffset
= Op
.getRawOperand(1);
1134 auto RefDie
= Unit
.getOrigUnit().getDIEForOffset(RefOffset
);
1135 uint32_t RefIdx
= Unit
.getOrigUnit().getDIEIndex(RefDie
);
1136 CompileUnit::DIEInfo
&Info
= Unit
.getInfo(RefIdx
);
1137 uint32_t Offset
= 0;
1138 if (DIE
*Clone
= Info
.Clone
)
1139 Offset
= Clone
->getOffset();
1141 Linker
.reportWarning("base type ref doesn't point to DW_TAG_base_type.",
1144 unsigned RealSize
= encodeULEB128(Offset
, ULEB
, ULEBsize
);
1145 if (RealSize
> ULEBsize
) {
1146 // Emit the generic type as a fallback.
1147 RealSize
= encodeULEB128(0, ULEB
, ULEBsize
);
1148 Linker
.reportWarning("base type ref doesn't fit.", DMO
);
1150 assert(RealSize
== ULEBsize
&& "padding failed");
1151 ArrayRef
<uint8_t> ULEBbytes(ULEB
, ULEBsize
);
1152 OutputBuffer
.append(ULEBbytes
.begin(), ULEBbytes
.end());
1154 // Copy over everything else unmodified.
1155 StringRef Bytes
= Data
.getData().slice(OpOffset
, Op
.getEndOffset());
1156 OutputBuffer
.append(Bytes
.begin(), Bytes
.end());
1158 OpOffset
= Op
.getEndOffset();
1162 unsigned DwarfLinker::DIECloner::cloneBlockAttribute(
1163 DIE
&Die
, const DebugMapObject
&DMO
, CompileUnit
&Unit
,
1164 AttributeSpec AttrSpec
, const DWARFFormValue
&Val
, unsigned AttrSize
,
1165 bool IsLittleEndian
) {
1168 DIELoc
*Loc
= nullptr;
1169 DIEBlock
*Block
= nullptr;
1170 if (AttrSpec
.Form
== dwarf::DW_FORM_exprloc
) {
1171 Loc
= new (DIEAlloc
) DIELoc
;
1172 Linker
.DIELocs
.push_back(Loc
);
1174 Block
= new (DIEAlloc
) DIEBlock
;
1175 Linker
.DIEBlocks
.push_back(Block
);
1177 Attr
= Loc
? static_cast<DIEValueList
*>(Loc
)
1178 : static_cast<DIEValueList
*>(Block
);
1181 Value
= DIEValue(dwarf::Attribute(AttrSpec
.Attr
),
1182 dwarf::Form(AttrSpec
.Form
), Loc
);
1184 Value
= DIEValue(dwarf::Attribute(AttrSpec
.Attr
),
1185 dwarf::Form(AttrSpec
.Form
), Block
);
1187 // If the block is a DWARF Expression, clone it into the temporary
1188 // buffer using cloneExpression(), otherwise copy the data directly.
1189 SmallVector
<uint8_t, 32> Buffer
;
1190 ArrayRef
<uint8_t> Bytes
= *Val
.getAsBlock();
1191 if (DWARFAttribute::mayHaveLocationDescription(AttrSpec
.Attr
) &&
1192 (Val
.isFormClass(DWARFFormValue::FC_Block
) ||
1193 Val
.isFormClass(DWARFFormValue::FC_Exprloc
))) {
1194 DWARFUnit
&OrigUnit
= Unit
.getOrigUnit();
1195 DataExtractor
Data(StringRef((const char *)Bytes
.data(), Bytes
.size()),
1196 IsLittleEndian
, OrigUnit
.getAddressByteSize());
1197 DWARFExpression
Expr(Data
, OrigUnit
.getVersion(),
1198 OrigUnit
.getAddressByteSize());
1199 cloneExpression(Data
, Expr
, DMO
, Unit
, Buffer
);
1202 for (auto Byte
: Bytes
)
1203 Attr
->addValue(DIEAlloc
, static_cast<dwarf::Attribute
>(0),
1204 dwarf::DW_FORM_data1
, DIEInteger(Byte
));
1206 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1207 // the DIE class, this if could be replaced by
1208 // Attr->setSize(Bytes.size()).
1209 if (Linker
.Streamer
) {
1210 auto *AsmPrinter
= &Linker
.Streamer
->getAsmPrinter();
1212 Loc
->ComputeSize(AsmPrinter
);
1214 Block
->ComputeSize(AsmPrinter
);
1216 Die
.addValue(DIEAlloc
, Value
);
1220 unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
1221 DIE
&Die
, AttributeSpec AttrSpec
, const DWARFFormValue
&Val
,
1222 const CompileUnit
&Unit
, AttributesInfo
&Info
) {
1223 uint64_t Addr
= *Val
.getAsAddress();
1225 if (LLVM_UNLIKELY(Linker
.Options
.Update
)) {
1226 if (AttrSpec
.Attr
== dwarf::DW_AT_low_pc
)
1227 Info
.HasLowPc
= true;
1228 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1229 dwarf::Form(AttrSpec
.Form
), DIEInteger(Addr
));
1230 return Unit
.getOrigUnit().getAddressByteSize();
1233 if (AttrSpec
.Attr
== dwarf::DW_AT_low_pc
) {
1234 if (Die
.getTag() == dwarf::DW_TAG_inlined_subroutine
||
1235 Die
.getTag() == dwarf::DW_TAG_lexical_block
)
1236 // The low_pc of a block or inline subroutine might get
1237 // relocated because it happens to match the low_pc of the
1238 // enclosing subprogram. To prevent issues with that, always use
1239 // the low_pc from the input DIE if relocations have been applied.
1240 Addr
= (Info
.OrigLowPc
!= std::numeric_limits
<uint64_t>::max()
1244 else if (Die
.getTag() == dwarf::DW_TAG_compile_unit
) {
1245 Addr
= Unit
.getLowPc();
1246 if (Addr
== std::numeric_limits
<uint64_t>::max())
1249 Info
.HasLowPc
= true;
1250 } else if (AttrSpec
.Attr
== dwarf::DW_AT_high_pc
) {
1251 if (Die
.getTag() == dwarf::DW_TAG_compile_unit
) {
1252 if (uint64_t HighPc
= Unit
.getHighPc())
1257 // If we have a high_pc recorded for the input DIE, use
1258 // it. Otherwise (when no relocations where applied) just use the
1259 // one we just decoded.
1260 Addr
= (Info
.OrigHighPc
? Info
.OrigHighPc
: Addr
) + Info
.PCOffset
;
1263 Die
.addValue(DIEAlloc
, static_cast<dwarf::Attribute
>(AttrSpec
.Attr
),
1264 static_cast<dwarf::Form
>(AttrSpec
.Form
), DIEInteger(Addr
));
1265 return Unit
.getOrigUnit().getAddressByteSize();
1268 unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
1269 DIE
&Die
, const DWARFDie
&InputDIE
, const DebugMapObject
&DMO
,
1270 CompileUnit
&Unit
, AttributeSpec AttrSpec
, const DWARFFormValue
&Val
,
1271 unsigned AttrSize
, AttributesInfo
&Info
) {
1274 if (LLVM_UNLIKELY(Linker
.Options
.Update
)) {
1275 if (auto OptionalValue
= Val
.getAsUnsignedConstant())
1276 Value
= *OptionalValue
;
1277 else if (auto OptionalValue
= Val
.getAsSignedConstant())
1278 Value
= *OptionalValue
;
1279 else if (auto OptionalValue
= Val
.getAsSectionOffset())
1280 Value
= *OptionalValue
;
1282 Linker
.reportWarning(
1283 "Unsupported scalar attribute form. Dropping attribute.", DMO
,
1287 if (AttrSpec
.Attr
== dwarf::DW_AT_declaration
&& Value
)
1288 Info
.IsDeclaration
= true;
1289 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1290 dwarf::Form(AttrSpec
.Form
), DIEInteger(Value
));
1294 if (AttrSpec
.Attr
== dwarf::DW_AT_high_pc
&&
1295 Die
.getTag() == dwarf::DW_TAG_compile_unit
) {
1296 if (Unit
.getLowPc() == -1ULL)
1298 // Dwarf >= 4 high_pc is an size, not an address.
1299 Value
= Unit
.getHighPc() - Unit
.getLowPc();
1300 } else if (AttrSpec
.Form
== dwarf::DW_FORM_sec_offset
)
1301 Value
= *Val
.getAsSectionOffset();
1302 else if (AttrSpec
.Form
== dwarf::DW_FORM_sdata
)
1303 Value
= *Val
.getAsSignedConstant();
1304 else if (auto OptionalValue
= Val
.getAsUnsignedConstant())
1305 Value
= *OptionalValue
;
1307 Linker
.reportWarning(
1308 "Unsupported scalar attribute form. Dropping attribute.", DMO
,
1312 PatchLocation Patch
=
1313 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1314 dwarf::Form(AttrSpec
.Form
), DIEInteger(Value
));
1315 if (AttrSpec
.Attr
== dwarf::DW_AT_ranges
) {
1316 Unit
.noteRangeAttribute(Die
, Patch
);
1317 Info
.HasRanges
= true;
1320 // A more generic way to check for location attributes would be
1321 // nice, but it's very unlikely that any other attribute needs a
1323 // FIXME: use DWARFAttribute::mayHaveLocationDescription().
1324 else if (AttrSpec
.Attr
== dwarf::DW_AT_location
||
1325 AttrSpec
.Attr
== dwarf::DW_AT_frame_base
)
1326 Unit
.noteLocationAttribute(Patch
, Info
.PCOffset
);
1327 else if (AttrSpec
.Attr
== dwarf::DW_AT_declaration
&& Value
)
1328 Info
.IsDeclaration
= true;
1333 /// Clone \p InputDIE's attribute described by \p AttrSpec with
1334 /// value \p Val, and add it to \p Die.
1335 /// \returns the size of the cloned attribute.
1336 unsigned DwarfLinker::DIECloner::cloneAttribute(
1337 DIE
&Die
, const DWARFDie
&InputDIE
, const DebugMapObject
&DMO
,
1338 CompileUnit
&Unit
, OffsetsStringPool
&StringPool
, const DWARFFormValue
&Val
,
1339 const AttributeSpec AttrSpec
, unsigned AttrSize
, AttributesInfo
&Info
,
1340 bool IsLittleEndian
) {
1341 const DWARFUnit
&U
= Unit
.getOrigUnit();
1343 switch (AttrSpec
.Form
) {
1344 case dwarf::DW_FORM_strp
:
1345 case dwarf::DW_FORM_string
:
1346 return cloneStringAttribute(Die
, AttrSpec
, Val
, U
, StringPool
, Info
);
1347 case dwarf::DW_FORM_ref_addr
:
1348 case dwarf::DW_FORM_ref1
:
1349 case dwarf::DW_FORM_ref2
:
1350 case dwarf::DW_FORM_ref4
:
1351 case dwarf::DW_FORM_ref8
:
1352 return cloneDieReferenceAttribute(Die
, InputDIE
, AttrSpec
, AttrSize
, Val
,
1354 case dwarf::DW_FORM_block
:
1355 case dwarf::DW_FORM_block1
:
1356 case dwarf::DW_FORM_block2
:
1357 case dwarf::DW_FORM_block4
:
1358 case dwarf::DW_FORM_exprloc
:
1359 return cloneBlockAttribute(Die
, DMO
, Unit
, AttrSpec
, Val
, AttrSize
,
1361 case dwarf::DW_FORM_addr
:
1362 return cloneAddressAttribute(Die
, AttrSpec
, Val
, Unit
, Info
);
1363 case dwarf::DW_FORM_data1
:
1364 case dwarf::DW_FORM_data2
:
1365 case dwarf::DW_FORM_data4
:
1366 case dwarf::DW_FORM_data8
:
1367 case dwarf::DW_FORM_udata
:
1368 case dwarf::DW_FORM_sdata
:
1369 case dwarf::DW_FORM_sec_offset
:
1370 case dwarf::DW_FORM_flag
:
1371 case dwarf::DW_FORM_flag_present
:
1372 return cloneScalarAttribute(Die
, InputDIE
, DMO
, Unit
, AttrSpec
, Val
,
1375 Linker
.reportWarning(
1376 "Unsupported attribute form in cloneAttribute. Dropping.", DMO
,
1383 /// Apply the valid relocations found by findValidRelocs() to
1384 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
1385 /// in the debug_info section.
1387 /// Like for findValidRelocs(), this function must be called with
1388 /// monotonic \p BaseOffset values.
1390 /// \returns whether any reloc has been applied.
1391 bool DwarfLinker::RelocationManager::applyValidRelocs(
1392 MutableArrayRef
<char> Data
, uint64_t BaseOffset
, bool IsLittleEndian
) {
1393 assert((NextValidReloc
== 0 ||
1394 BaseOffset
> ValidRelocs
[NextValidReloc
- 1].Offset
) &&
1395 "BaseOffset should only be increasing.");
1396 if (NextValidReloc
>= ValidRelocs
.size())
1399 // Skip relocs that haven't been applied.
1400 while (NextValidReloc
< ValidRelocs
.size() &&
1401 ValidRelocs
[NextValidReloc
].Offset
< BaseOffset
)
1404 bool Applied
= false;
1405 uint64_t EndOffset
= BaseOffset
+ Data
.size();
1406 while (NextValidReloc
< ValidRelocs
.size() &&
1407 ValidRelocs
[NextValidReloc
].Offset
>= BaseOffset
&&
1408 ValidRelocs
[NextValidReloc
].Offset
< EndOffset
) {
1409 const auto &ValidReloc
= ValidRelocs
[NextValidReloc
++];
1410 assert(ValidReloc
.Offset
- BaseOffset
< Data
.size());
1411 assert(ValidReloc
.Offset
- BaseOffset
+ ValidReloc
.Size
<= Data
.size());
1413 uint64_t Value
= ValidReloc
.Mapping
->getValue().BinaryAddress
;
1414 Value
+= ValidReloc
.Addend
;
1415 for (unsigned i
= 0; i
!= ValidReloc
.Size
; ++i
) {
1416 unsigned Index
= IsLittleEndian
? i
: (ValidReloc
.Size
- i
- 1);
1417 Buf
[i
] = uint8_t(Value
>> (Index
* 8));
1419 assert(ValidReloc
.Size
<= sizeof(Buf
));
1420 memcpy(&Data
[ValidReloc
.Offset
- BaseOffset
], Buf
, ValidReloc
.Size
);
1427 static bool isObjCSelector(StringRef Name
) {
1428 return Name
.size() > 2 && (Name
[0] == '-' || Name
[0] == '+') &&
1432 void DwarfLinker::DIECloner::addObjCAccelerator(CompileUnit
&Unit
,
1434 DwarfStringPoolEntryRef Name
,
1435 OffsetsStringPool
&StringPool
,
1436 bool SkipPubSection
) {
1437 assert(isObjCSelector(Name
.getString()) && "not an objc selector");
1438 // Objective C method or class function.
1439 // "- [Class(Category) selector :withArg ...]"
1440 StringRef
ClassNameStart(Name
.getString().drop_front(2));
1441 size_t FirstSpace
= ClassNameStart
.find(' ');
1442 if (FirstSpace
== StringRef::npos
)
1445 StringRef
SelectorStart(ClassNameStart
.data() + FirstSpace
+ 1);
1446 if (!SelectorStart
.size())
1449 StringRef
Selector(SelectorStart
.data(), SelectorStart
.size() - 1);
1450 Unit
.addNameAccelerator(Die
, StringPool
.getEntry(Selector
), SkipPubSection
);
1452 // Add an entry for the class name that points to this
1453 // method/class function.
1454 StringRef
ClassName(ClassNameStart
.data(), FirstSpace
);
1455 Unit
.addObjCAccelerator(Die
, StringPool
.getEntry(ClassName
), SkipPubSection
);
1457 if (ClassName
[ClassName
.size() - 1] == ')') {
1458 size_t OpenParens
= ClassName
.find('(');
1459 if (OpenParens
!= StringRef::npos
) {
1460 StringRef
ClassNameNoCategory(ClassName
.data(), OpenParens
);
1461 Unit
.addObjCAccelerator(Die
, StringPool
.getEntry(ClassNameNoCategory
),
1464 std::string
MethodNameNoCategory(Name
.getString().data(), OpenParens
+ 2);
1465 // FIXME: The missing space here may be a bug, but
1466 // dsymutil-classic also does it this way.
1467 MethodNameNoCategory
.append(SelectorStart
);
1468 Unit
.addNameAccelerator(Die
, StringPool
.getEntry(MethodNameNoCategory
),
1475 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec
,
1476 uint16_t Tag
, bool InDebugMap
, bool SkipPC
,
1477 bool InFunctionScope
) {
1478 switch (AttrSpec
.Attr
) {
1481 case dwarf::DW_AT_low_pc
:
1482 case dwarf::DW_AT_high_pc
:
1483 case dwarf::DW_AT_ranges
:
1485 case dwarf::DW_AT_location
:
1486 case dwarf::DW_AT_frame_base
:
1487 // FIXME: for some reason dsymutil-classic keeps the location attributes
1488 // when they are of block type (i.e. not location lists). This is totally
1489 // wrong for globals where we will keep a wrong address. It is mostly
1490 // harmless for locals, but there is no point in keeping these anyway when
1491 // the function wasn't linked.
1492 return (SkipPC
|| (!InFunctionScope
&& Tag
== dwarf::DW_TAG_variable
&&
1494 !DWARFFormValue(AttrSpec
.Form
).isFormClass(DWARFFormValue::FC_Block
);
1498 DIE
*DwarfLinker::DIECloner::cloneDIE(
1499 const DWARFDie
&InputDIE
, const DebugMapObject
&DMO
, CompileUnit
&Unit
,
1500 OffsetsStringPool
&StringPool
, int64_t PCOffset
, uint32_t OutOffset
,
1501 unsigned Flags
, bool IsLittleEndian
, DIE
*Die
) {
1502 DWARFUnit
&U
= Unit
.getOrigUnit();
1503 unsigned Idx
= U
.getDIEIndex(InputDIE
);
1504 CompileUnit::DIEInfo
&Info
= Unit
.getInfo(Idx
);
1506 // Should the DIE appear in the output?
1507 if (!Unit
.getInfo(Idx
).Keep
)
1510 uint64_t Offset
= InputDIE
.getOffset();
1511 assert(!(Die
&& Info
.Clone
) && "Can't supply a DIE and a cloned DIE");
1513 // The DIE might have been already created by a forward reference
1514 // (see cloneDieReferenceAttribute()).
1516 Info
.Clone
= DIE::get(DIEAlloc
, dwarf::Tag(InputDIE
.getTag()));
1520 assert(Die
->getTag() == InputDIE
.getTag());
1521 Die
->setOffset(OutOffset
);
1522 if ((Unit
.hasODR() || Unit
.isClangModule()) && !Info
.Incomplete
&&
1523 Die
->getTag() != dwarf::DW_TAG_namespace
&& Info
.Ctxt
&&
1524 Info
.Ctxt
!= Unit
.getInfo(Info
.ParentIdx
).Ctxt
&&
1525 !Info
.Ctxt
->getCanonicalDIEOffset()) {
1526 // We are about to emit a DIE that is the root of its own valid
1527 // DeclContext tree. Make the current offset the canonical offset
1528 // for this context.
1529 Info
.Ctxt
->setCanonicalDIEOffset(OutOffset
+ Unit
.getStartOffset());
1532 // Extract and clone every attribute.
1533 DWARFDataExtractor Data
= U
.getDebugInfoExtractor();
1534 // Point to the next DIE (generally there is always at least a NULL
1535 // entry after the current one). If this is a lone
1536 // DW_TAG_compile_unit without any children, point to the next unit.
1537 uint64_t NextOffset
= (Idx
+ 1 < U
.getNumDIEs())
1538 ? U
.getDIEAtIndex(Idx
+ 1).getOffset()
1539 : U
.getNextUnitOffset();
1540 AttributesInfo AttrInfo
;
1542 // We could copy the data only if we need to apply a relocation to it. After
1543 // testing, it seems there is no performance downside to doing the copy
1544 // unconditionally, and it makes the code simpler.
1545 SmallString
<40> DIECopy(Data
.getData().substr(Offset
, NextOffset
- Offset
));
1547 DWARFDataExtractor(DIECopy
, Data
.isLittleEndian(), Data
.getAddressSize());
1548 // Modify the copy with relocated addresses.
1549 if (RelocMgr
.applyValidRelocs(DIECopy
, Offset
, Data
.isLittleEndian())) {
1550 // If we applied relocations, we store the value of high_pc that was
1551 // potentially stored in the input DIE. If high_pc is an address
1552 // (Dwarf version == 2), then it might have been relocated to a
1553 // totally unrelated value (because the end address in the object
1554 // file might be start address of another function which got moved
1555 // independently by the linker). The computation of the actual
1556 // high_pc value is done in cloneAddressAttribute().
1557 AttrInfo
.OrigHighPc
=
1558 dwarf::toAddress(InputDIE
.find(dwarf::DW_AT_high_pc
), 0);
1559 // Also store the low_pc. It might get relocated in an
1560 // inline_subprogram that happens at the beginning of its
1561 // inlining function.
1562 AttrInfo
.OrigLowPc
= dwarf::toAddress(InputDIE
.find(dwarf::DW_AT_low_pc
),
1563 std::numeric_limits
<uint64_t>::max());
1566 // Reset the Offset to 0 as we will be working on the local copy of
1570 const auto *Abbrev
= InputDIE
.getAbbreviationDeclarationPtr();
1571 Offset
+= getULEB128Size(Abbrev
->getCode());
1573 // We are entering a subprogram. Get and propagate the PCOffset.
1574 if (Die
->getTag() == dwarf::DW_TAG_subprogram
)
1575 PCOffset
= Info
.AddrAdjust
;
1576 AttrInfo
.PCOffset
= PCOffset
;
1578 if (Abbrev
->getTag() == dwarf::DW_TAG_subprogram
) {
1579 Flags
|= TF_InFunctionScope
;
1580 if (!Info
.InDebugMap
&& LLVM_LIKELY(!Options
.Update
))
1584 bool Copied
= false;
1585 for (const auto &AttrSpec
: Abbrev
->attributes()) {
1586 if (LLVM_LIKELY(!Options
.Update
) &&
1587 shouldSkipAttribute(AttrSpec
, Die
->getTag(), Info
.InDebugMap
,
1588 Flags
& TF_SkipPC
, Flags
& TF_InFunctionScope
)) {
1589 DWARFFormValue::skipValue(AttrSpec
.Form
, Data
, &Offset
,
1591 // FIXME: dsymutil-classic keeps the old abbreviation around
1592 // even if it's not used. We can remove this (and the copyAbbrev
1593 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
1595 copyAbbrev(*InputDIE
.getAbbreviationDeclarationPtr(), Unit
.hasODR());
1601 DWARFFormValue
Val(AttrSpec
.Form
);
1602 uint64_t AttrSize
= Offset
;
1603 Val
.extractValue(Data
, &Offset
, U
.getFormParams(), &U
);
1604 AttrSize
= Offset
- AttrSize
;
1606 OutOffset
+= cloneAttribute(*Die
, InputDIE
, DMO
, Unit
, StringPool
, Val
,
1607 AttrSpec
, AttrSize
, AttrInfo
, IsLittleEndian
);
1610 // Look for accelerator entries.
1611 uint16_t Tag
= InputDIE
.getTag();
1612 // FIXME: This is slightly wrong. An inline_subroutine without a
1613 // low_pc, but with AT_ranges might be interesting to get into the
1614 // accelerator tables too. For now stick with dsymutil's behavior.
1615 if ((Info
.InDebugMap
|| AttrInfo
.HasLowPc
|| AttrInfo
.HasRanges
) &&
1616 Tag
!= dwarf::DW_TAG_compile_unit
&&
1617 getDIENames(InputDIE
, AttrInfo
, StringPool
,
1618 Tag
!= dwarf::DW_TAG_inlined_subroutine
)) {
1619 if (AttrInfo
.MangledName
&& AttrInfo
.MangledName
!= AttrInfo
.Name
)
1620 Unit
.addNameAccelerator(Die
, AttrInfo
.MangledName
,
1621 Tag
== dwarf::DW_TAG_inlined_subroutine
);
1622 if (AttrInfo
.Name
) {
1623 if (AttrInfo
.NameWithoutTemplate
)
1624 Unit
.addNameAccelerator(Die
, AttrInfo
.NameWithoutTemplate
,
1625 /* SkipPubSection */ true);
1626 Unit
.addNameAccelerator(Die
, AttrInfo
.Name
,
1627 Tag
== dwarf::DW_TAG_inlined_subroutine
);
1629 if (AttrInfo
.Name
&& isObjCSelector(AttrInfo
.Name
.getString()))
1630 addObjCAccelerator(Unit
, Die
, AttrInfo
.Name
, StringPool
,
1631 /* SkipPubSection =*/true);
1633 } else if (Tag
== dwarf::DW_TAG_namespace
) {
1635 AttrInfo
.Name
= StringPool
.getEntry("(anonymous namespace)");
1636 Unit
.addNamespaceAccelerator(Die
, AttrInfo
.Name
);
1637 } else if (isTypeTag(Tag
) && !AttrInfo
.IsDeclaration
&&
1638 getDIENames(InputDIE
, AttrInfo
, StringPool
) && AttrInfo
.Name
&&
1639 AttrInfo
.Name
.getString()[0]) {
1640 uint32_t Hash
= hashFullyQualifiedName(InputDIE
, Unit
, DMO
);
1641 uint64_t RuntimeLang
=
1642 dwarf::toUnsigned(InputDIE
.find(dwarf::DW_AT_APPLE_runtime_class
))
1644 bool ObjCClassIsImplementation
=
1645 (RuntimeLang
== dwarf::DW_LANG_ObjC
||
1646 RuntimeLang
== dwarf::DW_LANG_ObjC_plus_plus
) &&
1647 dwarf::toUnsigned(InputDIE
.find(dwarf::DW_AT_APPLE_objc_complete_type
))
1649 Unit
.addTypeAccelerator(Die
, AttrInfo
.Name
, ObjCClassIsImplementation
,
1653 // Determine whether there are any children that we want to keep.
1654 bool HasChildren
= false;
1655 for (auto Child
: InputDIE
.children()) {
1656 unsigned Idx
= U
.getDIEIndex(Child
);
1657 if (Unit
.getInfo(Idx
).Keep
) {
1663 DIEAbbrev NewAbbrev
= Die
->generateAbbrev();
1665 NewAbbrev
.setChildrenFlag(dwarf::DW_CHILDREN_yes
);
1666 // Assign a permanent abbrev number
1667 Linker
.AssignAbbrev(NewAbbrev
);
1668 Die
->setAbbrevNumber(NewAbbrev
.getNumber());
1670 // Add the size of the abbreviation number to the output offset.
1671 OutOffset
+= getULEB128Size(Die
->getAbbrevNumber());
1675 Die
->setSize(OutOffset
- Die
->getOffset());
1679 // Recursively clone children.
1680 for (auto Child
: InputDIE
.children()) {
1681 if (DIE
*Clone
= cloneDIE(Child
, DMO
, Unit
, StringPool
, PCOffset
, OutOffset
,
1682 Flags
, IsLittleEndian
)) {
1683 Die
->addChild(Clone
);
1684 OutOffset
= Clone
->getOffset() + Clone
->getSize();
1688 // Account for the end of children marker.
1689 OutOffset
+= sizeof(int8_t);
1691 Die
->setSize(OutOffset
- Die
->getOffset());
1695 /// Patch the input object file relevant debug_ranges entries
1696 /// and emit them in the output file. Update the relevant attributes
1697 /// to point at the new entries.
1698 void DwarfLinker::patchRangesForUnit(const CompileUnit
&Unit
,
1699 DWARFContext
&OrigDwarf
,
1700 const DebugMapObject
&DMO
) const {
1701 DWARFDebugRangeList RangeList
;
1702 const auto &FunctionRanges
= Unit
.getFunctionRanges();
1703 unsigned AddressSize
= Unit
.getOrigUnit().getAddressByteSize();
1704 DWARFDataExtractor
RangeExtractor(OrigDwarf
.getDWARFObj(),
1705 OrigDwarf
.getDWARFObj().getRangesSection(),
1706 OrigDwarf
.isLittleEndian(), AddressSize
);
1707 auto InvalidRange
= FunctionRanges
.end(), CurrRange
= InvalidRange
;
1708 DWARFUnit
&OrigUnit
= Unit
.getOrigUnit();
1709 auto OrigUnitDie
= OrigUnit
.getUnitDIE(false);
1710 uint64_t OrigLowPc
=
1711 dwarf::toAddress(OrigUnitDie
.find(dwarf::DW_AT_low_pc
), -1ULL);
1712 // Ranges addresses are based on the unit's low_pc. Compute the
1713 // offset we need to apply to adapt to the new unit's low_pc.
1714 int64_t UnitPcOffset
= 0;
1715 if (OrigLowPc
!= -1ULL)
1716 UnitPcOffset
= int64_t(OrigLowPc
) - Unit
.getLowPc();
1718 for (const auto &RangeAttribute
: Unit
.getRangesAttributes()) {
1719 uint64_t Offset
= RangeAttribute
.get();
1720 RangeAttribute
.set(Streamer
->getRangesSectionSize());
1721 if (Error E
= RangeList
.extract(RangeExtractor
, &Offset
)) {
1722 llvm::consumeError(std::move(E
));
1723 reportWarning("invalid range list ignored.", DMO
);
1726 const auto &Entries
= RangeList
.getEntries();
1727 if (!Entries
.empty()) {
1728 const DWARFDebugRangeList::RangeListEntry
&First
= Entries
.front();
1730 if (CurrRange
== InvalidRange
||
1731 First
.StartAddress
+ OrigLowPc
< CurrRange
.start() ||
1732 First
.StartAddress
+ OrigLowPc
>= CurrRange
.stop()) {
1733 CurrRange
= FunctionRanges
.find(First
.StartAddress
+ OrigLowPc
);
1734 if (CurrRange
== InvalidRange
||
1735 CurrRange
.start() > First
.StartAddress
+ OrigLowPc
) {
1736 reportWarning("no mapping for range.", DMO
);
1742 Streamer
->emitRangesEntries(UnitPcOffset
, OrigLowPc
, CurrRange
, Entries
,
1747 /// Generate the debug_aranges entries for \p Unit and if the
1748 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
1749 /// contribution for this attribute.
1750 /// FIXME: this could actually be done right in patchRangesForUnit,
1751 /// but for the sake of initial bit-for-bit compatibility with legacy
1752 /// dsymutil, we have to do it in a delayed pass.
1753 void DwarfLinker::generateUnitRanges(CompileUnit
&Unit
) const {
1754 auto Attr
= Unit
.getUnitRangesAttribute();
1756 Attr
->set(Streamer
->getRangesSectionSize());
1757 Streamer
->emitUnitRangesEntries(Unit
, static_cast<bool>(Attr
));
1760 /// Insert the new line info sequence \p Seq into the current
1761 /// set of already linked line info \p Rows.
1762 static void insertLineSequence(std::vector
<DWARFDebugLine::Row
> &Seq
,
1763 std::vector
<DWARFDebugLine::Row
> &Rows
) {
1767 if (!Rows
.empty() && Rows
.back().Address
< Seq
.front().Address
) {
1768 Rows
.insert(Rows
.end(), Seq
.begin(), Seq
.end());
1773 object::SectionedAddress Front
= Seq
.front().Address
;
1774 auto InsertPoint
= partition_point(
1775 Rows
, [=](const DWARFDebugLine::Row
&O
) { return O
.Address
< Front
; });
1777 // FIXME: this only removes the unneeded end_sequence if the
1778 // sequences have been inserted in order. Using a global sort like
1779 // described in patchLineTableForUnit() and delaying the end_sequene
1780 // elimination to emitLineTableForUnit() we can get rid of all of them.
1781 if (InsertPoint
!= Rows
.end() && InsertPoint
->Address
== Front
&&
1782 InsertPoint
->EndSequence
) {
1783 *InsertPoint
= Seq
.front();
1784 Rows
.insert(InsertPoint
+ 1, Seq
.begin() + 1, Seq
.end());
1786 Rows
.insert(InsertPoint
, Seq
.begin(), Seq
.end());
1792 static void patchStmtList(DIE
&Die
, DIEInteger Offset
) {
1793 for (auto &V
: Die
.values())
1794 if (V
.getAttribute() == dwarf::DW_AT_stmt_list
) {
1795 V
= DIEValue(V
.getAttribute(), V
.getForm(), Offset
);
1799 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
1802 /// Extract the line table for \p Unit from \p OrigDwarf, and
1803 /// recreate a relocated version of these for the address ranges that
1804 /// are present in the binary.
1805 void DwarfLinker::patchLineTableForUnit(CompileUnit
&Unit
,
1806 DWARFContext
&OrigDwarf
,
1808 const DebugMapObject
&DMO
) {
1809 DWARFDie CUDie
= Unit
.getOrigUnit().getUnitDIE();
1810 auto StmtList
= dwarf::toSectionOffset(CUDie
.find(dwarf::DW_AT_stmt_list
));
1814 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
1815 if (auto *OutputDIE
= Unit
.getOutputUnitDIE())
1816 patchStmtList(*OutputDIE
, DIEInteger(Streamer
->getLineSectionSize()));
1818 // Parse the original line info for the unit.
1819 DWARFDebugLine::LineTable LineTable
;
1820 uint64_t StmtOffset
= *StmtList
;
1821 DWARFDataExtractor
LineExtractor(
1822 OrigDwarf
.getDWARFObj(), OrigDwarf
.getDWARFObj().getLineSection(),
1823 OrigDwarf
.isLittleEndian(), Unit
.getOrigUnit().getAddressByteSize());
1824 if (Options
.Translator
)
1825 return Streamer
->translateLineTable(LineExtractor
, StmtOffset
);
1827 Error Err
= LineTable
.parse(LineExtractor
, &StmtOffset
, OrigDwarf
,
1828 &Unit
.getOrigUnit(), DWARFContext::dumpWarning
);
1829 DWARFContext::dumpWarning(std::move(Err
));
1831 // This vector is the output line table.
1832 std::vector
<DWARFDebugLine::Row
> NewRows
;
1833 NewRows
.reserve(LineTable
.Rows
.size());
1835 // Current sequence of rows being extracted, before being inserted
1837 std::vector
<DWARFDebugLine::Row
> Seq
;
1838 const auto &FunctionRanges
= Unit
.getFunctionRanges();
1839 auto InvalidRange
= FunctionRanges
.end(), CurrRange
= InvalidRange
;
1841 // FIXME: This logic is meant to generate exactly the same output as
1842 // Darwin's classic dsymutil. There is a nicer way to implement this
1843 // by simply putting all the relocated line info in NewRows and simply
1844 // sorting NewRows before passing it to emitLineTableForUnit. This
1845 // should be correct as sequences for a function should stay
1846 // together in the sorted output. There are a few corner cases that
1847 // look suspicious though, and that required to implement the logic
1848 // this way. Revisit that once initial validation is finished.
1850 // Iterate over the object file line info and extract the sequences
1851 // that correspond to linked functions.
1852 for (auto &Row
: LineTable
.Rows
) {
1853 // Check whether we stepped out of the range. The range is
1854 // half-open, but consider accept the end address of the range if
1855 // it is marked as end_sequence in the input (because in that
1856 // case, the relocation offset is accurate and that entry won't
1857 // serve as the start of another function).
1858 if (CurrRange
== InvalidRange
|| Row
.Address
.Address
< CurrRange
.start() ||
1859 Row
.Address
.Address
> CurrRange
.stop() ||
1860 (Row
.Address
.Address
== CurrRange
.stop() && !Row
.EndSequence
)) {
1861 // We just stepped out of a known range. Insert a end_sequence
1862 // corresponding to the end of the range.
1863 uint64_t StopAddress
= CurrRange
!= InvalidRange
1864 ? CurrRange
.stop() + CurrRange
.value()
1866 CurrRange
= FunctionRanges
.find(Row
.Address
.Address
);
1867 bool CurrRangeValid
=
1868 CurrRange
!= InvalidRange
&& CurrRange
.start() <= Row
.Address
.Address
;
1869 if (!CurrRangeValid
) {
1870 CurrRange
= InvalidRange
;
1871 if (StopAddress
!= -1ULL) {
1872 // Try harder by looking in the DebugMapObject function
1873 // ranges map. There are corner cases where this finds a
1874 // valid entry. It's unclear if this is right or wrong, but
1875 // for now do as dsymutil.
1876 // FIXME: Understand exactly what cases this addresses and
1877 // potentially remove it along with the Ranges map.
1878 auto Range
= Ranges
.lower_bound(Row
.Address
.Address
);
1879 if (Range
!= Ranges
.begin() && Range
!= Ranges
.end())
1882 if (Range
!= Ranges
.end() && Range
->first
<= Row
.Address
.Address
&&
1883 Range
->second
.HighPC
>= Row
.Address
.Address
) {
1884 StopAddress
= Row
.Address
.Address
+ Range
->second
.Offset
;
1888 if (StopAddress
!= -1ULL && !Seq
.empty()) {
1889 // Insert end sequence row with the computed end address, but
1890 // the same line as the previous one.
1891 auto NextLine
= Seq
.back();
1892 NextLine
.Address
.Address
= StopAddress
;
1893 NextLine
.EndSequence
= 1;
1894 NextLine
.PrologueEnd
= 0;
1895 NextLine
.BasicBlock
= 0;
1896 NextLine
.EpilogueBegin
= 0;
1897 Seq
.push_back(NextLine
);
1898 insertLineSequence(Seq
, NewRows
);
1901 if (!CurrRangeValid
)
1905 // Ignore empty sequences.
1906 if (Row
.EndSequence
&& Seq
.empty())
1909 // Relocate row address and add it to the current sequence.
1910 Row
.Address
.Address
+= CurrRange
.value();
1911 Seq
.emplace_back(Row
);
1913 if (Row
.EndSequence
)
1914 insertLineSequence(Seq
, NewRows
);
1917 // Finished extracting, now emit the line tables.
1918 // FIXME: LLVM hard-codes its prologue values. We just copy the
1919 // prologue over and that works because we act as both producer and
1920 // consumer. It would be nicer to have a real configurable line
1922 if (LineTable
.Prologue
.getVersion() < 2 ||
1923 LineTable
.Prologue
.getVersion() > 5 ||
1924 LineTable
.Prologue
.DefaultIsStmt
!= DWARF2_LINE_DEFAULT_IS_STMT
||
1925 LineTable
.Prologue
.OpcodeBase
> 13)
1926 reportWarning("line table parameters mismatch. Cannot emit.", DMO
);
1928 uint32_t PrologueEnd
= *StmtList
+ 10 + LineTable
.Prologue
.PrologueLength
;
1929 // DWARF v5 has an extra 2 bytes of information before the header_length
1931 if (LineTable
.Prologue
.getVersion() == 5)
1933 StringRef LineData
= OrigDwarf
.getDWARFObj().getLineSection().Data
;
1934 MCDwarfLineTableParams Params
;
1935 Params
.DWARF2LineOpcodeBase
= LineTable
.Prologue
.OpcodeBase
;
1936 Params
.DWARF2LineBase
= LineTable
.Prologue
.LineBase
;
1937 Params
.DWARF2LineRange
= LineTable
.Prologue
.LineRange
;
1938 Streamer
->emitLineTableForUnit(Params
,
1939 LineData
.slice(*StmtList
+ 4, PrologueEnd
),
1940 LineTable
.Prologue
.MinInstLength
, NewRows
,
1941 Unit
.getOrigUnit().getAddressByteSize());
1945 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit
&Unit
) {
1946 switch (Options
.TheAccelTableKind
) {
1947 case AccelTableKind::Apple
:
1948 emitAppleAcceleratorEntriesForUnit(Unit
);
1950 case AccelTableKind::Dwarf
:
1951 emitDwarfAcceleratorEntriesForUnit(Unit
);
1953 case AccelTableKind::Default
:
1954 llvm_unreachable("The default must be updated to a concrete value.");
1959 void DwarfLinker::emitAppleAcceleratorEntriesForUnit(CompileUnit
&Unit
) {
1961 for (const auto &Namespace
: Unit
.getNamespaces())
1962 AppleNamespaces
.addName(Namespace
.Name
,
1963 Namespace
.Die
->getOffset() + Unit
.getStartOffset());
1966 if (!Options
.Minimize
)
1967 Streamer
->emitPubNamesForUnit(Unit
);
1968 for (const auto &Pubname
: Unit
.getPubnames())
1969 AppleNames
.addName(Pubname
.Name
,
1970 Pubname
.Die
->getOffset() + Unit
.getStartOffset());
1973 if (!Options
.Minimize
)
1974 Streamer
->emitPubTypesForUnit(Unit
);
1975 for (const auto &Pubtype
: Unit
.getPubtypes())
1977 Pubtype
.Name
, Pubtype
.Die
->getOffset() + Unit
.getStartOffset(),
1978 Pubtype
.Die
->getTag(),
1979 Pubtype
.ObjcClassImplementation
? dwarf::DW_FLAG_type_implementation
1981 Pubtype
.QualifiedNameHash
);
1984 for (const auto &ObjC
: Unit
.getObjC())
1985 AppleObjc
.addName(ObjC
.Name
, ObjC
.Die
->getOffset() + Unit
.getStartOffset());
1988 void DwarfLinker::emitDwarfAcceleratorEntriesForUnit(CompileUnit
&Unit
) {
1989 for (const auto &Namespace
: Unit
.getNamespaces())
1990 DebugNames
.addName(Namespace
.Name
, Namespace
.Die
->getOffset(),
1991 Namespace
.Die
->getTag(), Unit
.getUniqueID());
1992 for (const auto &Pubname
: Unit
.getPubnames())
1993 DebugNames
.addName(Pubname
.Name
, Pubname
.Die
->getOffset(),
1994 Pubname
.Die
->getTag(), Unit
.getUniqueID());
1995 for (const auto &Pubtype
: Unit
.getPubtypes())
1996 DebugNames
.addName(Pubtype
.Name
, Pubtype
.Die
->getOffset(),
1997 Pubtype
.Die
->getTag(), Unit
.getUniqueID());
2000 /// Read the frame info stored in the object, and emit the
2001 /// patched frame descriptions for the linked binary.
2003 /// This is actually pretty easy as the data of the CIEs and FDEs can
2004 /// be considered as black boxes and moved as is. The only thing to do
2005 /// is to patch the addresses in the headers.
2006 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject
&DMO
,
2008 DWARFContext
&OrigDwarf
,
2009 unsigned AddrSize
) {
2010 StringRef FrameData
= OrigDwarf
.getDWARFObj().getFrameSection().Data
;
2011 if (FrameData
.empty())
2014 DataExtractor
Data(FrameData
, OrigDwarf
.isLittleEndian(), 0);
2015 uint64_t InputOffset
= 0;
2017 // Store the data of the CIEs defined in this object, keyed by their
2019 DenseMap
<uint64_t, StringRef
> LocalCIES
;
2021 while (Data
.isValidOffset(InputOffset
)) {
2022 uint64_t EntryOffset
= InputOffset
;
2023 uint32_t InitialLength
= Data
.getU32(&InputOffset
);
2024 if (InitialLength
== 0xFFFFFFFF)
2025 return reportWarning("Dwarf64 bits no supported", DMO
);
2027 uint32_t CIEId
= Data
.getU32(&InputOffset
);
2028 if (CIEId
== 0xFFFFFFFF) {
2029 // This is a CIE, store it.
2030 StringRef CIEData
= FrameData
.substr(EntryOffset
, InitialLength
+ 4);
2031 LocalCIES
[EntryOffset
] = CIEData
;
2032 // The -4 is to account for the CIEId we just read.
2033 InputOffset
+= InitialLength
- 4;
2037 uint32_t Loc
= Data
.getUnsigned(&InputOffset
, AddrSize
);
2039 // Some compilers seem to emit frame info that doesn't start at
2040 // the function entry point, thus we can't just lookup the address
2041 // in the debug map. Use the linker's range map to see if the FDE
2042 // describes something that we can relocate.
2043 auto Range
= Ranges
.upper_bound(Loc
);
2044 if (Range
!= Ranges
.begin())
2046 if (Range
== Ranges
.end() || Range
->first
> Loc
||
2047 Range
->second
.HighPC
<= Loc
) {
2048 // The +4 is to account for the size of the InitialLength field itself.
2049 InputOffset
= EntryOffset
+ InitialLength
+ 4;
2053 // This is an FDE, and we have a mapping.
2054 // Have we already emitted a corresponding CIE?
2055 StringRef CIEData
= LocalCIES
[CIEId
];
2056 if (CIEData
.empty())
2057 return reportWarning("Inconsistent debug_frame content. Dropping.", DMO
);
2059 // Look if we already emitted a CIE that corresponds to the
2060 // referenced one (the CIE data is the key of that lookup).
2061 auto IteratorInserted
= EmittedCIEs
.insert(
2062 std::make_pair(CIEData
, Streamer
->getFrameSectionSize()));
2063 // If there is no CIE yet for this ID, emit it.
2064 if (IteratorInserted
.second
||
2065 // FIXME: dsymutil-classic only caches the last used CIE for
2066 // reuse. Mimic that behavior for now. Just removing that
2067 // second half of the condition and the LastCIEOffset variable
2068 // makes the code DTRT.
2069 LastCIEOffset
!= IteratorInserted
.first
->getValue()) {
2070 LastCIEOffset
= Streamer
->getFrameSectionSize();
2071 IteratorInserted
.first
->getValue() = LastCIEOffset
;
2072 Streamer
->emitCIE(CIEData
);
2075 // Emit the FDE with updated address and CIE pointer.
2076 // (4 + AddrSize) is the size of the CIEId + initial_location
2077 // fields that will get reconstructed by emitFDE().
2078 unsigned FDERemainingBytes
= InitialLength
- (4 + AddrSize
);
2079 Streamer
->emitFDE(IteratorInserted
.first
->getValue(), AddrSize
,
2080 Loc
+ Range
->second
.Offset
,
2081 FrameData
.substr(InputOffset
, FDERemainingBytes
));
2082 InputOffset
+= FDERemainingBytes
;
2086 void DwarfLinker::DIECloner::copyAbbrev(
2087 const DWARFAbbreviationDeclaration
&Abbrev
, bool hasODR
) {
2088 DIEAbbrev
Copy(dwarf::Tag(Abbrev
.getTag()),
2089 dwarf::Form(Abbrev
.hasChildren()));
2091 for (const auto &Attr
: Abbrev
.attributes()) {
2092 uint16_t Form
= Attr
.Form
;
2093 if (hasODR
&& isODRAttribute(Attr
.Attr
))
2094 Form
= dwarf::DW_FORM_ref_addr
;
2095 Copy
.AddAttribute(dwarf::Attribute(Attr
.Attr
), dwarf::Form(Form
));
2098 Linker
.AssignAbbrev(Copy
);
2102 DwarfLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE
, CompileUnit
&U
,
2103 const DebugMapObject
&DMO
,
2104 int ChildRecurseDepth
) {
2105 const char *Name
= nullptr;
2106 DWARFUnit
*OrigUnit
= &U
.getOrigUnit();
2107 CompileUnit
*CU
= &U
;
2108 Optional
<DWARFFormValue
> Ref
;
2111 if (const char *CurrentName
= DIE
.getName(DINameKind::ShortName
))
2114 if (!(Ref
= DIE
.find(dwarf::DW_AT_specification
)) &&
2115 !(Ref
= DIE
.find(dwarf::DW_AT_abstract_origin
)))
2118 if (!Ref
->isFormClass(DWARFFormValue::FC_Reference
))
2123 resolveDIEReference(Linker
, DMO
, CompileUnits
, *Ref
, DIE
, RefCU
)) {
2125 OrigUnit
= &RefCU
->getOrigUnit();
2130 unsigned Idx
= OrigUnit
->getDIEIndex(DIE
);
2131 if (!Name
&& DIE
.getTag() == dwarf::DW_TAG_namespace
)
2132 Name
= "(anonymous namespace)";
2134 if (CU
->getInfo(Idx
).ParentIdx
== 0 ||
2135 // FIXME: dsymutil-classic compatibility. Ignore modules.
2136 CU
->getOrigUnit().getDIEAtIndex(CU
->getInfo(Idx
).ParentIdx
).getTag() ==
2137 dwarf::DW_TAG_module
)
2138 return djbHash(Name
? Name
: "", djbHash(ChildRecurseDepth
? "" : "::"));
2140 DWARFDie Die
= OrigUnit
->getDIEAtIndex(CU
->getInfo(Idx
).ParentIdx
);
2143 djbHash((Name
? "::" : ""),
2144 hashFullyQualifiedName(Die
, *CU
, DMO
, ++ChildRecurseDepth
)));
2147 static uint64_t getDwoId(const DWARFDie
&CUDie
, const DWARFUnit
&Unit
) {
2148 auto DwoId
= dwarf::toUnsigned(
2149 CUDie
.find({dwarf::DW_AT_dwo_id
, dwarf::DW_AT_GNU_dwo_id
}));
2155 bool DwarfLinker::registerModuleReference(
2156 DWARFDie CUDie
, const DWARFUnit
&Unit
, DebugMap
&ModuleMap
,
2157 const DebugMapObject
&DMO
, RangesTy
&Ranges
, OffsetsStringPool
&StringPool
,
2158 UniquingStringPool
&UniquingStringPool
, DeclContextTree
&ODRContexts
,
2159 uint64_t ModulesEndOffset
, unsigned &UnitID
, bool IsLittleEndian
,
2160 unsigned Indent
, bool Quiet
) {
2161 std::string PCMfile
= dwarf::toString(
2162 CUDie
.find({dwarf::DW_AT_dwo_name
, dwarf::DW_AT_GNU_dwo_name
}), "");
2163 if (PCMfile
.empty())
2166 // Clang module DWARF skeleton CUs abuse this for the path to the module.
2167 uint64_t DwoId
= getDwoId(CUDie
, Unit
);
2169 std::string Name
= dwarf::toString(CUDie
.find(dwarf::DW_AT_name
), "");
2172 reportWarning("Anonymous module skeleton CU for " + PCMfile
, DMO
);
2176 if (!Quiet
&& Options
.Verbose
) {
2177 outs().indent(Indent
);
2178 outs() << "Found clang module reference " << PCMfile
;
2181 auto Cached
= ClangModules
.find(PCMfile
);
2182 if (Cached
!= ClangModules
.end()) {
2183 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2184 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2185 // ASTFileSignatures will change randomly when a module is rebuilt.
2186 if (!Quiet
&& Options
.Verbose
&& (Cached
->second
!= DwoId
))
2187 reportWarning(Twine("hash mismatch: this object file was built against a "
2188 "different version of the module ") +
2191 if (!Quiet
&& Options
.Verbose
)
2192 outs() << " [cached].\n";
2195 if (!Quiet
&& Options
.Verbose
)
2198 // Cyclic dependencies are disallowed by Clang, but we still
2199 // shouldn't run into an infinite loop, so mark it as processed now.
2200 ClangModules
.insert({PCMfile
, DwoId
});
2202 if (Error E
= loadClangModule(CUDie
, PCMfile
, Name
, DwoId
, ModuleMap
, DMO
,
2203 Ranges
, StringPool
, UniquingStringPool
,
2204 ODRContexts
, ModulesEndOffset
, UnitID
,
2205 IsLittleEndian
, Indent
+ 2, Quiet
)) {
2206 consumeError(std::move(E
));
2212 ErrorOr
<const object::ObjectFile
&>
2213 DwarfLinker::loadObject(const DebugMapObject
&Obj
, const DebugMap
&Map
) {
2215 BinHolder
.getObjectEntry(Obj
.getObjectFilename(), Obj
.getTimestamp());
2217 auto Err
= ObjectEntry
.takeError();
2219 Twine(Obj
.getObjectFilename()) + ": " + toString(std::move(Err
)), Obj
);
2220 return errorToErrorCode(std::move(Err
));
2223 auto Object
= ObjectEntry
->getObject(Map
.getTriple());
2225 auto Err
= Object
.takeError();
2227 Twine(Obj
.getObjectFilename()) + ": " + toString(std::move(Err
)), Obj
);
2228 return errorToErrorCode(std::move(Err
));
2234 Error
DwarfLinker::loadClangModule(
2235 DWARFDie CUDie
, StringRef Filename
, StringRef ModuleName
, uint64_t DwoId
,
2236 DebugMap
&ModuleMap
, const DebugMapObject
&DMO
, RangesTy
&Ranges
,
2237 OffsetsStringPool
&StringPool
, UniquingStringPool
&UniquingStringPool
,
2238 DeclContextTree
&ODRContexts
, uint64_t ModulesEndOffset
, unsigned &UnitID
,
2239 bool IsLittleEndian
, unsigned Indent
, bool Quiet
) {
2240 /// Using a SmallString<0> because loadClangModule() is recursive.
2241 SmallString
<0> Path(Options
.PrependPath
);
2242 if (sys::path::is_relative(Filename
))
2243 resolveRelativeObjectPath(Path
, CUDie
);
2244 sys::path::append(Path
, Filename
);
2245 // Don't use the cached binary holder because we have no thread-safety
2246 // guarantee and the lifetime is limited.
2247 auto &Obj
= ModuleMap
.addDebugMapObject(
2248 Path
, sys::TimePoint
<std::chrono::seconds
>(), MachO::N_OSO
);
2249 auto ErrOrObj
= loadObject(Obj
, ModuleMap
);
2251 // Try and emit more helpful warnings by applying some heuristics.
2252 StringRef ObjFile
= DMO
.getObjectFilename();
2253 bool isClangModule
= sys::path::extension(Filename
).equals(".pcm");
2254 bool isArchive
= ObjFile
.endswith(")");
2255 if (isClangModule
) {
2256 StringRef ModuleCacheDir
= sys::path::parent_path(Path
);
2257 if (sys::fs::exists(ModuleCacheDir
)) {
2258 // If the module's parent directory exists, we assume that the module
2259 // cache has expired and was pruned by clang. A more adventurous
2260 // dsymutil would invoke clang to rebuild the module now.
2261 if (!ModuleCacheHintDisplayed
) {
2262 WithColor::note() << "The clang module cache may have expired since "
2263 "this object file was built. Rebuilding the "
2264 "object file will rebuild the module cache.\n";
2265 ModuleCacheHintDisplayed
= true;
2267 } else if (isArchive
) {
2268 // If the module cache directory doesn't exist at all and the object
2269 // file is inside a static library, we assume that the static library
2270 // was built on a different machine. We don't want to discourage module
2271 // debugging for convenience libraries within a project though.
2272 if (!ArchiveHintDisplayed
) {
2274 << "Linking a static library that was built with "
2275 "-gmodules, but the module cache was not found. "
2276 "Redistributable static libraries should never be "
2277 "built with module debugging enabled. The debug "
2278 "experience will be degraded due to incomplete "
2279 "debug information.\n";
2280 ArchiveHintDisplayed
= true;
2284 return Error::success();
2287 std::unique_ptr
<CompileUnit
> Unit
;
2289 // Setup access to the debug info.
2290 auto DwarfContext
= DWARFContext::create(*ErrOrObj
);
2291 RelocationManager
RelocMgr(*this);
2293 for (const auto &CU
: DwarfContext
->compile_units()) {
2294 updateDwarfVersion(CU
->getVersion());
2295 // Recursively get all modules imported by this one.
2296 auto CUDie
= CU
->getUnitDIE(false);
2299 if (!registerModuleReference(CUDie
, *CU
, ModuleMap
, DMO
, Ranges
, StringPool
,
2300 UniquingStringPool
, ODRContexts
,
2301 ModulesEndOffset
, UnitID
, IsLittleEndian
,
2306 ": Clang modules are expected to have exactly 1 compile unit.\n")
2309 return make_error
<StringError
>(Err
, inconvertibleErrorCode());
2311 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2312 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2313 // ASTFileSignatures will change randomly when a module is rebuilt.
2314 uint64_t PCMDwoId
= getDwoId(CUDie
, *CU
);
2315 if (PCMDwoId
!= DwoId
) {
2316 if (!Quiet
&& Options
.Verbose
)
2318 Twine("hash mismatch: this object file was built against a "
2319 "different version of the module ") +
2322 // Update the cache entry with the DwoId of the module loaded from disk.
2323 ClangModules
[Filename
] = PCMDwoId
;
2327 Unit
= std::make_unique
<CompileUnit
>(*CU
, UnitID
++, !Options
.NoODR
,
2329 Unit
->setHasInterestingContent();
2330 analyzeContextInfo(CUDie
, 0, *Unit
, &ODRContexts
.getRoot(),
2331 UniquingStringPool
, ODRContexts
, ModulesEndOffset
,
2332 ParseableSwiftInterfaces
,
2333 [&](const Twine
&Warning
, const DWARFDie
&DIE
) {
2334 reportWarning(Warning
, DMO
, &DIE
);
2337 Unit
->markEverythingAsKept();
2340 if (!Unit
->getOrigUnit().getUnitDIE().hasChildren())
2341 return Error::success();
2342 if (!Quiet
&& Options
.Verbose
) {
2343 outs().indent(Indent
);
2344 outs() << "cloning .debug_info from " << Filename
<< "\n";
2347 UnitListTy CompileUnits
;
2348 CompileUnits
.push_back(std::move(Unit
));
2349 DIECloner(*this, RelocMgr
, DIEAlloc
, CompileUnits
, Options
)
2350 .cloneAllCompileUnits(*DwarfContext
, DMO
, Ranges
, StringPool
,
2352 return Error::success();
2355 void DwarfLinker::DIECloner::cloneAllCompileUnits(
2356 DWARFContext
&DwarfContext
, const DebugMapObject
&DMO
, RangesTy
&Ranges
,
2357 OffsetsStringPool
&StringPool
, bool IsLittleEndian
) {
2358 if (!Linker
.Streamer
)
2361 for (auto &CurrentUnit
: CompileUnits
) {
2362 auto InputDIE
= CurrentUnit
->getOrigUnit().getUnitDIE();
2363 CurrentUnit
->setStartOffset(Linker
.OutputDebugInfoSize
);
2365 Linker
.OutputDebugInfoSize
= CurrentUnit
->computeNextUnitOffset();
2368 if (CurrentUnit
->getInfo(0).Keep
) {
2369 // Clone the InputDIE into your Unit DIE in our compile unit since it
2370 // already has a DIE inside of it.
2371 CurrentUnit
->createOutputDIE();
2372 cloneDIE(InputDIE
, DMO
, *CurrentUnit
, StringPool
, 0 /* PC offset */,
2373 11 /* Unit Header size */, 0, IsLittleEndian
,
2374 CurrentUnit
->getOutputUnitDIE());
2377 Linker
.OutputDebugInfoSize
= CurrentUnit
->computeNextUnitOffset();
2379 if (Linker
.Options
.NoOutput
)
2382 // FIXME: for compatibility with the classic dsymutil, we emit
2383 // an empty line table for the unit, even if the unit doesn't
2384 // actually exist in the DIE tree.
2385 if (LLVM_LIKELY(!Linker
.Options
.Update
) || Linker
.Options
.Translator
)
2386 Linker
.patchLineTableForUnit(*CurrentUnit
, DwarfContext
, Ranges
, DMO
);
2388 Linker
.emitAcceleratorEntriesForUnit(*CurrentUnit
);
2390 if (LLVM_UNLIKELY(Linker
.Options
.Update
))
2393 Linker
.patchRangesForUnit(*CurrentUnit
, DwarfContext
, DMO
);
2394 auto ProcessExpr
= [&](StringRef Bytes
, SmallVectorImpl
<uint8_t> &Buffer
) {
2395 DWARFUnit
&OrigUnit
= CurrentUnit
->getOrigUnit();
2396 DataExtractor
Data(Bytes
, IsLittleEndian
, OrigUnit
.getAddressByteSize());
2397 cloneExpression(Data
,
2398 DWARFExpression(Data
, OrigUnit
.getVersion(),
2399 OrigUnit
.getAddressByteSize()),
2400 DMO
, *CurrentUnit
, Buffer
);
2402 Linker
.Streamer
->emitLocationsForUnit(*CurrentUnit
, DwarfContext
,
2406 if (Linker
.Options
.NoOutput
)
2409 // Emit all the compile unit's debug information.
2410 for (auto &CurrentUnit
: CompileUnits
) {
2411 if (LLVM_LIKELY(!Linker
.Options
.Update
))
2412 Linker
.generateUnitRanges(*CurrentUnit
);
2414 CurrentUnit
->fixupForwardReferences();
2416 if (!CurrentUnit
->getOutputUnitDIE())
2419 Linker
.Streamer
->emitCompileUnitHeader(*CurrentUnit
);
2420 Linker
.Streamer
->emitDIE(*CurrentUnit
->getOutputUnitDIE());
2424 void DwarfLinker::updateAccelKind(DWARFContext
&Dwarf
) {
2425 if (Options
.TheAccelTableKind
!= AccelTableKind::Default
)
2428 auto &DwarfObj
= Dwarf
.getDWARFObj();
2430 if (!AtLeastOneDwarfAccelTable
&&
2431 (!DwarfObj
.getAppleNamesSection().Data
.empty() ||
2432 !DwarfObj
.getAppleTypesSection().Data
.empty() ||
2433 !DwarfObj
.getAppleNamespacesSection().Data
.empty() ||
2434 !DwarfObj
.getAppleObjCSection().Data
.empty())) {
2435 AtLeastOneAppleAccelTable
= true;
2438 if (!AtLeastOneDwarfAccelTable
&&
2439 !DwarfObj
.getNamesSection().Data
.empty()) {
2440 AtLeastOneDwarfAccelTable
= true;
2444 bool DwarfLinker::emitPaperTrailWarnings(const DebugMapObject
&DMO
,
2445 const DebugMap
&Map
,
2446 OffsetsStringPool
&StringPool
) {
2447 if (DMO
.getWarnings().empty() || !DMO
.empty())
2450 Streamer
->switchToDebugInfoSection(/* Version */ 2);
2451 DIE
*CUDie
= DIE::get(DIEAlloc
, dwarf::DW_TAG_compile_unit
);
2452 CUDie
->setOffset(11);
2453 StringRef Producer
= StringPool
.internString("dsymutil");
2454 StringRef File
= StringPool
.internString(DMO
.getObjectFilename());
2455 CUDie
->addValue(DIEAlloc
, dwarf::DW_AT_producer
, dwarf::DW_FORM_strp
,
2456 DIEInteger(StringPool
.getStringOffset(Producer
)));
2457 DIEBlock
*String
= new (DIEAlloc
) DIEBlock();
2458 DIEBlocks
.push_back(String
);
2459 for (auto &C
: File
)
2460 String
->addValue(DIEAlloc
, dwarf::Attribute(0), dwarf::DW_FORM_data1
,
2462 String
->addValue(DIEAlloc
, dwarf::Attribute(0), dwarf::DW_FORM_data1
,
2465 CUDie
->addValue(DIEAlloc
, dwarf::DW_AT_name
, dwarf::DW_FORM_string
, String
);
2466 for (const auto &Warning
: DMO
.getWarnings()) {
2467 DIE
&ConstDie
= CUDie
->addChild(DIE::get(DIEAlloc
, dwarf::DW_TAG_constant
));
2469 DIEAlloc
, dwarf::DW_AT_name
, dwarf::DW_FORM_strp
,
2470 DIEInteger(StringPool
.getStringOffset("dsymutil_warning")));
2471 ConstDie
.addValue(DIEAlloc
, dwarf::DW_AT_artificial
, dwarf::DW_FORM_flag
,
2473 ConstDie
.addValue(DIEAlloc
, dwarf::DW_AT_const_value
, dwarf::DW_FORM_strp
,
2474 DIEInteger(StringPool
.getStringOffset(Warning
)));
2476 unsigned Size
= 4 /* FORM_strp */ + File
.size() + 1 +
2477 DMO
.getWarnings().size() * (4 + 1 + 4) +
2478 1 /* End of children */;
2479 DIEAbbrev Abbrev
= CUDie
->generateAbbrev();
2480 AssignAbbrev(Abbrev
);
2481 CUDie
->setAbbrevNumber(Abbrev
.getNumber());
2482 Size
+= getULEB128Size(Abbrev
.getNumber());
2483 // Abbreviation ordering needed for classic compatibility.
2484 for (auto &Child
: CUDie
->children()) {
2485 Abbrev
= Child
.generateAbbrev();
2486 AssignAbbrev(Abbrev
);
2487 Child
.setAbbrevNumber(Abbrev
.getNumber());
2488 Size
+= getULEB128Size(Abbrev
.getNumber());
2490 CUDie
->setSize(Size
);
2491 auto &Asm
= Streamer
->getAsmPrinter();
2492 Asm
.emitInt32(11 + CUDie
->getSize() - 4);
2495 Asm
.emitInt8(Map
.getTriple().isArch64Bit() ? 8 : 4);
2496 Streamer
->emitDIE(*CUDie
);
2497 OutputDebugInfoSize
+= 11 /* Header */ + Size
;
2502 static Error
copySwiftInterfaces(
2503 const std::map
<std::string
, std::string
> &ParseableSwiftInterfaces
,
2504 StringRef Architecture
, const LinkOptions
&Options
) {
2506 SmallString
<128> InputPath
;
2507 SmallString
<128> Path
;
2508 sys::path::append(Path
, *Options
.ResourceDir
, "Swift", Architecture
);
2509 if ((EC
= sys::fs::create_directories(Path
.str(), true,
2510 sys::fs::perms::all_all
)))
2511 return make_error
<StringError
>(
2512 "cannot create directory: " + toString(errorCodeToError(EC
)), EC
);
2513 unsigned BaseLength
= Path
.size();
2515 for (auto &I
: ParseableSwiftInterfaces
) {
2516 StringRef ModuleName
= I
.first
;
2517 StringRef InterfaceFile
= I
.second
;
2518 if (!Options
.PrependPath
.empty()) {
2520 sys::path::append(InputPath
, Options
.PrependPath
, InterfaceFile
);
2521 InterfaceFile
= InputPath
;
2523 sys::path::append(Path
, ModuleName
);
2524 Path
.append(".swiftinterface");
2525 if (Options
.Verbose
)
2526 outs() << "copy parseable Swift interface " << InterfaceFile
<< " -> "
2527 << Path
.str() << '\n';
2529 // copy_file attempts an APFS clone first, so this should be cheap.
2530 if ((EC
= sys::fs::copy_file(InterfaceFile
, Path
.str())))
2531 warn(Twine("cannot copy parseable Swift interface ") +
2532 InterfaceFile
+ ": " +
2533 toString(errorCodeToError(EC
)));
2534 Path
.resize(BaseLength
);
2536 return Error::success();
2539 bool DwarfLinker::link(const DebugMap
&Map
) {
2540 if (!createStreamer(Map
.getTriple(), OutFile
))
2543 // Size of the DIEs (and headers) generated for the linked output.
2544 OutputDebugInfoSize
= 0;
2545 // A unique ID that identifies each compile unit.
2546 unsigned UnitID
= 0;
2547 DebugMap
ModuleMap(Map
.getTriple(), Map
.getBinaryPath());
2549 // First populate the data structure we need for each iteration of the
2551 unsigned NumObjects
= Map
.getNumberOfObjects();
2552 std::vector
<LinkContext
> ObjectContexts
;
2553 ObjectContexts
.reserve(NumObjects
);
2554 for (const auto &Obj
: Map
.objects()) {
2555 ObjectContexts
.emplace_back(Map
, *this, *Obj
.get());
2556 LinkContext
&LC
= ObjectContexts
.back();
2558 updateAccelKind(*LC
.DwarfContext
);
2561 // This Dwarf string pool which is only used for uniquing. This one should
2562 // never be used for offsets as its not thread-safe or predictable.
2563 UniquingStringPool UniquingStringPool
;
2565 // This Dwarf string pool which is used for emission. It must be used
2566 // serially as the order of calling getStringOffset matters for
2568 OffsetsStringPool
OffsetsStringPool(Options
.Translator
);
2570 // ODR Contexts for the link.
2571 DeclContextTree ODRContexts
;
2573 // If we haven't decided on an accelerator table kind yet, we base ourselves
2574 // on the DWARF we have seen so far. At this point we haven't pulled in debug
2575 // information from modules yet, so it is technically possible that they
2576 // would affect the decision. However, as they're built with the same
2577 // compiler and flags, it is safe to assume that they will follow the
2578 // decision made here.
2579 if (Options
.TheAccelTableKind
== AccelTableKind::Default
) {
2580 if (AtLeastOneDwarfAccelTable
&& !AtLeastOneAppleAccelTable
)
2581 Options
.TheAccelTableKind
= AccelTableKind::Dwarf
;
2583 Options
.TheAccelTableKind
= AccelTableKind::Apple
;
2586 for (LinkContext
&LinkContext
: ObjectContexts
) {
2587 if (Options
.Verbose
)
2588 outs() << "DEBUG MAP OBJECT: " << LinkContext
.DMO
.getObjectFilename()
2591 // N_AST objects (swiftmodule files) should get dumped directly into the
2592 // appropriate DWARF section.
2593 if (LinkContext
.DMO
.getType() == MachO::N_AST
) {
2594 StringRef File
= LinkContext
.DMO
.getObjectFilename();
2595 auto ErrorOrMem
= MemoryBuffer::getFile(File
);
2597 warn("Could not open '" + File
+ "'\n");
2600 sys::fs::file_status Stat
;
2601 if (auto Err
= sys::fs::status(File
, Stat
)) {
2602 warn(Err
.message());
2605 if (!Options
.NoTimestamp
) {
2606 // The modification can have sub-second precision so we need to cast
2607 // away the extra precision that's not present in the debug map.
2608 auto ModificationTime
=
2609 std::chrono::time_point_cast
<std::chrono::seconds
>(
2610 Stat
.getLastModificationTime());
2611 if (ModificationTime
!= LinkContext
.DMO
.getTimestamp()) {
2612 // Not using the helper here as we can easily stream TimePoint<>.
2613 WithColor::warning()
2614 << "Timestamp mismatch for " << File
<< ": "
2615 << Stat
.getLastModificationTime() << " and "
2616 << sys::TimePoint
<>(LinkContext
.DMO
.getTimestamp()) << "\n";
2621 // Copy the module into the .swift_ast section.
2622 if (!Options
.NoOutput
)
2623 Streamer
->emitSwiftAST((*ErrorOrMem
)->getBuffer());
2627 if (emitPaperTrailWarnings(LinkContext
.DMO
, Map
, OffsetsStringPool
))
2630 if (!LinkContext
.ObjectFile
)
2633 // Look for relocations that correspond to debug map entries.
2635 if (LLVM_LIKELY(!Options
.Update
) &&
2636 !LinkContext
.RelocMgr
.findValidRelocsInDebugInfo(
2637 *LinkContext
.ObjectFile
, LinkContext
.DMO
)) {
2638 if (Options
.Verbose
)
2639 outs() << "No valid relocations found. Skipping.\n";
2641 // Clear this ObjFile entry as a signal to other loops that we should not
2642 // process this iteration.
2643 LinkContext
.ObjectFile
= nullptr;
2647 // Setup access to the debug info.
2648 if (!LinkContext
.DwarfContext
)
2651 startDebugObject(LinkContext
);
2653 // In a first phase, just read in the debug info and load all clang modules.
2654 LinkContext
.CompileUnits
.reserve(
2655 LinkContext
.DwarfContext
->getNumCompileUnits());
2657 for (const auto &CU
: LinkContext
.DwarfContext
->compile_units()) {
2658 updateDwarfVersion(CU
->getVersion());
2659 auto CUDie
= CU
->getUnitDIE(false);
2660 if (Options
.Verbose
) {
2661 outs() << "Input compilation unit:";
2662 DIDumpOptions DumpOpts
;
2663 DumpOpts
.ChildRecurseDepth
= 0;
2664 DumpOpts
.Verbose
= Options
.Verbose
;
2665 CUDie
.dump(outs(), 0, DumpOpts
);
2667 if (CUDie
&& !LLVM_UNLIKELY(Options
.Update
))
2668 registerModuleReference(CUDie
, *CU
, ModuleMap
, LinkContext
.DMO
,
2669 LinkContext
.Ranges
, OffsetsStringPool
,
2670 UniquingStringPool
, ODRContexts
, 0, UnitID
,
2671 LinkContext
.DwarfContext
->isLittleEndian());
2675 // If we haven't seen any CUs, pick an arbitrary valid Dwarf version anyway.
2676 if (MaxDwarfVersion
== 0)
2677 MaxDwarfVersion
= 3;
2679 // At this point we know how much data we have emitted. We use this value to
2680 // compare canonical DIE offsets in analyzeContextInfo to see if a definition
2681 // is already emitted, without being affected by canonical die offsets set
2682 // later. This prevents undeterminism when analyze and clone execute
2683 // concurrently, as clone set the canonical DIE offset and analyze reads it.
2684 const uint64_t ModulesEndOffset
= OutputDebugInfoSize
;
2686 // These variables manage the list of processed object files.
2687 // The mutex and condition variable are to ensure that this is thread safe.
2688 std::mutex ProcessedFilesMutex
;
2689 std::condition_variable ProcessedFilesConditionVariable
;
2690 BitVector
ProcessedFiles(NumObjects
, false);
2692 // Analyzing the context info is particularly expensive so it is executed in
2693 // parallel with emitting the previous compile unit.
2694 auto AnalyzeLambda
= [&](size_t i
) {
2695 auto &LinkContext
= ObjectContexts
[i
];
2697 if (!LinkContext
.ObjectFile
|| !LinkContext
.DwarfContext
)
2700 for (const auto &CU
: LinkContext
.DwarfContext
->compile_units()) {
2701 updateDwarfVersion(CU
->getVersion());
2702 // The !registerModuleReference() condition effectively skips
2703 // over fully resolved skeleton units. This second pass of
2704 // registerModuleReferences doesn't do any new work, but it
2705 // will collect top-level errors, which are suppressed. Module
2706 // warnings were already displayed in the first iteration.
2708 auto CUDie
= CU
->getUnitDIE(false);
2709 if (!CUDie
|| LLVM_UNLIKELY(Options
.Update
) ||
2710 !registerModuleReference(CUDie
, *CU
, ModuleMap
, LinkContext
.DMO
,
2711 LinkContext
.Ranges
, OffsetsStringPool
,
2712 UniquingStringPool
, ODRContexts
,
2713 ModulesEndOffset
, UnitID
, Quiet
)) {
2714 LinkContext
.CompileUnits
.push_back(std::make_unique
<CompileUnit
>(
2715 *CU
, UnitID
++, !Options
.NoODR
&& !Options
.Update
, ""));
2719 // Now build the DIE parent links that we will use during the next phase.
2720 for (auto &CurrentUnit
: LinkContext
.CompileUnits
) {
2721 auto CUDie
= CurrentUnit
->getOrigUnit().getUnitDIE();
2724 analyzeContextInfo(CurrentUnit
->getOrigUnit().getUnitDIE(), 0,
2725 *CurrentUnit
, &ODRContexts
.getRoot(),
2726 UniquingStringPool
, ODRContexts
, ModulesEndOffset
,
2727 ParseableSwiftInterfaces
,
2728 [&](const Twine
&Warning
, const DWARFDie
&DIE
) {
2729 reportWarning(Warning
, LinkContext
.DMO
, &DIE
);
2734 // And then the remaining work in serial again.
2735 // Note, although this loop runs in serial, it can run in parallel with
2736 // the analyzeContextInfo loop so long as we process files with indices >=
2737 // than those processed by analyzeContextInfo.
2738 auto CloneLambda
= [&](size_t i
) {
2739 auto &LinkContext
= ObjectContexts
[i
];
2740 if (!LinkContext
.ObjectFile
)
2743 // Then mark all the DIEs that need to be present in the linked output
2744 // and collect some information about them.
2745 // Note that this loop can not be merged with the previous one because
2746 // cross-cu references require the ParentIdx to be setup for every CU in
2747 // the object file before calling this.
2748 if (LLVM_UNLIKELY(Options
.Update
)) {
2749 for (auto &CurrentUnit
: LinkContext
.CompileUnits
)
2750 CurrentUnit
->markEverythingAsKept();
2751 Streamer
->copyInvariantDebugSection(*LinkContext
.ObjectFile
);
2753 for (auto &CurrentUnit
: LinkContext
.CompileUnits
)
2754 lookForDIEsToKeep(LinkContext
.RelocMgr
, LinkContext
.Ranges
,
2755 LinkContext
.CompileUnits
,
2756 CurrentUnit
->getOrigUnit().getUnitDIE(),
2757 LinkContext
.DMO
, *CurrentUnit
, 0);
2760 // The calls to applyValidRelocs inside cloneDIE will walk the reloc
2761 // array again (in the same way findValidRelocsInDebugInfo() did). We
2762 // need to reset the NextValidReloc index to the beginning.
2763 LinkContext
.RelocMgr
.resetValidRelocs();
2764 if (LinkContext
.RelocMgr
.hasValidRelocs() || LLVM_UNLIKELY(Options
.Update
))
2765 DIECloner(*this, LinkContext
.RelocMgr
, DIEAlloc
, LinkContext
.CompileUnits
,
2767 .cloneAllCompileUnits(*LinkContext
.DwarfContext
, LinkContext
.DMO
,
2768 LinkContext
.Ranges
, OffsetsStringPool
,
2769 LinkContext
.DwarfContext
->isLittleEndian());
2770 if (!Options
.NoOutput
&& !LinkContext
.CompileUnits
.empty() &&
2771 LLVM_LIKELY(!Options
.Update
))
2772 patchFrameInfoForObject(
2773 LinkContext
.DMO
, LinkContext
.Ranges
, *LinkContext
.DwarfContext
,
2774 LinkContext
.CompileUnits
[0]->getOrigUnit().getAddressByteSize());
2776 // Clean-up before starting working on the next object.
2777 endDebugObject(LinkContext
);
2780 auto EmitLambda
= [&]() {
2781 // Emit everything that's global.
2782 if (!Options
.NoOutput
) {
2783 Streamer
->emitAbbrevs(Abbreviations
, MaxDwarfVersion
);
2784 Streamer
->emitStrings(OffsetsStringPool
);
2785 switch (Options
.TheAccelTableKind
) {
2786 case AccelTableKind::Apple
:
2787 Streamer
->emitAppleNames(AppleNames
);
2788 Streamer
->emitAppleNamespaces(AppleNamespaces
);
2789 Streamer
->emitAppleTypes(AppleTypes
);
2790 Streamer
->emitAppleObjc(AppleObjc
);
2792 case AccelTableKind::Dwarf
:
2793 Streamer
->emitDebugNames(DebugNames
);
2795 case AccelTableKind::Default
:
2796 llvm_unreachable("Default should have already been resolved.");
2802 auto AnalyzeAll
= [&]() {
2803 for (unsigned i
= 0, e
= NumObjects
; i
!= e
; ++i
) {
2806 std::unique_lock
<std::mutex
> LockGuard(ProcessedFilesMutex
);
2807 ProcessedFiles
.set(i
);
2808 ProcessedFilesConditionVariable
.notify_one();
2812 auto CloneAll
= [&]() {
2813 for (unsigned i
= 0, e
= NumObjects
; i
!= e
; ++i
) {
2815 std::unique_lock
<std::mutex
> LockGuard(ProcessedFilesMutex
);
2816 if (!ProcessedFiles
[i
]) {
2817 ProcessedFilesConditionVariable
.wait(
2818 LockGuard
, [&]() { return ProcessedFiles
[i
]; });
2827 // To limit memory usage in the single threaded case, analyze and clone are
2828 // run sequentially so the LinkContext is freed after processing each object
2829 // in endDebugObject.
2830 if (Options
.Threads
== 1) {
2831 for (unsigned i
= 0, e
= NumObjects
; i
!= e
; ++i
) {
2838 pool
.async(AnalyzeAll
);
2839 pool
.async(CloneAll
);
2843 if (Options
.NoOutput
)
2846 if (Options
.ResourceDir
&& !ParseableSwiftInterfaces
.empty()) {
2847 StringRef ArchName
= Triple::getArchTypeName(Map
.getTriple().getArch());
2849 copySwiftInterfaces(ParseableSwiftInterfaces
, ArchName
, Options
))
2850 return error(toString(std::move(E
)));
2853 return Streamer
->finish(Map
, Options
.Translator
);
2854 } // namespace dsymutil
2856 bool linkDwarf(raw_fd_ostream
&OutFile
, BinaryHolder
&BinHolder
,
2857 const DebugMap
&DM
, LinkOptions Options
) {
2858 DwarfLinker
Linker(OutFile
, BinHolder
, std::move(Options
));
2859 return Linker
.link(DM
);
2862 } // namespace dsymutil