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
, unsigned Offset
) {
109 auto CU
= std::upper_bound(
110 Units
.begin(), Units
.end(), Offset
,
111 [](uint32_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 DWARFUnit
&Unit
, const DWARFDie
&DIE
,
125 CompileUnit
*&RefCU
) {
126 assert(RefValue
.isFormClass(DWARFFormValue::FC_Reference
));
127 uint64_t RefOffset
= *RefValue
.getAsReference();
129 if ((RefCU
= getUnitForOffset(Units
, RefOffset
)))
130 if (const auto RefDie
= RefCU
->getOrigUnit().getDIEForOffset(RefOffset
)) {
131 // In a file with broken references, an attribute might point to a NULL
133 if (!RefDie
.isNULL())
137 Linker
.reportWarning("could not find referenced DIE", DMO
, &DIE
);
141 /// \returns whether the passed \a Attr type might contain a DIE reference
142 /// suitable for ODR uniquing.
143 static bool isODRAttribute(uint16_t Attr
) {
147 case dwarf::DW_AT_type
:
148 case dwarf::DW_AT_containing_type
:
149 case dwarf::DW_AT_specification
:
150 case dwarf::DW_AT_abstract_origin
:
151 case dwarf::DW_AT_import
:
154 llvm_unreachable("Improper attribute.");
157 static bool isTypeTag(uint16_t Tag
) {
159 case dwarf::DW_TAG_array_type
:
160 case dwarf::DW_TAG_class_type
:
161 case dwarf::DW_TAG_enumeration_type
:
162 case dwarf::DW_TAG_pointer_type
:
163 case dwarf::DW_TAG_reference_type
:
164 case dwarf::DW_TAG_string_type
:
165 case dwarf::DW_TAG_structure_type
:
166 case dwarf::DW_TAG_subroutine_type
:
167 case dwarf::DW_TAG_typedef
:
168 case dwarf::DW_TAG_union_type
:
169 case dwarf::DW_TAG_ptr_to_member_type
:
170 case dwarf::DW_TAG_set_type
:
171 case dwarf::DW_TAG_subrange_type
:
172 case dwarf::DW_TAG_base_type
:
173 case dwarf::DW_TAG_const_type
:
174 case dwarf::DW_TAG_constant
:
175 case dwarf::DW_TAG_file_type
:
176 case dwarf::DW_TAG_namelist
:
177 case dwarf::DW_TAG_packed_type
:
178 case dwarf::DW_TAG_volatile_type
:
179 case dwarf::DW_TAG_restrict_type
:
180 case dwarf::DW_TAG_atomic_type
:
181 case dwarf::DW_TAG_interface_type
:
182 case dwarf::DW_TAG_unspecified_type
:
183 case dwarf::DW_TAG_shared_type
:
191 bool DwarfLinker::DIECloner::getDIENames(const DWARFDie
&Die
,
192 AttributesInfo
&Info
,
193 OffsetsStringPool
&StringPool
,
194 bool StripTemplate
) {
195 // This function will be called on DIEs having low_pcs and
196 // ranges. As getting the name might be more expansive, filter out
198 if (Die
.getTag() == dwarf::DW_TAG_lexical_block
)
201 // FIXME: a bit wasteful as the first getName might return the
203 if (!Info
.MangledName
)
204 if (const char *MangledName
= Die
.getName(DINameKind::LinkageName
))
205 Info
.MangledName
= StringPool
.getEntry(MangledName
);
208 if (const char *Name
= Die
.getName(DINameKind::ShortName
))
209 Info
.Name
= StringPool
.getEntry(Name
);
211 if (StripTemplate
&& Info
.Name
&& Info
.MangledName
!= Info
.Name
) {
212 // FIXME: dsymutil compatibility. This is wrong for operator<
213 auto Split
= Info
.Name
.getString().split('<');
214 if (!Split
.second
.empty())
215 Info
.NameWithoutTemplate
= StringPool
.getEntry(Split
.first
);
218 return Info
.Name
|| Info
.MangledName
;
221 /// Report a warning to the user, optionally including information about a
222 /// specific \p DIE related to the warning.
223 void DwarfLinker::reportWarning(const Twine
&Warning
, const DebugMapObject
&DMO
,
224 const DWARFDie
*DIE
) const {
225 StringRef Context
= DMO
.getObjectFilename();
226 warn(Warning
, Context
);
228 if (!Options
.Verbose
|| !DIE
)
231 DIDumpOptions DumpOpts
;
232 DumpOpts
.RecurseDepth
= 0;
233 DumpOpts
.Verbose
= Options
.Verbose
;
235 WithColor::note() << " in DIE:\n";
236 DIE
->dump(errs(), 6 /* Indent */, DumpOpts
);
239 bool DwarfLinker::createStreamer(const Triple
&TheTriple
,
240 raw_fd_ostream
&OutFile
) {
241 if (Options
.NoOutput
)
244 Streamer
= llvm::make_unique
<DwarfStreamer
>(OutFile
, Options
);
245 return Streamer
->init(TheTriple
);
248 /// Recursive helper to build the global DeclContext information and
249 /// gather the child->parent relationships in the original compile unit.
251 /// \return true when this DIE and all of its children are only
252 /// forward declarations to types defined in external clang modules
253 /// (i.e., forward declarations that are children of a DW_TAG_module).
254 static bool analyzeContextInfo(const DWARFDie
&DIE
, unsigned ParentIdx
,
255 CompileUnit
&CU
, DeclContext
*CurrentDeclContext
,
256 UniquingStringPool
&StringPool
,
257 DeclContextTree
&Contexts
,
258 uint64_t ModulesEndOffset
,
259 bool InImportedModule
= false) {
260 unsigned MyIdx
= CU
.getOrigUnit().getDIEIndex(DIE
);
261 CompileUnit::DIEInfo
&Info
= CU
.getInfo(MyIdx
);
263 // Clang imposes an ODR on modules(!) regardless of the language:
264 // "The module-id should consist of only a single identifier,
265 // which provides the name of the module being defined. Each
266 // module shall have a single definition."
268 // This does not extend to the types inside the modules:
269 // "[I]n C, this implies that if two structs are defined in
270 // different submodules with the same name, those two types are
271 // distinct types (but may be compatible types if their
272 // definitions match)."
274 // We treat non-C++ modules like namespaces for this reason.
275 if (DIE
.getTag() == dwarf::DW_TAG_module
&& ParentIdx
== 0 &&
276 dwarf::toString(DIE
.find(dwarf::DW_AT_name
), "") !=
277 CU
.getClangModuleName()) {
278 InImportedModule
= true;
281 Info
.ParentIdx
= ParentIdx
;
282 bool InClangModule
= CU
.isClangModule() || InImportedModule
;
283 if (CU
.hasODR() || InClangModule
) {
284 if (CurrentDeclContext
) {
285 auto PtrInvalidPair
= Contexts
.getChildDeclContext(
286 *CurrentDeclContext
, DIE
, CU
, StringPool
, InClangModule
);
287 CurrentDeclContext
= PtrInvalidPair
.getPointer();
289 PtrInvalidPair
.getInt() ? nullptr : PtrInvalidPair
.getPointer();
291 Info
.Ctxt
->setDefinedInClangModule(InClangModule
);
293 Info
.Ctxt
= CurrentDeclContext
= nullptr;
296 Info
.Prune
= InImportedModule
;
297 if (DIE
.hasChildren())
298 for (auto Child
: DIE
.children())
300 analyzeContextInfo(Child
, MyIdx
, CU
, CurrentDeclContext
, StringPool
,
301 Contexts
, ModulesEndOffset
, InImportedModule
);
303 // Prune this DIE if it is either a forward declaration inside a
304 // DW_TAG_module or a DW_TAG_module that contains nothing but
305 // forward declarations.
306 Info
.Prune
&= (DIE
.getTag() == dwarf::DW_TAG_module
) ||
307 (isTypeTag(DIE
.getTag()) &&
308 dwarf::toUnsigned(DIE
.find(dwarf::DW_AT_declaration
), 0));
310 // Only prune forward declarations inside a DW_TAG_module for which a
311 // definition exists elsewhere.
312 if (ModulesEndOffset
== 0)
313 Info
.Prune
&= Info
.Ctxt
&& Info
.Ctxt
->getCanonicalDIEOffset();
315 Info
.Prune
&= Info
.Ctxt
&& Info
.Ctxt
->getCanonicalDIEOffset() > 0 &&
316 Info
.Ctxt
->getCanonicalDIEOffset() <= ModulesEndOffset
;
319 } // namespace dsymutil
321 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag
) {
325 case dwarf::DW_TAG_subprogram
:
326 case dwarf::DW_TAG_lexical_block
:
327 case dwarf::DW_TAG_subroutine_type
:
328 case dwarf::DW_TAG_structure_type
:
329 case dwarf::DW_TAG_class_type
:
330 case dwarf::DW_TAG_union_type
:
333 llvm_unreachable("Invalid Tag");
336 void DwarfLinker::startDebugObject(LinkContext
&Context
) {
337 // Iterate over the debug map entries and put all the ones that are
338 // functions (because they have a size) into the Ranges map. This map is
339 // very similar to the FunctionRanges that are stored in each unit, with 2
340 // notable differences:
342 // 1. Obviously this one is global, while the other ones are per-unit.
344 // 2. This one contains not only the functions described in the DIE
345 // tree, but also the ones that are only in the debug map.
347 // The latter information is required to reproduce dsymutil's logic while
348 // linking line tables. The cases where this information matters look like
349 // bugs that need to be investigated, but for now we need to reproduce
350 // dsymutil's behavior.
351 // FIXME: Once we understood exactly if that information is needed,
352 // maybe totally remove this (or try to use it to do a real
353 // -gline-tables-only on Darwin.
354 for (const auto &Entry
: Context
.DMO
.symbols()) {
355 const auto &Mapping
= Entry
.getValue();
356 if (Mapping
.Size
&& Mapping
.ObjectAddress
)
357 Context
.Ranges
[*Mapping
.ObjectAddress
] = DebugMapObjectRange(
358 *Mapping
.ObjectAddress
+ Mapping
.Size
,
359 int64_t(Mapping
.BinaryAddress
) - *Mapping
.ObjectAddress
);
363 void DwarfLinker::endDebugObject(LinkContext
&Context
) {
366 for (auto I
= DIEBlocks
.begin(), E
= DIEBlocks
.end(); I
!= E
; ++I
)
368 for (auto I
= DIELocs
.begin(), E
= DIELocs
.end(); I
!= E
; ++I
)
376 static bool isMachOPairedReloc(uint64_t RelocType
, uint64_t Arch
) {
379 return RelocType
== MachO::GENERIC_RELOC_SECTDIFF
||
380 RelocType
== MachO::GENERIC_RELOC_LOCAL_SECTDIFF
;
382 return RelocType
== MachO::X86_64_RELOC_SUBTRACTOR
;
385 return RelocType
== MachO::ARM_RELOC_SECTDIFF
||
386 RelocType
== MachO::ARM_RELOC_LOCAL_SECTDIFF
||
387 RelocType
== MachO::ARM_RELOC_HALF
||
388 RelocType
== MachO::ARM_RELOC_HALF_SECTDIFF
;
389 case Triple::aarch64
:
390 return RelocType
== MachO::ARM64_RELOC_SUBTRACTOR
;
396 /// Iterate over the relocations of the given \p Section and
397 /// store the ones that correspond to debug map entries into the
398 /// ValidRelocs array.
399 void DwarfLinker::RelocationManager::findValidRelocsMachO(
400 const object::SectionRef
&Section
, const object::MachOObjectFile
&Obj
,
401 const DebugMapObject
&DMO
) {
403 Section
.getContents(Contents
);
404 DataExtractor
Data(Contents
, Obj
.isLittleEndian(), 0);
405 bool SkipNext
= false;
407 for (const object::RelocationRef
&Reloc
: Section
.relocations()) {
413 object::DataRefImpl RelocDataRef
= Reloc
.getRawDataRefImpl();
414 MachO::any_relocation_info MachOReloc
= Obj
.getRelocation(RelocDataRef
);
416 if (isMachOPairedReloc(Obj
.getAnyRelocationType(MachOReloc
),
419 Linker
.reportWarning("unsupported relocation in debug_info section.",
424 unsigned RelocSize
= 1 << Obj
.getAnyRelocationLength(MachOReloc
);
425 uint64_t Offset64
= Reloc
.getOffset();
426 if ((RelocSize
!= 4 && RelocSize
!= 8)) {
427 Linker
.reportWarning("unsupported relocation in debug_info section.",
431 uint32_t Offset
= Offset64
;
432 // Mach-o uses REL relocations, the addend is at the relocation offset.
433 uint64_t Addend
= Data
.getUnsigned(&Offset
, RelocSize
);
437 if (Obj
.isRelocationScattered(MachOReloc
)) {
438 // The address of the base symbol for scattered relocations is
439 // stored in the reloc itself. The actual addend will store the
440 // base address plus the offset.
441 SymAddress
= Obj
.getScatteredRelocationValue(MachOReloc
);
442 SymOffset
= int64_t(Addend
) - SymAddress
;
448 auto Sym
= Reloc
.getSymbol();
449 if (Sym
!= Obj
.symbol_end()) {
450 Expected
<StringRef
> SymbolName
= Sym
->getName();
452 consumeError(SymbolName
.takeError());
453 Linker
.reportWarning("error getting relocation symbol name.", DMO
);
456 if (const auto *Mapping
= DMO
.lookupSymbol(*SymbolName
))
457 ValidRelocs
.emplace_back(Offset64
, RelocSize
, Addend
, Mapping
);
458 } else if (const auto *Mapping
= DMO
.lookupObjectAddress(SymAddress
)) {
459 // Do not store the addend. The addend was the address of the symbol in
460 // the object file, the address in the binary that is stored in the debug
461 // map doesn't need to be offset.
462 ValidRelocs
.emplace_back(Offset64
, RelocSize
, SymOffset
, Mapping
);
467 /// Dispatch the valid relocation finding logic to the
468 /// appropriate handler depending on the object file format.
469 bool DwarfLinker::RelocationManager::findValidRelocs(
470 const object::SectionRef
&Section
, const object::ObjectFile
&Obj
,
471 const DebugMapObject
&DMO
) {
472 // Dispatch to the right handler depending on the file type.
473 if (auto *MachOObj
= dyn_cast
<object::MachOObjectFile
>(&Obj
))
474 findValidRelocsMachO(Section
, *MachOObj
, DMO
);
476 Linker
.reportWarning(
477 Twine("unsupported object file type: ") + Obj
.getFileName(), DMO
);
479 if (ValidRelocs
.empty())
482 // Sort the relocations by offset. We will walk the DIEs linearly in
483 // the file, this allows us to just keep an index in the relocation
484 // array that we advance during our walk, rather than resorting to
485 // some associative container. See DwarfLinker::NextValidReloc.
486 llvm::sort(ValidRelocs
);
490 /// Look for relocations in the debug_info section that match
491 /// entries in the debug map. These relocations will drive the Dwarf
492 /// link by indicating which DIEs refer to symbols present in the
494 /// \returns whether there are any valid relocations in the debug info.
495 bool DwarfLinker::RelocationManager::findValidRelocsInDebugInfo(
496 const object::ObjectFile
&Obj
, const DebugMapObject
&DMO
) {
497 // Find the debug_info section.
498 for (const object::SectionRef
&Section
: Obj
.sections()) {
499 StringRef SectionName
;
500 Section
.getName(SectionName
);
501 SectionName
= SectionName
.substr(SectionName
.find_first_not_of("._"));
502 if (SectionName
!= "debug_info")
504 return findValidRelocs(Section
, Obj
, DMO
);
509 /// Checks that there is a relocation against an actual debug
510 /// map entry between \p StartOffset and \p NextOffset.
512 /// This function must be called with offsets in strictly ascending
513 /// order because it never looks back at relocations it already 'went past'.
514 /// \returns true and sets Info.InDebugMap if it is the case.
515 bool DwarfLinker::RelocationManager::hasValidRelocation(
516 uint32_t StartOffset
, uint32_t EndOffset
, CompileUnit::DIEInfo
&Info
) {
517 assert(NextValidReloc
== 0 ||
518 StartOffset
> ValidRelocs
[NextValidReloc
- 1].Offset
);
519 if (NextValidReloc
>= ValidRelocs
.size())
522 uint64_t RelocOffset
= ValidRelocs
[NextValidReloc
].Offset
;
524 // We might need to skip some relocs that we didn't consider. For
525 // example the high_pc of a discarded DIE might contain a reloc that
526 // is in the list because it actually corresponds to the start of a
527 // function that is in the debug map.
528 while (RelocOffset
< StartOffset
&& NextValidReloc
< ValidRelocs
.size() - 1)
529 RelocOffset
= ValidRelocs
[++NextValidReloc
].Offset
;
531 if (RelocOffset
< StartOffset
|| RelocOffset
>= EndOffset
)
534 const auto &ValidReloc
= ValidRelocs
[NextValidReloc
++];
535 const auto &Mapping
= ValidReloc
.Mapping
->getValue();
536 uint64_t ObjectAddress
= Mapping
.ObjectAddress
537 ? uint64_t(*Mapping
.ObjectAddress
)
538 : std::numeric_limits
<uint64_t>::max();
539 if (Linker
.Options
.Verbose
)
540 outs() << "Found valid debug map entry: " << ValidReloc
.Mapping
->getKey()
542 << format("\t%016" PRIx64
" => %016" PRIx64
, ObjectAddress
,
543 uint64_t(Mapping
.BinaryAddress
));
545 Info
.AddrAdjust
= int64_t(Mapping
.BinaryAddress
) + ValidReloc
.Addend
;
546 if (Mapping
.ObjectAddress
)
547 Info
.AddrAdjust
-= ObjectAddress
;
548 Info
.InDebugMap
= true;
552 /// Get the starting and ending (exclusive) offset for the
553 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
554 /// supposed to point to the position of the first attribute described
556 /// \return [StartOffset, EndOffset) as a pair.
557 static std::pair
<uint32_t, uint32_t>
558 getAttributeOffsets(const DWARFAbbreviationDeclaration
*Abbrev
, unsigned Idx
,
559 unsigned Offset
, const DWARFUnit
&Unit
) {
560 DataExtractor Data
= Unit
.getDebugInfoExtractor();
562 for (unsigned i
= 0; i
< Idx
; ++i
)
563 DWARFFormValue::skipValue(Abbrev
->getFormByIndex(i
), Data
, &Offset
,
564 Unit
.getFormParams());
566 uint32_t End
= Offset
;
567 DWARFFormValue::skipValue(Abbrev
->getFormByIndex(Idx
), Data
, &End
,
568 Unit
.getFormParams());
570 return std::make_pair(Offset
, End
);
573 /// Check if a variable describing DIE should be kept.
574 /// \returns updated TraversalFlags.
575 unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager
&RelocMgr
,
578 CompileUnit::DIEInfo
&MyInfo
,
580 const auto *Abbrev
= DIE
.getAbbreviationDeclarationPtr();
582 // Global variables with constant value can always be kept.
583 if (!(Flags
& TF_InFunctionScope
) &&
584 Abbrev
->findAttributeIndex(dwarf::DW_AT_const_value
)) {
585 MyInfo
.InDebugMap
= true;
586 return Flags
| TF_Keep
;
589 Optional
<uint32_t> LocationIdx
=
590 Abbrev
->findAttributeIndex(dwarf::DW_AT_location
);
594 uint32_t Offset
= DIE
.getOffset() + getULEB128Size(Abbrev
->getCode());
595 const DWARFUnit
&OrigUnit
= Unit
.getOrigUnit();
596 uint32_t LocationOffset
, LocationEndOffset
;
597 std::tie(LocationOffset
, LocationEndOffset
) =
598 getAttributeOffsets(Abbrev
, *LocationIdx
, Offset
, OrigUnit
);
600 // See if there is a relocation to a valid debug map entry inside
601 // this variable's location. The order is important here. We want to
602 // always check in the variable has a valid relocation, so that the
603 // DIEInfo is filled. However, we don't want a static variable in a
604 // function to force us to keep the enclosing function.
605 if (!RelocMgr
.hasValidRelocation(LocationOffset
, LocationEndOffset
, MyInfo
) ||
606 (Flags
& TF_InFunctionScope
))
609 if (Options
.Verbose
) {
610 DIDumpOptions DumpOpts
;
611 DumpOpts
.RecurseDepth
= 0;
612 DumpOpts
.Verbose
= Options
.Verbose
;
613 DIE
.dump(outs(), 8 /* Indent */, DumpOpts
);
616 return Flags
| TF_Keep
;
619 /// Check if a function describing DIE should be kept.
620 /// \returns updated TraversalFlags.
621 unsigned DwarfLinker::shouldKeepSubprogramDIE(
622 RelocationManager
&RelocMgr
, RangesTy
&Ranges
, const DWARFDie
&DIE
,
623 const DebugMapObject
&DMO
, CompileUnit
&Unit
, CompileUnit::DIEInfo
&MyInfo
,
625 const auto *Abbrev
= DIE
.getAbbreviationDeclarationPtr();
627 Flags
|= TF_InFunctionScope
;
629 Optional
<uint32_t> LowPcIdx
= Abbrev
->findAttributeIndex(dwarf::DW_AT_low_pc
);
633 uint32_t Offset
= DIE
.getOffset() + getULEB128Size(Abbrev
->getCode());
634 DWARFUnit
&OrigUnit
= Unit
.getOrigUnit();
635 uint32_t LowPcOffset
, LowPcEndOffset
;
636 std::tie(LowPcOffset
, LowPcEndOffset
) =
637 getAttributeOffsets(Abbrev
, *LowPcIdx
, Offset
, OrigUnit
);
639 auto LowPc
= dwarf::toAddress(DIE
.find(dwarf::DW_AT_low_pc
));
640 assert(LowPc
.hasValue() && "low_pc attribute is not an address.");
642 !RelocMgr
.hasValidRelocation(LowPcOffset
, LowPcEndOffset
, MyInfo
))
645 if (Options
.Verbose
) {
646 DIDumpOptions DumpOpts
;
647 DumpOpts
.RecurseDepth
= 0;
648 DumpOpts
.Verbose
= Options
.Verbose
;
649 DIE
.dump(outs(), 8 /* Indent */, DumpOpts
);
652 if (DIE
.getTag() == dwarf::DW_TAG_label
) {
653 if (Unit
.hasLabelAt(*LowPc
))
655 // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
656 // that don't fall into the CU's aranges. This is wrong IMO. Debug info
657 // generation bugs aside, this is really wrong in the case of labels, where
658 // a label marking the end of a function will have a PC == CU's high_pc.
659 if (dwarf::toAddress(OrigUnit
.getUnitDIE().find(dwarf::DW_AT_high_pc
))
660 .getValueOr(UINT64_MAX
) <= LowPc
)
662 Unit
.addLabelLowPc(*LowPc
, MyInfo
.AddrAdjust
);
663 return Flags
| TF_Keep
;
668 Optional
<uint64_t> HighPc
= DIE
.getHighPC(*LowPc
);
670 reportWarning("Function without high_pc. Range will be discarded.\n", DMO
,
675 // Replace the debug map range with a more accurate one.
676 Ranges
[*LowPc
] = DebugMapObjectRange(*HighPc
, MyInfo
.AddrAdjust
);
677 Unit
.addFunctionRange(*LowPc
, *HighPc
, MyInfo
.AddrAdjust
);
681 /// Check if a DIE should be kept.
682 /// \returns updated TraversalFlags.
683 unsigned DwarfLinker::shouldKeepDIE(RelocationManager
&RelocMgr
,
684 RangesTy
&Ranges
, const DWARFDie
&DIE
,
685 const DebugMapObject
&DMO
,
687 CompileUnit::DIEInfo
&MyInfo
,
689 switch (DIE
.getTag()) {
690 case dwarf::DW_TAG_constant
:
691 case dwarf::DW_TAG_variable
:
692 return shouldKeepVariableDIE(RelocMgr
, DIE
, Unit
, MyInfo
, Flags
);
693 case dwarf::DW_TAG_subprogram
:
694 case dwarf::DW_TAG_label
:
695 return shouldKeepSubprogramDIE(RelocMgr
, Ranges
, DIE
, DMO
, Unit
, MyInfo
,
697 case dwarf::DW_TAG_imported_module
:
698 case dwarf::DW_TAG_imported_declaration
:
699 case dwarf::DW_TAG_imported_unit
:
700 // We always want to keep these.
701 return Flags
| TF_Keep
;
709 /// Mark the passed DIE as well as all the ones it depends on
712 /// This function is called by lookForDIEsToKeep on DIEs that are
713 /// newly discovered to be needed in the link. It recursively calls
714 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
715 /// TraversalFlags to inform it that it's not doing the primary DIE
717 void DwarfLinker::keepDIEAndDependencies(
718 RelocationManager
&RelocMgr
, RangesTy
&Ranges
, const UnitListTy
&Units
,
719 const DWARFDie
&Die
, CompileUnit::DIEInfo
&MyInfo
,
720 const DebugMapObject
&DMO
, CompileUnit
&CU
, bool UseODR
) {
721 DWARFUnit
&Unit
= CU
.getOrigUnit();
724 // We're looking for incomplete types.
725 MyInfo
.Incomplete
= Die
.getTag() != dwarf::DW_TAG_subprogram
&&
726 Die
.getTag() != dwarf::DW_TAG_member
&&
727 dwarf::toUnsigned(Die
.find(dwarf::DW_AT_declaration
), 0);
729 // First mark all the parent chain as kept.
730 unsigned AncestorIdx
= MyInfo
.ParentIdx
;
731 while (!CU
.getInfo(AncestorIdx
).Keep
) {
732 unsigned ODRFlag
= UseODR
? TF_ODR
: 0;
733 lookForDIEsToKeep(RelocMgr
, Ranges
, Units
, Unit
.getDIEAtIndex(AncestorIdx
),
735 TF_ParentWalk
| TF_Keep
| TF_DependencyWalk
| ODRFlag
);
736 AncestorIdx
= CU
.getInfo(AncestorIdx
).ParentIdx
;
739 // Then we need to mark all the DIEs referenced by this DIE's
740 // attributes as kept.
741 DWARFDataExtractor Data
= Unit
.getDebugInfoExtractor();
742 const auto *Abbrev
= Die
.getAbbreviationDeclarationPtr();
743 uint32_t Offset
= Die
.getOffset() + getULEB128Size(Abbrev
->getCode());
745 // Mark all DIEs referenced through attributes as kept.
746 for (const auto &AttrSpec
: Abbrev
->attributes()) {
747 DWARFFormValue
Val(AttrSpec
.Form
);
749 if (!Val
.isFormClass(DWARFFormValue::FC_Reference
) ||
750 AttrSpec
.Attr
== dwarf::DW_AT_sibling
) {
751 DWARFFormValue::skipValue(AttrSpec
.Form
, Data
, &Offset
,
752 Unit
.getFormParams());
756 Val
.extractValue(Data
, &Offset
, Unit
.getFormParams(), &Unit
);
757 CompileUnit
*ReferencedCU
;
758 if (auto RefDie
= resolveDIEReference(*this, DMO
, Units
, Val
, Unit
, Die
,
760 uint32_t RefIdx
= ReferencedCU
->getOrigUnit().getDIEIndex(RefDie
);
761 CompileUnit::DIEInfo
&Info
= ReferencedCU
->getInfo(RefIdx
);
762 bool IsModuleRef
= Info
.Ctxt
&& Info
.Ctxt
->getCanonicalDIEOffset() &&
763 Info
.Ctxt
->isDefinedInClangModule();
764 // If the referenced DIE has a DeclContext that has already been
765 // emitted, then do not keep the one in this CU. We'll link to
766 // the canonical DIE in cloneDieReferenceAttribute.
767 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
768 // be necessary and could be advantageously replaced by
769 // ReferencedCU->hasODR() && CU.hasODR().
770 // FIXME: compatibility with dsymutil-classic. There is no
771 // reason not to unique ref_addr references.
772 if (AttrSpec
.Form
!= dwarf::DW_FORM_ref_addr
&& (UseODR
|| IsModuleRef
) &&
774 Info
.Ctxt
!= ReferencedCU
->getInfo(Info
.ParentIdx
).Ctxt
&&
775 Info
.Ctxt
->getCanonicalDIEOffset() && isODRAttribute(AttrSpec
.Attr
))
778 // Keep a module forward declaration if there is no definition.
779 if (!(isODRAttribute(AttrSpec
.Attr
) && Info
.Ctxt
&&
780 Info
.Ctxt
->getCanonicalDIEOffset()))
783 unsigned ODRFlag
= UseODR
? TF_ODR
: 0;
784 lookForDIEsToKeep(RelocMgr
, Ranges
, Units
, RefDie
, DMO
, *ReferencedCU
,
785 TF_Keep
| TF_DependencyWalk
| ODRFlag
);
787 // The incomplete property is propagated if the current DIE is complete
788 // but references an incomplete DIE.
789 if (Info
.Incomplete
&& !MyInfo
.Incomplete
&&
790 (Die
.getTag() == dwarf::DW_TAG_typedef
||
791 Die
.getTag() == dwarf::DW_TAG_member
||
792 Die
.getTag() == dwarf::DW_TAG_reference_type
||
793 Die
.getTag() == dwarf::DW_TAG_ptr_to_member_type
||
794 Die
.getTag() == dwarf::DW_TAG_pointer_type
))
795 MyInfo
.Incomplete
= true;
801 /// This class represents an item in the work list. In addition to it's obvious
802 /// purpose of representing the state associated with a particular run of the
803 /// work loop, it also serves as a marker to indicate that we should run the
804 /// "continuation" code.
806 /// Originally, the latter was lambda which allowed arbitrary code to be run.
807 /// Because we always need to run the exact same code, it made more sense to
808 /// use a boolean and repurpose the already existing DIE field.
809 struct WorklistItem
{
813 CompileUnit::DIEInfo
*ChildInfo
= nullptr;
815 /// Construct a classic worklist item.
816 WorklistItem(DWARFDie Die
, unsigned Flags
)
817 : Die(Die
), Flags(Flags
), IsContinuation(false){};
819 /// Creates a continuation marker.
820 WorklistItem(DWARFDie Die
) : Die(Die
), IsContinuation(true){};
824 // Helper that updates the completeness of the current DIE. It depends on the
825 // fact that the incompletness of its children is already computed.
826 static void updateIncompleteness(const DWARFDie
&Die
,
827 CompileUnit::DIEInfo
&ChildInfo
,
829 // Only propagate incomplete members.
830 if (Die
.getTag() != dwarf::DW_TAG_structure_type
&&
831 Die
.getTag() != dwarf::DW_TAG_class_type
)
834 unsigned Idx
= CU
.getOrigUnit().getDIEIndex(Die
);
835 CompileUnit::DIEInfo
&MyInfo
= CU
.getInfo(Idx
);
837 if (MyInfo
.Incomplete
)
840 if (ChildInfo
.Incomplete
|| ChildInfo
.Prune
)
841 MyInfo
.Incomplete
= true;
844 /// Recursively walk the \p DIE tree and look for DIEs to
845 /// keep. Store that information in \p CU's DIEInfo.
847 /// This function is the entry point of the DIE selection
848 /// algorithm. It is expected to walk the DIE tree in file order and
849 /// (though the mediation of its helper) call hasValidRelocation() on
850 /// each DIE that might be a 'root DIE' (See DwarfLinker class
852 /// While walking the dependencies of root DIEs, this function is
853 /// also called, but during these dependency walks the file order is
854 /// not respected. The TF_DependencyWalk flag tells us which kind of
855 /// traversal we are currently doing.
857 /// The return value indicates whether the DIE is incomplete.
858 void DwarfLinker::lookForDIEsToKeep(RelocationManager
&RelocMgr
,
859 RangesTy
&Ranges
, const UnitListTy
&Units
,
861 const DebugMapObject
&DMO
, CompileUnit
&CU
,
864 SmallVector
<WorklistItem
, 4> Worklist
;
865 Worklist
.emplace_back(Die
, Flags
);
867 while (!Worklist
.empty()) {
868 WorklistItem Current
= Worklist
.back();
871 if (Current
.IsContinuation
) {
872 updateIncompleteness(Current
.Die
, *Current
.ChildInfo
, CU
);
876 unsigned Idx
= CU
.getOrigUnit().getDIEIndex(Current
.Die
);
877 CompileUnit::DIEInfo
&MyInfo
= CU
.getInfo(Idx
);
879 // At this point we are guaranteed to have a continuation marker before us
880 // in the worklist, except for the last DIE.
881 if (!Worklist
.empty())
882 Worklist
.back().ChildInfo
= &MyInfo
;
887 // If the Keep flag is set, we are marking a required DIE's dependencies.
888 // If our target is already marked as kept, we're all set.
889 bool AlreadyKept
= MyInfo
.Keep
;
890 if ((Current
.Flags
& TF_DependencyWalk
) && AlreadyKept
)
893 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
894 // because it would screw up the relocation finding logic.
895 if (!(Current
.Flags
& TF_DependencyWalk
))
896 Current
.Flags
= shouldKeepDIE(RelocMgr
, Ranges
, Current
.Die
, DMO
, CU
,
897 MyInfo
, Current
.Flags
);
899 // If it is a newly kept DIE mark it as well as all its dependencies as
901 if (!AlreadyKept
&& (Current
.Flags
& TF_Keep
)) {
902 bool UseOdr
= (Current
.Flags
& TF_DependencyWalk
)
903 ? (Current
.Flags
& TF_ODR
)
905 keepDIEAndDependencies(RelocMgr
, Ranges
, Units
, Current
.Die
, MyInfo
, DMO
,
909 // The TF_ParentWalk flag tells us that we are currently walking up
910 // the parent chain of a required DIE, and we don't want to mark all
911 // the children of the parents as kept (consider for example a
912 // DW_TAG_namespace node in the parent chain). There are however a
913 // set of DIE types for which we want to ignore that directive and still
914 // walk their children.
915 if (dieNeedsChildrenToBeMeaningful(Current
.Die
.getTag()))
916 Current
.Flags
&= ~TF_ParentWalk
;
918 if (!Current
.Die
.hasChildren() || (Current
.Flags
& TF_ParentWalk
))
921 // Add children in reverse order to the worklist to effectively process
923 for (auto Child
: reverse(Current
.Die
.children())) {
924 // Add continuation marker before every child to calculate incompleteness
925 // after the last child is processed. We can't store this information in
926 // the same item because we might have to process other continuations
928 Worklist
.emplace_back(Current
.Die
);
929 Worklist
.emplace_back(Child
, Current
.Flags
);
934 /// Assign an abbreviation number to \p Abbrev.
936 /// Our DIEs get freed after every DebugMapObject has been processed,
937 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
938 /// the instances hold by the DIEs. When we encounter an abbreviation
939 /// that we don't know, we create a permanent copy of it.
940 void DwarfLinker::AssignAbbrev(DIEAbbrev
&Abbrev
) {
941 // Check the set for priors.
945 DIEAbbrev
*InSet
= AbbreviationsSet
.FindNodeOrInsertPos(ID
, InsertToken
);
947 // If it's newly added.
949 // Assign existing abbreviation number.
950 Abbrev
.setNumber(InSet
->getNumber());
952 // Add to abbreviation list.
953 Abbreviations
.push_back(
954 llvm::make_unique
<DIEAbbrev
>(Abbrev
.getTag(), Abbrev
.hasChildren()));
955 for (const auto &Attr
: Abbrev
.getData())
956 Abbreviations
.back()->AddAttribute(Attr
.getAttribute(), Attr
.getForm());
957 AbbreviationsSet
.InsertNode(Abbreviations
.back().get(), InsertToken
);
958 // Assign the unique abbreviation number.
959 Abbrev
.setNumber(Abbreviations
.size());
960 Abbreviations
.back()->setNumber(Abbreviations
.size());
964 unsigned DwarfLinker::DIECloner::cloneStringAttribute(
965 DIE
&Die
, AttributeSpec AttrSpec
, const DWARFFormValue
&Val
,
966 const DWARFUnit
&U
, OffsetsStringPool
&StringPool
, AttributesInfo
&Info
) {
967 // Switch everything to out of line strings.
968 const char *String
= *Val
.getAsCString();
969 auto StringEntry
= StringPool
.getEntry(String
);
971 // Update attributes info.
972 if (AttrSpec
.Attr
== dwarf::DW_AT_name
)
973 Info
.Name
= StringEntry
;
974 else if (AttrSpec
.Attr
== dwarf::DW_AT_MIPS_linkage_name
||
975 AttrSpec
.Attr
== dwarf::DW_AT_linkage_name
)
976 Info
.MangledName
= StringEntry
;
978 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
), dwarf::DW_FORM_strp
,
979 DIEInteger(StringEntry
.getOffset()));
984 unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
985 DIE
&Die
, const DWARFDie
&InputDIE
, AttributeSpec AttrSpec
,
986 unsigned AttrSize
, const DWARFFormValue
&Val
, const DebugMapObject
&DMO
,
988 const DWARFUnit
&U
= Unit
.getOrigUnit();
989 uint32_t Ref
= *Val
.getAsReference();
990 DIE
*NewRefDie
= nullptr;
991 CompileUnit
*RefUnit
= nullptr;
992 DeclContext
*Ctxt
= nullptr;
995 resolveDIEReference(Linker
, DMO
, CompileUnits
, Val
, U
, InputDIE
, RefUnit
);
997 // If the referenced DIE is not found, drop the attribute.
998 if (!RefDie
|| AttrSpec
.Attr
== dwarf::DW_AT_sibling
)
1001 unsigned Idx
= RefUnit
->getOrigUnit().getDIEIndex(RefDie
);
1002 CompileUnit::DIEInfo
&RefInfo
= RefUnit
->getInfo(Idx
);
1004 // If we already have emitted an equivalent DeclContext, just point
1006 if (isODRAttribute(AttrSpec
.Attr
)) {
1007 Ctxt
= RefInfo
.Ctxt
;
1008 if (Ctxt
&& Ctxt
->getCanonicalDIEOffset()) {
1009 DIEInteger
Attr(Ctxt
->getCanonicalDIEOffset());
1010 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1011 dwarf::DW_FORM_ref_addr
, Attr
);
1012 return U
.getRefAddrByteSize();
1016 if (!RefInfo
.Clone
) {
1017 assert(Ref
> InputDIE
.getOffset());
1018 // We haven't cloned this DIE yet. Just create an empty one and
1019 // store it. It'll get really cloned when we process it.
1020 RefInfo
.Clone
= DIE::get(DIEAlloc
, dwarf::Tag(RefDie
.getTag()));
1022 NewRefDie
= RefInfo
.Clone
;
1024 if (AttrSpec
.Form
== dwarf::DW_FORM_ref_addr
||
1025 (Unit
.hasODR() && isODRAttribute(AttrSpec
.Attr
))) {
1026 // We cannot currently rely on a DIEEntry to emit ref_addr
1027 // references, because the implementation calls back to DwarfDebug
1028 // to find the unit offset. (We don't have a DwarfDebug)
1029 // FIXME: we should be able to design DIEEntry reliance on
1032 if (Ref
< InputDIE
.getOffset()) {
1033 // We must have already cloned that DIE.
1034 uint32_t NewRefOffset
=
1035 RefUnit
->getStartOffset() + NewRefDie
->getOffset();
1036 Attr
= NewRefOffset
;
1037 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1038 dwarf::DW_FORM_ref_addr
, DIEInteger(Attr
));
1040 // A forward reference. Note and fixup later.
1042 Unit
.noteForwardReference(
1043 NewRefDie
, RefUnit
, Ctxt
,
1044 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1045 dwarf::DW_FORM_ref_addr
, DIEInteger(Attr
)));
1047 return U
.getRefAddrByteSize();
1050 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1051 dwarf::Form(AttrSpec
.Form
), DIEEntry(*NewRefDie
));
1055 unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE
&Die
,
1056 AttributeSpec AttrSpec
,
1057 const DWARFFormValue
&Val
,
1058 unsigned AttrSize
) {
1061 DIELoc
*Loc
= nullptr;
1062 DIEBlock
*Block
= nullptr;
1063 // Just copy the block data over.
1064 if (AttrSpec
.Form
== dwarf::DW_FORM_exprloc
) {
1065 Loc
= new (DIEAlloc
) DIELoc
;
1066 Linker
.DIELocs
.push_back(Loc
);
1068 Block
= new (DIEAlloc
) DIEBlock
;
1069 Linker
.DIEBlocks
.push_back(Block
);
1071 Attr
= Loc
? static_cast<DIEValueList
*>(Loc
)
1072 : static_cast<DIEValueList
*>(Block
);
1075 Value
= DIEValue(dwarf::Attribute(AttrSpec
.Attr
),
1076 dwarf::Form(AttrSpec
.Form
), Loc
);
1078 Value
= DIEValue(dwarf::Attribute(AttrSpec
.Attr
),
1079 dwarf::Form(AttrSpec
.Form
), Block
);
1080 ArrayRef
<uint8_t> Bytes
= *Val
.getAsBlock();
1081 for (auto Byte
: Bytes
)
1082 Attr
->addValue(DIEAlloc
, static_cast<dwarf::Attribute
>(0),
1083 dwarf::DW_FORM_data1
, DIEInteger(Byte
));
1084 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1085 // the DIE class, this if could be replaced by
1086 // Attr->setSize(Bytes.size()).
1087 if (Linker
.Streamer
) {
1088 auto *AsmPrinter
= &Linker
.Streamer
->getAsmPrinter();
1090 Loc
->ComputeSize(AsmPrinter
);
1092 Block
->ComputeSize(AsmPrinter
);
1094 Die
.addValue(DIEAlloc
, Value
);
1098 unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
1099 DIE
&Die
, AttributeSpec AttrSpec
, const DWARFFormValue
&Val
,
1100 const CompileUnit
&Unit
, AttributesInfo
&Info
) {
1101 uint64_t Addr
= *Val
.getAsAddress();
1103 if (LLVM_UNLIKELY(Linker
.Options
.Update
)) {
1104 if (AttrSpec
.Attr
== dwarf::DW_AT_low_pc
)
1105 Info
.HasLowPc
= true;
1106 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1107 dwarf::Form(AttrSpec
.Form
), DIEInteger(Addr
));
1108 return Unit
.getOrigUnit().getAddressByteSize();
1111 if (AttrSpec
.Attr
== dwarf::DW_AT_low_pc
) {
1112 if (Die
.getTag() == dwarf::DW_TAG_inlined_subroutine
||
1113 Die
.getTag() == dwarf::DW_TAG_lexical_block
)
1114 // The low_pc of a block or inline subroutine might get
1115 // relocated because it happens to match the low_pc of the
1116 // enclosing subprogram. To prevent issues with that, always use
1117 // the low_pc from the input DIE if relocations have been applied.
1118 Addr
= (Info
.OrigLowPc
!= std::numeric_limits
<uint64_t>::max()
1122 else if (Die
.getTag() == dwarf::DW_TAG_compile_unit
) {
1123 Addr
= Unit
.getLowPc();
1124 if (Addr
== std::numeric_limits
<uint64_t>::max())
1127 Info
.HasLowPc
= true;
1128 } else if (AttrSpec
.Attr
== dwarf::DW_AT_high_pc
) {
1129 if (Die
.getTag() == dwarf::DW_TAG_compile_unit
) {
1130 if (uint64_t HighPc
= Unit
.getHighPc())
1135 // If we have a high_pc recorded for the input DIE, use
1136 // it. Otherwise (when no relocations where applied) just use the
1137 // one we just decoded.
1138 Addr
= (Info
.OrigHighPc
? Info
.OrigHighPc
: Addr
) + Info
.PCOffset
;
1141 Die
.addValue(DIEAlloc
, static_cast<dwarf::Attribute
>(AttrSpec
.Attr
),
1142 static_cast<dwarf::Form
>(AttrSpec
.Form
), DIEInteger(Addr
));
1143 return Unit
.getOrigUnit().getAddressByteSize();
1146 unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
1147 DIE
&Die
, const DWARFDie
&InputDIE
, const DebugMapObject
&DMO
,
1148 CompileUnit
&Unit
, AttributeSpec AttrSpec
, const DWARFFormValue
&Val
,
1149 unsigned AttrSize
, AttributesInfo
&Info
) {
1152 if (LLVM_UNLIKELY(Linker
.Options
.Update
)) {
1153 if (auto OptionalValue
= Val
.getAsUnsignedConstant())
1154 Value
= *OptionalValue
;
1155 else if (auto OptionalValue
= Val
.getAsSignedConstant())
1156 Value
= *OptionalValue
;
1157 else if (auto OptionalValue
= Val
.getAsSectionOffset())
1158 Value
= *OptionalValue
;
1160 Linker
.reportWarning(
1161 "Unsupported scalar attribute form. Dropping attribute.", DMO
,
1165 if (AttrSpec
.Attr
== dwarf::DW_AT_declaration
&& Value
)
1166 Info
.IsDeclaration
= true;
1167 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1168 dwarf::Form(AttrSpec
.Form
), DIEInteger(Value
));
1172 if (AttrSpec
.Attr
== dwarf::DW_AT_high_pc
&&
1173 Die
.getTag() == dwarf::DW_TAG_compile_unit
) {
1174 if (Unit
.getLowPc() == -1ULL)
1176 // Dwarf >= 4 high_pc is an size, not an address.
1177 Value
= Unit
.getHighPc() - Unit
.getLowPc();
1178 } else if (AttrSpec
.Form
== dwarf::DW_FORM_sec_offset
)
1179 Value
= *Val
.getAsSectionOffset();
1180 else if (AttrSpec
.Form
== dwarf::DW_FORM_sdata
)
1181 Value
= *Val
.getAsSignedConstant();
1182 else if (auto OptionalValue
= Val
.getAsUnsignedConstant())
1183 Value
= *OptionalValue
;
1185 Linker
.reportWarning(
1186 "Unsupported scalar attribute form. Dropping attribute.", DMO
,
1190 PatchLocation Patch
=
1191 Die
.addValue(DIEAlloc
, dwarf::Attribute(AttrSpec
.Attr
),
1192 dwarf::Form(AttrSpec
.Form
), DIEInteger(Value
));
1193 if (AttrSpec
.Attr
== dwarf::DW_AT_ranges
) {
1194 Unit
.noteRangeAttribute(Die
, Patch
);
1195 Info
.HasRanges
= true;
1198 // A more generic way to check for location attributes would be
1199 // nice, but it's very unlikely that any other attribute needs a
1201 else if (AttrSpec
.Attr
== dwarf::DW_AT_location
||
1202 AttrSpec
.Attr
== dwarf::DW_AT_frame_base
)
1203 Unit
.noteLocationAttribute(Patch
, Info
.PCOffset
);
1204 else if (AttrSpec
.Attr
== dwarf::DW_AT_declaration
&& Value
)
1205 Info
.IsDeclaration
= true;
1210 /// Clone \p InputDIE's attribute described by \p AttrSpec with
1211 /// value \p Val, and add it to \p Die.
1212 /// \returns the size of the cloned attribute.
1213 unsigned DwarfLinker::DIECloner::cloneAttribute(
1214 DIE
&Die
, const DWARFDie
&InputDIE
, const DebugMapObject
&DMO
,
1215 CompileUnit
&Unit
, OffsetsStringPool
&StringPool
, const DWARFFormValue
&Val
,
1216 const AttributeSpec AttrSpec
, unsigned AttrSize
, AttributesInfo
&Info
) {
1217 const DWARFUnit
&U
= Unit
.getOrigUnit();
1219 switch (AttrSpec
.Form
) {
1220 case dwarf::DW_FORM_strp
:
1221 case dwarf::DW_FORM_string
:
1222 return cloneStringAttribute(Die
, AttrSpec
, Val
, U
, StringPool
, Info
);
1223 case dwarf::DW_FORM_ref_addr
:
1224 case dwarf::DW_FORM_ref1
:
1225 case dwarf::DW_FORM_ref2
:
1226 case dwarf::DW_FORM_ref4
:
1227 case dwarf::DW_FORM_ref8
:
1228 return cloneDieReferenceAttribute(Die
, InputDIE
, AttrSpec
, AttrSize
, Val
,
1230 case dwarf::DW_FORM_block
:
1231 case dwarf::DW_FORM_block1
:
1232 case dwarf::DW_FORM_block2
:
1233 case dwarf::DW_FORM_block4
:
1234 case dwarf::DW_FORM_exprloc
:
1235 return cloneBlockAttribute(Die
, AttrSpec
, Val
, AttrSize
);
1236 case dwarf::DW_FORM_addr
:
1237 return cloneAddressAttribute(Die
, AttrSpec
, Val
, Unit
, Info
);
1238 case dwarf::DW_FORM_data1
:
1239 case dwarf::DW_FORM_data2
:
1240 case dwarf::DW_FORM_data4
:
1241 case dwarf::DW_FORM_data8
:
1242 case dwarf::DW_FORM_udata
:
1243 case dwarf::DW_FORM_sdata
:
1244 case dwarf::DW_FORM_sec_offset
:
1245 case dwarf::DW_FORM_flag
:
1246 case dwarf::DW_FORM_flag_present
:
1247 return cloneScalarAttribute(Die
, InputDIE
, DMO
, Unit
, AttrSpec
, Val
,
1250 Linker
.reportWarning(
1251 "Unsupported attribute form in cloneAttribute. Dropping.", DMO
,
1258 /// Apply the valid relocations found by findValidRelocs() to
1259 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
1260 /// in the debug_info section.
1262 /// Like for findValidRelocs(), this function must be called with
1263 /// monotonic \p BaseOffset values.
1265 /// \returns whether any reloc has been applied.
1266 bool DwarfLinker::RelocationManager::applyValidRelocs(
1267 MutableArrayRef
<char> Data
, uint32_t BaseOffset
, bool isLittleEndian
) {
1268 assert((NextValidReloc
== 0 ||
1269 BaseOffset
> ValidRelocs
[NextValidReloc
- 1].Offset
) &&
1270 "BaseOffset should only be increasing.");
1271 if (NextValidReloc
>= ValidRelocs
.size())
1274 // Skip relocs that haven't been applied.
1275 while (NextValidReloc
< ValidRelocs
.size() &&
1276 ValidRelocs
[NextValidReloc
].Offset
< BaseOffset
)
1279 bool Applied
= false;
1280 uint64_t EndOffset
= BaseOffset
+ Data
.size();
1281 while (NextValidReloc
< ValidRelocs
.size() &&
1282 ValidRelocs
[NextValidReloc
].Offset
>= BaseOffset
&&
1283 ValidRelocs
[NextValidReloc
].Offset
< EndOffset
) {
1284 const auto &ValidReloc
= ValidRelocs
[NextValidReloc
++];
1285 assert(ValidReloc
.Offset
- BaseOffset
< Data
.size());
1286 assert(ValidReloc
.Offset
- BaseOffset
+ ValidReloc
.Size
<= Data
.size());
1288 uint64_t Value
= ValidReloc
.Mapping
->getValue().BinaryAddress
;
1289 Value
+= ValidReloc
.Addend
;
1290 for (unsigned i
= 0; i
!= ValidReloc
.Size
; ++i
) {
1291 unsigned Index
= isLittleEndian
? i
: (ValidReloc
.Size
- i
- 1);
1292 Buf
[i
] = uint8_t(Value
>> (Index
* 8));
1294 assert(ValidReloc
.Size
<= sizeof(Buf
));
1295 memcpy(&Data
[ValidReloc
.Offset
- BaseOffset
], Buf
, ValidReloc
.Size
);
1302 static bool isObjCSelector(StringRef Name
) {
1303 return Name
.size() > 2 && (Name
[0] == '-' || Name
[0] == '+') &&
1307 void DwarfLinker::DIECloner::addObjCAccelerator(CompileUnit
&Unit
,
1309 DwarfStringPoolEntryRef Name
,
1310 OffsetsStringPool
&StringPool
,
1311 bool SkipPubSection
) {
1312 assert(isObjCSelector(Name
.getString()) && "not an objc selector");
1313 // Objective C method or class function.
1314 // "- [Class(Category) selector :withArg ...]"
1315 StringRef
ClassNameStart(Name
.getString().drop_front(2));
1316 size_t FirstSpace
= ClassNameStart
.find(' ');
1317 if (FirstSpace
== StringRef::npos
)
1320 StringRef
SelectorStart(ClassNameStart
.data() + FirstSpace
+ 1);
1321 if (!SelectorStart
.size())
1324 StringRef
Selector(SelectorStart
.data(), SelectorStart
.size() - 1);
1325 Unit
.addNameAccelerator(Die
, StringPool
.getEntry(Selector
), SkipPubSection
);
1327 // Add an entry for the class name that points to this
1328 // method/class function.
1329 StringRef
ClassName(ClassNameStart
.data(), FirstSpace
);
1330 Unit
.addObjCAccelerator(Die
, StringPool
.getEntry(ClassName
), SkipPubSection
);
1332 if (ClassName
[ClassName
.size() - 1] == ')') {
1333 size_t OpenParens
= ClassName
.find('(');
1334 if (OpenParens
!= StringRef::npos
) {
1335 StringRef
ClassNameNoCategory(ClassName
.data(), OpenParens
);
1336 Unit
.addObjCAccelerator(Die
, StringPool
.getEntry(ClassNameNoCategory
),
1339 std::string
MethodNameNoCategory(Name
.getString().data(), OpenParens
+ 2);
1340 // FIXME: The missing space here may be a bug, but
1341 // dsymutil-classic also does it this way.
1342 MethodNameNoCategory
.append(SelectorStart
);
1343 Unit
.addNameAccelerator(Die
, StringPool
.getEntry(MethodNameNoCategory
),
1350 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec
,
1351 uint16_t Tag
, bool InDebugMap
, bool SkipPC
,
1352 bool InFunctionScope
) {
1353 switch (AttrSpec
.Attr
) {
1356 case dwarf::DW_AT_low_pc
:
1357 case dwarf::DW_AT_high_pc
:
1358 case dwarf::DW_AT_ranges
:
1360 case dwarf::DW_AT_location
:
1361 case dwarf::DW_AT_frame_base
:
1362 // FIXME: for some reason dsymutil-classic keeps the location attributes
1363 // when they are of block type (i.e. not location lists). This is totally
1364 // wrong for globals where we will keep a wrong address. It is mostly
1365 // harmless for locals, but there is no point in keeping these anyway when
1366 // the function wasn't linked.
1367 return (SkipPC
|| (!InFunctionScope
&& Tag
== dwarf::DW_TAG_variable
&&
1369 !DWARFFormValue(AttrSpec
.Form
).isFormClass(DWARFFormValue::FC_Block
);
1373 DIE
*DwarfLinker::DIECloner::cloneDIE(const DWARFDie
&InputDIE
,
1374 const DebugMapObject
&DMO
,
1376 OffsetsStringPool
&StringPool
,
1377 int64_t PCOffset
, uint32_t OutOffset
,
1378 unsigned Flags
, DIE
*Die
) {
1379 DWARFUnit
&U
= Unit
.getOrigUnit();
1380 unsigned Idx
= U
.getDIEIndex(InputDIE
);
1381 CompileUnit::DIEInfo
&Info
= Unit
.getInfo(Idx
);
1383 // Should the DIE appear in the output?
1384 if (!Unit
.getInfo(Idx
).Keep
)
1387 uint32_t Offset
= InputDIE
.getOffset();
1388 assert(!(Die
&& Info
.Clone
) && "Can't supply a DIE and a cloned DIE");
1390 // The DIE might have been already created by a forward reference
1391 // (see cloneDieReferenceAttribute()).
1393 Info
.Clone
= DIE::get(DIEAlloc
, dwarf::Tag(InputDIE
.getTag()));
1397 assert(Die
->getTag() == InputDIE
.getTag());
1398 Die
->setOffset(OutOffset
);
1399 if ((Unit
.hasODR() || Unit
.isClangModule()) && !Info
.Incomplete
&&
1400 Die
->getTag() != dwarf::DW_TAG_namespace
&& Info
.Ctxt
&&
1401 Info
.Ctxt
!= Unit
.getInfo(Info
.ParentIdx
).Ctxt
&&
1402 !Info
.Ctxt
->getCanonicalDIEOffset()) {
1403 // We are about to emit a DIE that is the root of its own valid
1404 // DeclContext tree. Make the current offset the canonical offset
1405 // for this context.
1406 Info
.Ctxt
->setCanonicalDIEOffset(OutOffset
+ Unit
.getStartOffset());
1409 // Extract and clone every attribute.
1410 DWARFDataExtractor Data
= U
.getDebugInfoExtractor();
1411 // Point to the next DIE (generally there is always at least a NULL
1412 // entry after the current one). If this is a lone
1413 // DW_TAG_compile_unit without any children, point to the next unit.
1414 uint32_t NextOffset
= (Idx
+ 1 < U
.getNumDIEs())
1415 ? U
.getDIEAtIndex(Idx
+ 1).getOffset()
1416 : U
.getNextUnitOffset();
1417 AttributesInfo AttrInfo
;
1419 // We could copy the data only if we need to apply a relocation to it. After
1420 // testing, it seems there is no performance downside to doing the copy
1421 // unconditionally, and it makes the code simpler.
1422 SmallString
<40> DIECopy(Data
.getData().substr(Offset
, NextOffset
- Offset
));
1424 DWARFDataExtractor(DIECopy
, Data
.isLittleEndian(), Data
.getAddressSize());
1425 // Modify the copy with relocated addresses.
1426 if (RelocMgr
.applyValidRelocs(DIECopy
, Offset
, Data
.isLittleEndian())) {
1427 // If we applied relocations, we store the value of high_pc that was
1428 // potentially stored in the input DIE. If high_pc is an address
1429 // (Dwarf version == 2), then it might have been relocated to a
1430 // totally unrelated value (because the end address in the object
1431 // file might be start address of another function which got moved
1432 // independently by the linker). The computation of the actual
1433 // high_pc value is done in cloneAddressAttribute().
1434 AttrInfo
.OrigHighPc
=
1435 dwarf::toAddress(InputDIE
.find(dwarf::DW_AT_high_pc
), 0);
1436 // Also store the low_pc. It might get relocated in an
1437 // inline_subprogram that happens at the beginning of its
1438 // inlining function.
1439 AttrInfo
.OrigLowPc
= dwarf::toAddress(InputDIE
.find(dwarf::DW_AT_low_pc
),
1440 std::numeric_limits
<uint64_t>::max());
1443 // Reset the Offset to 0 as we will be working on the local copy of
1447 const auto *Abbrev
= InputDIE
.getAbbreviationDeclarationPtr();
1448 Offset
+= getULEB128Size(Abbrev
->getCode());
1450 // We are entering a subprogram. Get and propagate the PCOffset.
1451 if (Die
->getTag() == dwarf::DW_TAG_subprogram
)
1452 PCOffset
= Info
.AddrAdjust
;
1453 AttrInfo
.PCOffset
= PCOffset
;
1455 if (Abbrev
->getTag() == dwarf::DW_TAG_subprogram
) {
1456 Flags
|= TF_InFunctionScope
;
1457 if (!Info
.InDebugMap
&& LLVM_LIKELY(!Options
.Update
))
1461 bool Copied
= false;
1462 for (const auto &AttrSpec
: Abbrev
->attributes()) {
1463 if (LLVM_LIKELY(!Options
.Update
) &&
1464 shouldSkipAttribute(AttrSpec
, Die
->getTag(), Info
.InDebugMap
,
1465 Flags
& TF_SkipPC
, Flags
& TF_InFunctionScope
)) {
1466 DWARFFormValue::skipValue(AttrSpec
.Form
, Data
, &Offset
,
1468 // FIXME: dsymutil-classic keeps the old abbreviation around
1469 // even if it's not used. We can remove this (and the copyAbbrev
1470 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
1472 copyAbbrev(*InputDIE
.getAbbreviationDeclarationPtr(), Unit
.hasODR());
1478 DWARFFormValue
Val(AttrSpec
.Form
);
1479 uint32_t AttrSize
= Offset
;
1480 Val
.extractValue(Data
, &Offset
, U
.getFormParams(), &U
);
1481 AttrSize
= Offset
- AttrSize
;
1483 OutOffset
+= cloneAttribute(*Die
, InputDIE
, DMO
, Unit
, StringPool
, Val
,
1484 AttrSpec
, AttrSize
, AttrInfo
);
1487 // Look for accelerator entries.
1488 uint16_t Tag
= InputDIE
.getTag();
1489 // FIXME: This is slightly wrong. An inline_subroutine without a
1490 // low_pc, but with AT_ranges might be interesting to get into the
1491 // accelerator tables too. For now stick with dsymutil's behavior.
1492 if ((Info
.InDebugMap
|| AttrInfo
.HasLowPc
|| AttrInfo
.HasRanges
) &&
1493 Tag
!= dwarf::DW_TAG_compile_unit
&&
1494 getDIENames(InputDIE
, AttrInfo
, StringPool
,
1495 Tag
!= dwarf::DW_TAG_inlined_subroutine
)) {
1496 if (AttrInfo
.MangledName
&& AttrInfo
.MangledName
!= AttrInfo
.Name
)
1497 Unit
.addNameAccelerator(Die
, AttrInfo
.MangledName
,
1498 Tag
== dwarf::DW_TAG_inlined_subroutine
);
1499 if (AttrInfo
.Name
) {
1500 if (AttrInfo
.NameWithoutTemplate
)
1501 Unit
.addNameAccelerator(Die
, AttrInfo
.NameWithoutTemplate
,
1502 /* SkipPubSection */ true);
1503 Unit
.addNameAccelerator(Die
, AttrInfo
.Name
,
1504 Tag
== dwarf::DW_TAG_inlined_subroutine
);
1506 if (AttrInfo
.Name
&& isObjCSelector(AttrInfo
.Name
.getString()))
1507 addObjCAccelerator(Unit
, Die
, AttrInfo
.Name
, StringPool
,
1508 /* SkipPubSection =*/true);
1510 } else if (Tag
== dwarf::DW_TAG_namespace
) {
1512 AttrInfo
.Name
= StringPool
.getEntry("(anonymous namespace)");
1513 Unit
.addNamespaceAccelerator(Die
, AttrInfo
.Name
);
1514 } else if (isTypeTag(Tag
) && !AttrInfo
.IsDeclaration
&&
1515 getDIENames(InputDIE
, AttrInfo
, StringPool
) && AttrInfo
.Name
&&
1516 AttrInfo
.Name
.getString()[0]) {
1517 uint32_t Hash
= hashFullyQualifiedName(InputDIE
, Unit
, DMO
);
1518 uint64_t RuntimeLang
=
1519 dwarf::toUnsigned(InputDIE
.find(dwarf::DW_AT_APPLE_runtime_class
))
1521 bool ObjCClassIsImplementation
=
1522 (RuntimeLang
== dwarf::DW_LANG_ObjC
||
1523 RuntimeLang
== dwarf::DW_LANG_ObjC_plus_plus
) &&
1524 dwarf::toUnsigned(InputDIE
.find(dwarf::DW_AT_APPLE_objc_complete_type
))
1526 Unit
.addTypeAccelerator(Die
, AttrInfo
.Name
, ObjCClassIsImplementation
,
1530 // Determine whether there are any children that we want to keep.
1531 bool HasChildren
= false;
1532 for (auto Child
: InputDIE
.children()) {
1533 unsigned Idx
= U
.getDIEIndex(Child
);
1534 if (Unit
.getInfo(Idx
).Keep
) {
1540 DIEAbbrev NewAbbrev
= Die
->generateAbbrev();
1542 NewAbbrev
.setChildrenFlag(dwarf::DW_CHILDREN_yes
);
1543 // Assign a permanent abbrev number
1544 Linker
.AssignAbbrev(NewAbbrev
);
1545 Die
->setAbbrevNumber(NewAbbrev
.getNumber());
1547 // Add the size of the abbreviation number to the output offset.
1548 OutOffset
+= getULEB128Size(Die
->getAbbrevNumber());
1552 Die
->setSize(OutOffset
- Die
->getOffset());
1556 // Recursively clone children.
1557 for (auto Child
: InputDIE
.children()) {
1558 if (DIE
*Clone
= cloneDIE(Child
, DMO
, Unit
, StringPool
, PCOffset
, OutOffset
,
1560 Die
->addChild(Clone
);
1561 OutOffset
= Clone
->getOffset() + Clone
->getSize();
1565 // Account for the end of children marker.
1566 OutOffset
+= sizeof(int8_t);
1568 Die
->setSize(OutOffset
- Die
->getOffset());
1572 /// Patch the input object file relevant debug_ranges entries
1573 /// and emit them in the output file. Update the relevant attributes
1574 /// to point at the new entries.
1575 void DwarfLinker::patchRangesForUnit(const CompileUnit
&Unit
,
1576 DWARFContext
&OrigDwarf
,
1577 const DebugMapObject
&DMO
) const {
1578 DWARFDebugRangeList RangeList
;
1579 const auto &FunctionRanges
= Unit
.getFunctionRanges();
1580 unsigned AddressSize
= Unit
.getOrigUnit().getAddressByteSize();
1581 DWARFDataExtractor
RangeExtractor(OrigDwarf
.getDWARFObj(),
1582 OrigDwarf
.getDWARFObj().getRangeSection(),
1583 OrigDwarf
.isLittleEndian(), AddressSize
);
1584 auto InvalidRange
= FunctionRanges
.end(), CurrRange
= InvalidRange
;
1585 DWARFUnit
&OrigUnit
= Unit
.getOrigUnit();
1586 auto OrigUnitDie
= OrigUnit
.getUnitDIE(false);
1587 uint64_t OrigLowPc
=
1588 dwarf::toAddress(OrigUnitDie
.find(dwarf::DW_AT_low_pc
), -1ULL);
1589 // Ranges addresses are based on the unit's low_pc. Compute the
1590 // offset we need to apply to adapt to the new unit's low_pc.
1591 int64_t UnitPcOffset
= 0;
1592 if (OrigLowPc
!= -1ULL)
1593 UnitPcOffset
= int64_t(OrigLowPc
) - Unit
.getLowPc();
1595 for (const auto &RangeAttribute
: Unit
.getRangesAttributes()) {
1596 uint32_t Offset
= RangeAttribute
.get();
1597 RangeAttribute
.set(Streamer
->getRangesSectionSize());
1598 if (Error E
= RangeList
.extract(RangeExtractor
, &Offset
)) {
1599 llvm::consumeError(std::move(E
));
1600 reportWarning("invalid range list ignored.", DMO
);
1603 const auto &Entries
= RangeList
.getEntries();
1604 if (!Entries
.empty()) {
1605 const DWARFDebugRangeList::RangeListEntry
&First
= Entries
.front();
1607 if (CurrRange
== InvalidRange
||
1608 First
.StartAddress
+ OrigLowPc
< CurrRange
.start() ||
1609 First
.StartAddress
+ OrigLowPc
>= CurrRange
.stop()) {
1610 CurrRange
= FunctionRanges
.find(First
.StartAddress
+ OrigLowPc
);
1611 if (CurrRange
== InvalidRange
||
1612 CurrRange
.start() > First
.StartAddress
+ OrigLowPc
) {
1613 reportWarning("no mapping for range.", DMO
);
1619 Streamer
->emitRangesEntries(UnitPcOffset
, OrigLowPc
, CurrRange
, Entries
,
1624 /// Generate the debug_aranges entries for \p Unit and if the
1625 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
1626 /// contribution for this attribute.
1627 /// FIXME: this could actually be done right in patchRangesForUnit,
1628 /// but for the sake of initial bit-for-bit compatibility with legacy
1629 /// dsymutil, we have to do it in a delayed pass.
1630 void DwarfLinker::generateUnitRanges(CompileUnit
&Unit
) const {
1631 auto Attr
= Unit
.getUnitRangesAttribute();
1633 Attr
->set(Streamer
->getRangesSectionSize());
1634 Streamer
->emitUnitRangesEntries(Unit
, static_cast<bool>(Attr
));
1637 /// Insert the new line info sequence \p Seq into the current
1638 /// set of already linked line info \p Rows.
1639 static void insertLineSequence(std::vector
<DWARFDebugLine::Row
> &Seq
,
1640 std::vector
<DWARFDebugLine::Row
> &Rows
) {
1644 if (!Rows
.empty() && Rows
.back().Address
< Seq
.front().Address
) {
1645 Rows
.insert(Rows
.end(), Seq
.begin(), Seq
.end());
1650 auto InsertPoint
= std::lower_bound(
1651 Rows
.begin(), Rows
.end(), Seq
.front(),
1652 [](const DWARFDebugLine::Row
&LHS
, const DWARFDebugLine::Row
&RHS
) {
1653 return LHS
.Address
< RHS
.Address
;
1656 // FIXME: this only removes the unneeded end_sequence if the
1657 // sequences have been inserted in order. Using a global sort like
1658 // described in patchLineTableForUnit() and delaying the end_sequene
1659 // elimination to emitLineTableForUnit() we can get rid of all of them.
1660 if (InsertPoint
!= Rows
.end() &&
1661 InsertPoint
->Address
== Seq
.front().Address
&& InsertPoint
->EndSequence
) {
1662 *InsertPoint
= Seq
.front();
1663 Rows
.insert(InsertPoint
+ 1, Seq
.begin() + 1, Seq
.end());
1665 Rows
.insert(InsertPoint
, Seq
.begin(), Seq
.end());
1671 static void patchStmtList(DIE
&Die
, DIEInteger Offset
) {
1672 for (auto &V
: Die
.values())
1673 if (V
.getAttribute() == dwarf::DW_AT_stmt_list
) {
1674 V
= DIEValue(V
.getAttribute(), V
.getForm(), Offset
);
1678 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
1681 /// Extract the line table for \p Unit from \p OrigDwarf, and
1682 /// recreate a relocated version of these for the address ranges that
1683 /// are present in the binary.
1684 void DwarfLinker::patchLineTableForUnit(CompileUnit
&Unit
,
1685 DWARFContext
&OrigDwarf
,
1687 const DebugMapObject
&DMO
) {
1688 DWARFDie CUDie
= Unit
.getOrigUnit().getUnitDIE();
1689 auto StmtList
= dwarf::toSectionOffset(CUDie
.find(dwarf::DW_AT_stmt_list
));
1693 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
1694 if (auto *OutputDIE
= Unit
.getOutputUnitDIE())
1695 patchStmtList(*OutputDIE
, DIEInteger(Streamer
->getLineSectionSize()));
1697 // Parse the original line info for the unit.
1698 DWARFDebugLine::LineTable LineTable
;
1699 uint32_t StmtOffset
= *StmtList
;
1700 DWARFDataExtractor
LineExtractor(
1701 OrigDwarf
.getDWARFObj(), OrigDwarf
.getDWARFObj().getLineSection(),
1702 OrigDwarf
.isLittleEndian(), Unit
.getOrigUnit().getAddressByteSize());
1703 if (Options
.Translator
)
1704 return Streamer
->translateLineTable(LineExtractor
, StmtOffset
, Options
);
1706 Error Err
= LineTable
.parse(LineExtractor
, &StmtOffset
, OrigDwarf
,
1707 &Unit
.getOrigUnit(), DWARFContext::dumpWarning
);
1708 DWARFContext::dumpWarning(std::move(Err
));
1710 // This vector is the output line table.
1711 std::vector
<DWARFDebugLine::Row
> NewRows
;
1712 NewRows
.reserve(LineTable
.Rows
.size());
1714 // Current sequence of rows being extracted, before being inserted
1716 std::vector
<DWARFDebugLine::Row
> Seq
;
1717 const auto &FunctionRanges
= Unit
.getFunctionRanges();
1718 auto InvalidRange
= FunctionRanges
.end(), CurrRange
= InvalidRange
;
1720 // FIXME: This logic is meant to generate exactly the same output as
1721 // Darwin's classic dsymutil. There is a nicer way to implement this
1722 // by simply putting all the relocated line info in NewRows and simply
1723 // sorting NewRows before passing it to emitLineTableForUnit. This
1724 // should be correct as sequences for a function should stay
1725 // together in the sorted output. There are a few corner cases that
1726 // look suspicious though, and that required to implement the logic
1727 // this way. Revisit that once initial validation is finished.
1729 // Iterate over the object file line info and extract the sequences
1730 // that correspond to linked functions.
1731 for (auto &Row
: LineTable
.Rows
) {
1732 // Check whether we stepped out of the range. The range is
1733 // half-open, but consider accept the end address of the range if
1734 // it is marked as end_sequence in the input (because in that
1735 // case, the relocation offset is accurate and that entry won't
1736 // serve as the start of another function).
1737 if (CurrRange
== InvalidRange
|| Row
.Address
< CurrRange
.start() ||
1738 Row
.Address
> CurrRange
.stop() ||
1739 (Row
.Address
== CurrRange
.stop() && !Row
.EndSequence
)) {
1740 // We just stepped out of a known range. Insert a end_sequence
1741 // corresponding to the end of the range.
1742 uint64_t StopAddress
= CurrRange
!= InvalidRange
1743 ? CurrRange
.stop() + CurrRange
.value()
1745 CurrRange
= FunctionRanges
.find(Row
.Address
);
1746 bool CurrRangeValid
=
1747 CurrRange
!= InvalidRange
&& CurrRange
.start() <= Row
.Address
;
1748 if (!CurrRangeValid
) {
1749 CurrRange
= InvalidRange
;
1750 if (StopAddress
!= -1ULL) {
1751 // Try harder by looking in the DebugMapObject function
1752 // ranges map. There are corner cases where this finds a
1753 // valid entry. It's unclear if this is right or wrong, but
1754 // for now do as dsymutil.
1755 // FIXME: Understand exactly what cases this addresses and
1756 // potentially remove it along with the Ranges map.
1757 auto Range
= Ranges
.lower_bound(Row
.Address
);
1758 if (Range
!= Ranges
.begin() && Range
!= Ranges
.end())
1761 if (Range
!= Ranges
.end() && Range
->first
<= Row
.Address
&&
1762 Range
->second
.HighPC
>= Row
.Address
) {
1763 StopAddress
= Row
.Address
+ Range
->second
.Offset
;
1767 if (StopAddress
!= -1ULL && !Seq
.empty()) {
1768 // Insert end sequence row with the computed end address, but
1769 // the same line as the previous one.
1770 auto NextLine
= Seq
.back();
1771 NextLine
.Address
= StopAddress
;
1772 NextLine
.EndSequence
= 1;
1773 NextLine
.PrologueEnd
= 0;
1774 NextLine
.BasicBlock
= 0;
1775 NextLine
.EpilogueBegin
= 0;
1776 Seq
.push_back(NextLine
);
1777 insertLineSequence(Seq
, NewRows
);
1780 if (!CurrRangeValid
)
1784 // Ignore empty sequences.
1785 if (Row
.EndSequence
&& Seq
.empty())
1788 // Relocate row address and add it to the current sequence.
1789 Row
.Address
+= CurrRange
.value();
1790 Seq
.emplace_back(Row
);
1792 if (Row
.EndSequence
)
1793 insertLineSequence(Seq
, NewRows
);
1796 // Finished extracting, now emit the line tables.
1797 // FIXME: LLVM hard-codes its prologue values. We just copy the
1798 // prologue over and that works because we act as both producer and
1799 // consumer. It would be nicer to have a real configurable line
1801 if (LineTable
.Prologue
.getVersion() < 2 ||
1802 LineTable
.Prologue
.getVersion() > 5 ||
1803 LineTable
.Prologue
.DefaultIsStmt
!= DWARF2_LINE_DEFAULT_IS_STMT
||
1804 LineTable
.Prologue
.OpcodeBase
> 13)
1805 reportWarning("line table parameters mismatch. Cannot emit.", DMO
);
1807 uint32_t PrologueEnd
= *StmtList
+ 10 + LineTable
.Prologue
.PrologueLength
;
1808 // DWARF v5 has an extra 2 bytes of information before the header_length
1810 if (LineTable
.Prologue
.getVersion() == 5)
1812 StringRef LineData
= OrigDwarf
.getDWARFObj().getLineSection().Data
;
1813 MCDwarfLineTableParams Params
;
1814 Params
.DWARF2LineOpcodeBase
= LineTable
.Prologue
.OpcodeBase
;
1815 Params
.DWARF2LineBase
= LineTable
.Prologue
.LineBase
;
1816 Params
.DWARF2LineRange
= LineTable
.Prologue
.LineRange
;
1817 Streamer
->emitLineTableForUnit(Params
,
1818 LineData
.slice(*StmtList
+ 4, PrologueEnd
),
1819 LineTable
.Prologue
.MinInstLength
, NewRows
,
1820 Unit
.getOrigUnit().getAddressByteSize());
1824 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit
&Unit
) {
1825 switch (Options
.TheAccelTableKind
) {
1826 case AccelTableKind::Apple
:
1827 emitAppleAcceleratorEntriesForUnit(Unit
);
1829 case AccelTableKind::Dwarf
:
1830 emitDwarfAcceleratorEntriesForUnit(Unit
);
1832 case AccelTableKind::Default
:
1833 llvm_unreachable("The default must be updated to a concrete value.");
1838 void DwarfLinker::emitAppleAcceleratorEntriesForUnit(CompileUnit
&Unit
) {
1840 for (const auto &Namespace
: Unit
.getNamespaces())
1841 AppleNamespaces
.addName(Namespace
.Name
,
1842 Namespace
.Die
->getOffset() + Unit
.getStartOffset());
1845 if (!Options
.Minimize
)
1846 Streamer
->emitPubNamesForUnit(Unit
);
1847 for (const auto &Pubname
: Unit
.getPubnames())
1848 AppleNames
.addName(Pubname
.Name
,
1849 Pubname
.Die
->getOffset() + Unit
.getStartOffset());
1852 if (!Options
.Minimize
)
1853 Streamer
->emitPubTypesForUnit(Unit
);
1854 for (const auto &Pubtype
: Unit
.getPubtypes())
1856 Pubtype
.Name
, Pubtype
.Die
->getOffset() + Unit
.getStartOffset(),
1857 Pubtype
.Die
->getTag(),
1858 Pubtype
.ObjcClassImplementation
? dwarf::DW_FLAG_type_implementation
1860 Pubtype
.QualifiedNameHash
);
1863 for (const auto &ObjC
: Unit
.getObjC())
1864 AppleObjc
.addName(ObjC
.Name
, ObjC
.Die
->getOffset() + Unit
.getStartOffset());
1867 void DwarfLinker::emitDwarfAcceleratorEntriesForUnit(CompileUnit
&Unit
) {
1868 for (const auto &Namespace
: Unit
.getNamespaces())
1869 DebugNames
.addName(Namespace
.Name
, Namespace
.Die
->getOffset(),
1870 Namespace
.Die
->getTag(), Unit
.getUniqueID());
1871 for (const auto &Pubname
: Unit
.getPubnames())
1872 DebugNames
.addName(Pubname
.Name
, Pubname
.Die
->getOffset(),
1873 Pubname
.Die
->getTag(), Unit
.getUniqueID());
1874 for (const auto &Pubtype
: Unit
.getPubtypes())
1875 DebugNames
.addName(Pubtype
.Name
, Pubtype
.Die
->getOffset(),
1876 Pubtype
.Die
->getTag(), Unit
.getUniqueID());
1879 /// Read the frame info stored in the object, and emit the
1880 /// patched frame descriptions for the linked binary.
1882 /// This is actually pretty easy as the data of the CIEs and FDEs can
1883 /// be considered as black boxes and moved as is. The only thing to do
1884 /// is to patch the addresses in the headers.
1885 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject
&DMO
,
1887 DWARFContext
&OrigDwarf
,
1888 unsigned AddrSize
) {
1889 StringRef FrameData
= OrigDwarf
.getDWARFObj().getDebugFrameSection();
1890 if (FrameData
.empty())
1893 DataExtractor
Data(FrameData
, OrigDwarf
.isLittleEndian(), 0);
1894 uint32_t InputOffset
= 0;
1896 // Store the data of the CIEs defined in this object, keyed by their
1898 DenseMap
<uint32_t, StringRef
> LocalCIES
;
1900 while (Data
.isValidOffset(InputOffset
)) {
1901 uint32_t EntryOffset
= InputOffset
;
1902 uint32_t InitialLength
= Data
.getU32(&InputOffset
);
1903 if (InitialLength
== 0xFFFFFFFF)
1904 return reportWarning("Dwarf64 bits no supported", DMO
);
1906 uint32_t CIEId
= Data
.getU32(&InputOffset
);
1907 if (CIEId
== 0xFFFFFFFF) {
1908 // This is a CIE, store it.
1909 StringRef CIEData
= FrameData
.substr(EntryOffset
, InitialLength
+ 4);
1910 LocalCIES
[EntryOffset
] = CIEData
;
1911 // The -4 is to account for the CIEId we just read.
1912 InputOffset
+= InitialLength
- 4;
1916 uint32_t Loc
= Data
.getUnsigned(&InputOffset
, AddrSize
);
1918 // Some compilers seem to emit frame info that doesn't start at
1919 // the function entry point, thus we can't just lookup the address
1920 // in the debug map. Use the linker's range map to see if the FDE
1921 // describes something that we can relocate.
1922 auto Range
= Ranges
.upper_bound(Loc
);
1923 if (Range
!= Ranges
.begin())
1925 if (Range
== Ranges
.end() || Range
->first
> Loc
||
1926 Range
->second
.HighPC
<= Loc
) {
1927 // The +4 is to account for the size of the InitialLength field itself.
1928 InputOffset
= EntryOffset
+ InitialLength
+ 4;
1932 // This is an FDE, and we have a mapping.
1933 // Have we already emitted a corresponding CIE?
1934 StringRef CIEData
= LocalCIES
[CIEId
];
1935 if (CIEData
.empty())
1936 return reportWarning("Inconsistent debug_frame content. Dropping.", DMO
);
1938 // Look if we already emitted a CIE that corresponds to the
1939 // referenced one (the CIE data is the key of that lookup).
1940 auto IteratorInserted
= EmittedCIEs
.insert(
1941 std::make_pair(CIEData
, Streamer
->getFrameSectionSize()));
1942 // If there is no CIE yet for this ID, emit it.
1943 if (IteratorInserted
.second
||
1944 // FIXME: dsymutil-classic only caches the last used CIE for
1945 // reuse. Mimic that behavior for now. Just removing that
1946 // second half of the condition and the LastCIEOffset variable
1947 // makes the code DTRT.
1948 LastCIEOffset
!= IteratorInserted
.first
->getValue()) {
1949 LastCIEOffset
= Streamer
->getFrameSectionSize();
1950 IteratorInserted
.first
->getValue() = LastCIEOffset
;
1951 Streamer
->emitCIE(CIEData
);
1954 // Emit the FDE with updated address and CIE pointer.
1955 // (4 + AddrSize) is the size of the CIEId + initial_location
1956 // fields that will get reconstructed by emitFDE().
1957 unsigned FDERemainingBytes
= InitialLength
- (4 + AddrSize
);
1958 Streamer
->emitFDE(IteratorInserted
.first
->getValue(), AddrSize
,
1959 Loc
+ Range
->second
.Offset
,
1960 FrameData
.substr(InputOffset
, FDERemainingBytes
));
1961 InputOffset
+= FDERemainingBytes
;
1965 void DwarfLinker::DIECloner::copyAbbrev(
1966 const DWARFAbbreviationDeclaration
&Abbrev
, bool hasODR
) {
1967 DIEAbbrev
Copy(dwarf::Tag(Abbrev
.getTag()),
1968 dwarf::Form(Abbrev
.hasChildren()));
1970 for (const auto &Attr
: Abbrev
.attributes()) {
1971 uint16_t Form
= Attr
.Form
;
1972 if (hasODR
&& isODRAttribute(Attr
.Attr
))
1973 Form
= dwarf::DW_FORM_ref_addr
;
1974 Copy
.AddAttribute(dwarf::Attribute(Attr
.Attr
), dwarf::Form(Form
));
1977 Linker
.AssignAbbrev(Copy
);
1980 uint32_t DwarfLinker::DIECloner::hashFullyQualifiedName(
1981 DWARFDie DIE
, CompileUnit
&U
, const DebugMapObject
&DMO
, int RecurseDepth
) {
1982 const char *Name
= nullptr;
1983 DWARFUnit
*OrigUnit
= &U
.getOrigUnit();
1984 CompileUnit
*CU
= &U
;
1985 Optional
<DWARFFormValue
> Ref
;
1988 if (const char *CurrentName
= DIE
.getName(DINameKind::ShortName
))
1991 if (!(Ref
= DIE
.find(dwarf::DW_AT_specification
)) &&
1992 !(Ref
= DIE
.find(dwarf::DW_AT_abstract_origin
)))
1995 if (!Ref
->isFormClass(DWARFFormValue::FC_Reference
))
1999 if (auto RefDIE
= resolveDIEReference(Linker
, DMO
, CompileUnits
, *Ref
,
2000 U
.getOrigUnit(), DIE
, RefCU
)) {
2002 OrigUnit
= &RefCU
->getOrigUnit();
2007 unsigned Idx
= OrigUnit
->getDIEIndex(DIE
);
2008 if (!Name
&& DIE
.getTag() == dwarf::DW_TAG_namespace
)
2009 Name
= "(anonymous namespace)";
2011 if (CU
->getInfo(Idx
).ParentIdx
== 0 ||
2012 // FIXME: dsymutil-classic compatibility. Ignore modules.
2013 CU
->getOrigUnit().getDIEAtIndex(CU
->getInfo(Idx
).ParentIdx
).getTag() ==
2014 dwarf::DW_TAG_module
)
2015 return djbHash(Name
? Name
: "", djbHash(RecurseDepth
? "" : "::"));
2017 DWARFDie Die
= OrigUnit
->getDIEAtIndex(CU
->getInfo(Idx
).ParentIdx
);
2020 djbHash((Name
? "::" : ""),
2021 hashFullyQualifiedName(Die
, *CU
, DMO
, ++RecurseDepth
)));
2024 static uint64_t getDwoId(const DWARFDie
&CUDie
, const DWARFUnit
&Unit
) {
2025 auto DwoId
= dwarf::toUnsigned(
2026 CUDie
.find({dwarf::DW_AT_dwo_id
, dwarf::DW_AT_GNU_dwo_id
}));
2032 bool DwarfLinker::registerModuleReference(
2033 const DWARFDie
&CUDie
, const DWARFUnit
&Unit
, DebugMap
&ModuleMap
,
2034 const DebugMapObject
&DMO
, RangesTy
&Ranges
, OffsetsStringPool
&StringPool
,
2035 UniquingStringPool
&UniquingStringPool
, DeclContextTree
&ODRContexts
,
2036 uint64_t ModulesEndOffset
, unsigned &UnitID
, unsigned Indent
, bool Quiet
) {
2037 std::string PCMfile
= dwarf::toString(
2038 CUDie
.find({dwarf::DW_AT_dwo_name
, dwarf::DW_AT_GNU_dwo_name
}), "");
2039 if (PCMfile
.empty())
2042 // Clang module DWARF skeleton CUs abuse this for the path to the module.
2043 std::string PCMpath
= dwarf::toString(CUDie
.find(dwarf::DW_AT_comp_dir
), "");
2044 uint64_t DwoId
= getDwoId(CUDie
, Unit
);
2046 std::string Name
= dwarf::toString(CUDie
.find(dwarf::DW_AT_name
), "");
2049 reportWarning("Anonymous module skeleton CU for " + PCMfile
, DMO
);
2053 if (!Quiet
&& Options
.Verbose
) {
2054 outs().indent(Indent
);
2055 outs() << "Found clang module reference " << PCMfile
;
2058 auto Cached
= ClangModules
.find(PCMfile
);
2059 if (Cached
!= ClangModules
.end()) {
2060 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2061 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2062 // ASTFileSignatures will change randomly when a module is rebuilt.
2063 if (!Quiet
&& Options
.Verbose
&& (Cached
->second
!= DwoId
))
2064 reportWarning(Twine("hash mismatch: this object file was built against a "
2065 "different version of the module ") +
2068 if (!Quiet
&& Options
.Verbose
)
2069 outs() << " [cached].\n";
2072 if (!Quiet
&& Options
.Verbose
)
2075 // Cyclic dependencies are disallowed by Clang, but we still
2076 // shouldn't run into an infinite loop, so mark it as processed now.
2077 ClangModules
.insert({PCMfile
, DwoId
});
2079 loadClangModule(PCMfile
, PCMpath
, Name
, DwoId
, ModuleMap
, DMO
, Ranges
,
2080 StringPool
, UniquingStringPool
, ODRContexts
,
2081 ModulesEndOffset
, UnitID
, Indent
+ 2, Quiet
)) {
2082 consumeError(std::move(E
));
2088 ErrorOr
<const object::ObjectFile
&>
2089 DwarfLinker::loadObject(const DebugMapObject
&Obj
, const DebugMap
&Map
) {
2091 BinHolder
.getObjectEntry(Obj
.getObjectFilename(), Obj
.getTimestamp());
2093 auto Err
= ObjectEntry
.takeError();
2095 Twine(Obj
.getObjectFilename()) + ": " + toString(std::move(Err
)), Obj
);
2096 return errorToErrorCode(std::move(Err
));
2099 auto Object
= ObjectEntry
->getObject(Map
.getTriple());
2101 auto Err
= Object
.takeError();
2103 Twine(Obj
.getObjectFilename()) + ": " + toString(std::move(Err
)), Obj
);
2104 return errorToErrorCode(std::move(Err
));
2110 Error
DwarfLinker::loadClangModule(
2111 StringRef Filename
, StringRef ModulePath
, StringRef ModuleName
,
2112 uint64_t DwoId
, DebugMap
&ModuleMap
, const DebugMapObject
&DMO
,
2113 RangesTy
&Ranges
, OffsetsStringPool
&StringPool
,
2114 UniquingStringPool
&UniquingStringPool
, DeclContextTree
&ODRContexts
,
2115 uint64_t ModulesEndOffset
, unsigned &UnitID
, unsigned Indent
, bool Quiet
) {
2116 SmallString
<80> Path(Options
.PrependPath
);
2117 if (sys::path::is_relative(Filename
))
2118 sys::path::append(Path
, ModulePath
, Filename
);
2120 sys::path::append(Path
, Filename
);
2121 // Don't use the cached binary holder because we have no thread-safety
2122 // guarantee and the lifetime is limited.
2123 auto &Obj
= ModuleMap
.addDebugMapObject(
2124 Path
, sys::TimePoint
<std::chrono::seconds
>(), MachO::N_OSO
);
2125 auto ErrOrObj
= loadObject(Obj
, ModuleMap
);
2127 // Try and emit more helpful warnings by applying some heuristics.
2128 StringRef ObjFile
= DMO
.getObjectFilename();
2129 bool isClangModule
= sys::path::extension(Filename
).equals(".pcm");
2130 bool isArchive
= ObjFile
.endswith(")");
2131 if (isClangModule
) {
2132 StringRef ModuleCacheDir
= sys::path::parent_path(Path
);
2133 if (sys::fs::exists(ModuleCacheDir
)) {
2134 // If the module's parent directory exists, we assume that the module
2135 // cache has expired and was pruned by clang. A more adventurous
2136 // dsymutil would invoke clang to rebuild the module now.
2137 if (!ModuleCacheHintDisplayed
) {
2138 WithColor::note() << "The clang module cache may have expired since "
2139 "this object file was built. Rebuilding the "
2140 "object file will rebuild the module cache.\n";
2141 ModuleCacheHintDisplayed
= true;
2143 } else if (isArchive
) {
2144 // If the module cache directory doesn't exist at all and the object
2145 // file is inside a static library, we assume that the static library
2146 // was built on a different machine. We don't want to discourage module
2147 // debugging for convenience libraries within a project though.
2148 if (!ArchiveHintDisplayed
) {
2150 << "Linking a static library that was built with "
2151 "-gmodules, but the module cache was not found. "
2152 "Redistributable static libraries should never be "
2153 "built with module debugging enabled. The debug "
2154 "experience will be degraded due to incomplete "
2155 "debug information.\n";
2156 ArchiveHintDisplayed
= true;
2160 return Error::success();
2163 std::unique_ptr
<CompileUnit
> Unit
;
2165 // Setup access to the debug info.
2166 auto DwarfContext
= DWARFContext::create(*ErrOrObj
);
2167 RelocationManager
RelocMgr(*this);
2169 for (const auto &CU
: DwarfContext
->compile_units()) {
2170 updateDwarfVersion(CU
->getVersion());
2171 // Recursively get all modules imported by this one.
2172 auto CUDie
= CU
->getUnitDIE(false);
2175 if (!registerModuleReference(CUDie
, *CU
, ModuleMap
, DMO
, Ranges
, StringPool
,
2176 UniquingStringPool
, ODRContexts
,
2177 ModulesEndOffset
, UnitID
, Indent
, Quiet
)) {
2181 ": Clang modules are expected to have exactly 1 compile unit.\n")
2184 return make_error
<StringError
>(Err
, inconvertibleErrorCode());
2186 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2187 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2188 // ASTFileSignatures will change randomly when a module is rebuilt.
2189 uint64_t PCMDwoId
= getDwoId(CUDie
, *CU
);
2190 if (PCMDwoId
!= DwoId
) {
2191 if (!Quiet
&& Options
.Verbose
)
2193 Twine("hash mismatch: this object file was built against a "
2194 "different version of the module ") +
2197 // Update the cache entry with the DwoId of the module loaded from disk.
2198 ClangModules
[Filename
] = PCMDwoId
;
2202 Unit
= llvm::make_unique
<CompileUnit
>(*CU
, UnitID
++, !Options
.NoODR
,
2204 Unit
->setHasInterestingContent();
2205 analyzeContextInfo(CUDie
, 0, *Unit
, &ODRContexts
.getRoot(),
2206 UniquingStringPool
, ODRContexts
, ModulesEndOffset
);
2208 Unit
->markEverythingAsKept();
2211 if (!Unit
->getOrigUnit().getUnitDIE().hasChildren())
2212 return Error::success();
2213 if (!Quiet
&& Options
.Verbose
) {
2214 outs().indent(Indent
);
2215 outs() << "cloning .debug_info from " << Filename
<< "\n";
2218 UnitListTy CompileUnits
;
2219 CompileUnits
.push_back(std::move(Unit
));
2220 DIECloner(*this, RelocMgr
, DIEAlloc
, CompileUnits
, Options
)
2221 .cloneAllCompileUnits(*DwarfContext
, DMO
, Ranges
, StringPool
);
2222 return Error::success();
2225 void DwarfLinker::DIECloner::cloneAllCompileUnits(
2226 DWARFContext
&DwarfContext
, const DebugMapObject
&DMO
, RangesTy
&Ranges
,
2227 OffsetsStringPool
&StringPool
) {
2228 if (!Linker
.Streamer
)
2231 for (auto &CurrentUnit
: CompileUnits
) {
2232 auto InputDIE
= CurrentUnit
->getOrigUnit().getUnitDIE();
2233 CurrentUnit
->setStartOffset(Linker
.OutputDebugInfoSize
);
2235 Linker
.OutputDebugInfoSize
= CurrentUnit
->computeNextUnitOffset();
2238 if (CurrentUnit
->getInfo(0).Keep
) {
2239 // Clone the InputDIE into your Unit DIE in our compile unit since it
2240 // already has a DIE inside of it.
2241 CurrentUnit
->createOutputDIE();
2242 cloneDIE(InputDIE
, DMO
, *CurrentUnit
, StringPool
, 0 /* PC offset */,
2243 11 /* Unit Header size */, 0, CurrentUnit
->getOutputUnitDIE());
2246 Linker
.OutputDebugInfoSize
= CurrentUnit
->computeNextUnitOffset();
2248 if (Linker
.Options
.NoOutput
)
2251 // FIXME: for compatibility with the classic dsymutil, we emit
2252 // an empty line table for the unit, even if the unit doesn't
2253 // actually exist in the DIE tree.
2254 if (LLVM_LIKELY(!Linker
.Options
.Update
) || Linker
.Options
.Translator
)
2255 Linker
.patchLineTableForUnit(*CurrentUnit
, DwarfContext
, Ranges
, DMO
);
2257 Linker
.emitAcceleratorEntriesForUnit(*CurrentUnit
);
2259 if (LLVM_UNLIKELY(Linker
.Options
.Update
))
2262 Linker
.patchRangesForUnit(*CurrentUnit
, DwarfContext
, DMO
);
2263 Linker
.Streamer
->emitLocationsForUnit(*CurrentUnit
, DwarfContext
);
2266 if (Linker
.Options
.NoOutput
)
2269 // Emit all the compile unit's debug information.
2270 for (auto &CurrentUnit
: CompileUnits
) {
2271 if (LLVM_LIKELY(!Linker
.Options
.Update
))
2272 Linker
.generateUnitRanges(*CurrentUnit
);
2274 CurrentUnit
->fixupForwardReferences();
2276 if (!CurrentUnit
->getOutputUnitDIE())
2279 Linker
.Streamer
->emitCompileUnitHeader(*CurrentUnit
);
2280 Linker
.Streamer
->emitDIE(*CurrentUnit
->getOutputUnitDIE());
2284 void DwarfLinker::updateAccelKind(DWARFContext
&Dwarf
) {
2285 if (Options
.TheAccelTableKind
!= AccelTableKind::Default
)
2288 auto &DwarfObj
= Dwarf
.getDWARFObj();
2290 if (!AtLeastOneDwarfAccelTable
&&
2291 (!DwarfObj
.getAppleNamesSection().Data
.empty() ||
2292 !DwarfObj
.getAppleTypesSection().Data
.empty() ||
2293 !DwarfObj
.getAppleNamespacesSection().Data
.empty() ||
2294 !DwarfObj
.getAppleObjCSection().Data
.empty())) {
2295 AtLeastOneAppleAccelTable
= true;
2298 if (!AtLeastOneDwarfAccelTable
&&
2299 !DwarfObj
.getDebugNamesSection().Data
.empty()) {
2300 AtLeastOneDwarfAccelTable
= true;
2304 bool DwarfLinker::emitPaperTrailWarnings(const DebugMapObject
&DMO
,
2305 const DebugMap
&Map
,
2306 OffsetsStringPool
&StringPool
) {
2307 if (DMO
.getWarnings().empty() || !DMO
.empty())
2310 Streamer
->switchToDebugInfoSection(/* Version */ 2);
2311 DIE
*CUDie
= DIE::get(DIEAlloc
, dwarf::DW_TAG_compile_unit
);
2312 CUDie
->setOffset(11);
2313 StringRef Producer
= StringPool
.internString("dsymutil");
2314 StringRef File
= StringPool
.internString(DMO
.getObjectFilename());
2315 CUDie
->addValue(DIEAlloc
, dwarf::DW_AT_producer
, dwarf::DW_FORM_strp
,
2316 DIEInteger(StringPool
.getStringOffset(Producer
)));
2317 DIEBlock
*String
= new (DIEAlloc
) DIEBlock();
2318 DIEBlocks
.push_back(String
);
2319 for (auto &C
: File
)
2320 String
->addValue(DIEAlloc
, dwarf::Attribute(0), dwarf::DW_FORM_data1
,
2322 String
->addValue(DIEAlloc
, dwarf::Attribute(0), dwarf::DW_FORM_data1
,
2325 CUDie
->addValue(DIEAlloc
, dwarf::DW_AT_name
, dwarf::DW_FORM_string
, String
);
2326 for (const auto &Warning
: DMO
.getWarnings()) {
2327 DIE
&ConstDie
= CUDie
->addChild(DIE::get(DIEAlloc
, dwarf::DW_TAG_constant
));
2329 DIEAlloc
, dwarf::DW_AT_name
, dwarf::DW_FORM_strp
,
2330 DIEInteger(StringPool
.getStringOffset("dsymutil_warning")));
2331 ConstDie
.addValue(DIEAlloc
, dwarf::DW_AT_artificial
, dwarf::DW_FORM_flag
,
2333 ConstDie
.addValue(DIEAlloc
, dwarf::DW_AT_const_value
, dwarf::DW_FORM_strp
,
2334 DIEInteger(StringPool
.getStringOffset(Warning
)));
2336 unsigned Size
= 4 /* FORM_strp */ + File
.size() + 1 +
2337 DMO
.getWarnings().size() * (4 + 1 + 4) +
2338 1 /* End of children */;
2339 DIEAbbrev Abbrev
= CUDie
->generateAbbrev();
2340 AssignAbbrev(Abbrev
);
2341 CUDie
->setAbbrevNumber(Abbrev
.getNumber());
2342 Size
+= getULEB128Size(Abbrev
.getNumber());
2343 // Abbreviation ordering needed for classic compatibility.
2344 for (auto &Child
: CUDie
->children()) {
2345 Abbrev
= Child
.generateAbbrev();
2346 AssignAbbrev(Abbrev
);
2347 Child
.setAbbrevNumber(Abbrev
.getNumber());
2348 Size
+= getULEB128Size(Abbrev
.getNumber());
2350 CUDie
->setSize(Size
);
2351 auto &Asm
= Streamer
->getAsmPrinter();
2352 Asm
.emitInt32(11 + CUDie
->getSize() - 4);
2355 Asm
.emitInt8(Map
.getTriple().isArch64Bit() ? 8 : 4);
2356 Streamer
->emitDIE(*CUDie
);
2357 OutputDebugInfoSize
+= 11 /* Header */ + Size
;
2362 bool DwarfLinker::link(const DebugMap
&Map
) {
2363 if (!createStreamer(Map
.getTriple(), OutFile
))
2366 // Size of the DIEs (and headers) generated for the linked output.
2367 OutputDebugInfoSize
= 0;
2368 // A unique ID that identifies each compile unit.
2369 unsigned UnitID
= 0;
2370 DebugMap
ModuleMap(Map
.getTriple(), Map
.getBinaryPath());
2372 // First populate the data structure we need for each iteration of the
2374 unsigned NumObjects
= Map
.getNumberOfObjects();
2375 std::vector
<LinkContext
> ObjectContexts
;
2376 ObjectContexts
.reserve(NumObjects
);
2377 for (const auto &Obj
: Map
.objects()) {
2378 ObjectContexts
.emplace_back(Map
, *this, *Obj
.get());
2379 LinkContext
&LC
= ObjectContexts
.back();
2381 updateAccelKind(*LC
.DwarfContext
);
2384 // This Dwarf string pool which is only used for uniquing. This one should
2385 // never be used for offsets as its not thread-safe or predictable.
2386 UniquingStringPool UniquingStringPool
;
2388 // This Dwarf string pool which is used for emission. It must be used
2389 // serially as the order of calling getStringOffset matters for
2391 OffsetsStringPool
OffsetsStringPool(Options
.Translator
);
2393 // ODR Contexts for the link.
2394 DeclContextTree ODRContexts
;
2396 // If we haven't decided on an accelerator table kind yet, we base ourselves
2397 // on the DWARF we have seen so far. At this point we haven't pulled in debug
2398 // information from modules yet, so it is technically possible that they
2399 // would affect the decision. However, as they're built with the same
2400 // compiler and flags, it is safe to assume that they will follow the
2401 // decision made here.
2402 if (Options
.TheAccelTableKind
== AccelTableKind::Default
) {
2403 if (AtLeastOneDwarfAccelTable
&& !AtLeastOneAppleAccelTable
)
2404 Options
.TheAccelTableKind
= AccelTableKind::Dwarf
;
2406 Options
.TheAccelTableKind
= AccelTableKind::Apple
;
2409 for (LinkContext
&LinkContext
: ObjectContexts
) {
2410 if (Options
.Verbose
)
2411 outs() << "DEBUG MAP OBJECT: " << LinkContext
.DMO
.getObjectFilename()
2414 // N_AST objects (swiftmodule files) should get dumped directly into the
2415 // appropriate DWARF section.
2416 if (LinkContext
.DMO
.getType() == MachO::N_AST
) {
2417 StringRef File
= LinkContext
.DMO
.getObjectFilename();
2418 auto ErrorOrMem
= MemoryBuffer::getFile(File
);
2420 warn("Could not open '" + File
+ "'\n");
2423 sys::fs::file_status Stat
;
2424 if (auto Err
= sys::fs::status(File
, Stat
)) {
2425 warn(Err
.message());
2428 if (!Options
.NoTimestamp
) {
2429 // The modification can have sub-second precision so we need to cast
2430 // away the extra precision that's not present in the debug map.
2431 auto ModificationTime
=
2432 std::chrono::time_point_cast
<std::chrono::seconds
>(
2433 Stat
.getLastModificationTime());
2434 if (ModificationTime
!= LinkContext
.DMO
.getTimestamp()) {
2435 // Not using the helper here as we can easily stream TimePoint<>.
2436 WithColor::warning()
2437 << "Timestamp mismatch for " << File
<< ": "
2438 << Stat
.getLastModificationTime() << " and "
2439 << sys::TimePoint
<>(LinkContext
.DMO
.getTimestamp()) << "\n";
2444 // Copy the module into the .swift_ast section.
2445 if (!Options
.NoOutput
)
2446 Streamer
->emitSwiftAST((*ErrorOrMem
)->getBuffer());
2450 if (emitPaperTrailWarnings(LinkContext
.DMO
, Map
, OffsetsStringPool
))
2453 if (!LinkContext
.ObjectFile
)
2456 // Look for relocations that correspond to debug map entries.
2458 if (LLVM_LIKELY(!Options
.Update
) &&
2459 !LinkContext
.RelocMgr
.findValidRelocsInDebugInfo(
2460 *LinkContext
.ObjectFile
, LinkContext
.DMO
)) {
2461 if (Options
.Verbose
)
2462 outs() << "No valid relocations found. Skipping.\n";
2464 // Clear this ObjFile entry as a signal to other loops that we should not
2465 // process this iteration.
2466 LinkContext
.ObjectFile
= nullptr;
2470 // Setup access to the debug info.
2471 if (!LinkContext
.DwarfContext
)
2474 startDebugObject(LinkContext
);
2476 // In a first phase, just read in the debug info and load all clang modules.
2477 LinkContext
.CompileUnits
.reserve(
2478 LinkContext
.DwarfContext
->getNumCompileUnits());
2480 for (const auto &CU
: LinkContext
.DwarfContext
->compile_units()) {
2481 updateDwarfVersion(CU
->getVersion());
2482 auto CUDie
= CU
->getUnitDIE(false);
2483 if (Options
.Verbose
) {
2484 outs() << "Input compilation unit:";
2485 DIDumpOptions DumpOpts
;
2486 DumpOpts
.RecurseDepth
= 0;
2487 DumpOpts
.Verbose
= Options
.Verbose
;
2488 CUDie
.dump(outs(), 0, DumpOpts
);
2490 if (CUDie
&& !LLVM_UNLIKELY(Options
.Update
))
2491 registerModuleReference(CUDie
, *CU
, ModuleMap
, LinkContext
.DMO
,
2492 LinkContext
.Ranges
, OffsetsStringPool
,
2493 UniquingStringPool
, ODRContexts
, 0, UnitID
);
2497 // If we haven't seen any CUs, pick an arbitrary valid Dwarf version anyway.
2498 if (MaxDwarfVersion
== 0)
2499 MaxDwarfVersion
= 3;
2501 // At this point we know how much data we have emitted. We use this value to
2502 // compare canonical DIE offsets in analyzeContextInfo to see if a definition
2503 // is already emitted, without being affected by canonical die offsets set
2504 // later. This prevents undeterminism when analyze and clone execute
2505 // concurrently, as clone set the canonical DIE offset and analyze reads it.
2506 const uint64_t ModulesEndOffset
= OutputDebugInfoSize
;
2508 // These variables manage the list of processed object files.
2509 // The mutex and condition variable are to ensure that this is thread safe.
2510 std::mutex ProcessedFilesMutex
;
2511 std::condition_variable ProcessedFilesConditionVariable
;
2512 BitVector
ProcessedFiles(NumObjects
, false);
2514 // Analyzing the context info is particularly expensive so it is executed in
2515 // parallel with emitting the previous compile unit.
2516 auto AnalyzeLambda
= [&](size_t i
) {
2517 auto &LinkContext
= ObjectContexts
[i
];
2519 if (!LinkContext
.ObjectFile
|| !LinkContext
.DwarfContext
)
2522 for (const auto &CU
: LinkContext
.DwarfContext
->compile_units()) {
2523 updateDwarfVersion(CU
->getVersion());
2524 // The !registerModuleReference() condition effectively skips
2525 // over fully resolved skeleton units. This second pass of
2526 // registerModuleReferences doesn't do any new work, but it
2527 // will collect top-level errors, which are suppressed. Module
2528 // warnings were already displayed in the first iteration.
2530 auto CUDie
= CU
->getUnitDIE(false);
2531 if (!CUDie
|| LLVM_UNLIKELY(Options
.Update
) ||
2532 !registerModuleReference(CUDie
, *CU
, ModuleMap
, LinkContext
.DMO
,
2533 LinkContext
.Ranges
, OffsetsStringPool
,
2534 UniquingStringPool
, ODRContexts
,
2535 ModulesEndOffset
, UnitID
, Quiet
)) {
2536 LinkContext
.CompileUnits
.push_back(llvm::make_unique
<CompileUnit
>(
2537 *CU
, UnitID
++, !Options
.NoODR
&& !Options
.Update
, ""));
2541 // Now build the DIE parent links that we will use during the next phase.
2542 for (auto &CurrentUnit
: LinkContext
.CompileUnits
) {
2543 auto CUDie
= CurrentUnit
->getOrigUnit().getUnitDIE();
2546 analyzeContextInfo(CurrentUnit
->getOrigUnit().getUnitDIE(), 0,
2547 *CurrentUnit
, &ODRContexts
.getRoot(),
2548 UniquingStringPool
, ODRContexts
, ModulesEndOffset
);
2552 // And then the remaining work in serial again.
2553 // Note, although this loop runs in serial, it can run in parallel with
2554 // the analyzeContextInfo loop so long as we process files with indices >=
2555 // than those processed by analyzeContextInfo.
2556 auto CloneLambda
= [&](size_t i
) {
2557 auto &LinkContext
= ObjectContexts
[i
];
2558 if (!LinkContext
.ObjectFile
)
2561 // Then mark all the DIEs that need to be present in the linked output
2562 // and collect some information about them.
2563 // Note that this loop can not be merged with the previous one because
2564 // cross-cu references require the ParentIdx to be setup for every CU in
2565 // the object file before calling this.
2566 if (LLVM_UNLIKELY(Options
.Update
)) {
2567 for (auto &CurrentUnit
: LinkContext
.CompileUnits
)
2568 CurrentUnit
->markEverythingAsKept();
2569 Streamer
->copyInvariantDebugSection(*LinkContext
.ObjectFile
);
2571 for (auto &CurrentUnit
: LinkContext
.CompileUnits
)
2572 lookForDIEsToKeep(LinkContext
.RelocMgr
, LinkContext
.Ranges
,
2573 LinkContext
.CompileUnits
,
2574 CurrentUnit
->getOrigUnit().getUnitDIE(),
2575 LinkContext
.DMO
, *CurrentUnit
, 0);
2578 // The calls to applyValidRelocs inside cloneDIE will walk the reloc
2579 // array again (in the same way findValidRelocsInDebugInfo() did). We
2580 // need to reset the NextValidReloc index to the beginning.
2581 LinkContext
.RelocMgr
.resetValidRelocs();
2582 if (LinkContext
.RelocMgr
.hasValidRelocs() || LLVM_UNLIKELY(Options
.Update
))
2583 DIECloner(*this, LinkContext
.RelocMgr
, DIEAlloc
, LinkContext
.CompileUnits
,
2585 .cloneAllCompileUnits(*LinkContext
.DwarfContext
, LinkContext
.DMO
,
2586 LinkContext
.Ranges
, OffsetsStringPool
);
2587 if (!Options
.NoOutput
&& !LinkContext
.CompileUnits
.empty() &&
2588 LLVM_LIKELY(!Options
.Update
))
2589 patchFrameInfoForObject(
2590 LinkContext
.DMO
, LinkContext
.Ranges
, *LinkContext
.DwarfContext
,
2591 LinkContext
.CompileUnits
[0]->getOrigUnit().getAddressByteSize());
2593 // Clean-up before starting working on the next object.
2594 endDebugObject(LinkContext
);
2597 auto EmitLambda
= [&]() {
2598 // Emit everything that's global.
2599 if (!Options
.NoOutput
) {
2600 Streamer
->emitAbbrevs(Abbreviations
, MaxDwarfVersion
);
2601 Streamer
->emitStrings(OffsetsStringPool
);
2602 switch (Options
.TheAccelTableKind
) {
2603 case AccelTableKind::Apple
:
2604 Streamer
->emitAppleNames(AppleNames
);
2605 Streamer
->emitAppleNamespaces(AppleNamespaces
);
2606 Streamer
->emitAppleTypes(AppleTypes
);
2607 Streamer
->emitAppleObjc(AppleObjc
);
2609 case AccelTableKind::Dwarf
:
2610 Streamer
->emitDebugNames(DebugNames
);
2612 case AccelTableKind::Default
:
2613 llvm_unreachable("Default should have already been resolved.");
2619 auto AnalyzeAll
= [&]() {
2620 for (unsigned i
= 0, e
= NumObjects
; i
!= e
; ++i
) {
2623 std::unique_lock
<std::mutex
> LockGuard(ProcessedFilesMutex
);
2624 ProcessedFiles
.set(i
);
2625 ProcessedFilesConditionVariable
.notify_one();
2629 auto CloneAll
= [&]() {
2630 for (unsigned i
= 0, e
= NumObjects
; i
!= e
; ++i
) {
2632 std::unique_lock
<std::mutex
> LockGuard(ProcessedFilesMutex
);
2633 if (!ProcessedFiles
[i
]) {
2634 ProcessedFilesConditionVariable
.wait(
2635 LockGuard
, [&]() { return ProcessedFiles
[i
]; });
2644 // To limit memory usage in the single threaded case, analyze and clone are
2645 // run sequentially so the LinkContext is freed after processing each object
2646 // in endDebugObject.
2647 if (Options
.Threads
== 1) {
2648 for (unsigned i
= 0, e
= NumObjects
; i
!= e
; ++i
) {
2655 pool
.async(AnalyzeAll
);
2656 pool
.async(CloneAll
);
2660 return Options
.NoOutput
? true : Streamer
->finish(Map
, Options
.Translator
);
2661 } // namespace dsymutil
2663 bool linkDwarf(raw_fd_ostream
&OutFile
, BinaryHolder
&BinHolder
,
2664 const DebugMap
&DM
, const LinkOptions
&Options
) {
2665 DwarfLinker
Linker(OutFile
, BinHolder
, Options
);
2666 return Linker
.link(DM
);
2669 } // namespace dsymutil