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/CodeGen/AsmPrinter.h"
14 #include "llvm/CodeGen/DIE.h"
15 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
16 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
17 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
18 #include "llvm/MC/MCAsmBackend.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCCodeEmitter.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/MC/MCObjectFileInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/Object/MachO.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/LEB128.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
39 void warn(const Twine &Warning, const Twine &Context) {
40 errs() << Twine("while processing ") + Context + ":\n";
41 errs() << Twine("warning: ") + Warning + "\n";
44 bool error(const Twine &Error, const Twine &Context) {
45 errs() << Twine("while processing ") + Context + ":\n";
46 errs() << Twine("error: ") + Error + "\n";
50 /// \brief Stores all information relating to a compile unit, be it in
51 /// its original instance in the object file to its brand new cloned
52 /// and linked DIE tree.
55 /// \brief Information gathered about a DIE in the object file.
57 uint64_t Address; ///< Linked address of the described entity.
58 DIE *Clone; ///< Cloned version of that DIE.
59 uint32_t ParentIdx; ///< The index of this DIE's parent.
60 bool Keep; ///< Is the DIE part of the linked output?
61 bool InDebugMap; ///< Was this DIE's entity found in the map?
64 CompileUnit(DWARFUnit &OrigUnit) : OrigUnit(OrigUnit) {
65 Info.resize(OrigUnit.getNumDIEs());
68 // Workaround MSVC not supporting implicit move ops
69 CompileUnit(CompileUnit &&RHS)
70 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
71 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
72 NextUnitOffset(RHS.NextUnitOffset) {}
74 DWARFUnit &getOrigUnit() const { return OrigUnit; }
76 DIE *getOutputUnitDIE() const { return CUDie.get(); }
77 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
79 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
80 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
82 uint64_t getStartOffset() const { return StartOffset; }
83 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
85 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
87 /// \brief Compute the end offset for this unit. Must be
88 /// called after the CU's DIEs have been cloned.
89 /// \returns the next unit offset (which is also the current
90 /// debug_info section size).
91 uint64_t computeNextUnitOffset();
93 /// \brief Keep track of a forward reference to DIE \p Die by
94 /// \p Attr. The attribute should be fixed up later to point to the
95 /// absolute offset of \p Die in the debug_info section.
96 void noteForwardReference(DIE *Die, DIEInteger *Attr);
98 /// \brief Apply all fixups recored by noteForwardReference().
99 void fixupForwardReferences();
103 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
104 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
106 uint64_t StartOffset;
107 uint64_t NextUnitOffset;
109 /// \brief A list of attributes to fixup with the absolute offset of
110 /// a DIE in the debug_info section.
112 /// The offsets for the attributes in this array couldn't be set while
113 /// cloning because for forward refences the target DIE's offset isn't
114 /// known you emit the reference attribute.
115 std::vector<std::pair<DIE *, DIEInteger *>> ForwardDIEReferences;
118 uint64_t CompileUnit::computeNextUnitOffset() {
119 NextUnitOffset = StartOffset + 11 /* Header size */;
120 // The root DIE might be null, meaning that the Unit had nothing to
121 // contribute to the linked output. In that case, we will emit the
122 // unit header without any actual DIE.
124 NextUnitOffset += CUDie->getSize();
125 return NextUnitOffset;
128 /// \brief Keep track of a forward reference to \p Die.
129 void CompileUnit::noteForwardReference(DIE *Die, DIEInteger *Attr) {
130 ForwardDIEReferences.emplace_back(Die, Attr);
133 /// \brief Apply all fixups recorded by noteForwardReference().
134 void CompileUnit::fixupForwardReferences() {
135 for (const auto &Ref : ForwardDIEReferences)
136 Ref.second->setValue(Ref.first->getOffset() + getStartOffset());
139 /// \brief A string table that doesn't need relocations.
141 /// We are doing a final link, no need for a string table that
142 /// has relocation entries for every reference to it. This class
143 /// provides this ablitity by just associating offsets with
145 class NonRelocatableStringpool {
147 /// \brief Entries are stored into the StringMap and simply linked
148 /// together through the second element of this pair in order to
149 /// keep track of insertion order.
150 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
153 NonRelocatableStringpool()
154 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
155 // Legacy dsymutil puts an empty string at the start of the line
160 /// \brief Get the offset of string \p S in the string table. This
161 /// can insert a new element or return the offset of a preexisitng
163 uint32_t getStringOffset(StringRef S);
165 /// \brief Get permanent storage for \p S (but do not necessarily
166 /// emit \p S in the output section).
167 /// \returns The StringRef that points to permanent storage to use
168 /// in place of \p S.
169 StringRef internString(StringRef S);
171 // \brief Return the first entry of the string table.
172 const MapTy::MapEntryTy *getFirstEntry() const {
173 return getNextEntry(&Sentinel);
176 // \brief Get the entry following \p E in the string table or null
177 // if \p E was the last entry.
178 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
179 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
182 uint64_t getSize() { return CurrentEndOffset; }
186 uint32_t CurrentEndOffset;
187 MapTy::MapEntryTy Sentinel, *Last;
190 /// \brief Get the offset of string \p S in the string table. This
191 /// can insert a new element or return the offset of a preexisitng
193 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
194 if (S.empty() && !Strings.empty())
197 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
201 // A non-empty string can't be at offset 0, so if we have an entry
202 // with a 0 offset, it must be a previously interned string.
203 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
204 if (Inserted || It->getValue().first == 0) {
205 // Set offset and chain at the end of the entries list.
206 It->getValue().first = CurrentEndOffset;
207 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
208 Last->getValue().second = &*It;
211 return It->getValue().first;
214 /// \brief Put \p S into the StringMap so that it gets permanent
215 /// storage, but do not actually link it in the chain of elements
216 /// that go into the output section. A latter call to
217 /// getStringOffset() with the same string will chain it though.
218 StringRef NonRelocatableStringpool::internString(StringRef S) {
219 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
220 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
221 return InsertResult.first->getKey();
224 /// \brief The Dwarf streaming logic
226 /// All interactions with the MC layer that is used to build the debug
227 /// information binary representation are handled in this class.
228 class DwarfStreamer {
229 /// \defgroup MCObjects MC layer objects constructed by the streamer
231 std::unique_ptr<MCRegisterInfo> MRI;
232 std::unique_ptr<MCAsmInfo> MAI;
233 std::unique_ptr<MCObjectFileInfo> MOFI;
234 std::unique_ptr<MCContext> MC;
235 MCAsmBackend *MAB; // Owned by MCStreamer
236 std::unique_ptr<MCInstrInfo> MII;
237 std::unique_ptr<MCSubtargetInfo> MSTI;
238 MCCodeEmitter *MCE; // Owned by MCStreamer
239 MCStreamer *MS; // Owned by AsmPrinter
240 std::unique_ptr<TargetMachine> TM;
241 std::unique_ptr<AsmPrinter> Asm;
244 /// \brief the file we stream the linked Dwarf to.
245 std::unique_ptr<raw_fd_ostream> OutFile;
248 /// \brief Actually create the streamer and the ouptut file.
250 /// This could be done directly in the constructor, but it feels
251 /// more natural to handle errors through return value.
252 bool init(Triple TheTriple, StringRef OutputFilename);
254 /// \brief Dump the file to the disk.
257 AsmPrinter &getAsmPrinter() const { return *Asm; }
259 /// \brief Set the current output section to debug_info and change
260 /// the MC Dwarf version to \p DwarfVersion.
261 void switchToDebugInfoSection(unsigned DwarfVersion);
263 /// \brief Emit the compilation unit header for \p Unit in the
264 /// debug_info section.
266 /// As a side effect, this also switches the current Dwarf version
267 /// of the MC layer to the one of U.getOrigUnit().
268 void emitCompileUnitHeader(CompileUnit &Unit);
270 /// \brief Recursively emit the DIE tree rooted at \p Die.
271 void emitDIE(DIE &Die);
273 /// \brief Emit the abbreviation table \p Abbrevs to the
274 /// debug_abbrev section.
275 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
277 /// \brief Emit the string table described by \p Pool.
278 void emitStrings(const NonRelocatableStringpool &Pool);
281 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
282 std::string ErrorStr;
283 std::string TripleName;
284 StringRef Context = "dwarf streamer init";
287 const Target *TheTarget =
288 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
290 return error(ErrorStr, Context);
291 TripleName = TheTriple.getTriple();
293 // Create all the MC Objects.
294 MRI.reset(TheTarget->createMCRegInfo(TripleName));
296 return error(Twine("no register info for target ") + TripleName, Context);
298 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
300 return error("no asm info for target " + TripleName, Context);
302 MOFI.reset(new MCObjectFileInfo);
303 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
304 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
307 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
309 return error("no asm backend for target " + TripleName, Context);
311 MII.reset(TheTarget->createMCInstrInfo());
313 return error("no instr info info for target " + TripleName, Context);
315 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
317 return error("no subtarget info for target " + TripleName, Context);
319 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
321 return error("no code emitter for target " + TripleName, Context);
323 // Create the output file.
326 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
328 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
330 MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
333 return error("no object streamer for target " + TripleName, Context);
335 // Finally create the AsmPrinter we'll use to emit the DIEs.
336 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
338 return error("no target machine for target " + TripleName, Context);
340 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
342 return error("no asm printer for target " + TripleName, Context);
347 bool DwarfStreamer::finish() {
352 /// \brief Set the current output section to debug_info and change
353 /// the MC Dwarf version to \p DwarfVersion.
354 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
355 MS->SwitchSection(MOFI->getDwarfInfoSection());
356 MC->setDwarfVersion(DwarfVersion);
359 /// \brief Emit the compilation unit header for \p Unit in the
360 /// debug_info section.
362 /// A Dwarf scetion header is encoded as:
363 /// uint32_t Unit length (omiting this field)
365 /// uint32_t Abbreviation table offset
366 /// uint8_t Address size
368 /// Leading to a total of 11 bytes.
369 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
370 unsigned Version = Unit.getOrigUnit().getVersion();
371 switchToDebugInfoSection(Version);
373 // Emit size of content not including length itself. The size has
374 // already been computed in CompileUnit::computeOffsets(). Substract
375 // 4 to that size to account for the length field.
376 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
377 Asm->EmitInt16(Version);
378 // We share one abbreviations table across all units so it's always at the
379 // start of the section.
381 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
384 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
385 /// for the linked Dwarf file.
386 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
387 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
388 Asm->emitDwarfAbbrevs(Abbrevs);
391 /// \brief Recursively emit the DIE tree rooted at \p Die.
392 void DwarfStreamer::emitDIE(DIE &Die) {
393 MS->SwitchSection(MOFI->getDwarfInfoSection());
394 Asm->emitDwarfDIE(Die);
397 /// \brief Emit the debug_str section stored in \p Pool.
398 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
399 Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
400 for (auto *Entry = Pool.getFirstEntry(); Entry;
401 Entry = Pool.getNextEntry(Entry))
402 Asm->OutStreamer.EmitBytes(
403 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
406 /// \brief The core of the Dwarf linking logic.
408 /// The link of the dwarf information from the object files will be
409 /// driven by the selection of 'root DIEs', which are DIEs that
410 /// describe variables or functions that are present in the linked
411 /// binary (and thus have entries in the debug map). All the debug
412 /// information that will be linked (the DIEs, but also the line
413 /// tables, ranges, ...) is derived from that set of root DIEs.
415 /// The root DIEs are identified because they contain relocations that
416 /// correspond to a debug map entry at specific places (the low_pc for
417 /// a function, the location for a variable). These relocations are
418 /// called ValidRelocs in the DwarfLinker and are gathered as a very
419 /// first step when we start processing a DebugMapObject.
422 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
423 : OutputFilename(OutputFilename), Options(Options),
424 BinHolder(Options.Verbose) {}
427 for (auto *Abbrev : Abbreviations)
431 /// \brief Link the contents of the DebugMap.
432 bool link(const DebugMap &);
435 /// \brief Called at the start of a debug object link.
436 void startDebugObject(DWARFContext &);
438 /// \brief Called at the end of a debug object link.
439 void endDebugObject();
441 /// \defgroup FindValidRelocations Translate debug map into a list
442 /// of relevant relocations
449 const DebugMapObject::DebugMapEntry *Mapping;
451 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
452 const DebugMapObject::DebugMapEntry *Mapping)
453 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
455 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
458 /// \brief The valid relocations for the current DebugMapObject.
459 /// This vector is sorted by relocation offset.
460 std::vector<ValidReloc> ValidRelocs;
462 /// \brief Index into ValidRelocs of the next relocation to
463 /// consider. As we walk the DIEs in acsending file offset and as
464 /// ValidRelocs is sorted by file offset, keeping this index
465 /// uptodate is all we have to do to have a cheap lookup during the
466 /// root DIE selection and during DIE cloning.
467 unsigned NextValidReloc;
469 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
470 const DebugMapObject &DMO);
472 bool findValidRelocs(const object::SectionRef &Section,
473 const object::ObjectFile &Obj,
474 const DebugMapObject &DMO);
476 void findValidRelocsMachO(const object::SectionRef &Section,
477 const object::MachOObjectFile &Obj,
478 const DebugMapObject &DMO);
481 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
484 /// \brief Recursively walk the \p DIE tree and look for DIEs to
485 /// keep. Store that information in \p CU's DIEInfo.
486 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
487 const DebugMapObject &DMO, CompileUnit &CU,
490 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
492 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
493 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
494 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
495 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
498 /// \brief Mark the passed DIE as well as all the ones it depends on
500 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
501 CompileUnit::DIEInfo &MyInfo,
502 const DebugMapObject &DMO, CompileUnit &CU,
505 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
506 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
509 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
511 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
513 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
515 CompileUnit::DIEInfo &MyInfo,
518 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
519 CompileUnit::DIEInfo &Info);
522 /// \defgroup Linking Methods used to link the debug information
525 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
526 /// where useless (as decided by lookForDIEsToKeep()) bits have been
527 /// stripped out and addresses have been rewritten according to the
530 /// \param OutOffset is the offset the cloned DIE in the output
533 /// \returns the root of the cloned tree.
534 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
537 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
539 /// \brief Helper for cloneDIE.
540 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
541 CompileUnit &U, const DWARFFormValue &Val,
542 const AttributeSpec AttrSpec, unsigned AttrSize);
544 /// \brief Helper for cloneDIE.
545 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
546 const DWARFFormValue &Val, const DWARFUnit &U);
548 /// \brief Helper for cloneDIE.
550 cloneDieReferenceAttribute(DIE &Die,
551 const DWARFDebugInfoEntryMinimal &InputDIE,
552 AttributeSpec AttrSpec, unsigned AttrSize,
553 const DWARFFormValue &Val, const DWARFUnit &U);
555 /// \brief Helper for cloneDIE.
556 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
557 const DWARFFormValue &Val, unsigned AttrSize);
559 /// \brief Helper for cloneDIE.
560 unsigned cloneScalarAttribute(DIE &Die,
561 const DWARFDebugInfoEntryMinimal &InputDIE,
562 const DWARFUnit &U, AttributeSpec AttrSpec,
563 const DWARFFormValue &Val, unsigned AttrSize);
565 /// \brief Helper for cloneDIE.
566 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
567 bool isLittleEndian);
569 /// \brief Assign an abbreviation number to \p Abbrev
570 void AssignAbbrev(DIEAbbrev &Abbrev);
572 /// \brief FoldingSet that uniques the abbreviations.
573 FoldingSet<DIEAbbrev> AbbreviationsSet;
574 /// \brief Storage for the unique Abbreviations.
575 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
576 /// be changed to a vecot of unique_ptrs.
577 std::vector<DIEAbbrev *> Abbreviations;
579 /// \brief DIELoc objects that need to be destructed (but not freed!).
580 std::vector<DIELoc *> DIELocs;
581 /// \brief DIEBlock objects that need to be destructed (but not freed!).
582 std::vector<DIEBlock *> DIEBlocks;
583 /// \brief Allocator used for all the DIEValue objects.
584 BumpPtrAllocator DIEAlloc;
587 /// \defgroup Helpers Various helper methods.
590 const DWARFDebugInfoEntryMinimal *
591 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
592 const DWARFDebugInfoEntryMinimal &DIE,
593 CompileUnit *&ReferencedCU);
595 CompileUnit *getUnitForOffset(unsigned Offset);
597 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
598 const DWARFDebugInfoEntryMinimal *DIE = nullptr);
600 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
604 std::string OutputFilename;
606 BinaryHolder BinHolder;
607 std::unique_ptr<DwarfStreamer> Streamer;
609 /// The units of the current debug map object.
610 std::vector<CompileUnit> Units;
612 /// The debug map object curently under consideration.
613 DebugMapObject *CurrentDebugObject;
615 /// \brief The Dwarf string pool
616 NonRelocatableStringpool StringPool;
619 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
620 /// returning our CompileUnit object instead.
621 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
623 std::upper_bound(Units.begin(), Units.end(), Offset,
624 [](uint32_t LHS, const CompileUnit &RHS) {
625 return LHS < RHS.getOrigUnit().getNextUnitOffset();
627 return CU != Units.end() ? &*CU : nullptr;
630 /// \brief Resolve the DIE attribute reference that has been
631 /// extracted in \p RefValue. The resulting DIE migh be in another
632 /// CompileUnit which is stored into \p ReferencedCU.
633 /// \returns null if resolving fails for any reason.
634 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
635 DWARFFormValue &RefValue, const DWARFUnit &Unit,
636 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
637 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
638 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
640 if ((RefCU = getUnitForOffset(RefOffset)))
641 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
644 reportWarning("could not find referenced DIE", &Unit, &DIE);
648 /// \brief Report a warning to the user, optionaly including
649 /// information about a specific \p DIE related to the warning.
650 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
651 const DWARFDebugInfoEntryMinimal *DIE) {
652 StringRef Context = "<debug map>";
653 if (CurrentDebugObject)
654 Context = CurrentDebugObject->getObjectFilename();
655 warn(Warning, Context);
657 if (!Options.Verbose || !DIE)
660 errs() << " in DIE:\n";
661 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
665 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
666 if (Options.NoOutput)
669 Streamer = llvm::make_unique<DwarfStreamer>();
670 return Streamer->init(TheTriple, OutputFilename);
673 /// \brief Recursive helper to gather the child->parent relationships in the
674 /// original compile unit.
675 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
676 unsigned ParentIdx, CompileUnit &CU) {
677 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
678 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
680 if (DIE->hasChildren())
681 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
682 Child = Child->getSibling())
683 gatherDIEParents(Child, MyIdx, CU);
686 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
690 case dwarf::DW_TAG_subprogram:
691 case dwarf::DW_TAG_lexical_block:
692 case dwarf::DW_TAG_subroutine_type:
693 case dwarf::DW_TAG_structure_type:
694 case dwarf::DW_TAG_class_type:
695 case dwarf::DW_TAG_union_type:
698 llvm_unreachable("Invalid Tag");
701 void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
702 Units.reserve(Dwarf.getNumCompileUnits());
706 void DwarfLinker::endDebugObject() {
710 for (auto *Block : DIEBlocks)
712 for (auto *Loc : DIELocs)
720 /// \brief Iterate over the relocations of the given \p Section and
721 /// store the ones that correspond to debug map entries into the
722 /// ValidRelocs array.
723 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
724 const object::MachOObjectFile &Obj,
725 const DebugMapObject &DMO) {
727 Section.getContents(Contents);
728 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
730 for (const object::RelocationRef &Reloc : Section.relocations()) {
731 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
732 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
733 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
735 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
736 reportWarning(" unsupported relocation in debug_info section.");
739 uint32_t Offset = Offset64;
740 // Mach-o uses REL relocations, the addend is at the relocation offset.
741 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
743 auto Sym = Reloc.getSymbol();
744 if (Sym != Obj.symbol_end()) {
745 StringRef SymbolName;
746 if (Sym->getName(SymbolName)) {
747 reportWarning("error getting relocation symbol name.");
750 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
751 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
752 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
753 // Do not store the addend. The addend was the address of the
754 // symbol in the object file, the address in the binary that is
755 // stored in the debug map doesn't need to be offseted.
756 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
761 /// \brief Dispatch the valid relocation finding logic to the
762 /// appropriate handler depending on the object file format.
763 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
764 const object::ObjectFile &Obj,
765 const DebugMapObject &DMO) {
766 // Dispatch to the right handler depending on the file type.
767 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
768 findValidRelocsMachO(Section, *MachOObj, DMO);
770 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
772 if (ValidRelocs.empty())
775 // Sort the relocations by offset. We will walk the DIEs linearly in
776 // the file, this allows us to just keep an index in the relocation
777 // array that we advance during our walk, rather than resorting to
778 // some associative container. See DwarfLinker::NextValidReloc.
779 std::sort(ValidRelocs.begin(), ValidRelocs.end());
783 /// \brief Look for relocations in the debug_info section that match
784 /// entries in the debug map. These relocations will drive the Dwarf
785 /// link by indicating which DIEs refer to symbols present in the
787 /// \returns wether there are any valid relocations in the debug info.
788 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
789 const DebugMapObject &DMO) {
790 // Find the debug_info section.
791 for (const object::SectionRef &Section : Obj.sections()) {
792 StringRef SectionName;
793 Section.getName(SectionName);
794 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
795 if (SectionName != "debug_info")
797 return findValidRelocs(Section, Obj, DMO);
802 /// \brief Checks that there is a relocation against an actual debug
803 /// map entry between \p StartOffset and \p NextOffset.
805 /// This function must be called with offsets in strictly ascending
806 /// order because it never looks back at relocations it already 'went past'.
807 /// \returns true and sets Info.InDebugMap if it is the case.
808 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
809 CompileUnit::DIEInfo &Info) {
810 assert(NextValidReloc == 0 ||
811 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
812 if (NextValidReloc >= ValidRelocs.size())
815 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
817 // We might need to skip some relocs that we didn't consider. For
818 // example the high_pc of a discarded DIE might contain a reloc that
819 // is in the list because it actually corresponds to the start of a
820 // function that is in the debug map.
821 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
822 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
824 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
827 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
829 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
830 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
831 ValidReloc.Mapping->getValue().ObjectAddress,
832 ValidReloc.Mapping->getValue().BinaryAddress);
835 ValidReloc.Mapping->getValue().BinaryAddress + ValidReloc.Addend;
836 Info.InDebugMap = true;
840 /// \brief Get the starting and ending (exclusive) offset for the
841 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
842 /// supposed to point to the position of the first attribute described
844 /// \return [StartOffset, EndOffset) as a pair.
845 static std::pair<uint32_t, uint32_t>
846 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
847 unsigned Offset, const DWARFUnit &Unit) {
848 DataExtractor Data = Unit.getDebugInfoExtractor();
850 for (unsigned i = 0; i < Idx; ++i)
851 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
853 uint32_t End = Offset;
854 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
856 return std::make_pair(Offset, End);
859 /// \brief Check if a variable describing DIE should be kept.
860 /// \returns updated TraversalFlags.
861 unsigned DwarfLinker::shouldKeepVariableDIE(
862 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
863 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
864 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
866 // Global variables with constant value can always be kept.
867 if (!(Flags & TF_InFunctionScope) &&
868 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
869 MyInfo.InDebugMap = true;
870 return Flags | TF_Keep;
873 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
874 if (LocationIdx == -1U)
877 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
878 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
879 uint32_t LocationOffset, LocationEndOffset;
880 std::tie(LocationOffset, LocationEndOffset) =
881 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
883 // See if there is a relocation to a valid debug map entry inside
884 // this variable's location. The order is important here. We want to
885 // always check in the variable has a valid relocation, so that the
886 // DIEInfo is filled. However, we don't want a static variable in a
887 // function to force us to keep the enclosing function.
888 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
889 (Flags & TF_InFunctionScope))
893 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
895 return Flags | TF_Keep;
898 /// \brief Check if a function describing DIE should be kept.
899 /// \returns updated TraversalFlags.
900 unsigned DwarfLinker::shouldKeepSubprogramDIE(
901 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
902 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
903 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
905 Flags |= TF_InFunctionScope;
907 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
911 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
912 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
913 uint32_t LowPcOffset, LowPcEndOffset;
914 std::tie(LowPcOffset, LowPcEndOffset) =
915 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
918 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
919 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
920 if (LowPc == -1ULL ||
921 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
925 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
927 return Flags | TF_Keep;
930 /// \brief Check if a DIE should be kept.
931 /// \returns updated TraversalFlags.
932 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
934 CompileUnit::DIEInfo &MyInfo,
936 switch (DIE.getTag()) {
937 case dwarf::DW_TAG_constant:
938 case dwarf::DW_TAG_variable:
939 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
940 case dwarf::DW_TAG_subprogram:
941 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
942 case dwarf::DW_TAG_module:
943 case dwarf::DW_TAG_imported_module:
944 case dwarf::DW_TAG_imported_declaration:
945 case dwarf::DW_TAG_imported_unit:
946 // We always want to keep these.
947 return Flags | TF_Keep;
953 /// \brief Mark the passed DIE as well as all the ones it depends on
956 /// This function is called by lookForDIEsToKeep on DIEs that are
957 /// newly discovered to be needed in the link. It recursively calls
958 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
959 /// TraversalFlags to inform it that it's not doing the primary DIE
961 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
962 CompileUnit::DIEInfo &MyInfo,
963 const DebugMapObject &DMO,
964 CompileUnit &CU, unsigned Flags) {
965 const DWARFUnit &Unit = CU.getOrigUnit();
968 // First mark all the parent chain as kept.
969 unsigned AncestorIdx = MyInfo.ParentIdx;
970 while (!CU.getInfo(AncestorIdx).Keep) {
971 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
972 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
973 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
976 // Then we need to mark all the DIEs referenced by this DIE's
977 // attributes as kept.
978 DataExtractor Data = Unit.getDebugInfoExtractor();
979 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
980 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
982 // Mark all DIEs referenced through atttributes as kept.
983 for (const auto &AttrSpec : Abbrev->attributes()) {
984 DWARFFormValue Val(AttrSpec.Form);
986 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
987 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
991 Val.extractValue(Data, &Offset, &Unit);
992 CompileUnit *ReferencedCU;
993 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
994 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
995 TF_Keep | TF_DependencyWalk);
999 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1000 /// keep. Store that information in \p CU's DIEInfo.
1002 /// This function is the entry point of the DIE selection
1003 /// algorithm. It is expected to walk the DIE tree in file order and
1004 /// (though the mediation of its helper) call hasValidRelocation() on
1005 /// each DIE that might be a 'root DIE' (See DwarfLinker class
1007 /// While walking the dependencies of root DIEs, this function is
1008 /// also called, but during these dependency walks the file order is
1009 /// not respected. The TF_DependencyWalk flag tells us which kind of
1010 /// traversal we are currently doing.
1011 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1012 const DebugMapObject &DMO, CompileUnit &CU,
1014 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1015 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1016 bool AlreadyKept = MyInfo.Keep;
1018 // If the Keep flag is set, we are marking a required DIE's
1019 // dependencies. If our target is already marked as kept, we're all
1021 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1024 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1025 // because it would screw up the relocation finding logic.
1026 if (!(Flags & TF_DependencyWalk))
1027 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1029 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1030 if (!AlreadyKept && (Flags & TF_Keep))
1031 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1033 // The TF_ParentWalk flag tells us that we are currently walking up
1034 // the parent chain of a required DIE, and we don't want to mark all
1035 // the children of the parents as kept (consider for example a
1036 // DW_TAG_namespace node in the parent chain). There are however a
1037 // set of DIE types for which we want to ignore that directive and still
1038 // walk their children.
1039 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1040 Flags &= ~TF_ParentWalk;
1042 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1045 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1046 Child = Child->getSibling())
1047 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1050 /// \brief Assign an abbreviation numer to \p Abbrev.
1052 /// Our DIEs get freed after every DebugMapObject has been processed,
1053 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1054 /// the instances hold by the DIEs. When we encounter an abbreviation
1055 /// that we don't know, we create a permanent copy of it.
1056 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1057 // Check the set for priors.
1058 FoldingSetNodeID ID;
1061 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1063 // If it's newly added.
1065 // Assign existing abbreviation number.
1066 Abbrev.setNumber(InSet->getNumber());
1068 // Add to abbreviation list.
1069 Abbreviations.push_back(
1070 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1071 for (const auto &Attr : Abbrev.getData())
1072 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1073 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1074 // Assign the unique abbreviation number.
1075 Abbrev.setNumber(Abbreviations.size());
1076 Abbreviations.back()->setNumber(Abbreviations.size());
1080 /// \brief Clone a string attribute described by \p AttrSpec and add
1082 /// \returns the size of the new attribute.
1083 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1084 const DWARFFormValue &Val,
1085 const DWARFUnit &U) {
1086 // Switch everything to out of line strings.
1087 const char *String = *Val.getAsCString(&U);
1088 unsigned Offset = StringPool.getStringOffset(String);
1089 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1090 new (DIEAlloc) DIEInteger(Offset));
1094 /// \brief Clone an attribute referencing another DIE and add
1096 /// \returns the size of the new attribute.
1097 unsigned DwarfLinker::cloneDieReferenceAttribute(
1098 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1099 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1100 const DWARFUnit &U) {
1101 uint32_t Ref = *Val.getAsReference(&U);
1102 DIE *NewRefDie = nullptr;
1103 CompileUnit *RefUnit = nullptr;
1104 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1106 if (!(RefUnit = getUnitForOffset(Ref)) ||
1107 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1108 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1109 if (!AttributeString)
1110 AttributeString = "DW_AT_???";
1111 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1117 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1118 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1119 if (!RefInfo.Clone) {
1120 assert(Ref > InputDIE.getOffset());
1121 // We haven't cloned this DIE yet. Just create an empty one and
1122 // store it. It'll get really cloned when we process it.
1123 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1125 NewRefDie = RefInfo.Clone;
1127 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1128 // We cannot currently rely on a DIEEntry to emit ref_addr
1129 // references, because the implementation calls back to DwarfDebug
1130 // to find the unit offset. (We don't have a DwarfDebug)
1131 // FIXME: we should be able to design DIEEntry reliance on
1134 if (Ref < InputDIE.getOffset()) {
1135 // We must have already cloned that DIE.
1136 uint32_t NewRefOffset =
1137 RefUnit->getStartOffset() + NewRefDie->getOffset();
1138 Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1140 // A forward reference. Note and fixup later.
1141 Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
1142 RefUnit->noteForwardReference(NewRefDie, Attr);
1144 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1149 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1150 new (DIEAlloc) DIEEntry(*NewRefDie));
1154 /// \brief Clone an attribute of block form (locations, constants) and add
1156 /// \returns the size of the new attribute.
1157 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1158 const DWARFFormValue &Val,
1159 unsigned AttrSize) {
1162 DIELoc *Loc = nullptr;
1163 DIEBlock *Block = nullptr;
1164 // Just copy the block data over.
1165 if (AttrSpec.Attr == dwarf::DW_FORM_exprloc) {
1166 Loc = new (DIEAlloc) DIELoc();
1167 DIELocs.push_back(Loc);
1169 Block = new (DIEAlloc) DIEBlock();
1170 DIEBlocks.push_back(Block);
1172 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1173 Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1174 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1175 for (auto Byte : Bytes)
1176 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1177 new (DIEAlloc) DIEInteger(Byte));
1178 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1179 // the DIE class, this if could be replaced by
1180 // Attr->setSize(Bytes.size()).
1183 Loc->ComputeSize(&Streamer->getAsmPrinter());
1185 Block->ComputeSize(&Streamer->getAsmPrinter());
1187 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1192 /// \brief Clone a scalar attribute and add it to \p Die.
1193 /// \returns the size of the new attribute.
1194 unsigned DwarfLinker::cloneScalarAttribute(
1195 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, const DWARFUnit &U,
1196 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize) {
1198 if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1199 Value = *Val.getAsSectionOffset();
1200 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1201 Value = *Val.getAsSignedConstant();
1202 else if (AttrSpec.Form == dwarf::DW_FORM_addr)
1203 Value = *Val.getAsAddress(&U);
1204 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1205 Value = *OptionalValue;
1207 reportWarning("Unsupported scalar attribute form. Dropping attribute.", &U,
1211 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1212 new (DIEAlloc) DIEInteger(Value));
1216 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1217 /// value \p Val, and add it to \p Die.
1218 /// \returns the size of the cloned attribute.
1219 unsigned DwarfLinker::cloneAttribute(DIE &Die,
1220 const DWARFDebugInfoEntryMinimal &InputDIE,
1222 const DWARFFormValue &Val,
1223 const AttributeSpec AttrSpec,
1224 unsigned AttrSize) {
1225 const DWARFUnit &U = Unit.getOrigUnit();
1227 switch (AttrSpec.Form) {
1228 case dwarf::DW_FORM_strp:
1229 case dwarf::DW_FORM_string:
1230 return cloneStringAttribute(Die, AttrSpec, Val, U);
1231 case dwarf::DW_FORM_ref_addr:
1232 case dwarf::DW_FORM_ref1:
1233 case dwarf::DW_FORM_ref2:
1234 case dwarf::DW_FORM_ref4:
1235 case dwarf::DW_FORM_ref8:
1236 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1238 case dwarf::DW_FORM_block:
1239 case dwarf::DW_FORM_block1:
1240 case dwarf::DW_FORM_block2:
1241 case dwarf::DW_FORM_block4:
1242 case dwarf::DW_FORM_exprloc:
1243 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1244 case dwarf::DW_FORM_addr:
1245 case dwarf::DW_FORM_data1:
1246 case dwarf::DW_FORM_data2:
1247 case dwarf::DW_FORM_data4:
1248 case dwarf::DW_FORM_data8:
1249 case dwarf::DW_FORM_udata:
1250 case dwarf::DW_FORM_sdata:
1251 case dwarf::DW_FORM_sec_offset:
1252 case dwarf::DW_FORM_flag:
1253 case dwarf::DW_FORM_flag_present:
1254 return cloneScalarAttribute(Die, InputDIE, U, AttrSpec, Val, AttrSize);
1256 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1263 /// \brief Apply the valid relocations found by findValidRelocs() to
1264 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
1265 /// in the debug_info section.
1267 /// Like for findValidRelocs(), this function must be called with
1268 /// monotonic \p BaseOffset values.
1270 /// \returns wether any reloc has been applied.
1271 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
1272 uint32_t BaseOffset, bool isLittleEndian) {
1273 assert((NextValidReloc == 0 ||
1274 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1275 "BaseOffset should only be increasing.");
1276 if (NextValidReloc >= ValidRelocs.size())
1279 // Skip relocs that haven't been applied.
1280 while (NextValidReloc < ValidRelocs.size() &&
1281 ValidRelocs[NextValidReloc].Offset < BaseOffset)
1284 bool Applied = false;
1285 uint64_t EndOffset = BaseOffset + Data.size();
1286 while (NextValidReloc < ValidRelocs.size() &&
1287 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1288 ValidRelocs[NextValidReloc].Offset < EndOffset) {
1289 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1290 assert(ValidReloc.Offset - BaseOffset < Data.size());
1291 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1293 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1294 Value += ValidReloc.Addend;
1295 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1296 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
1297 Buf[i] = uint8_t(Value >> (Index * 8));
1299 assert(ValidReloc.Size <= sizeof(Buf));
1300 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1307 /// \brief Recursively clone \p InputDIE's subtrees that have been
1308 /// selected to appear in the linked output.
1310 /// \param OutOffset is the Offset where the newly created DIE will
1311 /// lie in the linked compile unit.
1313 /// \returns the cloned DIE object or null if nothing was selected.
1314 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
1315 CompileUnit &Unit, uint32_t OutOffset) {
1316 DWARFUnit &U = Unit.getOrigUnit();
1317 unsigned Idx = U.getDIEIndex(&InputDIE);
1318 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1320 // Should the DIE appear in the output?
1321 if (!Unit.getInfo(Idx).Keep)
1324 uint32_t Offset = InputDIE.getOffset();
1325 // The DIE might have been already created by a forward reference
1326 // (see cloneDieReferenceAttribute()).
1327 DIE *Die = Info.Clone;
1329 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
1330 assert(Die->getTag() == InputDIE.getTag());
1331 Die->setOffset(OutOffset);
1333 // Extract and clone every attribute.
1334 DataExtractor Data = U.getDebugInfoExtractor();
1335 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
1337 // We could copy the data only if we need to aply a relocation to
1338 // it. After testing, it seems there is no performance downside to
1339 // doing the copy unconditionally, and it makes the code simpler.
1340 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1341 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1342 // Modify the copy with relocated addresses.
1343 applyValidRelocs(DIECopy, Offset, Data.isLittleEndian());
1345 // Reset the Offset to 0 as we will be working on the local copy of
1349 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1350 Offset += getULEB128Size(Abbrev->getCode());
1352 for (const auto &AttrSpec : Abbrev->attributes()) {
1353 DWARFFormValue Val(AttrSpec.Form);
1354 uint32_t AttrSize = Offset;
1355 Val.extractValue(Data, &Offset, &U);
1356 AttrSize = Offset - AttrSize;
1358 OutOffset += cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize);
1361 DIEAbbrev &NewAbbrev = Die->getAbbrev();
1362 // If a scope DIE is kept, we must have kept at least one child. If
1363 // it's not the case, we'll just be emitting one wasteful end of
1364 // children marker, but things won't break.
1365 if (InputDIE.hasChildren())
1366 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1367 // Assign a permanent abbrev number
1368 AssignAbbrev(Die->getAbbrev());
1370 // Add the size of the abbreviation number to the output offset.
1371 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1373 if (!Abbrev->hasChildren()) {
1375 Die->setSize(OutOffset - Die->getOffset());
1379 // Recursively clone children.
1380 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1381 Child = Child->getSibling()) {
1382 if (DIE *Clone = cloneDIE(*Child, Unit, OutOffset)) {
1383 Die->addChild(std::unique_ptr<DIE>(Clone));
1384 OutOffset = Clone->getOffset() + Clone->getSize();
1388 // Account for the end of children marker.
1389 OutOffset += sizeof(int8_t);
1391 Die->setSize(OutOffset - Die->getOffset());
1395 bool DwarfLinker::link(const DebugMap &Map) {
1397 if (Map.begin() == Map.end()) {
1398 errs() << "Empty debug map.\n";
1402 if (!createStreamer(Map.getTriple(), OutputFilename))
1405 // Size of the DIEs (and headers) generated for the linked output.
1406 uint64_t OutputDebugInfoSize = 0;
1408 for (const auto &Obj : Map.objects()) {
1409 CurrentDebugObject = Obj.get();
1411 if (Options.Verbose)
1412 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1413 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1414 if (std::error_code EC = ErrOrObj.getError()) {
1415 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
1419 // Look for relocations that correspond to debug map entries.
1420 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
1421 if (Options.Verbose)
1422 outs() << "No valid relocations found. Skipping.\n";
1426 // Setup access to the debug info.
1427 DWARFContextInMemory DwarfContext(*ErrOrObj);
1428 startDebugObject(DwarfContext);
1430 // In a first phase, just read in the debug info and store the DIE
1431 // parent links that we will use during the next phase.
1432 for (const auto &CU : DwarfContext.compile_units()) {
1433 auto *CUDie = CU->getCompileUnitDIE(false);
1434 if (Options.Verbose) {
1435 outs() << "Input compilation unit:";
1436 CUDie->dump(outs(), CU.get(), 0);
1438 Units.emplace_back(*CU);
1439 gatherDIEParents(CUDie, 0, Units.back());
1442 // Then mark all the DIEs that need to be present in the linked
1443 // output and collect some information about them. Note that this
1444 // loop can not be merged with the previous one becaue cross-cu
1445 // references require the ParentIdx to be setup for every CU in
1446 // the object file before calling this.
1447 for (auto &CurrentUnit : Units)
1448 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1451 // The calls to applyValidRelocs inside cloneDIE will walk the
1452 // reloc array again (in the same way findValidRelocsInDebugInfo()
1453 // did). We need to reset the NextValidReloc index to the beginning.
1456 // Construct the output DIE tree by cloning the DIEs we chose to
1457 // keep above. If there are no valid relocs, then there's nothing
1459 if (!ValidRelocs.empty())
1460 for (auto &CurrentUnit : Units) {
1461 const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
1462 CurrentUnit.setStartOffset(OutputDebugInfoSize);
1464 cloneDIE(*InputDIE, CurrentUnit, 11 /* Unit Header size */);
1465 CurrentUnit.setOutputUnitDIE(OutputDIE);
1466 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
1469 // Emit all the compile unit's debug information.
1470 if (!ValidRelocs.empty() && !Options.NoOutput)
1471 for (auto &CurrentUnit : Units) {
1472 CurrentUnit.fixupForwardReferences();
1473 Streamer->emitCompileUnitHeader(CurrentUnit);
1474 if (!CurrentUnit.getOutputUnitDIE())
1476 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1479 // Clean-up before starting working on the next object.
1483 // Emit everything that's global.
1484 if (!Options.NoOutput) {
1485 Streamer->emitAbbrevs(Abbreviations);
1486 Streamer->emitStrings(StringPool);
1489 return Options.NoOutput ? true : Streamer->finish();
1493 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1494 const LinkOptions &Options) {
1495 DwarfLinker Linker(OutputFilename, Options);
1496 return Linker.link(DM);