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"
42 void warn(const Twine &Warning, const Twine &Context) {
43 errs() << Twine("while processing ") + Context + ":\n";
44 errs() << Twine("warning: ") + Warning + "\n";
47 bool error(const Twine &Error, const Twine &Context) {
48 errs() << Twine("while processing ") + Context + ":\n";
49 errs() << Twine("error: ") + Error + "\n";
53 template <typename KeyT, typename ValT>
54 using HalfOpenIntervalMap =
55 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
56 IntervalMapHalfOpenInfo<KeyT>>;
58 /// \brief Stores all information relating to a compile unit, be it in
59 /// its original instance in the object file to its brand new cloned
60 /// and linked DIE tree.
63 /// \brief Information gathered about a DIE in the object file.
65 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
66 DIE *Clone; ///< Cloned version of that DIE.
67 uint32_t ParentIdx; ///< The index of this DIE's parent.
68 bool Keep; ///< Is the DIE part of the linked output?
69 bool InDebugMap; ///< Was this DIE's entity found in the map?
72 CompileUnit(DWARFUnit &OrigUnit)
73 : OrigUnit(OrigUnit), RangeAlloc(), Ranges(RangeAlloc) {
74 Info.resize(OrigUnit.getNumDIEs());
77 CompileUnit(CompileUnit &&RHS)
78 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
79 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
80 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
81 // The CompileUnit container has been 'reserve()'d with the right
82 // size. We cannot move the IntervalMap anyway.
83 llvm_unreachable("CompileUnits should not be moved.");
86 DWARFUnit &getOrigUnit() const { return OrigUnit; }
88 DIE *getOutputUnitDIE() const { return CUDie.get(); }
89 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
91 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
92 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
94 uint64_t getStartOffset() const { return StartOffset; }
95 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
97 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
99 /// \brief Compute the end offset for this unit. Must be
100 /// called after the CU's DIEs have been cloned.
101 /// \returns the next unit offset (which is also the current
102 /// debug_info section size).
103 uint64_t computeNextUnitOffset();
105 /// \brief Keep track of a forward reference to DIE \p Die by
106 /// \p Attr. The attribute should be fixed up later to point to the
107 /// absolute offset of \p Die in the debug_info section.
108 void noteForwardReference(DIE *Die, DIEInteger *Attr);
110 /// \brief Apply all fixups recored by noteForwardReference().
111 void fixupForwardReferences();
113 /// \brief Add a function range [\p LowPC, \p HighPC) that is
114 /// relocatad by applying offset \p PCOffset.
115 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
119 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
120 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
122 uint64_t StartOffset;
123 uint64_t NextUnitOffset;
125 /// \brief A list of attributes to fixup with the absolute offset of
126 /// a DIE in the debug_info section.
128 /// The offsets for the attributes in this array couldn't be set while
129 /// cloning because for forward refences the target DIE's offset isn't
130 /// known you emit the reference attribute.
131 std::vector<std::pair<DIE *, DIEInteger *>> ForwardDIEReferences;
133 HalfOpenIntervalMap<uint64_t, int64_t>::Allocator RangeAlloc;
134 /// \brief The ranges in that interval map are the PC ranges for
135 /// functions in this unit, associated with the PC offset to apply
136 /// to the addresses to get the linked address.
137 HalfOpenIntervalMap<uint64_t, int64_t> Ranges;
140 uint64_t CompileUnit::computeNextUnitOffset() {
141 NextUnitOffset = StartOffset + 11 /* Header size */;
142 // The root DIE might be null, meaning that the Unit had nothing to
143 // contribute to the linked output. In that case, we will emit the
144 // unit header without any actual DIE.
146 NextUnitOffset += CUDie->getSize();
147 return NextUnitOffset;
150 /// \brief Keep track of a forward reference to \p Die.
151 void CompileUnit::noteForwardReference(DIE *Die, DIEInteger *Attr) {
152 ForwardDIEReferences.emplace_back(Die, Attr);
155 /// \brief Apply all fixups recorded by noteForwardReference().
156 void CompileUnit::fixupForwardReferences() {
157 for (const auto &Ref : ForwardDIEReferences)
158 Ref.second->setValue(Ref.first->getOffset() + getStartOffset());
161 void CompileUnit::addFunctionRange(uint64_t LowPC, uint64_t HighPC,
163 Ranges.insert(LowPC, HighPC, PCOffset);
166 /// \brief A string table that doesn't need relocations.
168 /// We are doing a final link, no need for a string table that
169 /// has relocation entries for every reference to it. This class
170 /// provides this ablitity by just associating offsets with
172 class NonRelocatableStringpool {
174 /// \brief Entries are stored into the StringMap and simply linked
175 /// together through the second element of this pair in order to
176 /// keep track of insertion order.
177 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
180 NonRelocatableStringpool()
181 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
182 // Legacy dsymutil puts an empty string at the start of the line
187 /// \brief Get the offset of string \p S in the string table. This
188 /// can insert a new element or return the offset of a preexisitng
190 uint32_t getStringOffset(StringRef S);
192 /// \brief Get permanent storage for \p S (but do not necessarily
193 /// emit \p S in the output section).
194 /// \returns The StringRef that points to permanent storage to use
195 /// in place of \p S.
196 StringRef internString(StringRef S);
198 // \brief Return the first entry of the string table.
199 const MapTy::MapEntryTy *getFirstEntry() const {
200 return getNextEntry(&Sentinel);
203 // \brief Get the entry following \p E in the string table or null
204 // if \p E was the last entry.
205 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
206 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
209 uint64_t getSize() { return CurrentEndOffset; }
213 uint32_t CurrentEndOffset;
214 MapTy::MapEntryTy Sentinel, *Last;
217 /// \brief Get the offset of string \p S in the string table. This
218 /// can insert a new element or return the offset of a preexisitng
220 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
221 if (S.empty() && !Strings.empty())
224 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
228 // A non-empty string can't be at offset 0, so if we have an entry
229 // with a 0 offset, it must be a previously interned string.
230 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
231 if (Inserted || It->getValue().first == 0) {
232 // Set offset and chain at the end of the entries list.
233 It->getValue().first = CurrentEndOffset;
234 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
235 Last->getValue().second = &*It;
238 return It->getValue().first;
241 /// \brief Put \p S into the StringMap so that it gets permanent
242 /// storage, but do not actually link it in the chain of elements
243 /// that go into the output section. A latter call to
244 /// getStringOffset() with the same string will chain it though.
245 StringRef NonRelocatableStringpool::internString(StringRef S) {
246 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
247 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
248 return InsertResult.first->getKey();
251 /// \brief The Dwarf streaming logic
253 /// All interactions with the MC layer that is used to build the debug
254 /// information binary representation are handled in this class.
255 class DwarfStreamer {
256 /// \defgroup MCObjects MC layer objects constructed by the streamer
258 std::unique_ptr<MCRegisterInfo> MRI;
259 std::unique_ptr<MCAsmInfo> MAI;
260 std::unique_ptr<MCObjectFileInfo> MOFI;
261 std::unique_ptr<MCContext> MC;
262 MCAsmBackend *MAB; // Owned by MCStreamer
263 std::unique_ptr<MCInstrInfo> MII;
264 std::unique_ptr<MCSubtargetInfo> MSTI;
265 MCCodeEmitter *MCE; // Owned by MCStreamer
266 MCStreamer *MS; // Owned by AsmPrinter
267 std::unique_ptr<TargetMachine> TM;
268 std::unique_ptr<AsmPrinter> Asm;
271 /// \brief the file we stream the linked Dwarf to.
272 std::unique_ptr<raw_fd_ostream> OutFile;
275 /// \brief Actually create the streamer and the ouptut file.
277 /// This could be done directly in the constructor, but it feels
278 /// more natural to handle errors through return value.
279 bool init(Triple TheTriple, StringRef OutputFilename);
281 /// \brief Dump the file to the disk.
284 AsmPrinter &getAsmPrinter() const { return *Asm; }
286 /// \brief Set the current output section to debug_info and change
287 /// the MC Dwarf version to \p DwarfVersion.
288 void switchToDebugInfoSection(unsigned DwarfVersion);
290 /// \brief Emit the compilation unit header for \p Unit in the
291 /// debug_info section.
293 /// As a side effect, this also switches the current Dwarf version
294 /// of the MC layer to the one of U.getOrigUnit().
295 void emitCompileUnitHeader(CompileUnit &Unit);
297 /// \brief Recursively emit the DIE tree rooted at \p Die.
298 void emitDIE(DIE &Die);
300 /// \brief Emit the abbreviation table \p Abbrevs to the
301 /// debug_abbrev section.
302 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
304 /// \brief Emit the string table described by \p Pool.
305 void emitStrings(const NonRelocatableStringpool &Pool);
308 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
309 std::string ErrorStr;
310 std::string TripleName;
311 StringRef Context = "dwarf streamer init";
314 const Target *TheTarget =
315 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
317 return error(ErrorStr, Context);
318 TripleName = TheTriple.getTriple();
320 // Create all the MC Objects.
321 MRI.reset(TheTarget->createMCRegInfo(TripleName));
323 return error(Twine("no register info for target ") + TripleName, Context);
325 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
327 return error("no asm info for target " + TripleName, Context);
329 MOFI.reset(new MCObjectFileInfo);
330 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
331 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
334 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
336 return error("no asm backend for target " + TripleName, Context);
338 MII.reset(TheTarget->createMCInstrInfo());
340 return error("no instr info info for target " + TripleName, Context);
342 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
344 return error("no subtarget info for target " + TripleName, Context);
346 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
348 return error("no code emitter for target " + TripleName, Context);
350 // Create the output file.
353 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
355 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
357 MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
360 return error("no object streamer for target " + TripleName, Context);
362 // Finally create the AsmPrinter we'll use to emit the DIEs.
363 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
365 return error("no target machine for target " + TripleName, Context);
367 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
369 return error("no asm printer for target " + TripleName, Context);
374 bool DwarfStreamer::finish() {
379 /// \brief Set the current output section to debug_info and change
380 /// the MC Dwarf version to \p DwarfVersion.
381 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
382 MS->SwitchSection(MOFI->getDwarfInfoSection());
383 MC->setDwarfVersion(DwarfVersion);
386 /// \brief Emit the compilation unit header for \p Unit in the
387 /// debug_info section.
389 /// A Dwarf scetion header is encoded as:
390 /// uint32_t Unit length (omiting this field)
392 /// uint32_t Abbreviation table offset
393 /// uint8_t Address size
395 /// Leading to a total of 11 bytes.
396 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
397 unsigned Version = Unit.getOrigUnit().getVersion();
398 switchToDebugInfoSection(Version);
400 // Emit size of content not including length itself. The size has
401 // already been computed in CompileUnit::computeOffsets(). Substract
402 // 4 to that size to account for the length field.
403 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
404 Asm->EmitInt16(Version);
405 // We share one abbreviations table across all units so it's always at the
406 // start of the section.
408 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
411 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
412 /// for the linked Dwarf file.
413 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
414 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
415 Asm->emitDwarfAbbrevs(Abbrevs);
418 /// \brief Recursively emit the DIE tree rooted at \p Die.
419 void DwarfStreamer::emitDIE(DIE &Die) {
420 MS->SwitchSection(MOFI->getDwarfInfoSection());
421 Asm->emitDwarfDIE(Die);
424 /// \brief Emit the debug_str section stored in \p Pool.
425 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
426 Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
427 for (auto *Entry = Pool.getFirstEntry(); Entry;
428 Entry = Pool.getNextEntry(Entry))
429 Asm->OutStreamer.EmitBytes(
430 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
433 /// \brief The core of the Dwarf linking logic.
435 /// The link of the dwarf information from the object files will be
436 /// driven by the selection of 'root DIEs', which are DIEs that
437 /// describe variables or functions that are present in the linked
438 /// binary (and thus have entries in the debug map). All the debug
439 /// information that will be linked (the DIEs, but also the line
440 /// tables, ranges, ...) is derived from that set of root DIEs.
442 /// The root DIEs are identified because they contain relocations that
443 /// correspond to a debug map entry at specific places (the low_pc for
444 /// a function, the location for a variable). These relocations are
445 /// called ValidRelocs in the DwarfLinker and are gathered as a very
446 /// first step when we start processing a DebugMapObject.
449 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
450 : OutputFilename(OutputFilename), Options(Options),
451 BinHolder(Options.Verbose) {}
454 for (auto *Abbrev : Abbreviations)
458 /// \brief Link the contents of the DebugMap.
459 bool link(const DebugMap &);
462 /// \brief Called at the start of a debug object link.
463 void startDebugObject(DWARFContext &);
465 /// \brief Called at the end of a debug object link.
466 void endDebugObject();
468 /// \defgroup FindValidRelocations Translate debug map into a list
469 /// of relevant relocations
476 const DebugMapObject::DebugMapEntry *Mapping;
478 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
479 const DebugMapObject::DebugMapEntry *Mapping)
480 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
482 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
485 /// \brief The valid relocations for the current DebugMapObject.
486 /// This vector is sorted by relocation offset.
487 std::vector<ValidReloc> ValidRelocs;
489 /// \brief Index into ValidRelocs of the next relocation to
490 /// consider. As we walk the DIEs in acsending file offset and as
491 /// ValidRelocs is sorted by file offset, keeping this index
492 /// uptodate is all we have to do to have a cheap lookup during the
493 /// root DIE selection and during DIE cloning.
494 unsigned NextValidReloc;
496 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
497 const DebugMapObject &DMO);
499 bool findValidRelocs(const object::SectionRef &Section,
500 const object::ObjectFile &Obj,
501 const DebugMapObject &DMO);
503 void findValidRelocsMachO(const object::SectionRef &Section,
504 const object::MachOObjectFile &Obj,
505 const DebugMapObject &DMO);
508 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
511 /// \brief Recursively walk the \p DIE tree and look for DIEs to
512 /// keep. Store that information in \p CU's DIEInfo.
513 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
514 const DebugMapObject &DMO, CompileUnit &CU,
517 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
519 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
520 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
521 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
522 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
525 /// \brief Mark the passed DIE as well as all the ones it depends on
527 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
528 CompileUnit::DIEInfo &MyInfo,
529 const DebugMapObject &DMO, CompileUnit &CU,
532 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
533 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
536 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
538 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
540 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
542 CompileUnit::DIEInfo &MyInfo,
545 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
546 CompileUnit::DIEInfo &Info);
549 /// \defgroup Linking Methods used to link the debug information
552 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
553 /// where useless (as decided by lookForDIEsToKeep()) bits have been
554 /// stripped out and addresses have been rewritten according to the
557 /// \param OutOffset is the offset the cloned DIE in the output
559 /// \param PCOffset (while cloning a function scope) is the offset
560 /// applied to the entry point of the function to get the linked address.
562 /// \returns the root of the cloned tree.
563 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
564 int64_t PCOffset, uint32_t OutOffset);
566 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
568 /// \brief Information gathered and exchanged between the various
569 /// clone*Attributes helpers about the attributes of a particular DIE.
570 struct AttributesInfo {
571 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
572 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
574 AttributesInfo() : OrigHighPc(0), PCOffset(0) {}
577 /// \brief Helper for cloneDIE.
578 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
579 CompileUnit &U, const DWARFFormValue &Val,
580 const AttributeSpec AttrSpec, unsigned AttrSize,
581 AttributesInfo &AttrInfo);
583 /// \brief Helper for cloneDIE.
584 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
585 const DWARFFormValue &Val, const DWARFUnit &U);
587 /// \brief Helper for cloneDIE.
589 cloneDieReferenceAttribute(DIE &Die,
590 const DWARFDebugInfoEntryMinimal &InputDIE,
591 AttributeSpec AttrSpec, unsigned AttrSize,
592 const DWARFFormValue &Val, const DWARFUnit &U);
594 /// \brief Helper for cloneDIE.
595 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
596 const DWARFFormValue &Val, unsigned AttrSize);
598 /// \brief Helper for cloneDIE.
599 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
600 const DWARFFormValue &Val,
601 const CompileUnit &Unit, AttributesInfo &Info);
603 /// \brief Helper for cloneDIE.
604 unsigned cloneScalarAttribute(DIE &Die,
605 const DWARFDebugInfoEntryMinimal &InputDIE,
606 const DWARFUnit &U, AttributeSpec AttrSpec,
607 const DWARFFormValue &Val, unsigned AttrSize);
609 /// \brief Helper for cloneDIE.
610 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
611 bool isLittleEndian);
613 /// \brief Assign an abbreviation number to \p Abbrev
614 void AssignAbbrev(DIEAbbrev &Abbrev);
616 /// \brief FoldingSet that uniques the abbreviations.
617 FoldingSet<DIEAbbrev> AbbreviationsSet;
618 /// \brief Storage for the unique Abbreviations.
619 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
620 /// be changed to a vecot of unique_ptrs.
621 std::vector<DIEAbbrev *> Abbreviations;
623 /// \brief DIELoc objects that need to be destructed (but not freed!).
624 std::vector<DIELoc *> DIELocs;
625 /// \brief DIEBlock objects that need to be destructed (but not freed!).
626 std::vector<DIEBlock *> DIEBlocks;
627 /// \brief Allocator used for all the DIEValue objects.
628 BumpPtrAllocator DIEAlloc;
631 /// \defgroup Helpers Various helper methods.
634 const DWARFDebugInfoEntryMinimal *
635 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
636 const DWARFDebugInfoEntryMinimal &DIE,
637 CompileUnit *&ReferencedCU);
639 CompileUnit *getUnitForOffset(unsigned Offset);
641 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
642 const DWARFDebugInfoEntryMinimal *DIE = nullptr);
644 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
648 std::string OutputFilename;
650 BinaryHolder BinHolder;
651 std::unique_ptr<DwarfStreamer> Streamer;
653 /// The units of the current debug map object.
654 std::vector<CompileUnit> Units;
656 /// The debug map object curently under consideration.
657 DebugMapObject *CurrentDebugObject;
659 /// \brief The Dwarf string pool
660 NonRelocatableStringpool StringPool;
663 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
664 /// returning our CompileUnit object instead.
665 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
667 std::upper_bound(Units.begin(), Units.end(), Offset,
668 [](uint32_t LHS, const CompileUnit &RHS) {
669 return LHS < RHS.getOrigUnit().getNextUnitOffset();
671 return CU != Units.end() ? &*CU : nullptr;
674 /// \brief Resolve the DIE attribute reference that has been
675 /// extracted in \p RefValue. The resulting DIE migh be in another
676 /// CompileUnit which is stored into \p ReferencedCU.
677 /// \returns null if resolving fails for any reason.
678 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
679 DWARFFormValue &RefValue, const DWARFUnit &Unit,
680 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
681 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
682 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
684 if ((RefCU = getUnitForOffset(RefOffset)))
685 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
688 reportWarning("could not find referenced DIE", &Unit, &DIE);
692 /// \brief Report a warning to the user, optionaly including
693 /// information about a specific \p DIE related to the warning.
694 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
695 const DWARFDebugInfoEntryMinimal *DIE) {
696 StringRef Context = "<debug map>";
697 if (CurrentDebugObject)
698 Context = CurrentDebugObject->getObjectFilename();
699 warn(Warning, Context);
701 if (!Options.Verbose || !DIE)
704 errs() << " in DIE:\n";
705 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
709 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
710 if (Options.NoOutput)
713 Streamer = llvm::make_unique<DwarfStreamer>();
714 return Streamer->init(TheTriple, OutputFilename);
717 /// \brief Recursive helper to gather the child->parent relationships in the
718 /// original compile unit.
719 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
720 unsigned ParentIdx, CompileUnit &CU) {
721 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
722 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
724 if (DIE->hasChildren())
725 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
726 Child = Child->getSibling())
727 gatherDIEParents(Child, MyIdx, CU);
730 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
734 case dwarf::DW_TAG_subprogram:
735 case dwarf::DW_TAG_lexical_block:
736 case dwarf::DW_TAG_subroutine_type:
737 case dwarf::DW_TAG_structure_type:
738 case dwarf::DW_TAG_class_type:
739 case dwarf::DW_TAG_union_type:
742 llvm_unreachable("Invalid Tag");
745 void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
746 Units.reserve(Dwarf.getNumCompileUnits());
750 void DwarfLinker::endDebugObject() {
754 for (auto *Block : DIEBlocks)
756 for (auto *Loc : DIELocs)
764 /// \brief Iterate over the relocations of the given \p Section and
765 /// store the ones that correspond to debug map entries into the
766 /// ValidRelocs array.
767 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
768 const object::MachOObjectFile &Obj,
769 const DebugMapObject &DMO) {
771 Section.getContents(Contents);
772 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
774 for (const object::RelocationRef &Reloc : Section.relocations()) {
775 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
776 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
777 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
779 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
780 reportWarning(" unsupported relocation in debug_info section.");
783 uint32_t Offset = Offset64;
784 // Mach-o uses REL relocations, the addend is at the relocation offset.
785 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
787 auto Sym = Reloc.getSymbol();
788 if (Sym != Obj.symbol_end()) {
789 StringRef SymbolName;
790 if (Sym->getName(SymbolName)) {
791 reportWarning("error getting relocation symbol name.");
794 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
795 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
796 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
797 // Do not store the addend. The addend was the address of the
798 // symbol in the object file, the address in the binary that is
799 // stored in the debug map doesn't need to be offseted.
800 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
805 /// \brief Dispatch the valid relocation finding logic to the
806 /// appropriate handler depending on the object file format.
807 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
808 const object::ObjectFile &Obj,
809 const DebugMapObject &DMO) {
810 // Dispatch to the right handler depending on the file type.
811 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
812 findValidRelocsMachO(Section, *MachOObj, DMO);
814 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
816 if (ValidRelocs.empty())
819 // Sort the relocations by offset. We will walk the DIEs linearly in
820 // the file, this allows us to just keep an index in the relocation
821 // array that we advance during our walk, rather than resorting to
822 // some associative container. See DwarfLinker::NextValidReloc.
823 std::sort(ValidRelocs.begin(), ValidRelocs.end());
827 /// \brief Look for relocations in the debug_info section that match
828 /// entries in the debug map. These relocations will drive the Dwarf
829 /// link by indicating which DIEs refer to symbols present in the
831 /// \returns wether there are any valid relocations in the debug info.
832 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
833 const DebugMapObject &DMO) {
834 // Find the debug_info section.
835 for (const object::SectionRef &Section : Obj.sections()) {
836 StringRef SectionName;
837 Section.getName(SectionName);
838 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
839 if (SectionName != "debug_info")
841 return findValidRelocs(Section, Obj, DMO);
846 /// \brief Checks that there is a relocation against an actual debug
847 /// map entry between \p StartOffset and \p NextOffset.
849 /// This function must be called with offsets in strictly ascending
850 /// order because it never looks back at relocations it already 'went past'.
851 /// \returns true and sets Info.InDebugMap if it is the case.
852 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
853 CompileUnit::DIEInfo &Info) {
854 assert(NextValidReloc == 0 ||
855 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
856 if (NextValidReloc >= ValidRelocs.size())
859 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
861 // We might need to skip some relocs that we didn't consider. For
862 // example the high_pc of a discarded DIE might contain a reloc that
863 // is in the list because it actually corresponds to the start of a
864 // function that is in the debug map.
865 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
866 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
868 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
871 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
873 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
874 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
875 ValidReloc.Mapping->getValue().ObjectAddress,
876 ValidReloc.Mapping->getValue().BinaryAddress);
878 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
880 ValidReloc.Mapping->getValue().ObjectAddress;
881 Info.InDebugMap = true;
885 /// \brief Get the starting and ending (exclusive) offset for the
886 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
887 /// supposed to point to the position of the first attribute described
889 /// \return [StartOffset, EndOffset) as a pair.
890 static std::pair<uint32_t, uint32_t>
891 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
892 unsigned Offset, const DWARFUnit &Unit) {
893 DataExtractor Data = Unit.getDebugInfoExtractor();
895 for (unsigned i = 0; i < Idx; ++i)
896 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
898 uint32_t End = Offset;
899 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
901 return std::make_pair(Offset, End);
904 /// \brief Check if a variable describing DIE should be kept.
905 /// \returns updated TraversalFlags.
906 unsigned DwarfLinker::shouldKeepVariableDIE(
907 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
908 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
909 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
911 // Global variables with constant value can always be kept.
912 if (!(Flags & TF_InFunctionScope) &&
913 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
914 MyInfo.InDebugMap = true;
915 return Flags | TF_Keep;
918 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
919 if (LocationIdx == -1U)
922 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
923 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
924 uint32_t LocationOffset, LocationEndOffset;
925 std::tie(LocationOffset, LocationEndOffset) =
926 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
928 // See if there is a relocation to a valid debug map entry inside
929 // this variable's location. The order is important here. We want to
930 // always check in the variable has a valid relocation, so that the
931 // DIEInfo is filled. However, we don't want a static variable in a
932 // function to force us to keep the enclosing function.
933 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
934 (Flags & TF_InFunctionScope))
938 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
940 return Flags | TF_Keep;
943 /// \brief Check if a function describing DIE should be kept.
944 /// \returns updated TraversalFlags.
945 unsigned DwarfLinker::shouldKeepSubprogramDIE(
946 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
947 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
948 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
950 Flags |= TF_InFunctionScope;
952 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
956 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
957 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
958 uint32_t LowPcOffset, LowPcEndOffset;
959 std::tie(LowPcOffset, LowPcEndOffset) =
960 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
963 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
964 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
965 if (LowPc == -1ULL ||
966 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
970 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
974 DWARFFormValue HighPcValue;
975 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
976 reportWarning("Function without high_pc. Range will be discarded.\n",
982 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
983 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
985 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
986 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
989 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
993 /// \brief Check if a DIE should be kept.
994 /// \returns updated TraversalFlags.
995 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
997 CompileUnit::DIEInfo &MyInfo,
999 switch (DIE.getTag()) {
1000 case dwarf::DW_TAG_constant:
1001 case dwarf::DW_TAG_variable:
1002 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1003 case dwarf::DW_TAG_subprogram:
1004 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1005 case dwarf::DW_TAG_module:
1006 case dwarf::DW_TAG_imported_module:
1007 case dwarf::DW_TAG_imported_declaration:
1008 case dwarf::DW_TAG_imported_unit:
1009 // We always want to keep these.
1010 return Flags | TF_Keep;
1016 /// \brief Mark the passed DIE as well as all the ones it depends on
1019 /// This function is called by lookForDIEsToKeep on DIEs that are
1020 /// newly discovered to be needed in the link. It recursively calls
1021 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1022 /// TraversalFlags to inform it that it's not doing the primary DIE
1024 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1025 CompileUnit::DIEInfo &MyInfo,
1026 const DebugMapObject &DMO,
1027 CompileUnit &CU, unsigned Flags) {
1028 const DWARFUnit &Unit = CU.getOrigUnit();
1031 // First mark all the parent chain as kept.
1032 unsigned AncestorIdx = MyInfo.ParentIdx;
1033 while (!CU.getInfo(AncestorIdx).Keep) {
1034 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1035 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1036 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1039 // Then we need to mark all the DIEs referenced by this DIE's
1040 // attributes as kept.
1041 DataExtractor Data = Unit.getDebugInfoExtractor();
1042 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1043 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1045 // Mark all DIEs referenced through atttributes as kept.
1046 for (const auto &AttrSpec : Abbrev->attributes()) {
1047 DWARFFormValue Val(AttrSpec.Form);
1049 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1050 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1054 Val.extractValue(Data, &Offset, &Unit);
1055 CompileUnit *ReferencedCU;
1056 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1057 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1058 TF_Keep | TF_DependencyWalk);
1062 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1063 /// keep. Store that information in \p CU's DIEInfo.
1065 /// This function is the entry point of the DIE selection
1066 /// algorithm. It is expected to walk the DIE tree in file order and
1067 /// (though the mediation of its helper) call hasValidRelocation() on
1068 /// each DIE that might be a 'root DIE' (See DwarfLinker class
1070 /// While walking the dependencies of root DIEs, this function is
1071 /// also called, but during these dependency walks the file order is
1072 /// not respected. The TF_DependencyWalk flag tells us which kind of
1073 /// traversal we are currently doing.
1074 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1075 const DebugMapObject &DMO, CompileUnit &CU,
1077 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1078 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1079 bool AlreadyKept = MyInfo.Keep;
1081 // If the Keep flag is set, we are marking a required DIE's
1082 // dependencies. If our target is already marked as kept, we're all
1084 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1087 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1088 // because it would screw up the relocation finding logic.
1089 if (!(Flags & TF_DependencyWalk))
1090 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1092 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1093 if (!AlreadyKept && (Flags & TF_Keep))
1094 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1096 // The TF_ParentWalk flag tells us that we are currently walking up
1097 // the parent chain of a required DIE, and we don't want to mark all
1098 // the children of the parents as kept (consider for example a
1099 // DW_TAG_namespace node in the parent chain). There are however a
1100 // set of DIE types for which we want to ignore that directive and still
1101 // walk their children.
1102 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1103 Flags &= ~TF_ParentWalk;
1105 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1108 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1109 Child = Child->getSibling())
1110 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1113 /// \brief Assign an abbreviation numer to \p Abbrev.
1115 /// Our DIEs get freed after every DebugMapObject has been processed,
1116 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1117 /// the instances hold by the DIEs. When we encounter an abbreviation
1118 /// that we don't know, we create a permanent copy of it.
1119 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1120 // Check the set for priors.
1121 FoldingSetNodeID ID;
1124 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1126 // If it's newly added.
1128 // Assign existing abbreviation number.
1129 Abbrev.setNumber(InSet->getNumber());
1131 // Add to abbreviation list.
1132 Abbreviations.push_back(
1133 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1134 for (const auto &Attr : Abbrev.getData())
1135 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1136 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1137 // Assign the unique abbreviation number.
1138 Abbrev.setNumber(Abbreviations.size());
1139 Abbreviations.back()->setNumber(Abbreviations.size());
1143 /// \brief Clone a string attribute described by \p AttrSpec and add
1145 /// \returns the size of the new attribute.
1146 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1147 const DWARFFormValue &Val,
1148 const DWARFUnit &U) {
1149 // Switch everything to out of line strings.
1150 const char *String = *Val.getAsCString(&U);
1151 unsigned Offset = StringPool.getStringOffset(String);
1152 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1153 new (DIEAlloc) DIEInteger(Offset));
1157 /// \brief Clone an attribute referencing another DIE and add
1159 /// \returns the size of the new attribute.
1160 unsigned DwarfLinker::cloneDieReferenceAttribute(
1161 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1162 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1163 const DWARFUnit &U) {
1164 uint32_t Ref = *Val.getAsReference(&U);
1165 DIE *NewRefDie = nullptr;
1166 CompileUnit *RefUnit = nullptr;
1167 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1169 if (!(RefUnit = getUnitForOffset(Ref)) ||
1170 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1171 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1172 if (!AttributeString)
1173 AttributeString = "DW_AT_???";
1174 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1180 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1181 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1182 if (!RefInfo.Clone) {
1183 assert(Ref > InputDIE.getOffset());
1184 // We haven't cloned this DIE yet. Just create an empty one and
1185 // store it. It'll get really cloned when we process it.
1186 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1188 NewRefDie = RefInfo.Clone;
1190 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1191 // We cannot currently rely on a DIEEntry to emit ref_addr
1192 // references, because the implementation calls back to DwarfDebug
1193 // to find the unit offset. (We don't have a DwarfDebug)
1194 // FIXME: we should be able to design DIEEntry reliance on
1197 if (Ref < InputDIE.getOffset()) {
1198 // We must have already cloned that DIE.
1199 uint32_t NewRefOffset =
1200 RefUnit->getStartOffset() + NewRefDie->getOffset();
1201 Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1203 // A forward reference. Note and fixup later.
1204 Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
1205 RefUnit->noteForwardReference(NewRefDie, Attr);
1207 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1212 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1213 new (DIEAlloc) DIEEntry(*NewRefDie));
1217 /// \brief Clone an attribute of block form (locations, constants) and add
1219 /// \returns the size of the new attribute.
1220 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1221 const DWARFFormValue &Val,
1222 unsigned AttrSize) {
1225 DIELoc *Loc = nullptr;
1226 DIEBlock *Block = nullptr;
1227 // Just copy the block data over.
1228 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1229 Loc = new (DIEAlloc) DIELoc();
1230 DIELocs.push_back(Loc);
1232 Block = new (DIEAlloc) DIEBlock();
1233 DIEBlocks.push_back(Block);
1235 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1236 Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1237 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1238 for (auto Byte : Bytes)
1239 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1240 new (DIEAlloc) DIEInteger(Byte));
1241 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1242 // the DIE class, this if could be replaced by
1243 // Attr->setSize(Bytes.size()).
1246 Loc->ComputeSize(&Streamer->getAsmPrinter());
1248 Block->ComputeSize(&Streamer->getAsmPrinter());
1250 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1255 /// \brief Clone an address attribute and add it to \p Die.
1256 /// \returns the size of the new attribute.
1257 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1258 const DWARFFormValue &Val,
1259 const CompileUnit &Unit,
1260 AttributesInfo &Info) {
1261 int64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
1262 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1263 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1264 Die.getTag() == dwarf::DW_TAG_lexical_block)
1265 Addr += Info.PCOffset;
1266 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1267 // If we have a high_pc recorded for the input DIE, use
1268 // it. Otherwise (when no relocations where applied) just use the
1269 // one we just decoded.
1270 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1273 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1274 static_cast<dwarf::Form>(AttrSpec.Form),
1275 new (DIEAlloc) DIEInteger(Addr));
1276 return Unit.getOrigUnit().getAddressByteSize();
1279 /// \brief Clone a scalar attribute and add it to \p Die.
1280 /// \returns the size of the new attribute.
1281 unsigned DwarfLinker::cloneScalarAttribute(
1282 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, const DWARFUnit &U,
1283 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize) {
1285 if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1286 Value = *Val.getAsSectionOffset();
1287 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1288 Value = *Val.getAsSignedConstant();
1289 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1290 Value = *OptionalValue;
1292 reportWarning("Unsupported scalar attribute form. Dropping attribute.", &U,
1296 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1297 new (DIEAlloc) DIEInteger(Value));
1301 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1302 /// value \p Val, and add it to \p Die.
1303 /// \returns the size of the cloned attribute.
1304 unsigned DwarfLinker::cloneAttribute(DIE &Die,
1305 const DWARFDebugInfoEntryMinimal &InputDIE,
1307 const DWARFFormValue &Val,
1308 const AttributeSpec AttrSpec,
1309 unsigned AttrSize, AttributesInfo &Info) {
1310 const DWARFUnit &U = Unit.getOrigUnit();
1312 switch (AttrSpec.Form) {
1313 case dwarf::DW_FORM_strp:
1314 case dwarf::DW_FORM_string:
1315 return cloneStringAttribute(Die, AttrSpec, Val, U);
1316 case dwarf::DW_FORM_ref_addr:
1317 case dwarf::DW_FORM_ref1:
1318 case dwarf::DW_FORM_ref2:
1319 case dwarf::DW_FORM_ref4:
1320 case dwarf::DW_FORM_ref8:
1321 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1323 case dwarf::DW_FORM_block:
1324 case dwarf::DW_FORM_block1:
1325 case dwarf::DW_FORM_block2:
1326 case dwarf::DW_FORM_block4:
1327 case dwarf::DW_FORM_exprloc:
1328 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1329 case dwarf::DW_FORM_addr:
1330 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1331 case dwarf::DW_FORM_data1:
1332 case dwarf::DW_FORM_data2:
1333 case dwarf::DW_FORM_data4:
1334 case dwarf::DW_FORM_data8:
1335 case dwarf::DW_FORM_udata:
1336 case dwarf::DW_FORM_sdata:
1337 case dwarf::DW_FORM_sec_offset:
1338 case dwarf::DW_FORM_flag:
1339 case dwarf::DW_FORM_flag_present:
1340 return cloneScalarAttribute(Die, InputDIE, U, AttrSpec, Val, AttrSize);
1342 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1349 /// \brief Apply the valid relocations found by findValidRelocs() to
1350 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
1351 /// in the debug_info section.
1353 /// Like for findValidRelocs(), this function must be called with
1354 /// monotonic \p BaseOffset values.
1356 /// \returns wether any reloc has been applied.
1357 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
1358 uint32_t BaseOffset, bool isLittleEndian) {
1359 assert((NextValidReloc == 0 ||
1360 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1361 "BaseOffset should only be increasing.");
1362 if (NextValidReloc >= ValidRelocs.size())
1365 // Skip relocs that haven't been applied.
1366 while (NextValidReloc < ValidRelocs.size() &&
1367 ValidRelocs[NextValidReloc].Offset < BaseOffset)
1370 bool Applied = false;
1371 uint64_t EndOffset = BaseOffset + Data.size();
1372 while (NextValidReloc < ValidRelocs.size() &&
1373 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1374 ValidRelocs[NextValidReloc].Offset < EndOffset) {
1375 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1376 assert(ValidReloc.Offset - BaseOffset < Data.size());
1377 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1379 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1380 Value += ValidReloc.Addend;
1381 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1382 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
1383 Buf[i] = uint8_t(Value >> (Index * 8));
1385 assert(ValidReloc.Size <= sizeof(Buf));
1386 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1393 /// \brief Recursively clone \p InputDIE's subtrees that have been
1394 /// selected to appear in the linked output.
1396 /// \param OutOffset is the Offset where the newly created DIE will
1397 /// lie in the linked compile unit.
1399 /// \returns the cloned DIE object or null if nothing was selected.
1400 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
1401 CompileUnit &Unit, int64_t PCOffset,
1402 uint32_t OutOffset) {
1403 DWARFUnit &U = Unit.getOrigUnit();
1404 unsigned Idx = U.getDIEIndex(&InputDIE);
1405 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1407 // Should the DIE appear in the output?
1408 if (!Unit.getInfo(Idx).Keep)
1411 uint32_t Offset = InputDIE.getOffset();
1412 // The DIE might have been already created by a forward reference
1413 // (see cloneDieReferenceAttribute()).
1414 DIE *Die = Info.Clone;
1416 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
1417 assert(Die->getTag() == InputDIE.getTag());
1418 Die->setOffset(OutOffset);
1420 // Extract and clone every attribute.
1421 DataExtractor Data = U.getDebugInfoExtractor();
1422 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
1423 AttributesInfo AttrInfo;
1425 // We could copy the data only if we need to aply a relocation to
1426 // it. After testing, it seems there is no performance downside to
1427 // doing the copy unconditionally, and it makes the code simpler.
1428 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1429 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1430 // Modify the copy with relocated addresses.
1431 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
1432 // If we applied relocations, we store the value of high_pc that was
1433 // potentially stored in the input DIE. If high_pc is an address
1434 // (Dwarf version == 2), then it might have been relocated to a
1435 // totally unrelated value (because the end address in the object
1436 // file might be start address of another function which got moved
1437 // independantly by the linker). The computation of the actual
1438 // high_pc value is done in cloneAddressAttribute().
1439 AttrInfo.OrigHighPc =
1440 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
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 for (const auto &AttrSpec : Abbrev->attributes()) {
1456 DWARFFormValue Val(AttrSpec.Form);
1457 uint32_t AttrSize = Offset;
1458 Val.extractValue(Data, &Offset, &U);
1459 AttrSize = Offset - AttrSize;
1462 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
1465 DIEAbbrev &NewAbbrev = Die->getAbbrev();
1466 // If a scope DIE is kept, we must have kept at least one child. If
1467 // it's not the case, we'll just be emitting one wasteful end of
1468 // children marker, but things won't break.
1469 if (InputDIE.hasChildren())
1470 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1471 // Assign a permanent abbrev number
1472 AssignAbbrev(Die->getAbbrev());
1474 // Add the size of the abbreviation number to the output offset.
1475 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1477 if (!Abbrev->hasChildren()) {
1479 Die->setSize(OutOffset - Die->getOffset());
1483 // Recursively clone children.
1484 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1485 Child = Child->getSibling()) {
1486 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
1487 Die->addChild(std::unique_ptr<DIE>(Clone));
1488 OutOffset = Clone->getOffset() + Clone->getSize();
1492 // Account for the end of children marker.
1493 OutOffset += sizeof(int8_t);
1495 Die->setSize(OutOffset - Die->getOffset());
1499 bool DwarfLinker::link(const DebugMap &Map) {
1501 if (Map.begin() == Map.end()) {
1502 errs() << "Empty debug map.\n";
1506 if (!createStreamer(Map.getTriple(), OutputFilename))
1509 // Size of the DIEs (and headers) generated for the linked output.
1510 uint64_t OutputDebugInfoSize = 0;
1512 for (const auto &Obj : Map.objects()) {
1513 CurrentDebugObject = Obj.get();
1515 if (Options.Verbose)
1516 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1517 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1518 if (std::error_code EC = ErrOrObj.getError()) {
1519 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
1523 // Look for relocations that correspond to debug map entries.
1524 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
1525 if (Options.Verbose)
1526 outs() << "No valid relocations found. Skipping.\n";
1530 // Setup access to the debug info.
1531 DWARFContextInMemory DwarfContext(*ErrOrObj);
1532 startDebugObject(DwarfContext);
1534 // In a first phase, just read in the debug info and store the DIE
1535 // parent links that we will use during the next phase.
1536 for (const auto &CU : DwarfContext.compile_units()) {
1537 auto *CUDie = CU->getCompileUnitDIE(false);
1538 if (Options.Verbose) {
1539 outs() << "Input compilation unit:";
1540 CUDie->dump(outs(), CU.get(), 0);
1542 Units.emplace_back(*CU);
1543 gatherDIEParents(CUDie, 0, Units.back());
1546 // Then mark all the DIEs that need to be present in the linked
1547 // output and collect some information about them. Note that this
1548 // loop can not be merged with the previous one becaue cross-cu
1549 // references require the ParentIdx to be setup for every CU in
1550 // the object file before calling this.
1551 for (auto &CurrentUnit : Units)
1552 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1555 // The calls to applyValidRelocs inside cloneDIE will walk the
1556 // reloc array again (in the same way findValidRelocsInDebugInfo()
1557 // did). We need to reset the NextValidReloc index to the beginning.
1560 // Construct the output DIE tree by cloning the DIEs we chose to
1561 // keep above. If there are no valid relocs, then there's nothing
1563 if (!ValidRelocs.empty())
1564 for (auto &CurrentUnit : Units) {
1565 const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
1566 CurrentUnit.setStartOffset(OutputDebugInfoSize);
1567 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
1568 11 /* Unit Header size */);
1569 CurrentUnit.setOutputUnitDIE(OutputDIE);
1570 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
1573 // Emit all the compile unit's debug information.
1574 if (!ValidRelocs.empty() && !Options.NoOutput)
1575 for (auto &CurrentUnit : Units) {
1576 CurrentUnit.fixupForwardReferences();
1577 Streamer->emitCompileUnitHeader(CurrentUnit);
1578 if (!CurrentUnit.getOutputUnitDIE())
1580 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1583 // Clean-up before starting working on the next object.
1587 // Emit everything that's global.
1588 if (!Options.NoOutput) {
1589 Streamer->emitAbbrevs(Abbreviations);
1590 Streamer->emitStrings(StringPool);
1593 return Options.NoOutput ? true : Streamer->finish();
1597 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1598 const LinkOptions &Options) {
1599 DwarfLinker Linker(OutputFilename, Options);
1600 return Linker.link(DM);