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, unsigned ID)
76 : OrigUnit(OrigUnit), ID(ID), 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 unsigned getUniqueID() const { return ID; }
94 DIE *getOutputUnitDIE() const { return CUDie.get(); }
95 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
97 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
98 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
100 uint64_t getStartOffset() const { return StartOffset; }
101 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
102 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
104 uint64_t getLowPc() const { return LowPc; }
105 uint64_t getHighPc() const { return HighPc; }
107 DIEInteger *getUnitRangesAttribute() const { return UnitRangeAttribute; }
108 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
109 const std::vector<DIEInteger *> &getRangesAttributes() const {
110 return RangeAttributes;
113 /// \brief Compute the end offset for this unit. Must be
114 /// called after the CU's DIEs have been cloned.
115 /// \returns the next unit offset (which is also the current
116 /// debug_info section size).
117 uint64_t computeNextUnitOffset();
119 /// \brief Keep track of a forward reference to DIE \p Die in \p
120 /// RefUnit by \p Attr. The attribute should be fixed up later to
121 /// point to the absolute offset of \p Die in the debug_info section.
122 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
125 /// \brief Apply all fixups recored by noteForwardReference().
126 void fixupForwardReferences();
128 /// \brief Add a function range [\p LowPC, \p HighPC) that is
129 /// relocatad by applying offset \p PCOffset.
130 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
132 /// \brief Keep track of a DW_AT_range attribute that we will need to
134 void noteRangeAttribute(const DIE &Die, DIEInteger *Attr);
139 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
140 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
142 uint64_t StartOffset;
143 uint64_t NextUnitOffset;
148 /// \brief A list of attributes to fixup with the absolute offset of
149 /// a DIE in the debug_info section.
151 /// The offsets for the attributes in this array couldn't be set while
152 /// cloning because for cross-cu forward refences the target DIE's
153 /// offset isn't known you emit the reference attribute.
154 std::vector<std::tuple<DIE *, const CompileUnit *, DIEInteger *>>
155 ForwardDIEReferences;
157 FunctionIntervals::Allocator RangeAlloc;
158 /// \brief The ranges in that interval map are the PC ranges for
159 /// functions in this unit, associated with the PC offset to apply
160 /// to the addresses to get the linked address.
161 FunctionIntervals Ranges;
163 /// \brief DW_AT_ranges attributes to patch after we have gathered
164 /// all the unit's function addresses.
166 std::vector<DIEInteger *> RangeAttributes;
167 DIEInteger *UnitRangeAttribute;
171 uint64_t CompileUnit::computeNextUnitOffset() {
172 NextUnitOffset = StartOffset + 11 /* Header size */;
173 // The root DIE might be null, meaning that the Unit had nothing to
174 // contribute to the linked output. In that case, we will emit the
175 // unit header without any actual DIE.
177 NextUnitOffset += CUDie->getSize();
178 return NextUnitOffset;
181 /// \brief Keep track of a forward cross-cu reference from this unit
182 /// to \p Die that lives in \p RefUnit.
183 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
185 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
188 /// \brief Apply all fixups recorded by noteForwardReference().
189 void CompileUnit::fixupForwardReferences() {
190 for (const auto &Ref : ForwardDIEReferences) {
192 const CompileUnit *RefUnit;
194 std::tie(RefDie, RefUnit, Attr) = Ref;
195 Attr->setValue(RefDie->getOffset() + RefUnit->getStartOffset());
199 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
201 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
202 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
203 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
206 void CompileUnit::noteRangeAttribute(const DIE &Die, DIEInteger *Attr) {
207 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
208 RangeAttributes.push_back(Attr);
210 UnitRangeAttribute = Attr;
213 /// \brief A string table that doesn't need relocations.
215 /// We are doing a final link, no need for a string table that
216 /// has relocation entries for every reference to it. This class
217 /// provides this ablitity by just associating offsets with
219 class NonRelocatableStringpool {
221 /// \brief Entries are stored into the StringMap and simply linked
222 /// together through the second element of this pair in order to
223 /// keep track of insertion order.
224 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
227 NonRelocatableStringpool()
228 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
229 // Legacy dsymutil puts an empty string at the start of the line
234 /// \brief Get the offset of string \p S in the string table. This
235 /// can insert a new element or return the offset of a preexisitng
237 uint32_t getStringOffset(StringRef S);
239 /// \brief Get permanent storage for \p S (but do not necessarily
240 /// emit \p S in the output section).
241 /// \returns The StringRef that points to permanent storage to use
242 /// in place of \p S.
243 StringRef internString(StringRef S);
245 // \brief Return the first entry of the string table.
246 const MapTy::MapEntryTy *getFirstEntry() const {
247 return getNextEntry(&Sentinel);
250 // \brief Get the entry following \p E in the string table or null
251 // if \p E was the last entry.
252 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
253 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
256 uint64_t getSize() { return CurrentEndOffset; }
260 uint32_t CurrentEndOffset;
261 MapTy::MapEntryTy Sentinel, *Last;
264 /// \brief Get the offset of string \p S in the string table. This
265 /// can insert a new element or return the offset of a preexisitng
267 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
268 if (S.empty() && !Strings.empty())
271 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
275 // A non-empty string can't be at offset 0, so if we have an entry
276 // with a 0 offset, it must be a previously interned string.
277 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
278 if (Inserted || It->getValue().first == 0) {
279 // Set offset and chain at the end of the entries list.
280 It->getValue().first = CurrentEndOffset;
281 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
282 Last->getValue().second = &*It;
285 return It->getValue().first;
288 /// \brief Put \p S into the StringMap so that it gets permanent
289 /// storage, but do not actually link it in the chain of elements
290 /// that go into the output section. A latter call to
291 /// getStringOffset() with the same string will chain it though.
292 StringRef NonRelocatableStringpool::internString(StringRef S) {
293 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
294 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
295 return InsertResult.first->getKey();
298 /// \brief The Dwarf streaming logic
300 /// All interactions with the MC layer that is used to build the debug
301 /// information binary representation are handled in this class.
302 class DwarfStreamer {
303 /// \defgroup MCObjects MC layer objects constructed by the streamer
305 std::unique_ptr<MCRegisterInfo> MRI;
306 std::unique_ptr<MCAsmInfo> MAI;
307 std::unique_ptr<MCObjectFileInfo> MOFI;
308 std::unique_ptr<MCContext> MC;
309 MCAsmBackend *MAB; // Owned by MCStreamer
310 std::unique_ptr<MCInstrInfo> MII;
311 std::unique_ptr<MCSubtargetInfo> MSTI;
312 MCCodeEmitter *MCE; // Owned by MCStreamer
313 MCStreamer *MS; // Owned by AsmPrinter
314 std::unique_ptr<TargetMachine> TM;
315 std::unique_ptr<AsmPrinter> Asm;
318 /// \brief the file we stream the linked Dwarf to.
319 std::unique_ptr<raw_fd_ostream> OutFile;
321 uint32_t RangesSectionSize;
324 /// \brief Actually create the streamer and the ouptut file.
326 /// This could be done directly in the constructor, but it feels
327 /// more natural to handle errors through return value.
328 bool init(Triple TheTriple, StringRef OutputFilename);
330 /// \brief Dump the file to the disk.
333 AsmPrinter &getAsmPrinter() const { return *Asm; }
335 /// \brief Set the current output section to debug_info and change
336 /// the MC Dwarf version to \p DwarfVersion.
337 void switchToDebugInfoSection(unsigned DwarfVersion);
339 /// \brief Emit the compilation unit header for \p Unit in the
340 /// debug_info section.
342 /// As a side effect, this also switches the current Dwarf version
343 /// of the MC layer to the one of U.getOrigUnit().
344 void emitCompileUnitHeader(CompileUnit &Unit);
346 /// \brief Recursively emit the DIE tree rooted at \p Die.
347 void emitDIE(DIE &Die);
349 /// \brief Emit the abbreviation table \p Abbrevs to the
350 /// debug_abbrev section.
351 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
353 /// \brief Emit the string table described by \p Pool.
354 void emitStrings(const NonRelocatableStringpool &Pool);
356 /// \brief Emit debug_ranges for \p FuncRange by translating the
357 /// original \p Entries.
358 void emitRangesEntries(
359 int64_t UnitPcOffset, uint64_t OrigLowPc,
360 FunctionIntervals::const_iterator FuncRange,
361 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
362 unsigned AddressSize);
364 /// \brief Emit debug_aranges entries for \p Unit and if \p
365 /// DoRangesSection is true, also emit the debug_ranges entries for
366 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
367 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
369 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
372 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
373 std::string ErrorStr;
374 std::string TripleName;
375 StringRef Context = "dwarf streamer init";
378 const Target *TheTarget =
379 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
381 return error(ErrorStr, Context);
382 TripleName = TheTriple.getTriple();
384 // Create all the MC Objects.
385 MRI.reset(TheTarget->createMCRegInfo(TripleName));
387 return error(Twine("no register info for target ") + TripleName, Context);
389 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
391 return error("no asm info for target " + TripleName, Context);
393 MOFI.reset(new MCObjectFileInfo);
394 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
395 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
398 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
400 return error("no asm backend for target " + TripleName, Context);
402 MII.reset(TheTarget->createMCInstrInfo());
404 return error("no instr info info for target " + TripleName, Context);
406 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
408 return error("no subtarget info for target " + TripleName, Context);
410 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
412 return error("no code emitter for target " + TripleName, Context);
414 // Create the output file.
417 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
419 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
421 MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
424 return error("no object streamer for target " + TripleName, Context);
426 // Finally create the AsmPrinter we'll use to emit the DIEs.
427 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
429 return error("no target machine for target " + TripleName, Context);
431 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
433 return error("no asm printer for target " + TripleName, Context);
435 RangesSectionSize = 0;
440 bool DwarfStreamer::finish() {
445 /// \brief Set the current output section to debug_info and change
446 /// the MC Dwarf version to \p DwarfVersion.
447 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
448 MS->SwitchSection(MOFI->getDwarfInfoSection());
449 MC->setDwarfVersion(DwarfVersion);
452 /// \brief Emit the compilation unit header for \p Unit in the
453 /// debug_info section.
455 /// A Dwarf scetion header is encoded as:
456 /// uint32_t Unit length (omiting this field)
458 /// uint32_t Abbreviation table offset
459 /// uint8_t Address size
461 /// Leading to a total of 11 bytes.
462 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
463 unsigned Version = Unit.getOrigUnit().getVersion();
464 switchToDebugInfoSection(Version);
466 // Emit size of content not including length itself. The size has
467 // already been computed in CompileUnit::computeOffsets(). Substract
468 // 4 to that size to account for the length field.
469 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
470 Asm->EmitInt16(Version);
471 // We share one abbreviations table across all units so it's always at the
472 // start of the section.
474 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
477 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
478 /// for the linked Dwarf file.
479 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
480 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
481 Asm->emitDwarfAbbrevs(Abbrevs);
484 /// \brief Recursively emit the DIE tree rooted at \p Die.
485 void DwarfStreamer::emitDIE(DIE &Die) {
486 MS->SwitchSection(MOFI->getDwarfInfoSection());
487 Asm->emitDwarfDIE(Die);
490 /// \brief Emit the debug_str section stored in \p Pool.
491 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
492 Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
493 for (auto *Entry = Pool.getFirstEntry(); Entry;
494 Entry = Pool.getNextEntry(Entry))
495 Asm->OutStreamer.EmitBytes(
496 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
499 /// \brief Emit the debug_range section contents for \p FuncRange by
500 /// translating the original \p Entries. The debug_range section
501 /// format is totally trivial, consisting just of pairs of address
502 /// sized addresses describing the ranges.
503 void DwarfStreamer::emitRangesEntries(
504 int64_t UnitPcOffset, uint64_t OrigLowPc,
505 FunctionIntervals::const_iterator FuncRange,
506 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
507 unsigned AddressSize) {
508 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
510 // Offset each range by the right amount.
511 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
512 for (const auto &Range : Entries) {
513 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
514 warn("unsupported base address selection operation",
515 "emitting debug_ranges");
518 // Do not emit empty ranges.
519 if (Range.StartAddress == Range.EndAddress)
522 // All range entries should lie in the function range.
523 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
524 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
525 warn("inconsistent range data.", "emitting debug_ranges");
526 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
527 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
528 RangesSectionSize += 2 * AddressSize;
531 // Add the terminator entry.
532 MS->EmitIntValue(0, AddressSize);
533 MS->EmitIntValue(0, AddressSize);
534 RangesSectionSize += 2 * AddressSize;
537 /// \brief Emit the debug_aranges contribution of a unit and
538 /// if \p DoDebugRanges is true the debug_range contents for a
539 /// compile_unit level DW_AT_ranges attribute (Which are basically the
540 /// same thing with a different base address).
541 /// Just aggregate all the ranges gathered inside that unit.
542 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
543 bool DoDebugRanges) {
544 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
545 // Gather the ranges in a vector, so that we can simplify them. The
546 // IntervalMap will have coalesced the non-linked ranges, but here
547 // we want to coalesce the linked addresses.
548 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
549 const auto &FunctionRanges = Unit.getFunctionRanges();
550 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
551 Range != End; ++Range)
552 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
553 Range.stop() + Range.value()));
555 // The object addresses where sorted, but again, the linked
556 // addresses might end up in a different order.
557 std::sort(Ranges.begin(), Ranges.end());
559 if (!Ranges.empty()) {
560 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
562 MCSymbol *BeginLabel = Asm->GetTempSymbol("Barange", Unit.getUniqueID());
563 MCSymbol *EndLabel = Asm->GetTempSymbol("Earange", Unit.getUniqueID());
565 unsigned HeaderSize =
566 sizeof(int32_t) + // Size of contents (w/o this field
567 sizeof(int16_t) + // DWARF ARange version number
568 sizeof(int32_t) + // Offset of CU in the .debug_info section
569 sizeof(int8_t) + // Pointer Size (in bytes)
570 sizeof(int8_t); // Segment Size (in bytes)
572 unsigned TupleSize = AddressSize * 2;
573 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
575 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
576 Asm->OutStreamer.EmitLabel(BeginLabel);
577 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
578 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
579 Asm->EmitInt8(AddressSize); // Address size
580 Asm->EmitInt8(0); // Segment size
582 Asm->OutStreamer.EmitFill(Padding, 0x0);
584 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
586 uint64_t RangeStart = Range->first;
587 MS->EmitIntValue(RangeStart, AddressSize);
588 while ((Range + 1) != End && Range->second == (Range + 1)->first)
590 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
594 Asm->OutStreamer.EmitIntValue(0, AddressSize);
595 Asm->OutStreamer.EmitIntValue(0, AddressSize);
596 Asm->OutStreamer.EmitLabel(EndLabel);
602 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
603 // Offset each range by the right amount.
604 int64_t PcOffset = -Unit.getLowPc();
605 // Emit coalesced ranges.
606 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
607 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
608 while (Range + 1 != End && Range->second == (Range + 1)->first)
610 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
611 RangesSectionSize += 2 * AddressSize;
614 // Add the terminator entry.
615 MS->EmitIntValue(0, AddressSize);
616 MS->EmitIntValue(0, AddressSize);
617 RangesSectionSize += 2 * AddressSize;
620 /// \brief The core of the Dwarf linking logic.
622 /// The link of the dwarf information from the object files will be
623 /// driven by the selection of 'root DIEs', which are DIEs that
624 /// describe variables or functions that are present in the linked
625 /// binary (and thus have entries in the debug map). All the debug
626 /// information that will be linked (the DIEs, but also the line
627 /// tables, ranges, ...) is derived from that set of root DIEs.
629 /// The root DIEs are identified because they contain relocations that
630 /// correspond to a debug map entry at specific places (the low_pc for
631 /// a function, the location for a variable). These relocations are
632 /// called ValidRelocs in the DwarfLinker and are gathered as a very
633 /// first step when we start processing a DebugMapObject.
636 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
637 : OutputFilename(OutputFilename), Options(Options),
638 BinHolder(Options.Verbose) {}
641 for (auto *Abbrev : Abbreviations)
645 /// \brief Link the contents of the DebugMap.
646 bool link(const DebugMap &);
649 /// \brief Called at the start of a debug object link.
650 void startDebugObject(DWARFContext &);
652 /// \brief Called at the end of a debug object link.
653 void endDebugObject();
655 /// \defgroup FindValidRelocations Translate debug map into a list
656 /// of relevant relocations
663 const DebugMapObject::DebugMapEntry *Mapping;
665 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
666 const DebugMapObject::DebugMapEntry *Mapping)
667 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
669 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
672 /// \brief The valid relocations for the current DebugMapObject.
673 /// This vector is sorted by relocation offset.
674 std::vector<ValidReloc> ValidRelocs;
676 /// \brief Index into ValidRelocs of the next relocation to
677 /// consider. As we walk the DIEs in acsending file offset and as
678 /// ValidRelocs is sorted by file offset, keeping this index
679 /// uptodate is all we have to do to have a cheap lookup during the
680 /// root DIE selection and during DIE cloning.
681 unsigned NextValidReloc;
683 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
684 const DebugMapObject &DMO);
686 bool findValidRelocs(const object::SectionRef &Section,
687 const object::ObjectFile &Obj,
688 const DebugMapObject &DMO);
690 void findValidRelocsMachO(const object::SectionRef &Section,
691 const object::MachOObjectFile &Obj,
692 const DebugMapObject &DMO);
695 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
698 /// \brief Recursively walk the \p DIE tree and look for DIEs to
699 /// keep. Store that information in \p CU's DIEInfo.
700 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
701 const DebugMapObject &DMO, CompileUnit &CU,
704 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
706 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
707 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
708 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
709 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
712 /// \brief Mark the passed DIE as well as all the ones it depends on
714 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
715 CompileUnit::DIEInfo &MyInfo,
716 const DebugMapObject &DMO, CompileUnit &CU,
719 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
720 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
723 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
725 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
727 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
729 CompileUnit::DIEInfo &MyInfo,
732 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
733 CompileUnit::DIEInfo &Info);
736 /// \defgroup Linking Methods used to link the debug information
739 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
740 /// where useless (as decided by lookForDIEsToKeep()) bits have been
741 /// stripped out and addresses have been rewritten according to the
744 /// \param OutOffset is the offset the cloned DIE in the output
746 /// \param PCOffset (while cloning a function scope) is the offset
747 /// applied to the entry point of the function to get the linked address.
749 /// \returns the root of the cloned tree.
750 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
751 int64_t PCOffset, uint32_t OutOffset);
753 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
755 /// \brief Information gathered and exchanged between the various
756 /// clone*Attributes helpers about the attributes of a particular DIE.
757 struct AttributesInfo {
758 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
759 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
761 AttributesInfo() : OrigHighPc(0), PCOffset(0) {}
764 /// \brief Helper for cloneDIE.
765 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
766 CompileUnit &U, const DWARFFormValue &Val,
767 const AttributeSpec AttrSpec, unsigned AttrSize,
768 AttributesInfo &AttrInfo);
770 /// \brief Helper for cloneDIE.
771 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
772 const DWARFFormValue &Val, const DWARFUnit &U);
774 /// \brief Helper for cloneDIE.
776 cloneDieReferenceAttribute(DIE &Die,
777 const DWARFDebugInfoEntryMinimal &InputDIE,
778 AttributeSpec AttrSpec, unsigned AttrSize,
779 const DWARFFormValue &Val, CompileUnit &Unit);
781 /// \brief Helper for cloneDIE.
782 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
783 const DWARFFormValue &Val, unsigned AttrSize);
785 /// \brief Helper for cloneDIE.
786 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
787 const DWARFFormValue &Val,
788 const CompileUnit &Unit, AttributesInfo &Info);
790 /// \brief Helper for cloneDIE.
791 unsigned cloneScalarAttribute(DIE &Die,
792 const DWARFDebugInfoEntryMinimal &InputDIE,
793 CompileUnit &U, AttributeSpec AttrSpec,
794 const DWARFFormValue &Val, unsigned AttrSize);
796 /// \brief Helper for cloneDIE.
797 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
798 bool isLittleEndian);
800 /// \brief Assign an abbreviation number to \p Abbrev
801 void AssignAbbrev(DIEAbbrev &Abbrev);
803 /// \brief FoldingSet that uniques the abbreviations.
804 FoldingSet<DIEAbbrev> AbbreviationsSet;
805 /// \brief Storage for the unique Abbreviations.
806 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
807 /// be changed to a vecot of unique_ptrs.
808 std::vector<DIEAbbrev *> Abbreviations;
810 /// \brief Compute and emit debug_ranges section for \p Unit, and
811 /// patch the attributes referencing it.
812 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
814 /// \brief Generate and emit the DW_AT_ranges attribute for a
815 /// compile_unit if it had one.
816 void generateUnitRanges(CompileUnit &Unit) const;
818 /// \brief DIELoc objects that need to be destructed (but not freed!).
819 std::vector<DIELoc *> DIELocs;
820 /// \brief DIEBlock objects that need to be destructed (but not freed!).
821 std::vector<DIEBlock *> DIEBlocks;
822 /// \brief Allocator used for all the DIEValue objects.
823 BumpPtrAllocator DIEAlloc;
826 /// \defgroup Helpers Various helper methods.
829 const DWARFDebugInfoEntryMinimal *
830 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
831 const DWARFDebugInfoEntryMinimal &DIE,
832 CompileUnit *&ReferencedCU);
834 CompileUnit *getUnitForOffset(unsigned Offset);
836 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
837 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
839 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
843 std::string OutputFilename;
845 BinaryHolder BinHolder;
846 std::unique_ptr<DwarfStreamer> Streamer;
848 /// The units of the current debug map object.
849 std::vector<CompileUnit> Units;
851 /// The debug map object curently under consideration.
852 DebugMapObject *CurrentDebugObject;
854 /// \brief The Dwarf string pool
855 NonRelocatableStringpool StringPool;
858 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
859 /// returning our CompileUnit object instead.
860 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
862 std::upper_bound(Units.begin(), Units.end(), Offset,
863 [](uint32_t LHS, const CompileUnit &RHS) {
864 return LHS < RHS.getOrigUnit().getNextUnitOffset();
866 return CU != Units.end() ? &*CU : nullptr;
869 /// \brief Resolve the DIE attribute reference that has been
870 /// extracted in \p RefValue. The resulting DIE migh be in another
871 /// CompileUnit which is stored into \p ReferencedCU.
872 /// \returns null if resolving fails for any reason.
873 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
874 DWARFFormValue &RefValue, const DWARFUnit &Unit,
875 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
876 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
877 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
879 if ((RefCU = getUnitForOffset(RefOffset)))
880 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
883 reportWarning("could not find referenced DIE", &Unit, &DIE);
887 /// \brief Report a warning to the user, optionaly including
888 /// information about a specific \p DIE related to the warning.
889 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
890 const DWARFDebugInfoEntryMinimal *DIE) const {
891 StringRef Context = "<debug map>";
892 if (CurrentDebugObject)
893 Context = CurrentDebugObject->getObjectFilename();
894 warn(Warning, Context);
896 if (!Options.Verbose || !DIE)
899 errs() << " in DIE:\n";
900 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
904 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
905 if (Options.NoOutput)
908 Streamer = llvm::make_unique<DwarfStreamer>();
909 return Streamer->init(TheTriple, OutputFilename);
912 /// \brief Recursive helper to gather the child->parent relationships in the
913 /// original compile unit.
914 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
915 unsigned ParentIdx, CompileUnit &CU) {
916 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
917 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
919 if (DIE->hasChildren())
920 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
921 Child = Child->getSibling())
922 gatherDIEParents(Child, MyIdx, CU);
925 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
929 case dwarf::DW_TAG_subprogram:
930 case dwarf::DW_TAG_lexical_block:
931 case dwarf::DW_TAG_subroutine_type:
932 case dwarf::DW_TAG_structure_type:
933 case dwarf::DW_TAG_class_type:
934 case dwarf::DW_TAG_union_type:
937 llvm_unreachable("Invalid Tag");
940 void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
941 Units.reserve(Dwarf.getNumCompileUnits());
945 void DwarfLinker::endDebugObject() {
949 for (auto *Block : DIEBlocks)
951 for (auto *Loc : DIELocs)
959 /// \brief Iterate over the relocations of the given \p Section and
960 /// store the ones that correspond to debug map entries into the
961 /// ValidRelocs array.
962 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
963 const object::MachOObjectFile &Obj,
964 const DebugMapObject &DMO) {
966 Section.getContents(Contents);
967 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
969 for (const object::RelocationRef &Reloc : Section.relocations()) {
970 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
971 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
972 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
974 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
975 reportWarning(" unsupported relocation in debug_info section.");
978 uint32_t Offset = Offset64;
979 // Mach-o uses REL relocations, the addend is at the relocation offset.
980 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
982 auto Sym = Reloc.getSymbol();
983 if (Sym != Obj.symbol_end()) {
984 StringRef SymbolName;
985 if (Sym->getName(SymbolName)) {
986 reportWarning("error getting relocation symbol name.");
989 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
990 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
991 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
992 // Do not store the addend. The addend was the address of the
993 // symbol in the object file, the address in the binary that is
994 // stored in the debug map doesn't need to be offseted.
995 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1000 /// \brief Dispatch the valid relocation finding logic to the
1001 /// appropriate handler depending on the object file format.
1002 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1003 const object::ObjectFile &Obj,
1004 const DebugMapObject &DMO) {
1005 // Dispatch to the right handler depending on the file type.
1006 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1007 findValidRelocsMachO(Section, *MachOObj, DMO);
1009 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
1011 if (ValidRelocs.empty())
1014 // Sort the relocations by offset. We will walk the DIEs linearly in
1015 // the file, this allows us to just keep an index in the relocation
1016 // array that we advance during our walk, rather than resorting to
1017 // some associative container. See DwarfLinker::NextValidReloc.
1018 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1022 /// \brief Look for relocations in the debug_info section that match
1023 /// entries in the debug map. These relocations will drive the Dwarf
1024 /// link by indicating which DIEs refer to symbols present in the
1026 /// \returns wether there are any valid relocations in the debug info.
1027 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1028 const DebugMapObject &DMO) {
1029 // Find the debug_info section.
1030 for (const object::SectionRef &Section : Obj.sections()) {
1031 StringRef SectionName;
1032 Section.getName(SectionName);
1033 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1034 if (SectionName != "debug_info")
1036 return findValidRelocs(Section, Obj, DMO);
1041 /// \brief Checks that there is a relocation against an actual debug
1042 /// map entry between \p StartOffset and \p NextOffset.
1044 /// This function must be called with offsets in strictly ascending
1045 /// order because it never looks back at relocations it already 'went past'.
1046 /// \returns true and sets Info.InDebugMap if it is the case.
1047 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1048 CompileUnit::DIEInfo &Info) {
1049 assert(NextValidReloc == 0 ||
1050 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1051 if (NextValidReloc >= ValidRelocs.size())
1054 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1056 // We might need to skip some relocs that we didn't consider. For
1057 // example the high_pc of a discarded DIE might contain a reloc that
1058 // is in the list because it actually corresponds to the start of a
1059 // function that is in the debug map.
1060 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1061 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1063 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1066 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1067 if (Options.Verbose)
1068 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1069 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1070 ValidReloc.Mapping->getValue().ObjectAddress,
1071 ValidReloc.Mapping->getValue().BinaryAddress);
1073 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
1075 ValidReloc.Mapping->getValue().ObjectAddress;
1076 Info.InDebugMap = true;
1080 /// \brief Get the starting and ending (exclusive) offset for the
1081 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1082 /// supposed to point to the position of the first attribute described
1084 /// \return [StartOffset, EndOffset) as a pair.
1085 static std::pair<uint32_t, uint32_t>
1086 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1087 unsigned Offset, const DWARFUnit &Unit) {
1088 DataExtractor Data = Unit.getDebugInfoExtractor();
1090 for (unsigned i = 0; i < Idx; ++i)
1091 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1093 uint32_t End = Offset;
1094 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1096 return std::make_pair(Offset, End);
1099 /// \brief Check if a variable describing DIE should be kept.
1100 /// \returns updated TraversalFlags.
1101 unsigned DwarfLinker::shouldKeepVariableDIE(
1102 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1103 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1104 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1106 // Global variables with constant value can always be kept.
1107 if (!(Flags & TF_InFunctionScope) &&
1108 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1109 MyInfo.InDebugMap = true;
1110 return Flags | TF_Keep;
1113 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1114 if (LocationIdx == -1U)
1117 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1118 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1119 uint32_t LocationOffset, LocationEndOffset;
1120 std::tie(LocationOffset, LocationEndOffset) =
1121 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1123 // See if there is a relocation to a valid debug map entry inside
1124 // this variable's location. The order is important here. We want to
1125 // always check in the variable has a valid relocation, so that the
1126 // DIEInfo is filled. However, we don't want a static variable in a
1127 // function to force us to keep the enclosing function.
1128 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1129 (Flags & TF_InFunctionScope))
1132 if (Options.Verbose)
1133 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1135 return Flags | TF_Keep;
1138 /// \brief Check if a function describing DIE should be kept.
1139 /// \returns updated TraversalFlags.
1140 unsigned DwarfLinker::shouldKeepSubprogramDIE(
1141 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1142 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1143 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1145 Flags |= TF_InFunctionScope;
1147 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1148 if (LowPcIdx == -1U)
1151 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1152 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1153 uint32_t LowPcOffset, LowPcEndOffset;
1154 std::tie(LowPcOffset, LowPcEndOffset) =
1155 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1158 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1159 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1160 if (LowPc == -1ULL ||
1161 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1164 if (Options.Verbose)
1165 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1169 DWARFFormValue HighPcValue;
1170 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1171 reportWarning("Function without high_pc. Range will be discarded.\n",
1177 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1178 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1180 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1181 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1184 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1188 /// \brief Check if a DIE should be kept.
1189 /// \returns updated TraversalFlags.
1190 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1192 CompileUnit::DIEInfo &MyInfo,
1194 switch (DIE.getTag()) {
1195 case dwarf::DW_TAG_constant:
1196 case dwarf::DW_TAG_variable:
1197 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1198 case dwarf::DW_TAG_subprogram:
1199 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1200 case dwarf::DW_TAG_module:
1201 case dwarf::DW_TAG_imported_module:
1202 case dwarf::DW_TAG_imported_declaration:
1203 case dwarf::DW_TAG_imported_unit:
1204 // We always want to keep these.
1205 return Flags | TF_Keep;
1211 /// \brief Mark the passed DIE as well as all the ones it depends on
1214 /// This function is called by lookForDIEsToKeep on DIEs that are
1215 /// newly discovered to be needed in the link. It recursively calls
1216 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1217 /// TraversalFlags to inform it that it's not doing the primary DIE
1219 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1220 CompileUnit::DIEInfo &MyInfo,
1221 const DebugMapObject &DMO,
1222 CompileUnit &CU, unsigned Flags) {
1223 const DWARFUnit &Unit = CU.getOrigUnit();
1226 // First mark all the parent chain as kept.
1227 unsigned AncestorIdx = MyInfo.ParentIdx;
1228 while (!CU.getInfo(AncestorIdx).Keep) {
1229 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1230 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1231 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1234 // Then we need to mark all the DIEs referenced by this DIE's
1235 // attributes as kept.
1236 DataExtractor Data = Unit.getDebugInfoExtractor();
1237 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1238 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1240 // Mark all DIEs referenced through atttributes as kept.
1241 for (const auto &AttrSpec : Abbrev->attributes()) {
1242 DWARFFormValue Val(AttrSpec.Form);
1244 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1245 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1249 Val.extractValue(Data, &Offset, &Unit);
1250 CompileUnit *ReferencedCU;
1251 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1252 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1253 TF_Keep | TF_DependencyWalk);
1257 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1258 /// keep. Store that information in \p CU's DIEInfo.
1260 /// This function is the entry point of the DIE selection
1261 /// algorithm. It is expected to walk the DIE tree in file order and
1262 /// (though the mediation of its helper) call hasValidRelocation() on
1263 /// each DIE that might be a 'root DIE' (See DwarfLinker class
1265 /// While walking the dependencies of root DIEs, this function is
1266 /// also called, but during these dependency walks the file order is
1267 /// not respected. The TF_DependencyWalk flag tells us which kind of
1268 /// traversal we are currently doing.
1269 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1270 const DebugMapObject &DMO, CompileUnit &CU,
1272 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1273 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1274 bool AlreadyKept = MyInfo.Keep;
1276 // If the Keep flag is set, we are marking a required DIE's
1277 // dependencies. If our target is already marked as kept, we're all
1279 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1282 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1283 // because it would screw up the relocation finding logic.
1284 if (!(Flags & TF_DependencyWalk))
1285 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1287 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1288 if (!AlreadyKept && (Flags & TF_Keep))
1289 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1291 // The TF_ParentWalk flag tells us that we are currently walking up
1292 // the parent chain of a required DIE, and we don't want to mark all
1293 // the children of the parents as kept (consider for example a
1294 // DW_TAG_namespace node in the parent chain). There are however a
1295 // set of DIE types for which we want to ignore that directive and still
1296 // walk their children.
1297 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1298 Flags &= ~TF_ParentWalk;
1300 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1303 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1304 Child = Child->getSibling())
1305 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1308 /// \brief Assign an abbreviation numer to \p Abbrev.
1310 /// Our DIEs get freed after every DebugMapObject has been processed,
1311 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1312 /// the instances hold by the DIEs. When we encounter an abbreviation
1313 /// that we don't know, we create a permanent copy of it.
1314 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1315 // Check the set for priors.
1316 FoldingSetNodeID ID;
1319 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1321 // If it's newly added.
1323 // Assign existing abbreviation number.
1324 Abbrev.setNumber(InSet->getNumber());
1326 // Add to abbreviation list.
1327 Abbreviations.push_back(
1328 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1329 for (const auto &Attr : Abbrev.getData())
1330 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1331 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1332 // Assign the unique abbreviation number.
1333 Abbrev.setNumber(Abbreviations.size());
1334 Abbreviations.back()->setNumber(Abbreviations.size());
1338 /// \brief Clone a string attribute described by \p AttrSpec and add
1340 /// \returns the size of the new attribute.
1341 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1342 const DWARFFormValue &Val,
1343 const DWARFUnit &U) {
1344 // Switch everything to out of line strings.
1345 const char *String = *Val.getAsCString(&U);
1346 unsigned Offset = StringPool.getStringOffset(String);
1347 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1348 new (DIEAlloc) DIEInteger(Offset));
1352 /// \brief Clone an attribute referencing another DIE and add
1354 /// \returns the size of the new attribute.
1355 unsigned DwarfLinker::cloneDieReferenceAttribute(
1356 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1357 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1358 CompileUnit &Unit) {
1359 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
1360 DIE *NewRefDie = nullptr;
1361 CompileUnit *RefUnit = nullptr;
1362 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1364 if (!(RefUnit = getUnitForOffset(Ref)) ||
1365 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1366 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1367 if (!AttributeString)
1368 AttributeString = "DW_AT_???";
1369 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1371 &Unit.getOrigUnit(), &InputDIE);
1375 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1376 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1377 if (!RefInfo.Clone) {
1378 assert(Ref > InputDIE.getOffset());
1379 // We haven't cloned this DIE yet. Just create an empty one and
1380 // store it. It'll get really cloned when we process it.
1381 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1383 NewRefDie = RefInfo.Clone;
1385 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1386 // We cannot currently rely on a DIEEntry to emit ref_addr
1387 // references, because the implementation calls back to DwarfDebug
1388 // to find the unit offset. (We don't have a DwarfDebug)
1389 // FIXME: we should be able to design DIEEntry reliance on
1392 if (Ref < InputDIE.getOffset()) {
1393 // We must have already cloned that DIE.
1394 uint32_t NewRefOffset =
1395 RefUnit->getStartOffset() + NewRefDie->getOffset();
1396 Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1398 // A forward reference. Note and fixup later.
1399 Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
1400 Unit.noteForwardReference(NewRefDie, RefUnit, Attr);
1402 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1407 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1408 new (DIEAlloc) DIEEntry(*NewRefDie));
1412 /// \brief Clone an attribute of block form (locations, constants) and add
1414 /// \returns the size of the new attribute.
1415 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1416 const DWARFFormValue &Val,
1417 unsigned AttrSize) {
1420 DIELoc *Loc = nullptr;
1421 DIEBlock *Block = nullptr;
1422 // Just copy the block data over.
1423 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1424 Loc = new (DIEAlloc) DIELoc();
1425 DIELocs.push_back(Loc);
1427 Block = new (DIEAlloc) DIEBlock();
1428 DIEBlocks.push_back(Block);
1430 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1431 Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1432 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1433 for (auto Byte : Bytes)
1434 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1435 new (DIEAlloc) DIEInteger(Byte));
1436 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1437 // the DIE class, this if could be replaced by
1438 // Attr->setSize(Bytes.size()).
1441 Loc->ComputeSize(&Streamer->getAsmPrinter());
1443 Block->ComputeSize(&Streamer->getAsmPrinter());
1445 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1450 /// \brief Clone an address attribute and add it to \p Die.
1451 /// \returns the size of the new attribute.
1452 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1453 const DWARFFormValue &Val,
1454 const CompileUnit &Unit,
1455 AttributesInfo &Info) {
1456 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
1457 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1458 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1459 Die.getTag() == dwarf::DW_TAG_lexical_block)
1460 Addr += Info.PCOffset;
1461 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1462 Addr = Unit.getLowPc();
1463 if (Addr == UINT64_MAX)
1466 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1467 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1468 if (uint64_t HighPc = Unit.getHighPc())
1473 // If we have a high_pc recorded for the input DIE, use
1474 // it. Otherwise (when no relocations where applied) just use the
1475 // one we just decoded.
1476 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1479 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1480 static_cast<dwarf::Form>(AttrSpec.Form),
1481 new (DIEAlloc) DIEInteger(Addr));
1482 return Unit.getOrigUnit().getAddressByteSize();
1485 /// \brief Clone a scalar attribute and add it to \p Die.
1486 /// \returns the size of the new attribute.
1487 unsigned DwarfLinker::cloneScalarAttribute(
1488 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
1489 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize) {
1491 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1492 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1493 if (Unit.getLowPc() == -1ULL)
1495 // Dwarf >= 4 high_pc is an size, not an address.
1496 Value = Unit.getHighPc() - Unit.getLowPc();
1497 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1498 Value = *Val.getAsSectionOffset();
1499 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1500 Value = *Val.getAsSignedConstant();
1501 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1502 Value = *OptionalValue;
1504 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1505 &Unit.getOrigUnit(), &InputDIE);
1508 DIEInteger *Attr = new (DIEAlloc) DIEInteger(Value);
1509 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
1510 Unit.noteRangeAttribute(Die, Attr);
1511 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1516 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1517 /// value \p Val, and add it to \p Die.
1518 /// \returns the size of the cloned attribute.
1519 unsigned DwarfLinker::cloneAttribute(DIE &Die,
1520 const DWARFDebugInfoEntryMinimal &InputDIE,
1522 const DWARFFormValue &Val,
1523 const AttributeSpec AttrSpec,
1524 unsigned AttrSize, AttributesInfo &Info) {
1525 const DWARFUnit &U = Unit.getOrigUnit();
1527 switch (AttrSpec.Form) {
1528 case dwarf::DW_FORM_strp:
1529 case dwarf::DW_FORM_string:
1530 return cloneStringAttribute(Die, AttrSpec, Val, U);
1531 case dwarf::DW_FORM_ref_addr:
1532 case dwarf::DW_FORM_ref1:
1533 case dwarf::DW_FORM_ref2:
1534 case dwarf::DW_FORM_ref4:
1535 case dwarf::DW_FORM_ref8:
1536 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1538 case dwarf::DW_FORM_block:
1539 case dwarf::DW_FORM_block1:
1540 case dwarf::DW_FORM_block2:
1541 case dwarf::DW_FORM_block4:
1542 case dwarf::DW_FORM_exprloc:
1543 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1544 case dwarf::DW_FORM_addr:
1545 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1546 case dwarf::DW_FORM_data1:
1547 case dwarf::DW_FORM_data2:
1548 case dwarf::DW_FORM_data4:
1549 case dwarf::DW_FORM_data8:
1550 case dwarf::DW_FORM_udata:
1551 case dwarf::DW_FORM_sdata:
1552 case dwarf::DW_FORM_sec_offset:
1553 case dwarf::DW_FORM_flag:
1554 case dwarf::DW_FORM_flag_present:
1555 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize);
1557 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1564 /// \brief Apply the valid relocations found by findValidRelocs() to
1565 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
1566 /// in the debug_info section.
1568 /// Like for findValidRelocs(), this function must be called with
1569 /// monotonic \p BaseOffset values.
1571 /// \returns wether any reloc has been applied.
1572 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
1573 uint32_t BaseOffset, bool isLittleEndian) {
1574 assert((NextValidReloc == 0 ||
1575 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1576 "BaseOffset should only be increasing.");
1577 if (NextValidReloc >= ValidRelocs.size())
1580 // Skip relocs that haven't been applied.
1581 while (NextValidReloc < ValidRelocs.size() &&
1582 ValidRelocs[NextValidReloc].Offset < BaseOffset)
1585 bool Applied = false;
1586 uint64_t EndOffset = BaseOffset + Data.size();
1587 while (NextValidReloc < ValidRelocs.size() &&
1588 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1589 ValidRelocs[NextValidReloc].Offset < EndOffset) {
1590 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1591 assert(ValidReloc.Offset - BaseOffset < Data.size());
1592 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1594 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1595 Value += ValidReloc.Addend;
1596 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1597 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
1598 Buf[i] = uint8_t(Value >> (Index * 8));
1600 assert(ValidReloc.Size <= sizeof(Buf));
1601 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1608 /// \brief Recursively clone \p InputDIE's subtrees that have been
1609 /// selected to appear in the linked output.
1611 /// \param OutOffset is the Offset where the newly created DIE will
1612 /// lie in the linked compile unit.
1614 /// \returns the cloned DIE object or null if nothing was selected.
1615 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
1616 CompileUnit &Unit, int64_t PCOffset,
1617 uint32_t OutOffset) {
1618 DWARFUnit &U = Unit.getOrigUnit();
1619 unsigned Idx = U.getDIEIndex(&InputDIE);
1620 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1622 // Should the DIE appear in the output?
1623 if (!Unit.getInfo(Idx).Keep)
1626 uint32_t Offset = InputDIE.getOffset();
1627 // The DIE might have been already created by a forward reference
1628 // (see cloneDieReferenceAttribute()).
1629 DIE *Die = Info.Clone;
1631 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
1632 assert(Die->getTag() == InputDIE.getTag());
1633 Die->setOffset(OutOffset);
1635 // Extract and clone every attribute.
1636 DataExtractor Data = U.getDebugInfoExtractor();
1637 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
1638 AttributesInfo AttrInfo;
1640 // We could copy the data only if we need to aply a relocation to
1641 // it. After testing, it seems there is no performance downside to
1642 // doing the copy unconditionally, and it makes the code simpler.
1643 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1644 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1645 // Modify the copy with relocated addresses.
1646 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
1647 // If we applied relocations, we store the value of high_pc that was
1648 // potentially stored in the input DIE. If high_pc is an address
1649 // (Dwarf version == 2), then it might have been relocated to a
1650 // totally unrelated value (because the end address in the object
1651 // file might be start address of another function which got moved
1652 // independantly by the linker). The computation of the actual
1653 // high_pc value is done in cloneAddressAttribute().
1654 AttrInfo.OrigHighPc =
1655 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
1658 // Reset the Offset to 0 as we will be working on the local copy of
1662 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1663 Offset += getULEB128Size(Abbrev->getCode());
1665 // We are entering a subprogram. Get and propagate the PCOffset.
1666 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1667 PCOffset = Info.AddrAdjust;
1668 AttrInfo.PCOffset = PCOffset;
1670 for (const auto &AttrSpec : Abbrev->attributes()) {
1671 DWARFFormValue Val(AttrSpec.Form);
1672 uint32_t AttrSize = Offset;
1673 Val.extractValue(Data, &Offset, &U);
1674 AttrSize = Offset - AttrSize;
1677 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
1680 DIEAbbrev &NewAbbrev = Die->getAbbrev();
1681 // If a scope DIE is kept, we must have kept at least one child. If
1682 // it's not the case, we'll just be emitting one wasteful end of
1683 // children marker, but things won't break.
1684 if (InputDIE.hasChildren())
1685 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1686 // Assign a permanent abbrev number
1687 AssignAbbrev(Die->getAbbrev());
1689 // Add the size of the abbreviation number to the output offset.
1690 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1692 if (!Abbrev->hasChildren()) {
1694 Die->setSize(OutOffset - Die->getOffset());
1698 // Recursively clone children.
1699 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1700 Child = Child->getSibling()) {
1701 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
1702 Die->addChild(std::unique_ptr<DIE>(Clone));
1703 OutOffset = Clone->getOffset() + Clone->getSize();
1707 // Account for the end of children marker.
1708 OutOffset += sizeof(int8_t);
1710 Die->setSize(OutOffset - Die->getOffset());
1714 /// \brief Patch the input object file relevant debug_ranges entries
1715 /// and emit them in the output file. Update the relevant attributes
1716 /// to point at the new entries.
1717 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
1718 DWARFContext &OrigDwarf) const {
1719 DWARFDebugRangeList RangeList;
1720 const auto &FunctionRanges = Unit.getFunctionRanges();
1721 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
1722 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
1723 OrigDwarf.isLittleEndian(), AddressSize);
1724 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1725 DWARFUnit &OrigUnit = Unit.getOrigUnit();
1726 const auto *OrigUnitDie = OrigUnit.getCompileUnitDIE(false);
1727 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
1728 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1729 // Ranges addresses are based on the unit's low_pc. Compute the
1730 // offset we need to apply to adapt to the the new unit's low_pc.
1731 int64_t UnitPcOffset = 0;
1732 if (OrigLowPc != -1ULL)
1733 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
1735 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
1736 uint32_t Offset = RangeAttribute->getValue();
1737 RangeAttribute->setValue(Streamer->getRangesSectionSize());
1738 RangeList.extract(RangeExtractor, &Offset);
1739 const auto &Entries = RangeList.getEntries();
1740 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
1742 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
1743 First.StartAddress >= CurrRange.stop()) {
1744 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
1745 if (CurrRange == InvalidRange ||
1746 CurrRange.start() > First.StartAddress + OrigLowPc) {
1747 reportWarning("no mapping for range.");
1752 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
1757 /// \brief Generate the debug_aranges entries for \p Unit and if the
1758 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
1759 /// contribution for this attribute.
1760 /// FIXME: this could actually be done right in patchRangesForUnit,
1761 /// but for the sake of initial bit-for-bit compatibility with legacy
1762 /// dsymutil, we have to do it in a delayed pass.
1763 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
1764 DIEInteger *Attr = Unit.getUnitRangesAttribute();
1766 Attr->setValue(Streamer->getRangesSectionSize());
1767 Streamer->emitUnitRangesEntries(Unit, Attr != nullptr);
1770 bool DwarfLinker::link(const DebugMap &Map) {
1772 if (Map.begin() == Map.end()) {
1773 errs() << "Empty debug map.\n";
1777 if (!createStreamer(Map.getTriple(), OutputFilename))
1780 // Size of the DIEs (and headers) generated for the linked output.
1781 uint64_t OutputDebugInfoSize = 0;
1782 // A unique ID that identifies each compile unit.
1783 unsigned UnitID = 0;
1784 for (const auto &Obj : Map.objects()) {
1785 CurrentDebugObject = Obj.get();
1787 if (Options.Verbose)
1788 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1789 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1790 if (std::error_code EC = ErrOrObj.getError()) {
1791 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
1795 // Look for relocations that correspond to debug map entries.
1796 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
1797 if (Options.Verbose)
1798 outs() << "No valid relocations found. Skipping.\n";
1802 // Setup access to the debug info.
1803 DWARFContextInMemory DwarfContext(*ErrOrObj);
1804 startDebugObject(DwarfContext);
1806 // In a first phase, just read in the debug info and store the DIE
1807 // parent links that we will use during the next phase.
1808 for (const auto &CU : DwarfContext.compile_units()) {
1809 auto *CUDie = CU->getCompileUnitDIE(false);
1810 if (Options.Verbose) {
1811 outs() << "Input compilation unit:";
1812 CUDie->dump(outs(), CU.get(), 0);
1814 Units.emplace_back(*CU, UnitID++);
1815 gatherDIEParents(CUDie, 0, Units.back());
1818 // Then mark all the DIEs that need to be present in the linked
1819 // output and collect some information about them. Note that this
1820 // loop can not be merged with the previous one becaue cross-cu
1821 // references require the ParentIdx to be setup for every CU in
1822 // the object file before calling this.
1823 for (auto &CurrentUnit : Units)
1824 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1827 // The calls to applyValidRelocs inside cloneDIE will walk the
1828 // reloc array again (in the same way findValidRelocsInDebugInfo()
1829 // did). We need to reset the NextValidReloc index to the beginning.
1832 // Construct the output DIE tree by cloning the DIEs we chose to
1833 // keep above. If there are no valid relocs, then there's nothing
1835 if (!ValidRelocs.empty())
1836 for (auto &CurrentUnit : Units) {
1837 const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
1838 CurrentUnit.setStartOffset(OutputDebugInfoSize);
1839 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
1840 11 /* Unit Header size */);
1841 CurrentUnit.setOutputUnitDIE(OutputDIE);
1842 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
1843 if (!OutputDIE || Options.NoOutput)
1845 patchRangesForUnit(CurrentUnit, DwarfContext);
1848 // Emit all the compile unit's debug information.
1849 if (!ValidRelocs.empty() && !Options.NoOutput)
1850 for (auto &CurrentUnit : Units) {
1851 generateUnitRanges(CurrentUnit);
1852 CurrentUnit.fixupForwardReferences();
1853 Streamer->emitCompileUnitHeader(CurrentUnit);
1854 if (!CurrentUnit.getOutputUnitDIE())
1856 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1859 // Clean-up before starting working on the next object.
1863 // Emit everything that's global.
1864 if (!Options.NoOutput) {
1865 Streamer->emitAbbrevs(Abbreviations);
1866 Streamer->emitStrings(StringPool);
1869 return Options.NoOutput ? true : Streamer->finish();
1873 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1874 const LinkOptions &Options) {
1875 DwarfLinker Linker(OutputFilename, Options);
1876 return Linker.link(DM);