1 //===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "BinaryHolder.h"
13 #include "llvm/ADT/IntervalMap.h"
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/DIE.h"
18 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
20 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
21 #include "llvm/MC/MCAsmBackend.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCCodeEmitter.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCObjectFileInfo.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/Object/MachO.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/LEB128.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
43 void warn(const Twine &Warning, const Twine &Context) {
44 errs() << Twine("while processing ") + Context + ":\n";
45 errs() << Twine("warning: ") + Warning + "\n";
48 bool error(const Twine &Error, const Twine &Context) {
49 errs() << Twine("while processing ") + Context + ":\n";
50 errs() << Twine("error: ") + Error + "\n";
54 template <typename KeyT, typename ValT>
55 using HalfOpenIntervalMap =
56 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
57 IntervalMapHalfOpenInfo<KeyT>>;
59 /// \brief Stores all information relating to a compile unit, be it in
60 /// its original instance in the object file to its brand new cloned
61 /// and linked DIE tree.
64 /// \brief Information gathered about a DIE in the object file.
66 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
67 DIE *Clone; ///< Cloned version of that DIE.
68 uint32_t ParentIdx; ///< The index of this DIE's parent.
69 bool Keep; ///< Is the DIE part of the linked output?
70 bool InDebugMap; ///< Was this DIE's entity found in the map?
73 CompileUnit(DWARFUnit &OrigUnit)
74 : OrigUnit(OrigUnit), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
76 Info.resize(OrigUnit.getNumDIEs());
79 CompileUnit(CompileUnit &&RHS)
80 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
81 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
82 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
83 // The CompileUnit container has been 'reserve()'d with the right
84 // size. We cannot move the IntervalMap anyway.
85 llvm_unreachable("CompileUnits should not be moved.");
88 DWARFUnit &getOrigUnit() const { return OrigUnit; }
90 DIE *getOutputUnitDIE() const { return CUDie.get(); }
91 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
93 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
94 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
96 uint64_t getStartOffset() const { return StartOffset; }
97 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
99 uint64_t getLowPc() const { return LowPc; }
100 uint64_t getHighPc() const { return HighPc; }
102 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
104 /// \brief Compute the end offset for this unit. Must be
105 /// called after the CU's DIEs have been cloned.
106 /// \returns the next unit offset (which is also the current
107 /// debug_info section size).
108 uint64_t computeNextUnitOffset();
110 /// \brief Keep track of a forward reference to DIE \p Die in \p
111 /// RefUnit by \p Attr. The attribute should be fixed up later to
112 /// point to the absolute offset of \p Die in the debug_info section.
113 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
116 /// \brief Apply all fixups recored by noteForwardReference().
117 void fixupForwardReferences();
119 /// \brief Add a function range [\p LowPC, \p HighPC) that is
120 /// relocatad by applying offset \p PCOffset.
121 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
125 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
126 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
128 uint64_t StartOffset;
129 uint64_t NextUnitOffset;
134 /// \brief A list of attributes to fixup with the absolute offset of
135 /// a DIE in the debug_info section.
137 /// The offsets for the attributes in this array couldn't be set while
138 /// cloning because for cross-cu forward refences the target DIE's
139 /// offset isn't known you emit the reference attribute.
140 std::vector<std::tuple<DIE *, const CompileUnit *, DIEInteger *>>
141 ForwardDIEReferences;
143 HalfOpenIntervalMap<uint64_t, int64_t>::Allocator RangeAlloc;
144 /// \brief The ranges in that interval map are the PC ranges for
145 /// functions in this unit, associated with the PC offset to apply
146 /// to the addresses to get the linked address.
147 HalfOpenIntervalMap<uint64_t, int64_t> Ranges;
150 uint64_t CompileUnit::computeNextUnitOffset() {
151 NextUnitOffset = StartOffset + 11 /* Header size */;
152 // The root DIE might be null, meaning that the Unit had nothing to
153 // contribute to the linked output. In that case, we will emit the
154 // unit header without any actual DIE.
156 NextUnitOffset += CUDie->getSize();
157 return NextUnitOffset;
160 /// \brief Keep track of a forward cross-cu reference from this unit
161 /// to \p Die that lives in \p RefUnit.
162 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
164 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
167 /// \brief Apply all fixups recorded by noteForwardReference().
168 void CompileUnit::fixupForwardReferences() {
169 for (const auto &Ref : ForwardDIEReferences) {
171 const CompileUnit *RefUnit;
173 std::tie(RefDie, RefUnit, Attr) = Ref;
174 Attr->setValue(RefDie->getOffset() + RefUnit->getStartOffset());
178 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
180 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
181 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
182 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
185 /// \brief A string table that doesn't need relocations.
187 /// We are doing a final link, no need for a string table that
188 /// has relocation entries for every reference to it. This class
189 /// provides this ablitity by just associating offsets with
191 class NonRelocatableStringpool {
193 /// \brief Entries are stored into the StringMap and simply linked
194 /// together through the second element of this pair in order to
195 /// keep track of insertion order.
196 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
199 NonRelocatableStringpool()
200 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
201 // Legacy dsymutil puts an empty string at the start of the line
206 /// \brief Get the offset of string \p S in the string table. This
207 /// can insert a new element or return the offset of a preexisitng
209 uint32_t getStringOffset(StringRef S);
211 /// \brief Get permanent storage for \p S (but do not necessarily
212 /// emit \p S in the output section).
213 /// \returns The StringRef that points to permanent storage to use
214 /// in place of \p S.
215 StringRef internString(StringRef S);
217 // \brief Return the first entry of the string table.
218 const MapTy::MapEntryTy *getFirstEntry() const {
219 return getNextEntry(&Sentinel);
222 // \brief Get the entry following \p E in the string table or null
223 // if \p E was the last entry.
224 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
225 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
228 uint64_t getSize() { return CurrentEndOffset; }
232 uint32_t CurrentEndOffset;
233 MapTy::MapEntryTy Sentinel, *Last;
236 /// \brief Get the offset of string \p S in the string table. This
237 /// can insert a new element or return the offset of a preexisitng
239 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
240 if (S.empty() && !Strings.empty())
243 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
247 // A non-empty string can't be at offset 0, so if we have an entry
248 // with a 0 offset, it must be a previously interned string.
249 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
250 if (Inserted || It->getValue().first == 0) {
251 // Set offset and chain at the end of the entries list.
252 It->getValue().first = CurrentEndOffset;
253 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
254 Last->getValue().second = &*It;
257 return It->getValue().first;
260 /// \brief Put \p S into the StringMap so that it gets permanent
261 /// storage, but do not actually link it in the chain of elements
262 /// that go into the output section. A latter call to
263 /// getStringOffset() with the same string will chain it though.
264 StringRef NonRelocatableStringpool::internString(StringRef S) {
265 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
266 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
267 return InsertResult.first->getKey();
270 /// \brief The Dwarf streaming logic
272 /// All interactions with the MC layer that is used to build the debug
273 /// information binary representation are handled in this class.
274 class DwarfStreamer {
275 /// \defgroup MCObjects MC layer objects constructed by the streamer
277 std::unique_ptr<MCRegisterInfo> MRI;
278 std::unique_ptr<MCAsmInfo> MAI;
279 std::unique_ptr<MCObjectFileInfo> MOFI;
280 std::unique_ptr<MCContext> MC;
281 MCAsmBackend *MAB; // Owned by MCStreamer
282 std::unique_ptr<MCInstrInfo> MII;
283 std::unique_ptr<MCSubtargetInfo> MSTI;
284 MCCodeEmitter *MCE; // Owned by MCStreamer
285 MCStreamer *MS; // Owned by AsmPrinter
286 std::unique_ptr<TargetMachine> TM;
287 std::unique_ptr<AsmPrinter> Asm;
290 /// \brief the file we stream the linked Dwarf to.
291 std::unique_ptr<raw_fd_ostream> OutFile;
294 /// \brief Actually create the streamer and the ouptut file.
296 /// This could be done directly in the constructor, but it feels
297 /// more natural to handle errors through return value.
298 bool init(Triple TheTriple, StringRef OutputFilename);
300 /// \brief Dump the file to the disk.
303 AsmPrinter &getAsmPrinter() const { return *Asm; }
305 /// \brief Set the current output section to debug_info and change
306 /// the MC Dwarf version to \p DwarfVersion.
307 void switchToDebugInfoSection(unsigned DwarfVersion);
309 /// \brief Emit the compilation unit header for \p Unit in the
310 /// debug_info section.
312 /// As a side effect, this also switches the current Dwarf version
313 /// of the MC layer to the one of U.getOrigUnit().
314 void emitCompileUnitHeader(CompileUnit &Unit);
316 /// \brief Recursively emit the DIE tree rooted at \p Die.
317 void emitDIE(DIE &Die);
319 /// \brief Emit the abbreviation table \p Abbrevs to the
320 /// debug_abbrev section.
321 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
323 /// \brief Emit the string table described by \p Pool.
324 void emitStrings(const NonRelocatableStringpool &Pool);
327 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
328 std::string ErrorStr;
329 std::string TripleName;
330 StringRef Context = "dwarf streamer init";
333 const Target *TheTarget =
334 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
336 return error(ErrorStr, Context);
337 TripleName = TheTriple.getTriple();
339 // Create all the MC Objects.
340 MRI.reset(TheTarget->createMCRegInfo(TripleName));
342 return error(Twine("no register info for target ") + TripleName, Context);
344 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
346 return error("no asm info for target " + TripleName, Context);
348 MOFI.reset(new MCObjectFileInfo);
349 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
350 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
353 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
355 return error("no asm backend for target " + TripleName, Context);
357 MII.reset(TheTarget->createMCInstrInfo());
359 return error("no instr info info for target " + TripleName, Context);
361 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
363 return error("no subtarget info for target " + TripleName, Context);
365 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
367 return error("no code emitter for target " + TripleName, Context);
369 // Create the output file.
372 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
374 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
376 MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
379 return error("no object streamer for target " + TripleName, Context);
381 // Finally create the AsmPrinter we'll use to emit the DIEs.
382 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
384 return error("no target machine for target " + TripleName, Context);
386 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
388 return error("no asm printer for target " + TripleName, Context);
393 bool DwarfStreamer::finish() {
398 /// \brief Set the current output section to debug_info and change
399 /// the MC Dwarf version to \p DwarfVersion.
400 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
401 MS->SwitchSection(MOFI->getDwarfInfoSection());
402 MC->setDwarfVersion(DwarfVersion);
405 /// \brief Emit the compilation unit header for \p Unit in the
406 /// debug_info section.
408 /// A Dwarf scetion header is encoded as:
409 /// uint32_t Unit length (omiting this field)
411 /// uint32_t Abbreviation table offset
412 /// uint8_t Address size
414 /// Leading to a total of 11 bytes.
415 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
416 unsigned Version = Unit.getOrigUnit().getVersion();
417 switchToDebugInfoSection(Version);
419 // Emit size of content not including length itself. The size has
420 // already been computed in CompileUnit::computeOffsets(). Substract
421 // 4 to that size to account for the length field.
422 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
423 Asm->EmitInt16(Version);
424 // We share one abbreviations table across all units so it's always at the
425 // start of the section.
427 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
430 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
431 /// for the linked Dwarf file.
432 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
433 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
434 Asm->emitDwarfAbbrevs(Abbrevs);
437 /// \brief Recursively emit the DIE tree rooted at \p Die.
438 void DwarfStreamer::emitDIE(DIE &Die) {
439 MS->SwitchSection(MOFI->getDwarfInfoSection());
440 Asm->emitDwarfDIE(Die);
443 /// \brief Emit the debug_str section stored in \p Pool.
444 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
445 Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
446 for (auto *Entry = Pool.getFirstEntry(); Entry;
447 Entry = Pool.getNextEntry(Entry))
448 Asm->OutStreamer.EmitBytes(
449 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
452 /// \brief The core of the Dwarf linking logic.
454 /// The link of the dwarf information from the object files will be
455 /// driven by the selection of 'root DIEs', which are DIEs that
456 /// describe variables or functions that are present in the linked
457 /// binary (and thus have entries in the debug map). All the debug
458 /// information that will be linked (the DIEs, but also the line
459 /// tables, ranges, ...) is derived from that set of root DIEs.
461 /// The root DIEs are identified because they contain relocations that
462 /// correspond to a debug map entry at specific places (the low_pc for
463 /// a function, the location for a variable). These relocations are
464 /// called ValidRelocs in the DwarfLinker and are gathered as a very
465 /// first step when we start processing a DebugMapObject.
468 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
469 : OutputFilename(OutputFilename), Options(Options),
470 BinHolder(Options.Verbose) {}
473 for (auto *Abbrev : Abbreviations)
477 /// \brief Link the contents of the DebugMap.
478 bool link(const DebugMap &);
481 /// \brief Called at the start of a debug object link.
482 void startDebugObject(DWARFContext &);
484 /// \brief Called at the end of a debug object link.
485 void endDebugObject();
487 /// \defgroup FindValidRelocations Translate debug map into a list
488 /// of relevant relocations
495 const DebugMapObject::DebugMapEntry *Mapping;
497 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
498 const DebugMapObject::DebugMapEntry *Mapping)
499 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
501 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
504 /// \brief The valid relocations for the current DebugMapObject.
505 /// This vector is sorted by relocation offset.
506 std::vector<ValidReloc> ValidRelocs;
508 /// \brief Index into ValidRelocs of the next relocation to
509 /// consider. As we walk the DIEs in acsending file offset and as
510 /// ValidRelocs is sorted by file offset, keeping this index
511 /// uptodate is all we have to do to have a cheap lookup during the
512 /// root DIE selection and during DIE cloning.
513 unsigned NextValidReloc;
515 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
516 const DebugMapObject &DMO);
518 bool findValidRelocs(const object::SectionRef &Section,
519 const object::ObjectFile &Obj,
520 const DebugMapObject &DMO);
522 void findValidRelocsMachO(const object::SectionRef &Section,
523 const object::MachOObjectFile &Obj,
524 const DebugMapObject &DMO);
527 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
530 /// \brief Recursively walk the \p DIE tree and look for DIEs to
531 /// keep. Store that information in \p CU's DIEInfo.
532 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
533 const DebugMapObject &DMO, CompileUnit &CU,
536 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
538 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
539 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
540 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
541 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
544 /// \brief Mark the passed DIE as well as all the ones it depends on
546 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
547 CompileUnit::DIEInfo &MyInfo,
548 const DebugMapObject &DMO, CompileUnit &CU,
551 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
552 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
555 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
557 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
559 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
561 CompileUnit::DIEInfo &MyInfo,
564 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
565 CompileUnit::DIEInfo &Info);
568 /// \defgroup Linking Methods used to link the debug information
571 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
572 /// where useless (as decided by lookForDIEsToKeep()) bits have been
573 /// stripped out and addresses have been rewritten according to the
576 /// \param OutOffset is the offset the cloned DIE in the output
578 /// \param PCOffset (while cloning a function scope) is the offset
579 /// applied to the entry point of the function to get the linked address.
581 /// \returns the root of the cloned tree.
582 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
583 int64_t PCOffset, uint32_t OutOffset);
585 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
587 /// \brief Information gathered and exchanged between the various
588 /// clone*Attributes helpers about the attributes of a particular DIE.
589 struct AttributesInfo {
590 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
591 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
593 AttributesInfo() : OrigHighPc(0), PCOffset(0) {}
596 /// \brief Helper for cloneDIE.
597 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
598 CompileUnit &U, const DWARFFormValue &Val,
599 const AttributeSpec AttrSpec, unsigned AttrSize,
600 AttributesInfo &AttrInfo);
602 /// \brief Helper for cloneDIE.
603 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
604 const DWARFFormValue &Val, const DWARFUnit &U);
606 /// \brief Helper for cloneDIE.
608 cloneDieReferenceAttribute(DIE &Die,
609 const DWARFDebugInfoEntryMinimal &InputDIE,
610 AttributeSpec AttrSpec, unsigned AttrSize,
611 const DWARFFormValue &Val, CompileUnit &Unit);
613 /// \brief Helper for cloneDIE.
614 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
615 const DWARFFormValue &Val, unsigned AttrSize);
617 /// \brief Helper for cloneDIE.
618 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
619 const DWARFFormValue &Val,
620 const CompileUnit &Unit, AttributesInfo &Info);
622 /// \brief Helper for cloneDIE.
623 unsigned cloneScalarAttribute(DIE &Die,
624 const DWARFDebugInfoEntryMinimal &InputDIE,
625 const CompileUnit &U, AttributeSpec AttrSpec,
626 const DWARFFormValue &Val, unsigned AttrSize);
628 /// \brief Helper for cloneDIE.
629 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
630 bool isLittleEndian);
632 /// \brief Assign an abbreviation number to \p Abbrev
633 void AssignAbbrev(DIEAbbrev &Abbrev);
635 /// \brief FoldingSet that uniques the abbreviations.
636 FoldingSet<DIEAbbrev> AbbreviationsSet;
637 /// \brief Storage for the unique Abbreviations.
638 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
639 /// be changed to a vecot of unique_ptrs.
640 std::vector<DIEAbbrev *> Abbreviations;
642 /// \brief DIELoc objects that need to be destructed (but not freed!).
643 std::vector<DIELoc *> DIELocs;
644 /// \brief DIEBlock objects that need to be destructed (but not freed!).
645 std::vector<DIEBlock *> DIEBlocks;
646 /// \brief Allocator used for all the DIEValue objects.
647 BumpPtrAllocator DIEAlloc;
650 /// \defgroup Helpers Various helper methods.
653 const DWARFDebugInfoEntryMinimal *
654 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
655 const DWARFDebugInfoEntryMinimal &DIE,
656 CompileUnit *&ReferencedCU);
658 CompileUnit *getUnitForOffset(unsigned Offset);
660 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
661 const DWARFDebugInfoEntryMinimal *DIE = nullptr);
663 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
667 std::string OutputFilename;
669 BinaryHolder BinHolder;
670 std::unique_ptr<DwarfStreamer> Streamer;
672 /// The units of the current debug map object.
673 std::vector<CompileUnit> Units;
675 /// The debug map object curently under consideration.
676 DebugMapObject *CurrentDebugObject;
678 /// \brief The Dwarf string pool
679 NonRelocatableStringpool StringPool;
682 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
683 /// returning our CompileUnit object instead.
684 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
686 std::upper_bound(Units.begin(), Units.end(), Offset,
687 [](uint32_t LHS, const CompileUnit &RHS) {
688 return LHS < RHS.getOrigUnit().getNextUnitOffset();
690 return CU != Units.end() ? &*CU : nullptr;
693 /// \brief Resolve the DIE attribute reference that has been
694 /// extracted in \p RefValue. The resulting DIE migh be in another
695 /// CompileUnit which is stored into \p ReferencedCU.
696 /// \returns null if resolving fails for any reason.
697 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
698 DWARFFormValue &RefValue, const DWARFUnit &Unit,
699 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
700 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
701 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
703 if ((RefCU = getUnitForOffset(RefOffset)))
704 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
707 reportWarning("could not find referenced DIE", &Unit, &DIE);
711 /// \brief Report a warning to the user, optionaly including
712 /// information about a specific \p DIE related to the warning.
713 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
714 const DWARFDebugInfoEntryMinimal *DIE) {
715 StringRef Context = "<debug map>";
716 if (CurrentDebugObject)
717 Context = CurrentDebugObject->getObjectFilename();
718 warn(Warning, Context);
720 if (!Options.Verbose || !DIE)
723 errs() << " in DIE:\n";
724 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
728 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
729 if (Options.NoOutput)
732 Streamer = llvm::make_unique<DwarfStreamer>();
733 return Streamer->init(TheTriple, OutputFilename);
736 /// \brief Recursive helper to gather the child->parent relationships in the
737 /// original compile unit.
738 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
739 unsigned ParentIdx, CompileUnit &CU) {
740 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
741 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
743 if (DIE->hasChildren())
744 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
745 Child = Child->getSibling())
746 gatherDIEParents(Child, MyIdx, CU);
749 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
753 case dwarf::DW_TAG_subprogram:
754 case dwarf::DW_TAG_lexical_block:
755 case dwarf::DW_TAG_subroutine_type:
756 case dwarf::DW_TAG_structure_type:
757 case dwarf::DW_TAG_class_type:
758 case dwarf::DW_TAG_union_type:
761 llvm_unreachable("Invalid Tag");
764 void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
765 Units.reserve(Dwarf.getNumCompileUnits());
769 void DwarfLinker::endDebugObject() {
773 for (auto *Block : DIEBlocks)
775 for (auto *Loc : DIELocs)
783 /// \brief Iterate over the relocations of the given \p Section and
784 /// store the ones that correspond to debug map entries into the
785 /// ValidRelocs array.
786 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
787 const object::MachOObjectFile &Obj,
788 const DebugMapObject &DMO) {
790 Section.getContents(Contents);
791 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
793 for (const object::RelocationRef &Reloc : Section.relocations()) {
794 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
795 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
796 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
798 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
799 reportWarning(" unsupported relocation in debug_info section.");
802 uint32_t Offset = Offset64;
803 // Mach-o uses REL relocations, the addend is at the relocation offset.
804 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
806 auto Sym = Reloc.getSymbol();
807 if (Sym != Obj.symbol_end()) {
808 StringRef SymbolName;
809 if (Sym->getName(SymbolName)) {
810 reportWarning("error getting relocation symbol name.");
813 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
814 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
815 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
816 // Do not store the addend. The addend was the address of the
817 // symbol in the object file, the address in the binary that is
818 // stored in the debug map doesn't need to be offseted.
819 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
824 /// \brief Dispatch the valid relocation finding logic to the
825 /// appropriate handler depending on the object file format.
826 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
827 const object::ObjectFile &Obj,
828 const DebugMapObject &DMO) {
829 // Dispatch to the right handler depending on the file type.
830 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
831 findValidRelocsMachO(Section, *MachOObj, DMO);
833 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
835 if (ValidRelocs.empty())
838 // Sort the relocations by offset. We will walk the DIEs linearly in
839 // the file, this allows us to just keep an index in the relocation
840 // array that we advance during our walk, rather than resorting to
841 // some associative container. See DwarfLinker::NextValidReloc.
842 std::sort(ValidRelocs.begin(), ValidRelocs.end());
846 /// \brief Look for relocations in the debug_info section that match
847 /// entries in the debug map. These relocations will drive the Dwarf
848 /// link by indicating which DIEs refer to symbols present in the
850 /// \returns wether there are any valid relocations in the debug info.
851 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
852 const DebugMapObject &DMO) {
853 // Find the debug_info section.
854 for (const object::SectionRef &Section : Obj.sections()) {
855 StringRef SectionName;
856 Section.getName(SectionName);
857 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
858 if (SectionName != "debug_info")
860 return findValidRelocs(Section, Obj, DMO);
865 /// \brief Checks that there is a relocation against an actual debug
866 /// map entry between \p StartOffset and \p NextOffset.
868 /// This function must be called with offsets in strictly ascending
869 /// order because it never looks back at relocations it already 'went past'.
870 /// \returns true and sets Info.InDebugMap if it is the case.
871 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
872 CompileUnit::DIEInfo &Info) {
873 assert(NextValidReloc == 0 ||
874 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
875 if (NextValidReloc >= ValidRelocs.size())
878 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
880 // We might need to skip some relocs that we didn't consider. For
881 // example the high_pc of a discarded DIE might contain a reloc that
882 // is in the list because it actually corresponds to the start of a
883 // function that is in the debug map.
884 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
885 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
887 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
890 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
892 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
893 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
894 ValidReloc.Mapping->getValue().ObjectAddress,
895 ValidReloc.Mapping->getValue().BinaryAddress);
897 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
899 ValidReloc.Mapping->getValue().ObjectAddress;
900 Info.InDebugMap = true;
904 /// \brief Get the starting and ending (exclusive) offset for the
905 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
906 /// supposed to point to the position of the first attribute described
908 /// \return [StartOffset, EndOffset) as a pair.
909 static std::pair<uint32_t, uint32_t>
910 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
911 unsigned Offset, const DWARFUnit &Unit) {
912 DataExtractor Data = Unit.getDebugInfoExtractor();
914 for (unsigned i = 0; i < Idx; ++i)
915 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
917 uint32_t End = Offset;
918 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
920 return std::make_pair(Offset, End);
923 /// \brief Check if a variable describing DIE should be kept.
924 /// \returns updated TraversalFlags.
925 unsigned DwarfLinker::shouldKeepVariableDIE(
926 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
927 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
928 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
930 // Global variables with constant value can always be kept.
931 if (!(Flags & TF_InFunctionScope) &&
932 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
933 MyInfo.InDebugMap = true;
934 return Flags | TF_Keep;
937 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
938 if (LocationIdx == -1U)
941 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
942 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
943 uint32_t LocationOffset, LocationEndOffset;
944 std::tie(LocationOffset, LocationEndOffset) =
945 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
947 // See if there is a relocation to a valid debug map entry inside
948 // this variable's location. The order is important here. We want to
949 // always check in the variable has a valid relocation, so that the
950 // DIEInfo is filled. However, we don't want a static variable in a
951 // function to force us to keep the enclosing function.
952 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
953 (Flags & TF_InFunctionScope))
957 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
959 return Flags | TF_Keep;
962 /// \brief Check if a function describing DIE should be kept.
963 /// \returns updated TraversalFlags.
964 unsigned DwarfLinker::shouldKeepSubprogramDIE(
965 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
966 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
967 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
969 Flags |= TF_InFunctionScope;
971 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
975 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
976 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
977 uint32_t LowPcOffset, LowPcEndOffset;
978 std::tie(LowPcOffset, LowPcEndOffset) =
979 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
982 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
983 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
984 if (LowPc == -1ULL ||
985 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
989 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
993 DWARFFormValue HighPcValue;
994 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
995 reportWarning("Function without high_pc. Range will be discarded.\n",
1001 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1002 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1004 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1005 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1008 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1012 /// \brief Check if a DIE should be kept.
1013 /// \returns updated TraversalFlags.
1014 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1016 CompileUnit::DIEInfo &MyInfo,
1018 switch (DIE.getTag()) {
1019 case dwarf::DW_TAG_constant:
1020 case dwarf::DW_TAG_variable:
1021 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1022 case dwarf::DW_TAG_subprogram:
1023 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1024 case dwarf::DW_TAG_module:
1025 case dwarf::DW_TAG_imported_module:
1026 case dwarf::DW_TAG_imported_declaration:
1027 case dwarf::DW_TAG_imported_unit:
1028 // We always want to keep these.
1029 return Flags | TF_Keep;
1035 /// \brief Mark the passed DIE as well as all the ones it depends on
1038 /// This function is called by lookForDIEsToKeep on DIEs that are
1039 /// newly discovered to be needed in the link. It recursively calls
1040 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1041 /// TraversalFlags to inform it that it's not doing the primary DIE
1043 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1044 CompileUnit::DIEInfo &MyInfo,
1045 const DebugMapObject &DMO,
1046 CompileUnit &CU, unsigned Flags) {
1047 const DWARFUnit &Unit = CU.getOrigUnit();
1050 // First mark all the parent chain as kept.
1051 unsigned AncestorIdx = MyInfo.ParentIdx;
1052 while (!CU.getInfo(AncestorIdx).Keep) {
1053 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1054 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1055 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1058 // Then we need to mark all the DIEs referenced by this DIE's
1059 // attributes as kept.
1060 DataExtractor Data = Unit.getDebugInfoExtractor();
1061 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1062 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1064 // Mark all DIEs referenced through atttributes as kept.
1065 for (const auto &AttrSpec : Abbrev->attributes()) {
1066 DWARFFormValue Val(AttrSpec.Form);
1068 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1069 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1073 Val.extractValue(Data, &Offset, &Unit);
1074 CompileUnit *ReferencedCU;
1075 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1076 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1077 TF_Keep | TF_DependencyWalk);
1081 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1082 /// keep. Store that information in \p CU's DIEInfo.
1084 /// This function is the entry point of the DIE selection
1085 /// algorithm. It is expected to walk the DIE tree in file order and
1086 /// (though the mediation of its helper) call hasValidRelocation() on
1087 /// each DIE that might be a 'root DIE' (See DwarfLinker class
1089 /// While walking the dependencies of root DIEs, this function is
1090 /// also called, but during these dependency walks the file order is
1091 /// not respected. The TF_DependencyWalk flag tells us which kind of
1092 /// traversal we are currently doing.
1093 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1094 const DebugMapObject &DMO, CompileUnit &CU,
1096 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1097 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1098 bool AlreadyKept = MyInfo.Keep;
1100 // If the Keep flag is set, we are marking a required DIE's
1101 // dependencies. If our target is already marked as kept, we're all
1103 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1106 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1107 // because it would screw up the relocation finding logic.
1108 if (!(Flags & TF_DependencyWalk))
1109 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1111 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1112 if (!AlreadyKept && (Flags & TF_Keep))
1113 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1115 // The TF_ParentWalk flag tells us that we are currently walking up
1116 // the parent chain of a required DIE, and we don't want to mark all
1117 // the children of the parents as kept (consider for example a
1118 // DW_TAG_namespace node in the parent chain). There are however a
1119 // set of DIE types for which we want to ignore that directive and still
1120 // walk their children.
1121 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1122 Flags &= ~TF_ParentWalk;
1124 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1127 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1128 Child = Child->getSibling())
1129 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1132 /// \brief Assign an abbreviation numer to \p Abbrev.
1134 /// Our DIEs get freed after every DebugMapObject has been processed,
1135 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1136 /// the instances hold by the DIEs. When we encounter an abbreviation
1137 /// that we don't know, we create a permanent copy of it.
1138 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1139 // Check the set for priors.
1140 FoldingSetNodeID ID;
1143 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1145 // If it's newly added.
1147 // Assign existing abbreviation number.
1148 Abbrev.setNumber(InSet->getNumber());
1150 // Add to abbreviation list.
1151 Abbreviations.push_back(
1152 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1153 for (const auto &Attr : Abbrev.getData())
1154 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1155 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1156 // Assign the unique abbreviation number.
1157 Abbrev.setNumber(Abbreviations.size());
1158 Abbreviations.back()->setNumber(Abbreviations.size());
1162 /// \brief Clone a string attribute described by \p AttrSpec and add
1164 /// \returns the size of the new attribute.
1165 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1166 const DWARFFormValue &Val,
1167 const DWARFUnit &U) {
1168 // Switch everything to out of line strings.
1169 const char *String = *Val.getAsCString(&U);
1170 unsigned Offset = StringPool.getStringOffset(String);
1171 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1172 new (DIEAlloc) DIEInteger(Offset));
1176 /// \brief Clone an attribute referencing another DIE and add
1178 /// \returns the size of the new attribute.
1179 unsigned DwarfLinker::cloneDieReferenceAttribute(
1180 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1181 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1182 CompileUnit &Unit) {
1183 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
1184 DIE *NewRefDie = nullptr;
1185 CompileUnit *RefUnit = nullptr;
1186 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1188 if (!(RefUnit = getUnitForOffset(Ref)) ||
1189 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1190 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1191 if (!AttributeString)
1192 AttributeString = "DW_AT_???";
1193 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1195 &Unit.getOrigUnit(), &InputDIE);
1199 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1200 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1201 if (!RefInfo.Clone) {
1202 assert(Ref > InputDIE.getOffset());
1203 // We haven't cloned this DIE yet. Just create an empty one and
1204 // store it. It'll get really cloned when we process it.
1205 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1207 NewRefDie = RefInfo.Clone;
1209 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1210 // We cannot currently rely on a DIEEntry to emit ref_addr
1211 // references, because the implementation calls back to DwarfDebug
1212 // to find the unit offset. (We don't have a DwarfDebug)
1213 // FIXME: we should be able to design DIEEntry reliance on
1216 if (Ref < InputDIE.getOffset()) {
1217 // We must have already cloned that DIE.
1218 uint32_t NewRefOffset =
1219 RefUnit->getStartOffset() + NewRefDie->getOffset();
1220 Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1222 // A forward reference. Note and fixup later.
1223 Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
1224 Unit.noteForwardReference(NewRefDie, RefUnit, Attr);
1226 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1231 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1232 new (DIEAlloc) DIEEntry(*NewRefDie));
1236 /// \brief Clone an attribute of block form (locations, constants) and add
1238 /// \returns the size of the new attribute.
1239 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1240 const DWARFFormValue &Val,
1241 unsigned AttrSize) {
1244 DIELoc *Loc = nullptr;
1245 DIEBlock *Block = nullptr;
1246 // Just copy the block data over.
1247 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1248 Loc = new (DIEAlloc) DIELoc();
1249 DIELocs.push_back(Loc);
1251 Block = new (DIEAlloc) DIEBlock();
1252 DIEBlocks.push_back(Block);
1254 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1255 Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1256 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1257 for (auto Byte : Bytes)
1258 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1259 new (DIEAlloc) DIEInteger(Byte));
1260 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1261 // the DIE class, this if could be replaced by
1262 // Attr->setSize(Bytes.size()).
1265 Loc->ComputeSize(&Streamer->getAsmPrinter());
1267 Block->ComputeSize(&Streamer->getAsmPrinter());
1269 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1274 /// \brief Clone an address attribute and add it to \p Die.
1275 /// \returns the size of the new attribute.
1276 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1277 const DWARFFormValue &Val,
1278 const CompileUnit &Unit,
1279 AttributesInfo &Info) {
1280 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
1281 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1282 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1283 Die.getTag() == dwarf::DW_TAG_lexical_block)
1284 Addr += Info.PCOffset;
1285 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1286 Addr = Unit.getLowPc();
1287 if (Addr == UINT64_MAX)
1290 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1291 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1292 if (uint64_t HighPc = Unit.getHighPc())
1297 // If we have a high_pc recorded for the input DIE, use
1298 // it. Otherwise (when no relocations where applied) just use the
1299 // one we just decoded.
1300 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1303 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1304 static_cast<dwarf::Form>(AttrSpec.Form),
1305 new (DIEAlloc) DIEInteger(Addr));
1306 return Unit.getOrigUnit().getAddressByteSize();
1309 /// \brief Clone a scalar attribute and add it to \p Die.
1310 /// \returns the size of the new attribute.
1311 unsigned DwarfLinker::cloneScalarAttribute(
1312 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1313 const CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1314 unsigned AttrSize) {
1316 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1317 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1318 if (Unit.getLowPc() == -1ULL)
1320 // Dwarf >= 4 high_pc is an size, not an address.
1321 Value = Unit.getHighPc() - Unit.getLowPc();
1322 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1323 Value = *Val.getAsSectionOffset();
1324 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1325 Value = *Val.getAsSignedConstant();
1326 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1327 Value = *OptionalValue;
1329 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1330 &Unit.getOrigUnit(), &InputDIE);
1333 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1334 new (DIEAlloc) DIEInteger(Value));
1338 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1339 /// value \p Val, and add it to \p Die.
1340 /// \returns the size of the cloned attribute.
1341 unsigned DwarfLinker::cloneAttribute(DIE &Die,
1342 const DWARFDebugInfoEntryMinimal &InputDIE,
1344 const DWARFFormValue &Val,
1345 const AttributeSpec AttrSpec,
1346 unsigned AttrSize, AttributesInfo &Info) {
1347 const DWARFUnit &U = Unit.getOrigUnit();
1349 switch (AttrSpec.Form) {
1350 case dwarf::DW_FORM_strp:
1351 case dwarf::DW_FORM_string:
1352 return cloneStringAttribute(Die, AttrSpec, Val, U);
1353 case dwarf::DW_FORM_ref_addr:
1354 case dwarf::DW_FORM_ref1:
1355 case dwarf::DW_FORM_ref2:
1356 case dwarf::DW_FORM_ref4:
1357 case dwarf::DW_FORM_ref8:
1358 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1360 case dwarf::DW_FORM_block:
1361 case dwarf::DW_FORM_block1:
1362 case dwarf::DW_FORM_block2:
1363 case dwarf::DW_FORM_block4:
1364 case dwarf::DW_FORM_exprloc:
1365 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1366 case dwarf::DW_FORM_addr:
1367 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1368 case dwarf::DW_FORM_data1:
1369 case dwarf::DW_FORM_data2:
1370 case dwarf::DW_FORM_data4:
1371 case dwarf::DW_FORM_data8:
1372 case dwarf::DW_FORM_udata:
1373 case dwarf::DW_FORM_sdata:
1374 case dwarf::DW_FORM_sec_offset:
1375 case dwarf::DW_FORM_flag:
1376 case dwarf::DW_FORM_flag_present:
1377 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize);
1379 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1386 /// \brief Apply the valid relocations found by findValidRelocs() to
1387 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
1388 /// in the debug_info section.
1390 /// Like for findValidRelocs(), this function must be called with
1391 /// monotonic \p BaseOffset values.
1393 /// \returns wether any reloc has been applied.
1394 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
1395 uint32_t BaseOffset, bool isLittleEndian) {
1396 assert((NextValidReloc == 0 ||
1397 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1398 "BaseOffset should only be increasing.");
1399 if (NextValidReloc >= ValidRelocs.size())
1402 // Skip relocs that haven't been applied.
1403 while (NextValidReloc < ValidRelocs.size() &&
1404 ValidRelocs[NextValidReloc].Offset < BaseOffset)
1407 bool Applied = false;
1408 uint64_t EndOffset = BaseOffset + Data.size();
1409 while (NextValidReloc < ValidRelocs.size() &&
1410 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1411 ValidRelocs[NextValidReloc].Offset < EndOffset) {
1412 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1413 assert(ValidReloc.Offset - BaseOffset < Data.size());
1414 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1416 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1417 Value += ValidReloc.Addend;
1418 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1419 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
1420 Buf[i] = uint8_t(Value >> (Index * 8));
1422 assert(ValidReloc.Size <= sizeof(Buf));
1423 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1430 /// \brief Recursively clone \p InputDIE's subtrees that have been
1431 /// selected to appear in the linked output.
1433 /// \param OutOffset is the Offset where the newly created DIE will
1434 /// lie in the linked compile unit.
1436 /// \returns the cloned DIE object or null if nothing was selected.
1437 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
1438 CompileUnit &Unit, int64_t PCOffset,
1439 uint32_t OutOffset) {
1440 DWARFUnit &U = Unit.getOrigUnit();
1441 unsigned Idx = U.getDIEIndex(&InputDIE);
1442 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1444 // Should the DIE appear in the output?
1445 if (!Unit.getInfo(Idx).Keep)
1448 uint32_t Offset = InputDIE.getOffset();
1449 // The DIE might have been already created by a forward reference
1450 // (see cloneDieReferenceAttribute()).
1451 DIE *Die = Info.Clone;
1453 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
1454 assert(Die->getTag() == InputDIE.getTag());
1455 Die->setOffset(OutOffset);
1457 // Extract and clone every attribute.
1458 DataExtractor Data = U.getDebugInfoExtractor();
1459 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
1460 AttributesInfo AttrInfo;
1462 // We could copy the data only if we need to aply a relocation to
1463 // it. After testing, it seems there is no performance downside to
1464 // doing the copy unconditionally, and it makes the code simpler.
1465 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1466 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1467 // Modify the copy with relocated addresses.
1468 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
1469 // If we applied relocations, we store the value of high_pc that was
1470 // potentially stored in the input DIE. If high_pc is an address
1471 // (Dwarf version == 2), then it might have been relocated to a
1472 // totally unrelated value (because the end address in the object
1473 // file might be start address of another function which got moved
1474 // independantly by the linker). The computation of the actual
1475 // high_pc value is done in cloneAddressAttribute().
1476 AttrInfo.OrigHighPc =
1477 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
1480 // Reset the Offset to 0 as we will be working on the local copy of
1484 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1485 Offset += getULEB128Size(Abbrev->getCode());
1487 // We are entering a subprogram. Get and propagate the PCOffset.
1488 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1489 PCOffset = Info.AddrAdjust;
1490 AttrInfo.PCOffset = PCOffset;
1492 for (const auto &AttrSpec : Abbrev->attributes()) {
1493 DWARFFormValue Val(AttrSpec.Form);
1494 uint32_t AttrSize = Offset;
1495 Val.extractValue(Data, &Offset, &U);
1496 AttrSize = Offset - AttrSize;
1499 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
1502 DIEAbbrev &NewAbbrev = Die->getAbbrev();
1503 // If a scope DIE is kept, we must have kept at least one child. If
1504 // it's not the case, we'll just be emitting one wasteful end of
1505 // children marker, but things won't break.
1506 if (InputDIE.hasChildren())
1507 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1508 // Assign a permanent abbrev number
1509 AssignAbbrev(Die->getAbbrev());
1511 // Add the size of the abbreviation number to the output offset.
1512 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1514 if (!Abbrev->hasChildren()) {
1516 Die->setSize(OutOffset - Die->getOffset());
1520 // Recursively clone children.
1521 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1522 Child = Child->getSibling()) {
1523 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
1524 Die->addChild(std::unique_ptr<DIE>(Clone));
1525 OutOffset = Clone->getOffset() + Clone->getSize();
1529 // Account for the end of children marker.
1530 OutOffset += sizeof(int8_t);
1532 Die->setSize(OutOffset - Die->getOffset());
1536 bool DwarfLinker::link(const DebugMap &Map) {
1538 if (Map.begin() == Map.end()) {
1539 errs() << "Empty debug map.\n";
1543 if (!createStreamer(Map.getTriple(), OutputFilename))
1546 // Size of the DIEs (and headers) generated for the linked output.
1547 uint64_t OutputDebugInfoSize = 0;
1549 for (const auto &Obj : Map.objects()) {
1550 CurrentDebugObject = Obj.get();
1552 if (Options.Verbose)
1553 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1554 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1555 if (std::error_code EC = ErrOrObj.getError()) {
1556 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
1560 // Look for relocations that correspond to debug map entries.
1561 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
1562 if (Options.Verbose)
1563 outs() << "No valid relocations found. Skipping.\n";
1567 // Setup access to the debug info.
1568 DWARFContextInMemory DwarfContext(*ErrOrObj);
1569 startDebugObject(DwarfContext);
1571 // In a first phase, just read in the debug info and store the DIE
1572 // parent links that we will use during the next phase.
1573 for (const auto &CU : DwarfContext.compile_units()) {
1574 auto *CUDie = CU->getCompileUnitDIE(false);
1575 if (Options.Verbose) {
1576 outs() << "Input compilation unit:";
1577 CUDie->dump(outs(), CU.get(), 0);
1579 Units.emplace_back(*CU);
1580 gatherDIEParents(CUDie, 0, Units.back());
1583 // Then mark all the DIEs that need to be present in the linked
1584 // output and collect some information about them. Note that this
1585 // loop can not be merged with the previous one becaue cross-cu
1586 // references require the ParentIdx to be setup for every CU in
1587 // the object file before calling this.
1588 for (auto &CurrentUnit : Units)
1589 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1592 // The calls to applyValidRelocs inside cloneDIE will walk the
1593 // reloc array again (in the same way findValidRelocsInDebugInfo()
1594 // did). We need to reset the NextValidReloc index to the beginning.
1597 // Construct the output DIE tree by cloning the DIEs we chose to
1598 // keep above. If there are no valid relocs, then there's nothing
1600 if (!ValidRelocs.empty())
1601 for (auto &CurrentUnit : Units) {
1602 const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
1603 CurrentUnit.setStartOffset(OutputDebugInfoSize);
1604 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
1605 11 /* Unit Header size */);
1606 CurrentUnit.setOutputUnitDIE(OutputDIE);
1607 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
1610 // Emit all the compile unit's debug information.
1611 if (!ValidRelocs.empty() && !Options.NoOutput)
1612 for (auto &CurrentUnit : Units) {
1613 CurrentUnit.fixupForwardReferences();
1614 Streamer->emitCompileUnitHeader(CurrentUnit);
1615 if (!CurrentUnit.getOutputUnitDIE())
1617 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1620 // Clean-up before starting working on the next object.
1624 // Emit everything that's global.
1625 if (!Options.NoOutput) {
1626 Streamer->emitAbbrevs(Abbreviations);
1627 Streamer->emitStrings(StringPool);
1630 return Options.NoOutput ? true : Streamer->finish();
1634 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1635 const LinkOptions &Options) {
1636 DwarfLinker Linker(OutputFilename, Options);
1637 return Linker.link(DM);