1 //===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "BinaryHolder.h"
13 #include "llvm/ADT/IntervalMap.h"
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/DIE.h"
18 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
20 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
21 #include "llvm/MC/MCAsmBackend.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCCodeEmitter.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCObjectFileInfo.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/Object/MachO.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/LEB128.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
43 void warn(const Twine &Warning, const Twine &Context) {
44 errs() << Twine("while processing ") + Context + ":\n";
45 errs() << Twine("warning: ") + Warning + "\n";
48 bool error(const Twine &Error, const Twine &Context) {
49 errs() << Twine("while processing ") + Context + ":\n";
50 errs() << Twine("error: ") + Error + "\n";
54 template <typename KeyT, typename ValT>
55 using HalfOpenIntervalMap =
56 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
57 IntervalMapHalfOpenInfo<KeyT>>;
59 typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
61 /// \brief Stores all information relating to a compile unit, be it in
62 /// its original instance in the object file to its brand new cloned
63 /// and linked DIE tree.
66 /// \brief Information gathered about a DIE in the object file.
68 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
69 DIE *Clone; ///< Cloned version of that DIE.
70 uint32_t ParentIdx; ///< The index of this DIE's parent.
71 bool Keep; ///< Is the DIE part of the linked output?
72 bool InDebugMap; ///< Was this DIE's entity found in the map?
75 CompileUnit(DWARFUnit &OrigUnit)
76 : OrigUnit(OrigUnit), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
77 Ranges(RangeAlloc), UnitRangeAttribute(nullptr) {
78 Info.resize(OrigUnit.getNumDIEs());
81 CompileUnit(CompileUnit &&RHS)
82 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
83 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
84 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
85 // The CompileUnit container has been 'reserve()'d with the right
86 // size. We cannot move the IntervalMap anyway.
87 llvm_unreachable("CompileUnits should not be moved.");
90 DWARFUnit &getOrigUnit() const { return OrigUnit; }
92 DIE *getOutputUnitDIE() const { return CUDie.get(); }
93 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
95 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
96 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
98 uint64_t getStartOffset() const { return StartOffset; }
99 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
100 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
102 uint64_t getLowPc() const { return LowPc; }
103 uint64_t getHighPc() const { return HighPc; }
105 DIEInteger *getUnitRangesAttribute() const { return UnitRangeAttribute; }
106 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
107 const std::vector<DIEInteger *> &getRangesAttributes() const {
108 return RangeAttributes;
111 /// \brief Compute the end offset for this unit. Must be
112 /// called after the CU's DIEs have been cloned.
113 /// \returns the next unit offset (which is also the current
114 /// debug_info section size).
115 uint64_t computeNextUnitOffset();
117 /// \brief Keep track of a forward reference to DIE \p Die in \p
118 /// RefUnit by \p Attr. The attribute should be fixed up later to
119 /// point to the absolute offset of \p Die in the debug_info section.
120 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
123 /// \brief Apply all fixups recored by noteForwardReference().
124 void fixupForwardReferences();
126 /// \brief Add a function range [\p LowPC, \p HighPC) that is
127 /// relocatad by applying offset \p PCOffset.
128 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
130 /// \bried Keep trak of a DW_AT_range attribute that we will need to
132 void noteRangeAttribute(const DIE &Die, DIEInteger *Attr);
136 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
137 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
139 uint64_t StartOffset;
140 uint64_t NextUnitOffset;
145 /// \brief A list of attributes to fixup with the absolute offset of
146 /// a DIE in the debug_info section.
148 /// The offsets for the attributes in this array couldn't be set while
149 /// cloning because for cross-cu forward refences the target DIE's
150 /// offset isn't known you emit the reference attribute.
151 std::vector<std::tuple<DIE *, const CompileUnit *, DIEInteger *>>
152 ForwardDIEReferences;
154 FunctionIntervals::Allocator RangeAlloc;
155 /// \brief The ranges in that interval map are the PC ranges for
156 /// functions in this unit, associated with the PC offset to apply
157 /// to the addresses to get the linked address.
158 FunctionIntervals Ranges;
160 /// \brief DW_AT_ranges attributes to patch after we have gathered
161 /// all the unit's function addresses.
163 std::vector<DIEInteger *> RangeAttributes;
164 DIEInteger *UnitRangeAttribute;
168 uint64_t CompileUnit::computeNextUnitOffset() {
169 NextUnitOffset = StartOffset + 11 /* Header size */;
170 // The root DIE might be null, meaning that the Unit had nothing to
171 // contribute to the linked output. In that case, we will emit the
172 // unit header without any actual DIE.
174 NextUnitOffset += CUDie->getSize();
175 return NextUnitOffset;
178 /// \brief Keep track of a forward cross-cu reference from this unit
179 /// to \p Die that lives in \p RefUnit.
180 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
182 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
185 /// \brief Apply all fixups recorded by noteForwardReference().
186 void CompileUnit::fixupForwardReferences() {
187 for (const auto &Ref : ForwardDIEReferences) {
189 const CompileUnit *RefUnit;
191 std::tie(RefDie, RefUnit, Attr) = Ref;
192 Attr->setValue(RefDie->getOffset() + RefUnit->getStartOffset());
196 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
198 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
199 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
200 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
203 void CompileUnit::noteRangeAttribute(const DIE &Die, DIEInteger *Attr) {
204 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
205 RangeAttributes.push_back(Attr);
207 UnitRangeAttribute = Attr;
210 /// \brief A string table that doesn't need relocations.
212 /// We are doing a final link, no need for a string table that
213 /// has relocation entries for every reference to it. This class
214 /// provides this ablitity by just associating offsets with
216 class NonRelocatableStringpool {
218 /// \brief Entries are stored into the StringMap and simply linked
219 /// together through the second element of this pair in order to
220 /// keep track of insertion order.
221 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
224 NonRelocatableStringpool()
225 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
226 // Legacy dsymutil puts an empty string at the start of the line
231 /// \brief Get the offset of string \p S in the string table. This
232 /// can insert a new element or return the offset of a preexisitng
234 uint32_t getStringOffset(StringRef S);
236 /// \brief Get permanent storage for \p S (but do not necessarily
237 /// emit \p S in the output section).
238 /// \returns The StringRef that points to permanent storage to use
239 /// in place of \p S.
240 StringRef internString(StringRef S);
242 // \brief Return the first entry of the string table.
243 const MapTy::MapEntryTy *getFirstEntry() const {
244 return getNextEntry(&Sentinel);
247 // \brief Get the entry following \p E in the string table or null
248 // if \p E was the last entry.
249 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
250 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
253 uint64_t getSize() { return CurrentEndOffset; }
257 uint32_t CurrentEndOffset;
258 MapTy::MapEntryTy Sentinel, *Last;
261 /// \brief Get the offset of string \p S in the string table. This
262 /// can insert a new element or return the offset of a preexisitng
264 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
265 if (S.empty() && !Strings.empty())
268 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
272 // A non-empty string can't be at offset 0, so if we have an entry
273 // with a 0 offset, it must be a previously interned string.
274 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
275 if (Inserted || It->getValue().first == 0) {
276 // Set offset and chain at the end of the entries list.
277 It->getValue().first = CurrentEndOffset;
278 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
279 Last->getValue().second = &*It;
282 return It->getValue().first;
285 /// \brief Put \p S into the StringMap so that it gets permanent
286 /// storage, but do not actually link it in the chain of elements
287 /// that go into the output section. A latter call to
288 /// getStringOffset() with the same string will chain it though.
289 StringRef NonRelocatableStringpool::internString(StringRef S) {
290 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
291 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
292 return InsertResult.first->getKey();
295 /// \brief The Dwarf streaming logic
297 /// All interactions with the MC layer that is used to build the debug
298 /// information binary representation are handled in this class.
299 class DwarfStreamer {
300 /// \defgroup MCObjects MC layer objects constructed by the streamer
302 std::unique_ptr<MCRegisterInfo> MRI;
303 std::unique_ptr<MCAsmInfo> MAI;
304 std::unique_ptr<MCObjectFileInfo> MOFI;
305 std::unique_ptr<MCContext> MC;
306 MCAsmBackend *MAB; // Owned by MCStreamer
307 std::unique_ptr<MCInstrInfo> MII;
308 std::unique_ptr<MCSubtargetInfo> MSTI;
309 MCCodeEmitter *MCE; // Owned by MCStreamer
310 MCStreamer *MS; // Owned by AsmPrinter
311 std::unique_ptr<TargetMachine> TM;
312 std::unique_ptr<AsmPrinter> Asm;
315 /// \brief the file we stream the linked Dwarf to.
316 std::unique_ptr<raw_fd_ostream> OutFile;
318 uint32_t RangesSectionSize;
321 /// \brief Actually create the streamer and the ouptut file.
323 /// This could be done directly in the constructor, but it feels
324 /// more natural to handle errors through return value.
325 bool init(Triple TheTriple, StringRef OutputFilename);
327 /// \brief Dump the file to the disk.
330 AsmPrinter &getAsmPrinter() const { return *Asm; }
332 /// \brief Set the current output section to debug_info and change
333 /// the MC Dwarf version to \p DwarfVersion.
334 void switchToDebugInfoSection(unsigned DwarfVersion);
336 /// \brief Emit the compilation unit header for \p Unit in the
337 /// debug_info section.
339 /// As a side effect, this also switches the current Dwarf version
340 /// of the MC layer to the one of U.getOrigUnit().
341 void emitCompileUnitHeader(CompileUnit &Unit);
343 /// \brief Recursively emit the DIE tree rooted at \p Die.
344 void emitDIE(DIE &Die);
346 /// \brief Emit the abbreviation table \p Abbrevs to the
347 /// debug_abbrev section.
348 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
350 /// \brief Emit the string table described by \p Pool.
351 void emitStrings(const NonRelocatableStringpool &Pool);
353 /// \brief Emit debug_ranges for \p FuncRange by translating the
354 /// original \p Entries.
355 void emitRangesEntries(
356 int64_t UnitPcOffset, uint64_t OrigLowPc,
357 FunctionIntervals::const_iterator FuncRange,
358 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
359 unsigned AddressSize);
361 /// \brief Emit debug_ranges entries for a DW_TAG_compile_unit's DW_AT_ranges.
362 void emitUnitRangesEntries(CompileUnit &Unit);
364 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
367 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
368 std::string ErrorStr;
369 std::string TripleName;
370 StringRef Context = "dwarf streamer init";
373 const Target *TheTarget =
374 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
376 return error(ErrorStr, Context);
377 TripleName = TheTriple.getTriple();
379 // Create all the MC Objects.
380 MRI.reset(TheTarget->createMCRegInfo(TripleName));
382 return error(Twine("no register info for target ") + TripleName, Context);
384 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
386 return error("no asm info for target " + TripleName, Context);
388 MOFI.reset(new MCObjectFileInfo);
389 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
390 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
393 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
395 return error("no asm backend for target " + TripleName, Context);
397 MII.reset(TheTarget->createMCInstrInfo());
399 return error("no instr info info for target " + TripleName, Context);
401 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
403 return error("no subtarget info for target " + TripleName, Context);
405 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
407 return error("no code emitter for target " + TripleName, Context);
409 // Create the output file.
412 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
414 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
416 MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
419 return error("no object streamer for target " + TripleName, Context);
421 // Finally create the AsmPrinter we'll use to emit the DIEs.
422 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
424 return error("no target machine for target " + TripleName, Context);
426 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
428 return error("no asm printer for target " + TripleName, Context);
430 RangesSectionSize = 0;
435 bool DwarfStreamer::finish() {
440 /// \brief Set the current output section to debug_info and change
441 /// the MC Dwarf version to \p DwarfVersion.
442 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
443 MS->SwitchSection(MOFI->getDwarfInfoSection());
444 MC->setDwarfVersion(DwarfVersion);
447 /// \brief Emit the compilation unit header for \p Unit in the
448 /// debug_info section.
450 /// A Dwarf scetion header is encoded as:
451 /// uint32_t Unit length (omiting this field)
453 /// uint32_t Abbreviation table offset
454 /// uint8_t Address size
456 /// Leading to a total of 11 bytes.
457 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
458 unsigned Version = Unit.getOrigUnit().getVersion();
459 switchToDebugInfoSection(Version);
461 // Emit size of content not including length itself. The size has
462 // already been computed in CompileUnit::computeOffsets(). Substract
463 // 4 to that size to account for the length field.
464 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
465 Asm->EmitInt16(Version);
466 // We share one abbreviations table across all units so it's always at the
467 // start of the section.
469 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
472 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
473 /// for the linked Dwarf file.
474 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
475 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
476 Asm->emitDwarfAbbrevs(Abbrevs);
479 /// \brief Recursively emit the DIE tree rooted at \p Die.
480 void DwarfStreamer::emitDIE(DIE &Die) {
481 MS->SwitchSection(MOFI->getDwarfInfoSection());
482 Asm->emitDwarfDIE(Die);
485 /// \brief Emit the debug_str section stored in \p Pool.
486 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
487 Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
488 for (auto *Entry = Pool.getFirstEntry(); Entry;
489 Entry = Pool.getNextEntry(Entry))
490 Asm->OutStreamer.EmitBytes(
491 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
494 /// \brief Emit the debug_range section contents for \p FuncRange by
495 /// translating the original \p Entries. The debug_range section
496 /// format is totally trivial, consisting just of pairs of address
497 /// sized addresses describing the ranges.
498 void DwarfStreamer::emitRangesEntries(
499 int64_t UnitPcOffset, uint64_t OrigLowPc,
500 FunctionIntervals::const_iterator FuncRange,
501 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
502 unsigned AddressSize) {
503 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
505 // Offset each range by the right amount.
506 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
507 for (const auto &Range : Entries) {
508 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
509 warn("unsupported base address selection operation",
510 "emitting debug_ranges");
513 // Do not emit empty ranges.
514 if (Range.StartAddress == Range.EndAddress)
517 // All range entries should lie in the function range.
518 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
519 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
520 warn("inconsistent range data.", "emitting debug_ranges");
521 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
522 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
523 RangesSectionSize += 2 * AddressSize;
526 // Add the terminator entry.
527 MS->EmitIntValue(0, AddressSize);
528 MS->EmitIntValue(0, AddressSize);
529 RangesSectionSize += 2 * AddressSize;
532 /// \brief Emit the debug_range contents for a compile_unit level
533 /// DW_AT_ranges attribute. Just aggregate all the ranges gathered
534 /// inside that unit.
535 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit) {
536 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
538 // Offset each range by the right amount.
539 int64_t PcOffset = -Unit.getLowPc();
540 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
541 // Gather the ranges in a vector, so that we can simplify them. The
542 // IntervalMap will have coalesced the non-linked ranges, but here
543 // we want to coalesce the linked addresses.
544 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
545 const auto &FunctionRanges = Unit.getFunctionRanges();
546 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
547 Range != End; ++Range)
548 Ranges.push_back(std::make_pair(Range.start() + Range.value() + PcOffset,
549 Range.stop() + Range.value() + PcOffset));
551 // The object addresses where sorted, but again, the linked
552 // addresses might end up in a different order.
553 std::sort(Ranges.begin(), Ranges.end());
555 // Emit coalesced ranges.
556 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
557 MS->EmitIntValue(Range->first, AddressSize);
558 while (Range + 1 != End && Range->second == (Range + 1)->first)
560 MS->EmitIntValue(Range->second, AddressSize);
561 RangesSectionSize += 2 * AddressSize;
564 // Add the terminator entry.
565 MS->EmitIntValue(0, AddressSize);
566 MS->EmitIntValue(0, AddressSize);
567 RangesSectionSize += 2 * AddressSize;
570 /// \brief The core of the Dwarf linking logic.
572 /// The link of the dwarf information from the object files will be
573 /// driven by the selection of 'root DIEs', which are DIEs that
574 /// describe variables or functions that are present in the linked
575 /// binary (and thus have entries in the debug map). All the debug
576 /// information that will be linked (the DIEs, but also the line
577 /// tables, ranges, ...) is derived from that set of root DIEs.
579 /// The root DIEs are identified because they contain relocations that
580 /// correspond to a debug map entry at specific places (the low_pc for
581 /// a function, the location for a variable). These relocations are
582 /// called ValidRelocs in the DwarfLinker and are gathered as a very
583 /// first step when we start processing a DebugMapObject.
586 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
587 : OutputFilename(OutputFilename), Options(Options),
588 BinHolder(Options.Verbose) {}
591 for (auto *Abbrev : Abbreviations)
595 /// \brief Link the contents of the DebugMap.
596 bool link(const DebugMap &);
599 /// \brief Called at the start of a debug object link.
600 void startDebugObject(DWARFContext &);
602 /// \brief Called at the end of a debug object link.
603 void endDebugObject();
605 /// \defgroup FindValidRelocations Translate debug map into a list
606 /// of relevant relocations
613 const DebugMapObject::DebugMapEntry *Mapping;
615 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
616 const DebugMapObject::DebugMapEntry *Mapping)
617 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
619 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
622 /// \brief The valid relocations for the current DebugMapObject.
623 /// This vector is sorted by relocation offset.
624 std::vector<ValidReloc> ValidRelocs;
626 /// \brief Index into ValidRelocs of the next relocation to
627 /// consider. As we walk the DIEs in acsending file offset and as
628 /// ValidRelocs is sorted by file offset, keeping this index
629 /// uptodate is all we have to do to have a cheap lookup during the
630 /// root DIE selection and during DIE cloning.
631 unsigned NextValidReloc;
633 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
634 const DebugMapObject &DMO);
636 bool findValidRelocs(const object::SectionRef &Section,
637 const object::ObjectFile &Obj,
638 const DebugMapObject &DMO);
640 void findValidRelocsMachO(const object::SectionRef &Section,
641 const object::MachOObjectFile &Obj,
642 const DebugMapObject &DMO);
645 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
648 /// \brief Recursively walk the \p DIE tree and look for DIEs to
649 /// keep. Store that information in \p CU's DIEInfo.
650 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
651 const DebugMapObject &DMO, CompileUnit &CU,
654 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
656 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
657 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
658 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
659 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
662 /// \brief Mark the passed DIE as well as all the ones it depends on
664 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
665 CompileUnit::DIEInfo &MyInfo,
666 const DebugMapObject &DMO, CompileUnit &CU,
669 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
670 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
673 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
675 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
677 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
679 CompileUnit::DIEInfo &MyInfo,
682 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
683 CompileUnit::DIEInfo &Info);
686 /// \defgroup Linking Methods used to link the debug information
689 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
690 /// where useless (as decided by lookForDIEsToKeep()) bits have been
691 /// stripped out and addresses have been rewritten according to the
694 /// \param OutOffset is the offset the cloned DIE in the output
696 /// \param PCOffset (while cloning a function scope) is the offset
697 /// applied to the entry point of the function to get the linked address.
699 /// \returns the root of the cloned tree.
700 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
701 int64_t PCOffset, uint32_t OutOffset);
703 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
705 /// \brief Information gathered and exchanged between the various
706 /// clone*Attributes helpers about the attributes of a particular DIE.
707 struct AttributesInfo {
708 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
709 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
711 AttributesInfo() : OrigHighPc(0), PCOffset(0) {}
714 /// \brief Helper for cloneDIE.
715 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
716 CompileUnit &U, const DWARFFormValue &Val,
717 const AttributeSpec AttrSpec, unsigned AttrSize,
718 AttributesInfo &AttrInfo);
720 /// \brief Helper for cloneDIE.
721 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
722 const DWARFFormValue &Val, const DWARFUnit &U);
724 /// \brief Helper for cloneDIE.
726 cloneDieReferenceAttribute(DIE &Die,
727 const DWARFDebugInfoEntryMinimal &InputDIE,
728 AttributeSpec AttrSpec, unsigned AttrSize,
729 const DWARFFormValue &Val, CompileUnit &Unit);
731 /// \brief Helper for cloneDIE.
732 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
733 const DWARFFormValue &Val, unsigned AttrSize);
735 /// \brief Helper for cloneDIE.
736 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
737 const DWARFFormValue &Val,
738 const CompileUnit &Unit, AttributesInfo &Info);
740 /// \brief Helper for cloneDIE.
741 unsigned cloneScalarAttribute(DIE &Die,
742 const DWARFDebugInfoEntryMinimal &InputDIE,
743 CompileUnit &U, AttributeSpec AttrSpec,
744 const DWARFFormValue &Val, unsigned AttrSize);
746 /// \brief Helper for cloneDIE.
747 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
748 bool isLittleEndian);
750 /// \brief Assign an abbreviation number to \p Abbrev
751 void AssignAbbrev(DIEAbbrev &Abbrev);
753 /// \brief FoldingSet that uniques the abbreviations.
754 FoldingSet<DIEAbbrev> AbbreviationsSet;
755 /// \brief Storage for the unique Abbreviations.
756 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
757 /// be changed to a vecot of unique_ptrs.
758 std::vector<DIEAbbrev *> Abbreviations;
760 /// \brief Compute and emit debug_ranges section for \p Unit, and
761 /// patch the attributes referencing it.
762 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
764 /// \brief Generate and emit the DW_AT_ranges attribute for a
765 /// compile_unit if it had one.
766 void generateUnitRanges(CompileUnit &Unit) const;
768 /// \brief DIELoc objects that need to be destructed (but not freed!).
769 std::vector<DIELoc *> DIELocs;
770 /// \brief DIEBlock objects that need to be destructed (but not freed!).
771 std::vector<DIEBlock *> DIEBlocks;
772 /// \brief Allocator used for all the DIEValue objects.
773 BumpPtrAllocator DIEAlloc;
776 /// \defgroup Helpers Various helper methods.
779 const DWARFDebugInfoEntryMinimal *
780 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
781 const DWARFDebugInfoEntryMinimal &DIE,
782 CompileUnit *&ReferencedCU);
784 CompileUnit *getUnitForOffset(unsigned Offset);
786 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
787 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
789 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
793 std::string OutputFilename;
795 BinaryHolder BinHolder;
796 std::unique_ptr<DwarfStreamer> Streamer;
798 /// The units of the current debug map object.
799 std::vector<CompileUnit> Units;
801 /// The debug map object curently under consideration.
802 DebugMapObject *CurrentDebugObject;
804 /// \brief The Dwarf string pool
805 NonRelocatableStringpool StringPool;
808 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
809 /// returning our CompileUnit object instead.
810 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
812 std::upper_bound(Units.begin(), Units.end(), Offset,
813 [](uint32_t LHS, const CompileUnit &RHS) {
814 return LHS < RHS.getOrigUnit().getNextUnitOffset();
816 return CU != Units.end() ? &*CU : nullptr;
819 /// \brief Resolve the DIE attribute reference that has been
820 /// extracted in \p RefValue. The resulting DIE migh be in another
821 /// CompileUnit which is stored into \p ReferencedCU.
822 /// \returns null if resolving fails for any reason.
823 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
824 DWARFFormValue &RefValue, const DWARFUnit &Unit,
825 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
826 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
827 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
829 if ((RefCU = getUnitForOffset(RefOffset)))
830 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
833 reportWarning("could not find referenced DIE", &Unit, &DIE);
837 /// \brief Report a warning to the user, optionaly including
838 /// information about a specific \p DIE related to the warning.
839 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
840 const DWARFDebugInfoEntryMinimal *DIE) const {
841 StringRef Context = "<debug map>";
842 if (CurrentDebugObject)
843 Context = CurrentDebugObject->getObjectFilename();
844 warn(Warning, Context);
846 if (!Options.Verbose || !DIE)
849 errs() << " in DIE:\n";
850 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
854 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
855 if (Options.NoOutput)
858 Streamer = llvm::make_unique<DwarfStreamer>();
859 return Streamer->init(TheTriple, OutputFilename);
862 /// \brief Recursive helper to gather the child->parent relationships in the
863 /// original compile unit.
864 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
865 unsigned ParentIdx, CompileUnit &CU) {
866 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
867 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
869 if (DIE->hasChildren())
870 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
871 Child = Child->getSibling())
872 gatherDIEParents(Child, MyIdx, CU);
875 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
879 case dwarf::DW_TAG_subprogram:
880 case dwarf::DW_TAG_lexical_block:
881 case dwarf::DW_TAG_subroutine_type:
882 case dwarf::DW_TAG_structure_type:
883 case dwarf::DW_TAG_class_type:
884 case dwarf::DW_TAG_union_type:
887 llvm_unreachable("Invalid Tag");
890 void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
891 Units.reserve(Dwarf.getNumCompileUnits());
895 void DwarfLinker::endDebugObject() {
899 for (auto *Block : DIEBlocks)
901 for (auto *Loc : DIELocs)
909 /// \brief Iterate over the relocations of the given \p Section and
910 /// store the ones that correspond to debug map entries into the
911 /// ValidRelocs array.
912 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
913 const object::MachOObjectFile &Obj,
914 const DebugMapObject &DMO) {
916 Section.getContents(Contents);
917 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
919 for (const object::RelocationRef &Reloc : Section.relocations()) {
920 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
921 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
922 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
924 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
925 reportWarning(" unsupported relocation in debug_info section.");
928 uint32_t Offset = Offset64;
929 // Mach-o uses REL relocations, the addend is at the relocation offset.
930 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
932 auto Sym = Reloc.getSymbol();
933 if (Sym != Obj.symbol_end()) {
934 StringRef SymbolName;
935 if (Sym->getName(SymbolName)) {
936 reportWarning("error getting relocation symbol name.");
939 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
940 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
941 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
942 // Do not store the addend. The addend was the address of the
943 // symbol in the object file, the address in the binary that is
944 // stored in the debug map doesn't need to be offseted.
945 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
950 /// \brief Dispatch the valid relocation finding logic to the
951 /// appropriate handler depending on the object file format.
952 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
953 const object::ObjectFile &Obj,
954 const DebugMapObject &DMO) {
955 // Dispatch to the right handler depending on the file type.
956 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
957 findValidRelocsMachO(Section, *MachOObj, DMO);
959 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
961 if (ValidRelocs.empty())
964 // Sort the relocations by offset. We will walk the DIEs linearly in
965 // the file, this allows us to just keep an index in the relocation
966 // array that we advance during our walk, rather than resorting to
967 // some associative container. See DwarfLinker::NextValidReloc.
968 std::sort(ValidRelocs.begin(), ValidRelocs.end());
972 /// \brief Look for relocations in the debug_info section that match
973 /// entries in the debug map. These relocations will drive the Dwarf
974 /// link by indicating which DIEs refer to symbols present in the
976 /// \returns wether there are any valid relocations in the debug info.
977 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
978 const DebugMapObject &DMO) {
979 // Find the debug_info section.
980 for (const object::SectionRef &Section : Obj.sections()) {
981 StringRef SectionName;
982 Section.getName(SectionName);
983 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
984 if (SectionName != "debug_info")
986 return findValidRelocs(Section, Obj, DMO);
991 /// \brief Checks that there is a relocation against an actual debug
992 /// map entry between \p StartOffset and \p NextOffset.
994 /// This function must be called with offsets in strictly ascending
995 /// order because it never looks back at relocations it already 'went past'.
996 /// \returns true and sets Info.InDebugMap if it is the case.
997 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
998 CompileUnit::DIEInfo &Info) {
999 assert(NextValidReloc == 0 ||
1000 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1001 if (NextValidReloc >= ValidRelocs.size())
1004 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1006 // We might need to skip some relocs that we didn't consider. For
1007 // example the high_pc of a discarded DIE might contain a reloc that
1008 // is in the list because it actually corresponds to the start of a
1009 // function that is in the debug map.
1010 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1011 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1013 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1016 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1017 if (Options.Verbose)
1018 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1019 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1020 ValidReloc.Mapping->getValue().ObjectAddress,
1021 ValidReloc.Mapping->getValue().BinaryAddress);
1023 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
1025 ValidReloc.Mapping->getValue().ObjectAddress;
1026 Info.InDebugMap = true;
1030 /// \brief Get the starting and ending (exclusive) offset for the
1031 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1032 /// supposed to point to the position of the first attribute described
1034 /// \return [StartOffset, EndOffset) as a pair.
1035 static std::pair<uint32_t, uint32_t>
1036 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1037 unsigned Offset, const DWARFUnit &Unit) {
1038 DataExtractor Data = Unit.getDebugInfoExtractor();
1040 for (unsigned i = 0; i < Idx; ++i)
1041 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1043 uint32_t End = Offset;
1044 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1046 return std::make_pair(Offset, End);
1049 /// \brief Check if a variable describing DIE should be kept.
1050 /// \returns updated TraversalFlags.
1051 unsigned DwarfLinker::shouldKeepVariableDIE(
1052 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1053 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1054 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1056 // Global variables with constant value can always be kept.
1057 if (!(Flags & TF_InFunctionScope) &&
1058 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1059 MyInfo.InDebugMap = true;
1060 return Flags | TF_Keep;
1063 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1064 if (LocationIdx == -1U)
1067 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1068 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1069 uint32_t LocationOffset, LocationEndOffset;
1070 std::tie(LocationOffset, LocationEndOffset) =
1071 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1073 // See if there is a relocation to a valid debug map entry inside
1074 // this variable's location. The order is important here. We want to
1075 // always check in the variable has a valid relocation, so that the
1076 // DIEInfo is filled. However, we don't want a static variable in a
1077 // function to force us to keep the enclosing function.
1078 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1079 (Flags & TF_InFunctionScope))
1082 if (Options.Verbose)
1083 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1085 return Flags | TF_Keep;
1088 /// \brief Check if a function describing DIE should be kept.
1089 /// \returns updated TraversalFlags.
1090 unsigned DwarfLinker::shouldKeepSubprogramDIE(
1091 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1092 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1093 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1095 Flags |= TF_InFunctionScope;
1097 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1098 if (LowPcIdx == -1U)
1101 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1102 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1103 uint32_t LowPcOffset, LowPcEndOffset;
1104 std::tie(LowPcOffset, LowPcEndOffset) =
1105 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1108 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1109 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1110 if (LowPc == -1ULL ||
1111 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1114 if (Options.Verbose)
1115 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1119 DWARFFormValue HighPcValue;
1120 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1121 reportWarning("Function without high_pc. Range will be discarded.\n",
1127 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1128 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1130 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1131 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1134 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1138 /// \brief Check if a DIE should be kept.
1139 /// \returns updated TraversalFlags.
1140 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1142 CompileUnit::DIEInfo &MyInfo,
1144 switch (DIE.getTag()) {
1145 case dwarf::DW_TAG_constant:
1146 case dwarf::DW_TAG_variable:
1147 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1148 case dwarf::DW_TAG_subprogram:
1149 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1150 case dwarf::DW_TAG_module:
1151 case dwarf::DW_TAG_imported_module:
1152 case dwarf::DW_TAG_imported_declaration:
1153 case dwarf::DW_TAG_imported_unit:
1154 // We always want to keep these.
1155 return Flags | TF_Keep;
1161 /// \brief Mark the passed DIE as well as all the ones it depends on
1164 /// This function is called by lookForDIEsToKeep on DIEs that are
1165 /// newly discovered to be needed in the link. It recursively calls
1166 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1167 /// TraversalFlags to inform it that it's not doing the primary DIE
1169 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1170 CompileUnit::DIEInfo &MyInfo,
1171 const DebugMapObject &DMO,
1172 CompileUnit &CU, unsigned Flags) {
1173 const DWARFUnit &Unit = CU.getOrigUnit();
1176 // First mark all the parent chain as kept.
1177 unsigned AncestorIdx = MyInfo.ParentIdx;
1178 while (!CU.getInfo(AncestorIdx).Keep) {
1179 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1180 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1181 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1184 // Then we need to mark all the DIEs referenced by this DIE's
1185 // attributes as kept.
1186 DataExtractor Data = Unit.getDebugInfoExtractor();
1187 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1188 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1190 // Mark all DIEs referenced through atttributes as kept.
1191 for (const auto &AttrSpec : Abbrev->attributes()) {
1192 DWARFFormValue Val(AttrSpec.Form);
1194 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1195 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1199 Val.extractValue(Data, &Offset, &Unit);
1200 CompileUnit *ReferencedCU;
1201 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1202 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1203 TF_Keep | TF_DependencyWalk);
1207 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1208 /// keep. Store that information in \p CU's DIEInfo.
1210 /// This function is the entry point of the DIE selection
1211 /// algorithm. It is expected to walk the DIE tree in file order and
1212 /// (though the mediation of its helper) call hasValidRelocation() on
1213 /// each DIE that might be a 'root DIE' (See DwarfLinker class
1215 /// While walking the dependencies of root DIEs, this function is
1216 /// also called, but during these dependency walks the file order is
1217 /// not respected. The TF_DependencyWalk flag tells us which kind of
1218 /// traversal we are currently doing.
1219 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1220 const DebugMapObject &DMO, CompileUnit &CU,
1222 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1223 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1224 bool AlreadyKept = MyInfo.Keep;
1226 // If the Keep flag is set, we are marking a required DIE's
1227 // dependencies. If our target is already marked as kept, we're all
1229 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1232 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1233 // because it would screw up the relocation finding logic.
1234 if (!(Flags & TF_DependencyWalk))
1235 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1237 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1238 if (!AlreadyKept && (Flags & TF_Keep))
1239 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1241 // The TF_ParentWalk flag tells us that we are currently walking up
1242 // the parent chain of a required DIE, and we don't want to mark all
1243 // the children of the parents as kept (consider for example a
1244 // DW_TAG_namespace node in the parent chain). There are however a
1245 // set of DIE types for which we want to ignore that directive and still
1246 // walk their children.
1247 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1248 Flags &= ~TF_ParentWalk;
1250 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1253 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1254 Child = Child->getSibling())
1255 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1258 /// \brief Assign an abbreviation numer to \p Abbrev.
1260 /// Our DIEs get freed after every DebugMapObject has been processed,
1261 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1262 /// the instances hold by the DIEs. When we encounter an abbreviation
1263 /// that we don't know, we create a permanent copy of it.
1264 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1265 // Check the set for priors.
1266 FoldingSetNodeID ID;
1269 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1271 // If it's newly added.
1273 // Assign existing abbreviation number.
1274 Abbrev.setNumber(InSet->getNumber());
1276 // Add to abbreviation list.
1277 Abbreviations.push_back(
1278 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1279 for (const auto &Attr : Abbrev.getData())
1280 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1281 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1282 // Assign the unique abbreviation number.
1283 Abbrev.setNumber(Abbreviations.size());
1284 Abbreviations.back()->setNumber(Abbreviations.size());
1288 /// \brief Clone a string attribute described by \p AttrSpec and add
1290 /// \returns the size of the new attribute.
1291 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1292 const DWARFFormValue &Val,
1293 const DWARFUnit &U) {
1294 // Switch everything to out of line strings.
1295 const char *String = *Val.getAsCString(&U);
1296 unsigned Offset = StringPool.getStringOffset(String);
1297 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1298 new (DIEAlloc) DIEInteger(Offset));
1302 /// \brief Clone an attribute referencing another DIE and add
1304 /// \returns the size of the new attribute.
1305 unsigned DwarfLinker::cloneDieReferenceAttribute(
1306 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1307 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1308 CompileUnit &Unit) {
1309 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
1310 DIE *NewRefDie = nullptr;
1311 CompileUnit *RefUnit = nullptr;
1312 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1314 if (!(RefUnit = getUnitForOffset(Ref)) ||
1315 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1316 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1317 if (!AttributeString)
1318 AttributeString = "DW_AT_???";
1319 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1321 &Unit.getOrigUnit(), &InputDIE);
1325 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1326 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1327 if (!RefInfo.Clone) {
1328 assert(Ref > InputDIE.getOffset());
1329 // We haven't cloned this DIE yet. Just create an empty one and
1330 // store it. It'll get really cloned when we process it.
1331 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1333 NewRefDie = RefInfo.Clone;
1335 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1336 // We cannot currently rely on a DIEEntry to emit ref_addr
1337 // references, because the implementation calls back to DwarfDebug
1338 // to find the unit offset. (We don't have a DwarfDebug)
1339 // FIXME: we should be able to design DIEEntry reliance on
1342 if (Ref < InputDIE.getOffset()) {
1343 // We must have already cloned that DIE.
1344 uint32_t NewRefOffset =
1345 RefUnit->getStartOffset() + NewRefDie->getOffset();
1346 Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1348 // A forward reference. Note and fixup later.
1349 Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
1350 Unit.noteForwardReference(NewRefDie, RefUnit, Attr);
1352 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1357 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1358 new (DIEAlloc) DIEEntry(*NewRefDie));
1362 /// \brief Clone an attribute of block form (locations, constants) and add
1364 /// \returns the size of the new attribute.
1365 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1366 const DWARFFormValue &Val,
1367 unsigned AttrSize) {
1370 DIELoc *Loc = nullptr;
1371 DIEBlock *Block = nullptr;
1372 // Just copy the block data over.
1373 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1374 Loc = new (DIEAlloc) DIELoc();
1375 DIELocs.push_back(Loc);
1377 Block = new (DIEAlloc) DIEBlock();
1378 DIEBlocks.push_back(Block);
1380 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1381 Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1382 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1383 for (auto Byte : Bytes)
1384 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1385 new (DIEAlloc) DIEInteger(Byte));
1386 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1387 // the DIE class, this if could be replaced by
1388 // Attr->setSize(Bytes.size()).
1391 Loc->ComputeSize(&Streamer->getAsmPrinter());
1393 Block->ComputeSize(&Streamer->getAsmPrinter());
1395 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1400 /// \brief Clone an address attribute and add it to \p Die.
1401 /// \returns the size of the new attribute.
1402 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1403 const DWARFFormValue &Val,
1404 const CompileUnit &Unit,
1405 AttributesInfo &Info) {
1406 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
1407 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1408 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1409 Die.getTag() == dwarf::DW_TAG_lexical_block)
1410 Addr += Info.PCOffset;
1411 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1412 Addr = Unit.getLowPc();
1413 if (Addr == UINT64_MAX)
1416 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1417 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1418 if (uint64_t HighPc = Unit.getHighPc())
1423 // If we have a high_pc recorded for the input DIE, use
1424 // it. Otherwise (when no relocations where applied) just use the
1425 // one we just decoded.
1426 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1429 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1430 static_cast<dwarf::Form>(AttrSpec.Form),
1431 new (DIEAlloc) DIEInteger(Addr));
1432 return Unit.getOrigUnit().getAddressByteSize();
1435 /// \brief Clone a scalar attribute and add it to \p Die.
1436 /// \returns the size of the new attribute.
1437 unsigned DwarfLinker::cloneScalarAttribute(
1438 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
1439 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize) {
1441 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1442 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1443 if (Unit.getLowPc() == -1ULL)
1445 // Dwarf >= 4 high_pc is an size, not an address.
1446 Value = Unit.getHighPc() - Unit.getLowPc();
1447 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1448 Value = *Val.getAsSectionOffset();
1449 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1450 Value = *Val.getAsSignedConstant();
1451 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1452 Value = *OptionalValue;
1454 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1455 &Unit.getOrigUnit(), &InputDIE);
1458 DIEInteger *Attr = new (DIEAlloc) DIEInteger(Value);
1459 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
1460 Unit.noteRangeAttribute(Die, Attr);
1461 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1466 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1467 /// value \p Val, and add it to \p Die.
1468 /// \returns the size of the cloned attribute.
1469 unsigned DwarfLinker::cloneAttribute(DIE &Die,
1470 const DWARFDebugInfoEntryMinimal &InputDIE,
1472 const DWARFFormValue &Val,
1473 const AttributeSpec AttrSpec,
1474 unsigned AttrSize, AttributesInfo &Info) {
1475 const DWARFUnit &U = Unit.getOrigUnit();
1477 switch (AttrSpec.Form) {
1478 case dwarf::DW_FORM_strp:
1479 case dwarf::DW_FORM_string:
1480 return cloneStringAttribute(Die, AttrSpec, Val, U);
1481 case dwarf::DW_FORM_ref_addr:
1482 case dwarf::DW_FORM_ref1:
1483 case dwarf::DW_FORM_ref2:
1484 case dwarf::DW_FORM_ref4:
1485 case dwarf::DW_FORM_ref8:
1486 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1488 case dwarf::DW_FORM_block:
1489 case dwarf::DW_FORM_block1:
1490 case dwarf::DW_FORM_block2:
1491 case dwarf::DW_FORM_block4:
1492 case dwarf::DW_FORM_exprloc:
1493 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1494 case dwarf::DW_FORM_addr:
1495 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1496 case dwarf::DW_FORM_data1:
1497 case dwarf::DW_FORM_data2:
1498 case dwarf::DW_FORM_data4:
1499 case dwarf::DW_FORM_data8:
1500 case dwarf::DW_FORM_udata:
1501 case dwarf::DW_FORM_sdata:
1502 case dwarf::DW_FORM_sec_offset:
1503 case dwarf::DW_FORM_flag:
1504 case dwarf::DW_FORM_flag_present:
1505 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize);
1507 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1514 /// \brief Apply the valid relocations found by findValidRelocs() to
1515 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
1516 /// in the debug_info section.
1518 /// Like for findValidRelocs(), this function must be called with
1519 /// monotonic \p BaseOffset values.
1521 /// \returns wether any reloc has been applied.
1522 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
1523 uint32_t BaseOffset, bool isLittleEndian) {
1524 assert((NextValidReloc == 0 ||
1525 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1526 "BaseOffset should only be increasing.");
1527 if (NextValidReloc >= ValidRelocs.size())
1530 // Skip relocs that haven't been applied.
1531 while (NextValidReloc < ValidRelocs.size() &&
1532 ValidRelocs[NextValidReloc].Offset < BaseOffset)
1535 bool Applied = false;
1536 uint64_t EndOffset = BaseOffset + Data.size();
1537 while (NextValidReloc < ValidRelocs.size() &&
1538 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1539 ValidRelocs[NextValidReloc].Offset < EndOffset) {
1540 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1541 assert(ValidReloc.Offset - BaseOffset < Data.size());
1542 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1544 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1545 Value += ValidReloc.Addend;
1546 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1547 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
1548 Buf[i] = uint8_t(Value >> (Index * 8));
1550 assert(ValidReloc.Size <= sizeof(Buf));
1551 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1558 /// \brief Recursively clone \p InputDIE's subtrees that have been
1559 /// selected to appear in the linked output.
1561 /// \param OutOffset is the Offset where the newly created DIE will
1562 /// lie in the linked compile unit.
1564 /// \returns the cloned DIE object or null if nothing was selected.
1565 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
1566 CompileUnit &Unit, int64_t PCOffset,
1567 uint32_t OutOffset) {
1568 DWARFUnit &U = Unit.getOrigUnit();
1569 unsigned Idx = U.getDIEIndex(&InputDIE);
1570 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1572 // Should the DIE appear in the output?
1573 if (!Unit.getInfo(Idx).Keep)
1576 uint32_t Offset = InputDIE.getOffset();
1577 // The DIE might have been already created by a forward reference
1578 // (see cloneDieReferenceAttribute()).
1579 DIE *Die = Info.Clone;
1581 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
1582 assert(Die->getTag() == InputDIE.getTag());
1583 Die->setOffset(OutOffset);
1585 // Extract and clone every attribute.
1586 DataExtractor Data = U.getDebugInfoExtractor();
1587 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
1588 AttributesInfo AttrInfo;
1590 // We could copy the data only if we need to aply a relocation to
1591 // it. After testing, it seems there is no performance downside to
1592 // doing the copy unconditionally, and it makes the code simpler.
1593 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1594 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1595 // Modify the copy with relocated addresses.
1596 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
1597 // If we applied relocations, we store the value of high_pc that was
1598 // potentially stored in the input DIE. If high_pc is an address
1599 // (Dwarf version == 2), then it might have been relocated to a
1600 // totally unrelated value (because the end address in the object
1601 // file might be start address of another function which got moved
1602 // independantly by the linker). The computation of the actual
1603 // high_pc value is done in cloneAddressAttribute().
1604 AttrInfo.OrigHighPc =
1605 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
1608 // Reset the Offset to 0 as we will be working on the local copy of
1612 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1613 Offset += getULEB128Size(Abbrev->getCode());
1615 // We are entering a subprogram. Get and propagate the PCOffset.
1616 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1617 PCOffset = Info.AddrAdjust;
1618 AttrInfo.PCOffset = PCOffset;
1620 for (const auto &AttrSpec : Abbrev->attributes()) {
1621 DWARFFormValue Val(AttrSpec.Form);
1622 uint32_t AttrSize = Offset;
1623 Val.extractValue(Data, &Offset, &U);
1624 AttrSize = Offset - AttrSize;
1627 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
1630 DIEAbbrev &NewAbbrev = Die->getAbbrev();
1631 // If a scope DIE is kept, we must have kept at least one child. If
1632 // it's not the case, we'll just be emitting one wasteful end of
1633 // children marker, but things won't break.
1634 if (InputDIE.hasChildren())
1635 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1636 // Assign a permanent abbrev number
1637 AssignAbbrev(Die->getAbbrev());
1639 // Add the size of the abbreviation number to the output offset.
1640 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1642 if (!Abbrev->hasChildren()) {
1644 Die->setSize(OutOffset - Die->getOffset());
1648 // Recursively clone children.
1649 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1650 Child = Child->getSibling()) {
1651 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
1652 Die->addChild(std::unique_ptr<DIE>(Clone));
1653 OutOffset = Clone->getOffset() + Clone->getSize();
1657 // Account for the end of children marker.
1658 OutOffset += sizeof(int8_t);
1660 Die->setSize(OutOffset - Die->getOffset());
1664 /// \brief Patch the input object file relevant debug_ranges entries
1665 /// and emit them in the output file. Update the relevant attributes
1666 /// to point at the new entries.
1667 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
1668 DWARFContext &OrigDwarf) const {
1669 DWARFDebugRangeList RangeList;
1670 const auto &FunctionRanges = Unit.getFunctionRanges();
1671 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
1672 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
1673 OrigDwarf.isLittleEndian(), AddressSize);
1674 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1675 DWARFUnit &OrigUnit = Unit.getOrigUnit();
1676 const auto *OrigUnitDie = OrigUnit.getCompileUnitDIE(false);
1677 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
1678 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1679 // Ranges addresses are based on the unit's low_pc. Compute the
1680 // offset we need to apply to adapt to the the new unit's low_pc.
1681 int64_t UnitPcOffset = 0;
1682 if (OrigLowPc != -1ULL)
1683 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
1685 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
1686 uint32_t Offset = RangeAttribute->getValue();
1687 RangeAttribute->setValue(Streamer->getRangesSectionSize());
1688 RangeList.extract(RangeExtractor, &Offset);
1689 const auto &Entries = RangeList.getEntries();
1690 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
1692 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
1693 First.StartAddress >= CurrRange.stop()) {
1694 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
1695 if (CurrRange == InvalidRange ||
1696 CurrRange.start() > First.StartAddress + OrigLowPc) {
1697 reportWarning("no mapping for range.");
1702 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
1707 /// \brief Generate the debug_ranges entries for \p Unit's
1708 /// DW_AT_ranges attribute if there is one.
1709 /// FIXME: this could actually be done right in patchRangesForUnit,
1710 /// but for the sake of initial bit-for-bit compatibility with legacy
1711 /// dsymutil, we have to do it in a delayed pass.
1712 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
1713 if (DIEInteger *Attr = Unit.getUnitRangesAttribute()) {
1714 Attr->setValue(Streamer->getRangesSectionSize());
1715 Streamer->emitUnitRangesEntries(Unit);
1719 bool DwarfLinker::link(const DebugMap &Map) {
1721 if (Map.begin() == Map.end()) {
1722 errs() << "Empty debug map.\n";
1726 if (!createStreamer(Map.getTriple(), OutputFilename))
1729 // Size of the DIEs (and headers) generated for the linked output.
1730 uint64_t OutputDebugInfoSize = 0;
1732 for (const auto &Obj : Map.objects()) {
1733 CurrentDebugObject = Obj.get();
1735 if (Options.Verbose)
1736 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1737 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1738 if (std::error_code EC = ErrOrObj.getError()) {
1739 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
1743 // Look for relocations that correspond to debug map entries.
1744 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
1745 if (Options.Verbose)
1746 outs() << "No valid relocations found. Skipping.\n";
1750 // Setup access to the debug info.
1751 DWARFContextInMemory DwarfContext(*ErrOrObj);
1752 startDebugObject(DwarfContext);
1754 // In a first phase, just read in the debug info and store the DIE
1755 // parent links that we will use during the next phase.
1756 for (const auto &CU : DwarfContext.compile_units()) {
1757 auto *CUDie = CU->getCompileUnitDIE(false);
1758 if (Options.Verbose) {
1759 outs() << "Input compilation unit:";
1760 CUDie->dump(outs(), CU.get(), 0);
1762 Units.emplace_back(*CU);
1763 gatherDIEParents(CUDie, 0, Units.back());
1766 // Then mark all the DIEs that need to be present in the linked
1767 // output and collect some information about them. Note that this
1768 // loop can not be merged with the previous one becaue cross-cu
1769 // references require the ParentIdx to be setup for every CU in
1770 // the object file before calling this.
1771 for (auto &CurrentUnit : Units)
1772 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1775 // The calls to applyValidRelocs inside cloneDIE will walk the
1776 // reloc array again (in the same way findValidRelocsInDebugInfo()
1777 // did). We need to reset the NextValidReloc index to the beginning.
1780 // Construct the output DIE tree by cloning the DIEs we chose to
1781 // keep above. If there are no valid relocs, then there's nothing
1783 if (!ValidRelocs.empty())
1784 for (auto &CurrentUnit : Units) {
1785 const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
1786 CurrentUnit.setStartOffset(OutputDebugInfoSize);
1787 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
1788 11 /* Unit Header size */);
1789 CurrentUnit.setOutputUnitDIE(OutputDIE);
1790 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
1791 if (!OutputDIE || Options.NoOutput)
1793 patchRangesForUnit(CurrentUnit, DwarfContext);
1796 // Emit all the compile unit's debug information.
1797 if (!ValidRelocs.empty() && !Options.NoOutput)
1798 for (auto &CurrentUnit : Units) {
1799 generateUnitRanges(CurrentUnit);
1800 CurrentUnit.fixupForwardReferences();
1801 Streamer->emitCompileUnitHeader(CurrentUnit);
1802 if (!CurrentUnit.getOutputUnitDIE())
1804 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1807 // Clean-up before starting working on the next object.
1811 // Emit everything that's global.
1812 if (!Options.NoOutput) {
1813 Streamer->emitAbbrevs(Abbreviations);
1814 Streamer->emitStrings(StringPool);
1817 return Options.NoOutput ? true : Streamer->finish();
1821 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1822 const LinkOptions &Options) {
1823 DwarfLinker Linker(OutputFilename, Options);
1824 return Linker.link(DM);