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/MCDwarf.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCObjectFileInfo.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/Object/MachO.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/Support/LEB128.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
45 void warn(const Twine &Warning, const Twine &Context) {
46 errs() << Twine("while processing ") + Context + ":\n";
47 errs() << Twine("warning: ") + Warning + "\n";
50 bool error(const Twine &Error, const Twine &Context) {
51 errs() << Twine("while processing ") + Context + ":\n";
52 errs() << Twine("error: ") + Error + "\n";
56 template <typename KeyT, typename ValT>
57 using HalfOpenIntervalMap =
58 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
59 IntervalMapHalfOpenInfo<KeyT>>;
61 typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
63 // FIXME: Delete this structure.
64 struct PatchLocation {
65 DIE::value_iterator I;
67 PatchLocation() = default;
68 PatchLocation(DIE::value_iterator I) : I(I) {}
70 void set(uint64_t New) const {
73 assert(Old.getType() == DIEValue::isInteger);
74 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
77 uint64_t get() const {
79 return I->getDIEInteger().getValue();
83 /// \brief Stores all information relating to a compile unit, be it in
84 /// its original instance in the object file to its brand new cloned
85 /// and linked DIE tree.
88 /// \brief Information gathered about a DIE in the object file.
90 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
91 DIE *Clone; ///< Cloned version of that DIE.
92 uint32_t ParentIdx; ///< The index of this DIE's parent.
93 bool Keep; ///< Is the DIE part of the linked output?
94 bool InDebugMap; ///< Was this DIE's entity found in the map?
97 CompileUnit(DWARFUnit &OrigUnit, unsigned ID)
98 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
100 Info.resize(OrigUnit.getNumDIEs());
103 CompileUnit(CompileUnit &&RHS)
104 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
105 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
106 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
107 // The CompileUnit container has been 'reserve()'d with the right
108 // size. We cannot move the IntervalMap anyway.
109 llvm_unreachable("CompileUnits should not be moved.");
112 DWARFUnit &getOrigUnit() const { return OrigUnit; }
114 unsigned getUniqueID() const { return ID; }
116 DIE *getOutputUnitDIE() const { return CUDie.get(); }
117 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
119 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
120 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
122 uint64_t getStartOffset() const { return StartOffset; }
123 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
124 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
126 uint64_t getLowPc() const { return LowPc; }
127 uint64_t getHighPc() const { return HighPc; }
129 Optional<PatchLocation> getUnitRangesAttribute() const {
130 return UnitRangeAttribute;
132 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
133 const std::vector<PatchLocation> &getRangesAttributes() const {
134 return RangeAttributes;
137 const std::vector<std::pair<PatchLocation, int64_t>> &
138 getLocationAttributes() const {
139 return LocationAttributes;
142 /// \brief Compute the end offset for this unit. Must be
143 /// called after the CU's DIEs have been cloned.
144 /// \returns the next unit offset (which is also the current
145 /// debug_info section size).
146 uint64_t computeNextUnitOffset();
148 /// \brief Keep track of a forward reference to DIE \p Die in \p
149 /// RefUnit by \p Attr. The attribute should be fixed up later to
150 /// point to the absolute offset of \p Die in the debug_info section.
151 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
154 /// \brief Apply all fixups recored by noteForwardReference().
155 void fixupForwardReferences();
157 /// \brief Add a function range [\p LowPC, \p HighPC) that is
158 /// relocatad by applying offset \p PCOffset.
159 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
161 /// \brief Keep track of a DW_AT_range attribute that we will need to
163 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
165 /// \brief Keep track of a location attribute pointing to a location
166 /// list in the debug_loc section.
167 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
169 /// \brief Add a name accelerator entry for \p Die with \p Name
170 /// which is stored in the string table at \p Offset.
171 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
172 bool SkipPubnamesSection = false);
174 /// \brief Add a type accelerator entry for \p Die with \p Name
175 /// which is stored in the string table at \p Offset.
176 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
179 StringRef Name; ///< Name of the entry.
180 const DIE *Die; ///< DIE this entry describes.
181 uint32_t NameOffset; ///< Offset of Name in the string pool.
182 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
184 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
185 bool SkipPubSection = false)
186 : Name(Name), Die(Die), NameOffset(NameOffset),
187 SkipPubSection(SkipPubSection) {}
190 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
191 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
196 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
197 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
199 uint64_t StartOffset;
200 uint64_t NextUnitOffset;
205 /// \brief A list of attributes to fixup with the absolute offset of
206 /// a DIE in the debug_info section.
208 /// The offsets for the attributes in this array couldn't be set while
209 /// cloning because for cross-cu forward refences the target DIE's
210 /// offset isn't known you emit the reference attribute.
211 std::vector<std::tuple<DIE *, const CompileUnit *, PatchLocation>>
212 ForwardDIEReferences;
214 FunctionIntervals::Allocator RangeAlloc;
215 /// \brief The ranges in that interval map are the PC ranges for
216 /// functions in this unit, associated with the PC offset to apply
217 /// to the addresses to get the linked address.
218 FunctionIntervals Ranges;
220 /// \brief DW_AT_ranges attributes to patch after we have gathered
221 /// all the unit's function addresses.
223 std::vector<PatchLocation> RangeAttributes;
224 Optional<PatchLocation> UnitRangeAttribute;
227 /// \brief Location attributes that need to be transfered from th
228 /// original debug_loc section to the liked one. They are stored
229 /// along with the PC offset that is to be applied to their
230 /// function's address.
231 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
233 /// \brief Accelerator entries for the unit, both for the pub*
234 /// sections and the apple* ones.
236 std::vector<AccelInfo> Pubnames;
237 std::vector<AccelInfo> Pubtypes;
241 uint64_t CompileUnit::computeNextUnitOffset() {
242 NextUnitOffset = StartOffset + 11 /* Header size */;
243 // The root DIE might be null, meaning that the Unit had nothing to
244 // contribute to the linked output. In that case, we will emit the
245 // unit header without any actual DIE.
247 NextUnitOffset += CUDie->getSize();
248 return NextUnitOffset;
251 /// \brief Keep track of a forward cross-cu reference from this unit
252 /// to \p Die that lives in \p RefUnit.
253 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
254 PatchLocation Attr) {
255 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
258 /// \brief Apply all fixups recorded by noteForwardReference().
259 void CompileUnit::fixupForwardReferences() {
260 for (const auto &Ref : ForwardDIEReferences) {
262 const CompileUnit *RefUnit;
264 std::tie(RefDie, RefUnit, Attr) = Ref;
265 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
269 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
271 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
272 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
273 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
276 void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
277 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
278 RangeAttributes.push_back(Attr);
280 UnitRangeAttribute = Attr;
283 void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
284 LocationAttributes.emplace_back(Attr, PcOffset);
287 /// \brief Add a name accelerator entry for \p Die with \p Name
288 /// which is stored in the string table at \p Offset.
289 void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
290 uint32_t Offset, bool SkipPubSection) {
291 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
294 /// \brief Add a type accelerator entry for \p Die with \p Name
295 /// which is stored in the string table at \p Offset.
296 void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
298 Pubtypes.emplace_back(Name, Die, Offset, false);
301 /// \brief A string table that doesn't need relocations.
303 /// We are doing a final link, no need for a string table that
304 /// has relocation entries for every reference to it. This class
305 /// provides this ablitity by just associating offsets with
307 class NonRelocatableStringpool {
309 /// \brief Entries are stored into the StringMap and simply linked
310 /// together through the second element of this pair in order to
311 /// keep track of insertion order.
312 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
315 NonRelocatableStringpool()
316 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
317 // Legacy dsymutil puts an empty string at the start of the line
322 /// \brief Get the offset of string \p S in the string table. This
323 /// can insert a new element or return the offset of a preexisitng
325 uint32_t getStringOffset(StringRef S);
327 /// \brief Get permanent storage for \p S (but do not necessarily
328 /// emit \p S in the output section).
329 /// \returns The StringRef that points to permanent storage to use
330 /// in place of \p S.
331 StringRef internString(StringRef S);
333 // \brief Return the first entry of the string table.
334 const MapTy::MapEntryTy *getFirstEntry() const {
335 return getNextEntry(&Sentinel);
338 // \brief Get the entry following \p E in the string table or null
339 // if \p E was the last entry.
340 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
341 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
344 uint64_t getSize() { return CurrentEndOffset; }
348 uint32_t CurrentEndOffset;
349 MapTy::MapEntryTy Sentinel, *Last;
352 /// \brief Get the offset of string \p S in the string table. This
353 /// can insert a new element or return the offset of a preexisitng
355 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
356 if (S.empty() && !Strings.empty())
359 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
363 // A non-empty string can't be at offset 0, so if we have an entry
364 // with a 0 offset, it must be a previously interned string.
365 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
366 if (Inserted || It->getValue().first == 0) {
367 // Set offset and chain at the end of the entries list.
368 It->getValue().first = CurrentEndOffset;
369 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
370 Last->getValue().second = &*It;
373 return It->getValue().first;
376 /// \brief Put \p S into the StringMap so that it gets permanent
377 /// storage, but do not actually link it in the chain of elements
378 /// that go into the output section. A latter call to
379 /// getStringOffset() with the same string will chain it though.
380 StringRef NonRelocatableStringpool::internString(StringRef S) {
381 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
382 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
383 return InsertResult.first->getKey();
386 /// \brief The Dwarf streaming logic
388 /// All interactions with the MC layer that is used to build the debug
389 /// information binary representation are handled in this class.
390 class DwarfStreamer {
391 /// \defgroup MCObjects MC layer objects constructed by the streamer
393 std::unique_ptr<MCRegisterInfo> MRI;
394 std::unique_ptr<MCAsmInfo> MAI;
395 std::unique_ptr<MCObjectFileInfo> MOFI;
396 std::unique_ptr<MCContext> MC;
397 MCAsmBackend *MAB; // Owned by MCStreamer
398 std::unique_ptr<MCInstrInfo> MII;
399 std::unique_ptr<MCSubtargetInfo> MSTI;
400 MCCodeEmitter *MCE; // Owned by MCStreamer
401 MCStreamer *MS; // Owned by AsmPrinter
402 std::unique_ptr<TargetMachine> TM;
403 std::unique_ptr<AsmPrinter> Asm;
406 /// \brief the file we stream the linked Dwarf to.
407 std::unique_ptr<raw_fd_ostream> OutFile;
409 uint32_t RangesSectionSize;
410 uint32_t LocSectionSize;
411 uint32_t LineSectionSize;
412 uint32_t FrameSectionSize;
414 /// \brief Emit the pubnames or pubtypes section contribution for \p
415 /// Unit into \p Sec. The data is provided in \p Names.
416 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
417 const CompileUnit &Unit,
418 const std::vector<CompileUnit::AccelInfo> &Names);
421 /// \brief Actually create the streamer and the ouptut file.
423 /// This could be done directly in the constructor, but it feels
424 /// more natural to handle errors through return value.
425 bool init(Triple TheTriple, StringRef OutputFilename);
427 /// \brief Dump the file to the disk.
430 AsmPrinter &getAsmPrinter() const { return *Asm; }
432 /// \brief Set the current output section to debug_info and change
433 /// the MC Dwarf version to \p DwarfVersion.
434 void switchToDebugInfoSection(unsigned DwarfVersion);
436 /// \brief Emit the compilation unit header for \p Unit in the
437 /// debug_info section.
439 /// As a side effect, this also switches the current Dwarf version
440 /// of the MC layer to the one of U.getOrigUnit().
441 void emitCompileUnitHeader(CompileUnit &Unit);
443 /// \brief Recursively emit the DIE tree rooted at \p Die.
444 void emitDIE(DIE &Die);
446 /// \brief Emit the abbreviation table \p Abbrevs to the
447 /// debug_abbrev section.
448 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
450 /// \brief Emit the string table described by \p Pool.
451 void emitStrings(const NonRelocatableStringpool &Pool);
453 /// \brief Emit debug_ranges for \p FuncRange by translating the
454 /// original \p Entries.
455 void emitRangesEntries(
456 int64_t UnitPcOffset, uint64_t OrigLowPc,
457 FunctionIntervals::const_iterator FuncRange,
458 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
459 unsigned AddressSize);
461 /// \brief Emit debug_aranges entries for \p Unit and if \p
462 /// DoRangesSection is true, also emit the debug_ranges entries for
463 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
464 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
466 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
468 /// \brief Emit the debug_loc contribution for \p Unit by copying
469 /// the entries from \p Dwarf and offseting them. Update the
470 /// location attributes to point to the new entries.
471 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
473 /// \brief Emit the line table described in \p Rows into the
474 /// debug_line section.
475 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
476 std::vector<DWARFDebugLine::Row> &Rows,
477 unsigned AdddressSize);
479 uint32_t getLineSectionSize() const { return LineSectionSize; }
481 /// \brief Emit the .debug_pubnames contribution for \p Unit.
482 void emitPubNamesForUnit(const CompileUnit &Unit);
484 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
485 void emitPubTypesForUnit(const CompileUnit &Unit);
487 /// \brief Emit a CIE.
488 void emitCIE(StringRef CIEBytes);
490 /// \brief Emit an FDE with data \p Bytes.
491 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
494 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
497 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
498 std::string ErrorStr;
499 std::string TripleName;
500 StringRef Context = "dwarf streamer init";
503 const Target *TheTarget =
504 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
506 return error(ErrorStr, Context);
507 TripleName = TheTriple.getTriple();
509 // Create all the MC Objects.
510 MRI.reset(TheTarget->createMCRegInfo(TripleName));
512 return error(Twine("no register info for target ") + TripleName, Context);
514 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
516 return error("no asm info for target " + TripleName, Context);
518 MOFI.reset(new MCObjectFileInfo);
519 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
520 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
523 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
525 return error("no asm backend for target " + TripleName, Context);
527 MII.reset(TheTarget->createMCInstrInfo());
529 return error("no instr info info for target " + TripleName, Context);
531 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
533 return error("no subtarget info for target " + TripleName, Context);
535 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
537 return error("no code emitter for target " + TripleName, Context);
539 // Create the output file.
542 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
544 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
546 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
548 /*DWARFMustBeAtTheEnd*/ false);
550 return error("no object streamer for target " + TripleName, Context);
552 // Finally create the AsmPrinter we'll use to emit the DIEs.
553 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
555 return error("no target machine for target " + TripleName, Context);
557 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
559 return error("no asm printer for target " + TripleName, Context);
561 RangesSectionSize = 0;
564 FrameSectionSize = 0;
569 bool DwarfStreamer::finish() {
574 /// \brief Set the current output section to debug_info and change
575 /// the MC Dwarf version to \p DwarfVersion.
576 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
577 MS->SwitchSection(MOFI->getDwarfInfoSection());
578 MC->setDwarfVersion(DwarfVersion);
581 /// \brief Emit the compilation unit header for \p Unit in the
582 /// debug_info section.
584 /// A Dwarf scetion header is encoded as:
585 /// uint32_t Unit length (omiting this field)
587 /// uint32_t Abbreviation table offset
588 /// uint8_t Address size
590 /// Leading to a total of 11 bytes.
591 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
592 unsigned Version = Unit.getOrigUnit().getVersion();
593 switchToDebugInfoSection(Version);
595 // Emit size of content not including length itself. The size has
596 // already been computed in CompileUnit::computeOffsets(). Substract
597 // 4 to that size to account for the length field.
598 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
599 Asm->EmitInt16(Version);
600 // We share one abbreviations table across all units so it's always at the
601 // start of the section.
603 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
606 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
607 /// for the linked Dwarf file.
608 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
609 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
610 Asm->emitDwarfAbbrevs(Abbrevs);
613 /// \brief Recursively emit the DIE tree rooted at \p Die.
614 void DwarfStreamer::emitDIE(DIE &Die) {
615 MS->SwitchSection(MOFI->getDwarfInfoSection());
616 Asm->emitDwarfDIE(Die);
619 /// \brief Emit the debug_str section stored in \p Pool.
620 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
621 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
622 for (auto *Entry = Pool.getFirstEntry(); Entry;
623 Entry = Pool.getNextEntry(Entry))
624 Asm->OutStreamer->EmitBytes(
625 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
628 /// \brief Emit the debug_range section contents for \p FuncRange by
629 /// translating the original \p Entries. The debug_range section
630 /// format is totally trivial, consisting just of pairs of address
631 /// sized addresses describing the ranges.
632 void DwarfStreamer::emitRangesEntries(
633 int64_t UnitPcOffset, uint64_t OrigLowPc,
634 FunctionIntervals::const_iterator FuncRange,
635 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
636 unsigned AddressSize) {
637 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
639 // Offset each range by the right amount.
640 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
641 for (const auto &Range : Entries) {
642 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
643 warn("unsupported base address selection operation",
644 "emitting debug_ranges");
647 // Do not emit empty ranges.
648 if (Range.StartAddress == Range.EndAddress)
651 // All range entries should lie in the function range.
652 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
653 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
654 warn("inconsistent range data.", "emitting debug_ranges");
655 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
656 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
657 RangesSectionSize += 2 * AddressSize;
660 // Add the terminator entry.
661 MS->EmitIntValue(0, AddressSize);
662 MS->EmitIntValue(0, AddressSize);
663 RangesSectionSize += 2 * AddressSize;
666 /// \brief Emit the debug_aranges contribution of a unit and
667 /// if \p DoDebugRanges is true the debug_range contents for a
668 /// compile_unit level DW_AT_ranges attribute (Which are basically the
669 /// same thing with a different base address).
670 /// Just aggregate all the ranges gathered inside that unit.
671 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
672 bool DoDebugRanges) {
673 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
674 // Gather the ranges in a vector, so that we can simplify them. The
675 // IntervalMap will have coalesced the non-linked ranges, but here
676 // we want to coalesce the linked addresses.
677 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
678 const auto &FunctionRanges = Unit.getFunctionRanges();
679 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
680 Range != End; ++Range)
681 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
682 Range.stop() + Range.value()));
684 // The object addresses where sorted, but again, the linked
685 // addresses might end up in a different order.
686 std::sort(Ranges.begin(), Ranges.end());
688 if (!Ranges.empty()) {
689 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
691 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
692 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
694 unsigned HeaderSize =
695 sizeof(int32_t) + // Size of contents (w/o this field
696 sizeof(int16_t) + // DWARF ARange version number
697 sizeof(int32_t) + // Offset of CU in the .debug_info section
698 sizeof(int8_t) + // Pointer Size (in bytes)
699 sizeof(int8_t); // Segment Size (in bytes)
701 unsigned TupleSize = AddressSize * 2;
702 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
704 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
705 Asm->OutStreamer->EmitLabel(BeginLabel);
706 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
707 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
708 Asm->EmitInt8(AddressSize); // Address size
709 Asm->EmitInt8(0); // Segment size
711 Asm->OutStreamer->EmitFill(Padding, 0x0);
713 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
715 uint64_t RangeStart = Range->first;
716 MS->EmitIntValue(RangeStart, AddressSize);
717 while ((Range + 1) != End && Range->second == (Range + 1)->first)
719 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
723 Asm->OutStreamer->EmitIntValue(0, AddressSize);
724 Asm->OutStreamer->EmitIntValue(0, AddressSize);
725 Asm->OutStreamer->EmitLabel(EndLabel);
731 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
732 // Offset each range by the right amount.
733 int64_t PcOffset = -Unit.getLowPc();
734 // Emit coalesced ranges.
735 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
736 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
737 while (Range + 1 != End && Range->second == (Range + 1)->first)
739 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
740 RangesSectionSize += 2 * AddressSize;
743 // Add the terminator entry.
744 MS->EmitIntValue(0, AddressSize);
745 MS->EmitIntValue(0, AddressSize);
746 RangesSectionSize += 2 * AddressSize;
749 /// \brief Emit location lists for \p Unit and update attribtues to
750 /// point to the new entries.
751 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
752 DWARFContext &Dwarf) {
753 const auto &Attributes = Unit.getLocationAttributes();
755 if (Attributes.empty())
758 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
760 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
761 const DWARFSection &InputSec = Dwarf.getLocSection();
762 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
763 DWARFUnit &OrigUnit = Unit.getOrigUnit();
764 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
765 int64_t UnitPcOffset = 0;
766 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
767 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
768 if (OrigLowPc != -1ULL)
769 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
771 for (const auto &Attr : Attributes) {
772 uint32_t Offset = Attr.first.get();
773 Attr.first.set(LocSectionSize);
774 // This is the quantity to add to the old location address to get
775 // the correct address for the new one.
776 int64_t LocPcOffset = Attr.second + UnitPcOffset;
777 while (Data.isValidOffset(Offset)) {
778 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
779 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
780 LocSectionSize += 2 * AddressSize;
781 if (Low == 0 && High == 0) {
782 Asm->OutStreamer->EmitIntValue(0, AddressSize);
783 Asm->OutStreamer->EmitIntValue(0, AddressSize);
786 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
787 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
788 uint64_t Length = Data.getU16(&Offset);
789 Asm->OutStreamer->EmitIntValue(Length, 2);
790 // Just copy the bytes over.
791 Asm->OutStreamer->EmitBytes(
792 StringRef(InputSec.Data.substr(Offset, Length)));
794 LocSectionSize += Length + 2;
799 void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
800 unsigned MinInstLength,
801 std::vector<DWARFDebugLine::Row> &Rows,
802 unsigned PointerSize) {
803 // Switch to the section where the table will be emitted into.
804 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
805 MCSymbol *LineStartSym = MC->createTempSymbol();
806 MCSymbol *LineEndSym = MC->createTempSymbol();
808 // The first 4 bytes is the total length of the information for this
809 // compilation unit (not including these 4 bytes for the length).
810 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
811 Asm->OutStreamer->EmitLabel(LineStartSym);
813 MS->EmitBytes(PrologueBytes);
814 LineSectionSize += PrologueBytes.size() + 4;
816 SmallString<128> EncodingBuffer;
817 raw_svector_ostream EncodingOS(EncodingBuffer);
820 // We only have the dummy entry, dsymutil emits an entry with a 0
821 // address in that case.
822 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
823 MS->EmitBytes(EncodingOS.str());
824 LineSectionSize += EncodingBuffer.size();
825 MS->EmitLabel(LineEndSym);
829 // Line table state machine fields
830 unsigned FileNum = 1;
831 unsigned LastLine = 1;
833 unsigned IsStatement = 1;
835 uint64_t Address = -1ULL;
837 unsigned RowsSinceLastSequence = 0;
839 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
840 auto &Row = Rows[Idx];
842 int64_t AddressDelta;
843 if (Address == -1ULL) {
844 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
845 MS->EmitULEB128IntValue(PointerSize + 1);
846 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
847 MS->EmitIntValue(Row.Address, PointerSize);
848 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
851 AddressDelta = (Row.Address - Address) / MinInstLength;
854 // FIXME: code copied and transfromed from
855 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
856 // this code, but the current compatibility requirement with
857 // classic dsymutil makes it hard. Revisit that once this
858 // requirement is dropped.
860 if (FileNum != Row.File) {
862 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
863 MS->EmitULEB128IntValue(FileNum);
864 LineSectionSize += 1 + getULEB128Size(FileNum);
866 if (Column != Row.Column) {
868 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
869 MS->EmitULEB128IntValue(Column);
870 LineSectionSize += 1 + getULEB128Size(Column);
873 // FIXME: We should handle the discriminator here, but dsymutil
874 // doesn' consider it, thus ignore it for now.
876 if (Isa != Row.Isa) {
878 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
879 MS->EmitULEB128IntValue(Isa);
880 LineSectionSize += 1 + getULEB128Size(Isa);
882 if (IsStatement != Row.IsStmt) {
883 IsStatement = Row.IsStmt;
884 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
885 LineSectionSize += 1;
887 if (Row.BasicBlock) {
888 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
889 LineSectionSize += 1;
892 if (Row.PrologueEnd) {
893 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
894 LineSectionSize += 1;
897 if (Row.EpilogueBegin) {
898 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
899 LineSectionSize += 1;
902 int64_t LineDelta = int64_t(Row.Line) - LastLine;
903 if (!Row.EndSequence) {
904 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
905 MS->EmitBytes(EncodingOS.str());
906 LineSectionSize += EncodingBuffer.size();
907 EncodingBuffer.resize(0);
909 Address = Row.Address;
911 RowsSinceLastSequence++;
914 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
915 MS->EmitSLEB128IntValue(LineDelta);
916 LineSectionSize += 1 + getSLEB128Size(LineDelta);
919 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
920 MS->EmitULEB128IntValue(AddressDelta);
921 LineSectionSize += 1 + getULEB128Size(AddressDelta);
923 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
924 MS->EmitBytes(EncodingOS.str());
925 LineSectionSize += EncodingBuffer.size();
926 EncodingBuffer.resize(0);
929 LastLine = FileNum = IsStatement = 1;
930 RowsSinceLastSequence = Column = Isa = 0;
934 if (RowsSinceLastSequence) {
935 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
936 MS->EmitBytes(EncodingOS.str());
937 LineSectionSize += EncodingBuffer.size();
938 EncodingBuffer.resize(0);
942 MS->EmitLabel(LineEndSym);
945 /// \brief Emit the pubnames or pubtypes section contribution for \p
946 /// Unit into \p Sec. The data is provided in \p Names.
947 void DwarfStreamer::emitPubSectionForUnit(
948 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
949 const std::vector<CompileUnit::AccelInfo> &Names) {
953 // Start the dwarf pubnames section.
954 Asm->OutStreamer->SwitchSection(Sec);
955 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
956 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
958 bool HeaderEmitted = false;
959 // Emit the pubnames for this compilation unit.
960 for (const auto &Name : Names) {
961 if (Name.SkipPubSection)
964 if (!HeaderEmitted) {
966 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
967 Asm->OutStreamer->EmitLabel(BeginLabel);
968 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
969 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
970 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
971 HeaderEmitted = true;
973 Asm->EmitInt32(Name.Die->getOffset());
974 Asm->OutStreamer->EmitBytes(
975 StringRef(Name.Name.data(), Name.Name.size() + 1));
980 Asm->EmitInt32(0); // End marker.
981 Asm->OutStreamer->EmitLabel(EndLabel);
984 /// \brief Emit .debug_pubnames for \p Unit.
985 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
986 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
987 "names", Unit, Unit.getPubnames());
990 /// \brief Emit .debug_pubtypes for \p Unit.
991 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
992 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
993 "types", Unit, Unit.getPubtypes());
996 /// \brief Emit a CIE into the debug_frame section.
997 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
998 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1000 MS->EmitBytes(CIEBytes);
1001 FrameSectionSize += CIEBytes.size();
1004 /// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1005 /// contains the FDE data without the length, CIE offset and address
1006 /// which will be replaced with the paramter values.
1007 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1008 uint32_t Address, StringRef FDEBytes) {
1009 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1011 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1012 MS->EmitIntValue(CIEOffset, 4);
1013 MS->EmitIntValue(Address, AddrSize);
1014 MS->EmitBytes(FDEBytes);
1015 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1018 /// \brief The core of the Dwarf linking logic.
1020 /// The link of the dwarf information from the object files will be
1021 /// driven by the selection of 'root DIEs', which are DIEs that
1022 /// describe variables or functions that are present in the linked
1023 /// binary (and thus have entries in the debug map). All the debug
1024 /// information that will be linked (the DIEs, but also the line
1025 /// tables, ranges, ...) is derived from that set of root DIEs.
1027 /// The root DIEs are identified because they contain relocations that
1028 /// correspond to a debug map entry at specific places (the low_pc for
1029 /// a function, the location for a variable). These relocations are
1030 /// called ValidRelocs in the DwarfLinker and are gathered as a very
1031 /// first step when we start processing a DebugMapObject.
1034 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1035 : OutputFilename(OutputFilename), Options(Options),
1036 BinHolder(Options.Verbose), LastCIEOffset(0) {}
1039 for (auto *Abbrev : Abbreviations)
1043 /// \brief Link the contents of the DebugMap.
1044 bool link(const DebugMap &);
1047 /// \brief Called at the start of a debug object link.
1048 void startDebugObject(DWARFContext &, DebugMapObject &);
1050 /// \brief Called at the end of a debug object link.
1051 void endDebugObject();
1053 /// \defgroup FindValidRelocations Translate debug map into a list
1054 /// of relevant relocations
1061 const DebugMapObject::DebugMapEntry *Mapping;
1063 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1064 const DebugMapObject::DebugMapEntry *Mapping)
1065 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1067 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1070 /// \brief The valid relocations for the current DebugMapObject.
1071 /// This vector is sorted by relocation offset.
1072 std::vector<ValidReloc> ValidRelocs;
1074 /// \brief Index into ValidRelocs of the next relocation to
1075 /// consider. As we walk the DIEs in acsending file offset and as
1076 /// ValidRelocs is sorted by file offset, keeping this index
1077 /// uptodate is all we have to do to have a cheap lookup during the
1078 /// root DIE selection and during DIE cloning.
1079 unsigned NextValidReloc;
1081 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1082 const DebugMapObject &DMO);
1084 bool findValidRelocs(const object::SectionRef &Section,
1085 const object::ObjectFile &Obj,
1086 const DebugMapObject &DMO);
1088 void findValidRelocsMachO(const object::SectionRef &Section,
1089 const object::MachOObjectFile &Obj,
1090 const DebugMapObject &DMO);
1093 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1096 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1097 /// keep. Store that information in \p CU's DIEInfo.
1098 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1099 const DebugMapObject &DMO, CompileUnit &CU,
1102 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1103 enum TravesalFlags {
1104 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1105 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1106 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1107 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1110 /// \brief Mark the passed DIE as well as all the ones it depends on
1112 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1113 CompileUnit::DIEInfo &MyInfo,
1114 const DebugMapObject &DMO, CompileUnit &CU,
1117 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1118 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1121 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1123 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1125 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1127 CompileUnit::DIEInfo &MyInfo,
1130 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1131 CompileUnit::DIEInfo &Info);
1134 /// \defgroup Linking Methods used to link the debug information
1137 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1138 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1139 /// stripped out and addresses have been rewritten according to the
1142 /// \param OutOffset is the offset the cloned DIE in the output
1144 /// \param PCOffset (while cloning a function scope) is the offset
1145 /// applied to the entry point of the function to get the linked address.
1147 /// \returns the root of the cloned tree.
1148 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
1149 int64_t PCOffset, uint32_t OutOffset);
1151 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1153 /// \brief Information gathered and exchanged between the various
1154 /// clone*Attributes helpers about the attributes of a particular DIE.
1155 struct AttributesInfo {
1156 const char *Name, *MangledName; ///< Names.
1157 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1159 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1160 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1162 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1163 bool IsDeclaration; ///< Is this DIE only a declaration?
1166 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1167 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1168 IsDeclaration(false) {}
1171 /// \brief Helper for cloneDIE.
1172 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1173 CompileUnit &U, const DWARFFormValue &Val,
1174 const AttributeSpec AttrSpec, unsigned AttrSize,
1175 AttributesInfo &AttrInfo);
1177 /// \brief Helper for cloneDIE.
1178 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1179 const DWARFFormValue &Val, const DWARFUnit &U);
1181 /// \brief Helper for cloneDIE.
1183 cloneDieReferenceAttribute(DIE &Die,
1184 const DWARFDebugInfoEntryMinimal &InputDIE,
1185 AttributeSpec AttrSpec, unsigned AttrSize,
1186 const DWARFFormValue &Val, CompileUnit &Unit);
1188 /// \brief Helper for cloneDIE.
1189 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1190 const DWARFFormValue &Val, unsigned AttrSize);
1192 /// \brief Helper for cloneDIE.
1193 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1194 const DWARFFormValue &Val,
1195 const CompileUnit &Unit, AttributesInfo &Info);
1197 /// \brief Helper for cloneDIE.
1198 unsigned cloneScalarAttribute(DIE &Die,
1199 const DWARFDebugInfoEntryMinimal &InputDIE,
1200 CompileUnit &U, AttributeSpec AttrSpec,
1201 const DWARFFormValue &Val, unsigned AttrSize,
1202 AttributesInfo &Info);
1204 /// \brief Helper for cloneDIE.
1205 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1206 bool isLittleEndian);
1208 /// \brief Assign an abbreviation number to \p Abbrev
1209 void AssignAbbrev(DIEAbbrev &Abbrev);
1211 /// \brief FoldingSet that uniques the abbreviations.
1212 FoldingSet<DIEAbbrev> AbbreviationsSet;
1213 /// \brief Storage for the unique Abbreviations.
1214 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1215 /// be changed to a vecot of unique_ptrs.
1216 std::vector<DIEAbbrev *> Abbreviations;
1218 /// \brief Compute and emit debug_ranges section for \p Unit, and
1219 /// patch the attributes referencing it.
1220 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1222 /// \brief Generate and emit the DW_AT_ranges attribute for a
1223 /// compile_unit if it had one.
1224 void generateUnitRanges(CompileUnit &Unit) const;
1226 /// \brief Extract the line tables fromt he original dwarf, extract
1227 /// the relevant parts according to the linked function ranges and
1228 /// emit the result in the debug_line section.
1229 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1231 /// \brief Emit the accelerator entries for \p Unit.
1232 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1234 /// \brief Patch the frame info for an object file and emit it.
1235 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1236 unsigned AddressSize);
1238 /// \brief DIELoc objects that need to be destructed (but not freed!).
1239 std::vector<DIELoc *> DIELocs;
1240 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1241 std::vector<DIEBlock *> DIEBlocks;
1242 /// \brief Allocator used for all the DIEValue objects.
1243 BumpPtrAllocator DIEAlloc;
1246 /// \defgroup Helpers Various helper methods.
1249 const DWARFDebugInfoEntryMinimal *
1250 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
1251 const DWARFDebugInfoEntryMinimal &DIE,
1252 CompileUnit *&ReferencedCU);
1254 CompileUnit *getUnitForOffset(unsigned Offset);
1256 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1257 AttributesInfo &Info);
1259 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1260 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1262 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
1266 std::string OutputFilename;
1267 LinkOptions Options;
1268 BinaryHolder BinHolder;
1269 std::unique_ptr<DwarfStreamer> Streamer;
1271 /// The units of the current debug map object.
1272 std::vector<CompileUnit> Units;
1274 /// The debug map object curently under consideration.
1275 DebugMapObject *CurrentDebugObject;
1277 /// \brief The Dwarf string pool
1278 NonRelocatableStringpool StringPool;
1280 /// \brief This map is keyed by the entry PC of functions in that
1281 /// debug object and the associated value is a pair storing the
1282 /// corresponding end PC and the offset to apply to get the linked
1285 /// See startDebugObject() for a more complete description of its use.
1286 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1288 /// \brief The CIEs that have been emitted in the output
1289 /// section. The actual CIE data serves a the key to this StringMap,
1290 /// this takes care of comparing the semantics of CIEs defined in
1291 /// different object files.
1292 StringMap<uint32_t> EmittedCIEs;
1294 /// Offset of the last CIE that has been emitted in the output
1295 /// debug_frame section.
1296 uint32_t LastCIEOffset;
1299 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1300 /// returning our CompileUnit object instead.
1301 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1303 std::upper_bound(Units.begin(), Units.end(), Offset,
1304 [](uint32_t LHS, const CompileUnit &RHS) {
1305 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1307 return CU != Units.end() ? &*CU : nullptr;
1310 /// \brief Resolve the DIE attribute reference that has been
1311 /// extracted in \p RefValue. The resulting DIE migh be in another
1312 /// CompileUnit which is stored into \p ReferencedCU.
1313 /// \returns null if resolving fails for any reason.
1314 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1315 DWARFFormValue &RefValue, const DWARFUnit &Unit,
1316 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1317 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1318 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1320 if ((RefCU = getUnitForOffset(RefOffset)))
1321 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1324 reportWarning("could not find referenced DIE", &Unit, &DIE);
1328 /// \brief Get the potential name and mangled name for the entity
1329 /// described by \p Die and store them in \Info if they are not
1331 /// \returns is a name was found.
1332 bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1333 DWARFUnit &U, AttributesInfo &Info) {
1334 // FIXME: a bit wastefull as the first getName might return the
1336 if (!Info.MangledName &&
1337 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1338 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1340 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1341 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1343 return Info.Name || Info.MangledName;
1346 /// \brief Report a warning to the user, optionaly including
1347 /// information about a specific \p DIE related to the warning.
1348 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
1349 const DWARFDebugInfoEntryMinimal *DIE) const {
1350 StringRef Context = "<debug map>";
1351 if (CurrentDebugObject)
1352 Context = CurrentDebugObject->getObjectFilename();
1353 warn(Warning, Context);
1355 if (!Options.Verbose || !DIE)
1358 errs() << " in DIE:\n";
1359 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1363 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1364 if (Options.NoOutput)
1367 Streamer = llvm::make_unique<DwarfStreamer>();
1368 return Streamer->init(TheTriple, OutputFilename);
1371 /// \brief Recursive helper to gather the child->parent relationships in the
1372 /// original compile unit.
1373 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1374 unsigned ParentIdx, CompileUnit &CU) {
1375 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1376 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
1378 if (DIE->hasChildren())
1379 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1380 Child = Child->getSibling())
1381 gatherDIEParents(Child, MyIdx, CU);
1384 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1388 case dwarf::DW_TAG_subprogram:
1389 case dwarf::DW_TAG_lexical_block:
1390 case dwarf::DW_TAG_subroutine_type:
1391 case dwarf::DW_TAG_structure_type:
1392 case dwarf::DW_TAG_class_type:
1393 case dwarf::DW_TAG_union_type:
1396 llvm_unreachable("Invalid Tag");
1399 void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1400 Units.reserve(Dwarf.getNumCompileUnits());
1402 // Iterate over the debug map entries and put all the ones that are
1403 // functions (because they have a size) into the Ranges map. This
1404 // map is very similar to the FunctionRanges that are stored in each
1405 // unit, with 2 notable differences:
1406 // - obviously this one is global, while the other ones are per-unit.
1407 // - this one contains not only the functions described in the DIE
1408 // tree, but also the ones that are only in the debug map.
1409 // The latter information is required to reproduce dsymutil's logic
1410 // while linking line tables. The cases where this information
1411 // matters look like bugs that need to be investigated, but for now
1412 // we need to reproduce dsymutil's behavior.
1413 // FIXME: Once we understood exactly if that information is needed,
1414 // maybe totally remove this (or try to use it to do a real
1415 // -gline-tables-only on Darwin.
1416 for (const auto &Entry : Obj.symbols()) {
1417 const auto &Mapping = Entry.getValue();
1419 Ranges[Mapping.ObjectAddress] = std::make_pair(
1420 Mapping.ObjectAddress + Mapping.Size,
1421 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1425 void DwarfLinker::endDebugObject() {
1427 ValidRelocs.clear();
1430 for (auto *Block : DIEBlocks)
1432 for (auto *Loc : DIELocs)
1440 /// \brief Iterate over the relocations of the given \p Section and
1441 /// store the ones that correspond to debug map entries into the
1442 /// ValidRelocs array.
1443 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1444 const object::MachOObjectFile &Obj,
1445 const DebugMapObject &DMO) {
1447 Section.getContents(Contents);
1448 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1450 for (const object::RelocationRef &Reloc : Section.relocations()) {
1451 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1452 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1453 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1455 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
1456 reportWarning(" unsupported relocation in debug_info section.");
1459 uint32_t Offset = Offset64;
1460 // Mach-o uses REL relocations, the addend is at the relocation offset.
1461 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1463 auto Sym = Reloc.getSymbol();
1464 if (Sym != Obj.symbol_end()) {
1465 StringRef SymbolName;
1466 if (Sym->getName(SymbolName)) {
1467 reportWarning("error getting relocation symbol name.");
1470 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
1471 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1472 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1473 // Do not store the addend. The addend was the address of the
1474 // symbol in the object file, the address in the binary that is
1475 // stored in the debug map doesn't need to be offseted.
1476 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1481 /// \brief Dispatch the valid relocation finding logic to the
1482 /// appropriate handler depending on the object file format.
1483 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1484 const object::ObjectFile &Obj,
1485 const DebugMapObject &DMO) {
1486 // Dispatch to the right handler depending on the file type.
1487 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1488 findValidRelocsMachO(Section, *MachOObj, DMO);
1490 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
1492 if (ValidRelocs.empty())
1495 // Sort the relocations by offset. We will walk the DIEs linearly in
1496 // the file, this allows us to just keep an index in the relocation
1497 // array that we advance during our walk, rather than resorting to
1498 // some associative container. See DwarfLinker::NextValidReloc.
1499 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1503 /// \brief Look for relocations in the debug_info section that match
1504 /// entries in the debug map. These relocations will drive the Dwarf
1505 /// link by indicating which DIEs refer to symbols present in the
1507 /// \returns wether there are any valid relocations in the debug info.
1508 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1509 const DebugMapObject &DMO) {
1510 // Find the debug_info section.
1511 for (const object::SectionRef &Section : Obj.sections()) {
1512 StringRef SectionName;
1513 Section.getName(SectionName);
1514 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1515 if (SectionName != "debug_info")
1517 return findValidRelocs(Section, Obj, DMO);
1522 /// \brief Checks that there is a relocation against an actual debug
1523 /// map entry between \p StartOffset and \p NextOffset.
1525 /// This function must be called with offsets in strictly ascending
1526 /// order because it never looks back at relocations it already 'went past'.
1527 /// \returns true and sets Info.InDebugMap if it is the case.
1528 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1529 CompileUnit::DIEInfo &Info) {
1530 assert(NextValidReloc == 0 ||
1531 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1532 if (NextValidReloc >= ValidRelocs.size())
1535 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1537 // We might need to skip some relocs that we didn't consider. For
1538 // example the high_pc of a discarded DIE might contain a reloc that
1539 // is in the list because it actually corresponds to the start of a
1540 // function that is in the debug map.
1541 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1542 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1544 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1547 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1548 const auto &Mapping = ValidReloc.Mapping->getValue();
1549 if (Options.Verbose)
1550 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1551 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1552 uint64_t(Mapping.ObjectAddress),
1553 uint64_t(Mapping.BinaryAddress));
1555 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1556 Mapping.ObjectAddress;
1557 Info.InDebugMap = true;
1561 /// \brief Get the starting and ending (exclusive) offset for the
1562 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1563 /// supposed to point to the position of the first attribute described
1565 /// \return [StartOffset, EndOffset) as a pair.
1566 static std::pair<uint32_t, uint32_t>
1567 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1568 unsigned Offset, const DWARFUnit &Unit) {
1569 DataExtractor Data = Unit.getDebugInfoExtractor();
1571 for (unsigned i = 0; i < Idx; ++i)
1572 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1574 uint32_t End = Offset;
1575 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1577 return std::make_pair(Offset, End);
1580 /// \brief Check if a variable describing DIE should be kept.
1581 /// \returns updated TraversalFlags.
1582 unsigned DwarfLinker::shouldKeepVariableDIE(
1583 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1584 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1585 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1587 // Global variables with constant value can always be kept.
1588 if (!(Flags & TF_InFunctionScope) &&
1589 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1590 MyInfo.InDebugMap = true;
1591 return Flags | TF_Keep;
1594 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1595 if (LocationIdx == -1U)
1598 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1599 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1600 uint32_t LocationOffset, LocationEndOffset;
1601 std::tie(LocationOffset, LocationEndOffset) =
1602 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1604 // See if there is a relocation to a valid debug map entry inside
1605 // this variable's location. The order is important here. We want to
1606 // always check in the variable has a valid relocation, so that the
1607 // DIEInfo is filled. However, we don't want a static variable in a
1608 // function to force us to keep the enclosing function.
1609 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1610 (Flags & TF_InFunctionScope))
1613 if (Options.Verbose)
1614 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1616 return Flags | TF_Keep;
1619 /// \brief Check if a function describing DIE should be kept.
1620 /// \returns updated TraversalFlags.
1621 unsigned DwarfLinker::shouldKeepSubprogramDIE(
1622 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1623 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1624 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1626 Flags |= TF_InFunctionScope;
1628 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1629 if (LowPcIdx == -1U)
1632 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1633 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1634 uint32_t LowPcOffset, LowPcEndOffset;
1635 std::tie(LowPcOffset, LowPcEndOffset) =
1636 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1639 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1640 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1641 if (LowPc == -1ULL ||
1642 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1645 if (Options.Verbose)
1646 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1650 DWARFFormValue HighPcValue;
1651 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1652 reportWarning("Function without high_pc. Range will be discarded.\n",
1658 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1659 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1661 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1662 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1665 // Replace the debug map range with a more accurate one.
1666 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
1667 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1671 /// \brief Check if a DIE should be kept.
1672 /// \returns updated TraversalFlags.
1673 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1675 CompileUnit::DIEInfo &MyInfo,
1677 switch (DIE.getTag()) {
1678 case dwarf::DW_TAG_constant:
1679 case dwarf::DW_TAG_variable:
1680 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1681 case dwarf::DW_TAG_subprogram:
1682 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1683 case dwarf::DW_TAG_module:
1684 case dwarf::DW_TAG_imported_module:
1685 case dwarf::DW_TAG_imported_declaration:
1686 case dwarf::DW_TAG_imported_unit:
1687 // We always want to keep these.
1688 return Flags | TF_Keep;
1694 /// \brief Mark the passed DIE as well as all the ones it depends on
1697 /// This function is called by lookForDIEsToKeep on DIEs that are
1698 /// newly discovered to be needed in the link. It recursively calls
1699 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1700 /// TraversalFlags to inform it that it's not doing the primary DIE
1702 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1703 CompileUnit::DIEInfo &MyInfo,
1704 const DebugMapObject &DMO,
1705 CompileUnit &CU, unsigned Flags) {
1706 const DWARFUnit &Unit = CU.getOrigUnit();
1709 // First mark all the parent chain as kept.
1710 unsigned AncestorIdx = MyInfo.ParentIdx;
1711 while (!CU.getInfo(AncestorIdx).Keep) {
1712 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1713 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1714 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1717 // Then we need to mark all the DIEs referenced by this DIE's
1718 // attributes as kept.
1719 DataExtractor Data = Unit.getDebugInfoExtractor();
1720 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1721 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1723 // Mark all DIEs referenced through atttributes as kept.
1724 for (const auto &AttrSpec : Abbrev->attributes()) {
1725 DWARFFormValue Val(AttrSpec.Form);
1727 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1728 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1732 Val.extractValue(Data, &Offset, &Unit);
1733 CompileUnit *ReferencedCU;
1734 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1735 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1736 TF_Keep | TF_DependencyWalk);
1740 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1741 /// keep. Store that information in \p CU's DIEInfo.
1743 /// This function is the entry point of the DIE selection
1744 /// algorithm. It is expected to walk the DIE tree in file order and
1745 /// (though the mediation of its helper) call hasValidRelocation() on
1746 /// each DIE that might be a 'root DIE' (See DwarfLinker class
1748 /// While walking the dependencies of root DIEs, this function is
1749 /// also called, but during these dependency walks the file order is
1750 /// not respected. The TF_DependencyWalk flag tells us which kind of
1751 /// traversal we are currently doing.
1752 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1753 const DebugMapObject &DMO, CompileUnit &CU,
1755 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1756 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1757 bool AlreadyKept = MyInfo.Keep;
1759 // If the Keep flag is set, we are marking a required DIE's
1760 // dependencies. If our target is already marked as kept, we're all
1762 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1765 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1766 // because it would screw up the relocation finding logic.
1767 if (!(Flags & TF_DependencyWalk))
1768 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1770 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1771 if (!AlreadyKept && (Flags & TF_Keep))
1772 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1774 // The TF_ParentWalk flag tells us that we are currently walking up
1775 // the parent chain of a required DIE, and we don't want to mark all
1776 // the children of the parents as kept (consider for example a
1777 // DW_TAG_namespace node in the parent chain). There are however a
1778 // set of DIE types for which we want to ignore that directive and still
1779 // walk their children.
1780 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1781 Flags &= ~TF_ParentWalk;
1783 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1786 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1787 Child = Child->getSibling())
1788 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1791 /// \brief Assign an abbreviation numer to \p Abbrev.
1793 /// Our DIEs get freed after every DebugMapObject has been processed,
1794 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1795 /// the instances hold by the DIEs. When we encounter an abbreviation
1796 /// that we don't know, we create a permanent copy of it.
1797 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1798 // Check the set for priors.
1799 FoldingSetNodeID ID;
1802 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1804 // If it's newly added.
1806 // Assign existing abbreviation number.
1807 Abbrev.setNumber(InSet->getNumber());
1809 // Add to abbreviation list.
1810 Abbreviations.push_back(
1811 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1812 for (const auto &Attr : Abbrev.getData())
1813 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1814 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1815 // Assign the unique abbreviation number.
1816 Abbrev.setNumber(Abbreviations.size());
1817 Abbreviations.back()->setNumber(Abbreviations.size());
1821 /// \brief Clone a string attribute described by \p AttrSpec and add
1823 /// \returns the size of the new attribute.
1824 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1825 const DWARFFormValue &Val,
1826 const DWARFUnit &U) {
1827 // Switch everything to out of line strings.
1828 const char *String = *Val.getAsCString(&U);
1829 unsigned Offset = StringPool.getStringOffset(String);
1830 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1831 DIEInteger(Offset));
1835 /// \brief Clone an attribute referencing another DIE and add
1837 /// \returns the size of the new attribute.
1838 unsigned DwarfLinker::cloneDieReferenceAttribute(
1839 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1840 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1841 CompileUnit &Unit) {
1842 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
1843 DIE *NewRefDie = nullptr;
1844 CompileUnit *RefUnit = nullptr;
1845 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1847 if (!(RefUnit = getUnitForOffset(Ref)) ||
1848 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1849 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1850 if (!AttributeString)
1851 AttributeString = "DW_AT_???";
1852 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1854 &Unit.getOrigUnit(), &InputDIE);
1858 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1859 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1860 if (!RefInfo.Clone) {
1861 assert(Ref > InputDIE.getOffset());
1862 // We haven't cloned this DIE yet. Just create an empty one and
1863 // store it. It'll get really cloned when we process it.
1864 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1866 NewRefDie = RefInfo.Clone;
1868 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1869 // We cannot currently rely on a DIEEntry to emit ref_addr
1870 // references, because the implementation calls back to DwarfDebug
1871 // to find the unit offset. (We don't have a DwarfDebug)
1872 // FIXME: we should be able to design DIEEntry reliance on
1875 if (Ref < InputDIE.getOffset()) {
1876 // We must have already cloned that DIE.
1877 uint32_t NewRefOffset =
1878 RefUnit->getStartOffset() + NewRefDie->getOffset();
1879 Attr = NewRefOffset;
1880 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1881 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
1883 // A forward reference. Note and fixup later.
1885 Unit.noteForwardReference(
1887 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1888 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
1893 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1894 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
1898 /// \brief Clone an attribute of block form (locations, constants) and add
1900 /// \returns the size of the new attribute.
1901 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1902 const DWARFFormValue &Val,
1903 unsigned AttrSize) {
1906 DIELoc *Loc = nullptr;
1907 DIEBlock *Block = nullptr;
1908 // Just copy the block data over.
1909 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1910 Loc = new (DIEAlloc) DIELoc;
1911 DIELocs.push_back(Loc);
1913 Block = new (DIEAlloc) DIEBlock;
1914 DIEBlocks.push_back(Block);
1916 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1919 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1920 dwarf::Form(AttrSpec.Form), Loc);
1922 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1923 dwarf::Form(AttrSpec.Form), Block);
1924 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1925 for (auto Byte : Bytes)
1926 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
1927 dwarf::DW_FORM_data1, DIEInteger(Byte));
1928 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1929 // the DIE class, this if could be replaced by
1930 // Attr->setSize(Bytes.size()).
1933 Loc->ComputeSize(&Streamer->getAsmPrinter());
1935 Block->ComputeSize(&Streamer->getAsmPrinter());
1937 Die.addValue(DIEAlloc, Value);
1941 /// \brief Clone an address attribute and add it to \p Die.
1942 /// \returns the size of the new attribute.
1943 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1944 const DWARFFormValue &Val,
1945 const CompileUnit &Unit,
1946 AttributesInfo &Info) {
1947 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
1948 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1949 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1950 Die.getTag() == dwarf::DW_TAG_lexical_block)
1951 Addr += Info.PCOffset;
1952 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1953 Addr = Unit.getLowPc();
1954 if (Addr == UINT64_MAX)
1957 Info.HasLowPc = true;
1958 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1959 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1960 if (uint64_t HighPc = Unit.getHighPc())
1965 // If we have a high_pc recorded for the input DIE, use
1966 // it. Otherwise (when no relocations where applied) just use the
1967 // one we just decoded.
1968 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1971 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1972 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
1973 return Unit.getOrigUnit().getAddressByteSize();
1976 /// \brief Clone a scalar attribute and add it to \p Die.
1977 /// \returns the size of the new attribute.
1978 unsigned DwarfLinker::cloneScalarAttribute(
1979 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
1980 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
1981 AttributesInfo &Info) {
1983 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1984 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1985 if (Unit.getLowPc() == -1ULL)
1987 // Dwarf >= 4 high_pc is an size, not an address.
1988 Value = Unit.getHighPc() - Unit.getLowPc();
1989 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1990 Value = *Val.getAsSectionOffset();
1991 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1992 Value = *Val.getAsSignedConstant();
1993 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1994 Value = *OptionalValue;
1996 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1997 &Unit.getOrigUnit(), &InputDIE);
2000 PatchLocation Patch =
2001 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2002 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
2003 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
2004 Unit.noteRangeAttribute(Die, Patch);
2005 // A more generic way to check for location attributes would be
2006 // nice, but it's very unlikely that any other attribute needs a
2008 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2009 AttrSpec.Attr == dwarf::DW_AT_frame_base)
2010 Unit.noteLocationAttribute(Patch, Info.PCOffset);
2011 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2012 Info.IsDeclaration = true;
2017 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2018 /// value \p Val, and add it to \p Die.
2019 /// \returns the size of the cloned attribute.
2020 unsigned DwarfLinker::cloneAttribute(DIE &Die,
2021 const DWARFDebugInfoEntryMinimal &InputDIE,
2023 const DWARFFormValue &Val,
2024 const AttributeSpec AttrSpec,
2025 unsigned AttrSize, AttributesInfo &Info) {
2026 const DWARFUnit &U = Unit.getOrigUnit();
2028 switch (AttrSpec.Form) {
2029 case dwarf::DW_FORM_strp:
2030 case dwarf::DW_FORM_string:
2031 return cloneStringAttribute(Die, AttrSpec, Val, U);
2032 case dwarf::DW_FORM_ref_addr:
2033 case dwarf::DW_FORM_ref1:
2034 case dwarf::DW_FORM_ref2:
2035 case dwarf::DW_FORM_ref4:
2036 case dwarf::DW_FORM_ref8:
2037 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
2039 case dwarf::DW_FORM_block:
2040 case dwarf::DW_FORM_block1:
2041 case dwarf::DW_FORM_block2:
2042 case dwarf::DW_FORM_block4:
2043 case dwarf::DW_FORM_exprloc:
2044 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2045 case dwarf::DW_FORM_addr:
2046 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
2047 case dwarf::DW_FORM_data1:
2048 case dwarf::DW_FORM_data2:
2049 case dwarf::DW_FORM_data4:
2050 case dwarf::DW_FORM_data8:
2051 case dwarf::DW_FORM_udata:
2052 case dwarf::DW_FORM_sdata:
2053 case dwarf::DW_FORM_sec_offset:
2054 case dwarf::DW_FORM_flag:
2055 case dwarf::DW_FORM_flag_present:
2056 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2059 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2066 /// \brief Apply the valid relocations found by findValidRelocs() to
2067 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
2068 /// in the debug_info section.
2070 /// Like for findValidRelocs(), this function must be called with
2071 /// monotonic \p BaseOffset values.
2073 /// \returns wether any reloc has been applied.
2074 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2075 uint32_t BaseOffset, bool isLittleEndian) {
2076 assert((NextValidReloc == 0 ||
2077 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2078 "BaseOffset should only be increasing.");
2079 if (NextValidReloc >= ValidRelocs.size())
2082 // Skip relocs that haven't been applied.
2083 while (NextValidReloc < ValidRelocs.size() &&
2084 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2087 bool Applied = false;
2088 uint64_t EndOffset = BaseOffset + Data.size();
2089 while (NextValidReloc < ValidRelocs.size() &&
2090 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2091 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2092 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2093 assert(ValidReloc.Offset - BaseOffset < Data.size());
2094 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2096 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2097 Value += ValidReloc.Addend;
2098 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2099 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2100 Buf[i] = uint8_t(Value >> (Index * 8));
2102 assert(ValidReloc.Size <= sizeof(Buf));
2103 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2110 static bool isTypeTag(uint16_t Tag) {
2112 case dwarf::DW_TAG_array_type:
2113 case dwarf::DW_TAG_class_type:
2114 case dwarf::DW_TAG_enumeration_type:
2115 case dwarf::DW_TAG_pointer_type:
2116 case dwarf::DW_TAG_reference_type:
2117 case dwarf::DW_TAG_string_type:
2118 case dwarf::DW_TAG_structure_type:
2119 case dwarf::DW_TAG_subroutine_type:
2120 case dwarf::DW_TAG_typedef:
2121 case dwarf::DW_TAG_union_type:
2122 case dwarf::DW_TAG_ptr_to_member_type:
2123 case dwarf::DW_TAG_set_type:
2124 case dwarf::DW_TAG_subrange_type:
2125 case dwarf::DW_TAG_base_type:
2126 case dwarf::DW_TAG_const_type:
2127 case dwarf::DW_TAG_constant:
2128 case dwarf::DW_TAG_file_type:
2129 case dwarf::DW_TAG_namelist:
2130 case dwarf::DW_TAG_packed_type:
2131 case dwarf::DW_TAG_volatile_type:
2132 case dwarf::DW_TAG_restrict_type:
2133 case dwarf::DW_TAG_interface_type:
2134 case dwarf::DW_TAG_unspecified_type:
2135 case dwarf::DW_TAG_shared_type:
2143 /// \brief Recursively clone \p InputDIE's subtrees that have been
2144 /// selected to appear in the linked output.
2146 /// \param OutOffset is the Offset where the newly created DIE will
2147 /// lie in the linked compile unit.
2149 /// \returns the cloned DIE object or null if nothing was selected.
2150 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
2151 CompileUnit &Unit, int64_t PCOffset,
2152 uint32_t OutOffset) {
2153 DWARFUnit &U = Unit.getOrigUnit();
2154 unsigned Idx = U.getDIEIndex(&InputDIE);
2155 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2157 // Should the DIE appear in the output?
2158 if (!Unit.getInfo(Idx).Keep)
2161 uint32_t Offset = InputDIE.getOffset();
2162 // The DIE might have been already created by a forward reference
2163 // (see cloneDieReferenceAttribute()).
2164 DIE *Die = Info.Clone;
2166 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
2167 assert(Die->getTag() == InputDIE.getTag());
2168 Die->setOffset(OutOffset);
2170 // Extract and clone every attribute.
2171 DataExtractor Data = U.getDebugInfoExtractor();
2172 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
2173 AttributesInfo AttrInfo;
2175 // We could copy the data only if we need to aply a relocation to
2176 // it. After testing, it seems there is no performance downside to
2177 // doing the copy unconditionally, and it makes the code simpler.
2178 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2179 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2180 // Modify the copy with relocated addresses.
2181 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2182 // If we applied relocations, we store the value of high_pc that was
2183 // potentially stored in the input DIE. If high_pc is an address
2184 // (Dwarf version == 2), then it might have been relocated to a
2185 // totally unrelated value (because the end address in the object
2186 // file might be start address of another function which got moved
2187 // independantly by the linker). The computation of the actual
2188 // high_pc value is done in cloneAddressAttribute().
2189 AttrInfo.OrigHighPc =
2190 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2193 // Reset the Offset to 0 as we will be working on the local copy of
2197 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2198 Offset += getULEB128Size(Abbrev->getCode());
2200 // We are entering a subprogram. Get and propagate the PCOffset.
2201 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2202 PCOffset = Info.AddrAdjust;
2203 AttrInfo.PCOffset = PCOffset;
2205 for (const auto &AttrSpec : Abbrev->attributes()) {
2206 DWARFFormValue Val(AttrSpec.Form);
2207 uint32_t AttrSize = Offset;
2208 Val.extractValue(Data, &Offset, &U);
2209 AttrSize = Offset - AttrSize;
2212 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2215 // Look for accelerator entries.
2216 uint16_t Tag = InputDIE.getTag();
2217 // FIXME: This is slightly wrong. An inline_subroutine without a
2218 // low_pc, but with AT_ranges might be interesting to get into the
2219 // accelerator tables too. For now stick with dsymutil's behavior.
2220 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2221 Tag != dwarf::DW_TAG_compile_unit &&
2222 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2223 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2224 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2225 AttrInfo.MangledNameOffset,
2226 Tag == dwarf::DW_TAG_inlined_subroutine);
2228 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2229 Tag == dwarf::DW_TAG_inlined_subroutine);
2230 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2231 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2232 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2235 DIEAbbrev NewAbbrev = Die->generateAbbrev();
2236 // If a scope DIE is kept, we must have kept at least one child. If
2237 // it's not the case, we'll just be emitting one wasteful end of
2238 // children marker, but things won't break.
2239 if (InputDIE.hasChildren())
2240 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2241 // Assign a permanent abbrev number
2242 AssignAbbrev(NewAbbrev);
2243 Die->setAbbrevNumber(NewAbbrev.getNumber());
2245 // Add the size of the abbreviation number to the output offset.
2246 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2248 if (!Abbrev->hasChildren()) {
2250 Die->setSize(OutOffset - Die->getOffset());
2254 // Recursively clone children.
2255 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2256 Child = Child->getSibling()) {
2257 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
2258 Die->addChild(std::unique_ptr<DIE>(Clone));
2259 OutOffset = Clone->getOffset() + Clone->getSize();
2263 // Account for the end of children marker.
2264 OutOffset += sizeof(int8_t);
2266 Die->setSize(OutOffset - Die->getOffset());
2270 /// \brief Patch the input object file relevant debug_ranges entries
2271 /// and emit them in the output file. Update the relevant attributes
2272 /// to point at the new entries.
2273 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2274 DWARFContext &OrigDwarf) const {
2275 DWARFDebugRangeList RangeList;
2276 const auto &FunctionRanges = Unit.getFunctionRanges();
2277 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2278 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2279 OrigDwarf.isLittleEndian(), AddressSize);
2280 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2281 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2282 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
2283 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2284 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2285 // Ranges addresses are based on the unit's low_pc. Compute the
2286 // offset we need to apply to adapt to the the new unit's low_pc.
2287 int64_t UnitPcOffset = 0;
2288 if (OrigLowPc != -1ULL)
2289 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2291 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2292 uint32_t Offset = RangeAttribute.get();
2293 RangeAttribute.set(Streamer->getRangesSectionSize());
2294 RangeList.extract(RangeExtractor, &Offset);
2295 const auto &Entries = RangeList.getEntries();
2296 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2298 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2299 First.StartAddress >= CurrRange.stop()) {
2300 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2301 if (CurrRange == InvalidRange ||
2302 CurrRange.start() > First.StartAddress + OrigLowPc) {
2303 reportWarning("no mapping for range.");
2308 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2313 /// \brief Generate the debug_aranges entries for \p Unit and if the
2314 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2315 /// contribution for this attribute.
2316 /// FIXME: this could actually be done right in patchRangesForUnit,
2317 /// but for the sake of initial bit-for-bit compatibility with legacy
2318 /// dsymutil, we have to do it in a delayed pass.
2319 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2320 auto Attr = Unit.getUnitRangesAttribute();
2322 Attr->set(Streamer->getRangesSectionSize());
2323 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
2326 /// \brief Insert the new line info sequence \p Seq into the current
2327 /// set of already linked line info \p Rows.
2328 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2329 std::vector<DWARFDebugLine::Row> &Rows) {
2333 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2334 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2339 auto InsertPoint = std::lower_bound(
2340 Rows.begin(), Rows.end(), Seq.front(),
2341 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2342 return LHS.Address < RHS.Address;
2345 // FIXME: this only removes the unneeded end_sequence if the
2346 // sequences have been inserted in order. using a global sort like
2347 // described in patchLineTableForUnit() and delaying the end_sequene
2348 // elimination to emitLineTableForUnit() we can get rid of all of them.
2349 if (InsertPoint != Rows.end() &&
2350 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2351 *InsertPoint = Seq.front();
2352 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2354 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2360 static void patchStmtList(DIE &Die, DIEInteger Offset) {
2361 for (auto &V : Die.values())
2362 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2363 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2367 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2370 /// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2371 /// recreate a relocated version of these for the address ranges that
2372 /// are present in the binary.
2373 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2374 DWARFContext &OrigDwarf) {
2375 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
2376 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2377 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2378 if (StmtList == -1ULL)
2381 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2382 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2383 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
2385 // Parse the original line info for the unit.
2386 DWARFDebugLine::LineTable LineTable;
2387 uint32_t StmtOffset = StmtList;
2388 StringRef LineData = OrigDwarf.getLineSection().Data;
2389 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2390 Unit.getOrigUnit().getAddressByteSize());
2391 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2394 // This vector is the output line table.
2395 std::vector<DWARFDebugLine::Row> NewRows;
2396 NewRows.reserve(LineTable.Rows.size());
2398 // Current sequence of rows being extracted, before being inserted
2400 std::vector<DWARFDebugLine::Row> Seq;
2401 const auto &FunctionRanges = Unit.getFunctionRanges();
2402 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2404 // FIXME: This logic is meant to generate exactly the same output as
2405 // Darwin's classic dsynutil. There is a nicer way to implement this
2406 // by simply putting all the relocated line info in NewRows and simply
2407 // sorting NewRows before passing it to emitLineTableForUnit. This
2408 // should be correct as sequences for a function should stay
2409 // together in the sorted output. There are a few corner cases that
2410 // look suspicious though, and that required to implement the logic
2411 // this way. Revisit that once initial validation is finished.
2413 // Iterate over the object file line info and extract the sequences
2414 // that correspond to linked functions.
2415 for (auto &Row : LineTable.Rows) {
2416 // Check wether we stepped out of the range. The range is
2417 // half-open, but consider accept the end address of the range if
2418 // it is marked as end_sequence in the input (because in that
2419 // case, the relocation offset is accurate and that entry won't
2420 // serve as the start of another function).
2421 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2422 Row.Address > CurrRange.stop() ||
2423 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2424 // We just stepped out of a known range. Insert a end_sequence
2425 // corresponding to the end of the range.
2426 uint64_t StopAddress = CurrRange != InvalidRange
2427 ? CurrRange.stop() + CurrRange.value()
2429 CurrRange = FunctionRanges.find(Row.Address);
2430 bool CurrRangeValid =
2431 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2432 if (!CurrRangeValid) {
2433 CurrRange = InvalidRange;
2434 if (StopAddress != -1ULL) {
2435 // Try harder by looking in the DebugMapObject function
2436 // ranges map. There are corner cases where this finds a
2437 // valid entry. It's unclear if this is right or wrong, but
2438 // for now do as dsymutil.
2439 // FIXME: Understand exactly what cases this addresses and
2440 // potentially remove it along with the Ranges map.
2441 auto Range = Ranges.lower_bound(Row.Address);
2442 if (Range != Ranges.begin() && Range != Ranges.end())
2445 if (Range != Ranges.end() && Range->first <= Row.Address &&
2446 Range->second.first >= Row.Address) {
2447 StopAddress = Row.Address + Range->second.second;
2451 if (StopAddress != -1ULL && !Seq.empty()) {
2452 // Insert end sequence row with the computed end address, but
2453 // the same line as the previous one.
2454 Seq.emplace_back(Seq.back());
2455 Seq.back().Address = StopAddress;
2456 Seq.back().EndSequence = 1;
2457 Seq.back().PrologueEnd = 0;
2458 Seq.back().BasicBlock = 0;
2459 Seq.back().EpilogueBegin = 0;
2460 insertLineSequence(Seq, NewRows);
2463 if (!CurrRangeValid)
2467 // Ignore empty sequences.
2468 if (Row.EndSequence && Seq.empty())
2471 // Relocate row address and add it to the current sequence.
2472 Row.Address += CurrRange.value();
2473 Seq.emplace_back(Row);
2475 if (Row.EndSequence)
2476 insertLineSequence(Seq, NewRows);
2479 // Finished extracting, now emit the line tables.
2480 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2481 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2482 // prologue over and that works because we act as both producer and
2483 // consumer. It would be nicer to have a real configurable line
2485 if (LineTable.Prologue.Version != 2 ||
2486 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2487 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2488 LineTable.Prologue.OpcodeBase != 13)
2489 reportWarning("line table paramters mismatch. Cannot emit.");
2491 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2492 LineTable.Prologue.MinInstLength, NewRows,
2493 Unit.getOrigUnit().getAddressByteSize());
2496 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2497 Streamer->emitPubNamesForUnit(Unit);
2498 Streamer->emitPubTypesForUnit(Unit);
2501 /// \brief Read the frame info stored in the object, and emit the
2502 /// patched frame descriptions for the linked binary.
2504 /// This is actually pretty easy as the data of the CIEs and FDEs can
2505 /// be considered as black boxes and moved as is. The only thing to do
2506 /// is to patch the addresses in the headers.
2507 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2508 DWARFContext &OrigDwarf,
2509 unsigned AddrSize) {
2510 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2511 if (FrameData.empty())
2514 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2515 uint32_t InputOffset = 0;
2517 // Store the data of the CIEs defined in this object, keyed by their
2519 DenseMap<uint32_t, StringRef> LocalCIES;
2521 while (Data.isValidOffset(InputOffset)) {
2522 uint32_t EntryOffset = InputOffset;
2523 uint32_t InitialLength = Data.getU32(&InputOffset);
2524 if (InitialLength == 0xFFFFFFFF)
2525 return reportWarning("Dwarf64 bits no supported");
2527 uint32_t CIEId = Data.getU32(&InputOffset);
2528 if (CIEId == 0xFFFFFFFF) {
2529 // This is a CIE, store it.
2530 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2531 LocalCIES[EntryOffset] = CIEData;
2532 // The -4 is to account for the CIEId we just read.
2533 InputOffset += InitialLength - 4;
2537 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2539 // Some compilers seem to emit frame info that doesn't start at
2540 // the function entry point, thus we can't just lookup the address
2541 // in the debug map. Use the linker's range map to see if the FDE
2542 // describes something that we can relocate.
2543 auto Range = Ranges.upper_bound(Loc);
2544 if (Range != Ranges.begin())
2546 if (Range == Ranges.end() || Range->first > Loc ||
2547 Range->second.first <= Loc) {
2548 // The +4 is to account for the size of the InitialLength field itself.
2549 InputOffset = EntryOffset + InitialLength + 4;
2553 // This is an FDE, and we have a mapping.
2554 // Have we already emitted a corresponding CIE?
2555 StringRef CIEData = LocalCIES[CIEId];
2556 if (CIEData.empty())
2557 return reportWarning("Inconsistent debug_frame content. Dropping.");
2559 // Look if we already emitted a CIE that corresponds to the
2560 // referenced one (the CIE data is the key of that lookup).
2561 auto IteratorInserted = EmittedCIEs.insert(
2562 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2563 // If there is no CIE yet for this ID, emit it.
2564 if (IteratorInserted.second ||
2565 // FIXME: dsymutil-classic only caches the last used CIE for
2566 // reuse. Mimic that behavior for now. Just removing that
2567 // second half of the condition and the LastCIEOffset variable
2568 // makes the code DTRT.
2569 LastCIEOffset != IteratorInserted.first->getValue()) {
2570 LastCIEOffset = Streamer->getFrameSectionSize();
2571 IteratorInserted.first->getValue() = LastCIEOffset;
2572 Streamer->emitCIE(CIEData);
2575 // Emit the FDE with updated address and CIE pointer.
2576 // (4 + AddrSize) is the size of the CIEId + initial_location
2577 // fields that will get reconstructed by emitFDE().
2578 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
2579 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
2580 Loc + Range->second.second,
2581 FrameData.substr(InputOffset, FDERemainingBytes));
2582 InputOffset += FDERemainingBytes;
2586 bool DwarfLinker::link(const DebugMap &Map) {
2588 if (Map.begin() == Map.end()) {
2589 errs() << "Empty debug map.\n";
2593 if (!createStreamer(Map.getTriple(), OutputFilename))
2596 // Size of the DIEs (and headers) generated for the linked output.
2597 uint64_t OutputDebugInfoSize = 0;
2598 // A unique ID that identifies each compile unit.
2599 unsigned UnitID = 0;
2600 for (const auto &Obj : Map.objects()) {
2601 CurrentDebugObject = Obj.get();
2603 if (Options.Verbose)
2604 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2605 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
2606 if (std::error_code EC = ErrOrObj.getError()) {
2607 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
2611 // Look for relocations that correspond to debug map entries.
2612 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
2613 if (Options.Verbose)
2614 outs() << "No valid relocations found. Skipping.\n";
2618 // Setup access to the debug info.
2619 DWARFContextInMemory DwarfContext(*ErrOrObj);
2620 startDebugObject(DwarfContext, *Obj);
2622 // In a first phase, just read in the debug info and store the DIE
2623 // parent links that we will use during the next phase.
2624 for (const auto &CU : DwarfContext.compile_units()) {
2625 auto *CUDie = CU->getUnitDIE(false);
2626 if (Options.Verbose) {
2627 outs() << "Input compilation unit:";
2628 CUDie->dump(outs(), CU.get(), 0);
2630 Units.emplace_back(*CU, UnitID++);
2631 gatherDIEParents(CUDie, 0, Units.back());
2634 // Then mark all the DIEs that need to be present in the linked
2635 // output and collect some information about them. Note that this
2636 // loop can not be merged with the previous one becaue cross-cu
2637 // references require the ParentIdx to be setup for every CU in
2638 // the object file before calling this.
2639 for (auto &CurrentUnit : Units)
2640 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
2643 // The calls to applyValidRelocs inside cloneDIE will walk the
2644 // reloc array again (in the same way findValidRelocsInDebugInfo()
2645 // did). We need to reset the NextValidReloc index to the beginning.
2648 // Construct the output DIE tree by cloning the DIEs we chose to
2649 // keep above. If there are no valid relocs, then there's nothing
2651 if (!ValidRelocs.empty())
2652 for (auto &CurrentUnit : Units) {
2653 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
2654 CurrentUnit.setStartOffset(OutputDebugInfoSize);
2655 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
2656 11 /* Unit Header size */);
2657 CurrentUnit.setOutputUnitDIE(OutputDIE);
2658 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
2659 if (Options.NoOutput)
2661 // FIXME: for compatibility with the classic dsymutil, we emit
2662 // an empty line table for the unit, even if the unit doesn't
2663 // actually exist in the DIE tree.
2664 patchLineTableForUnit(CurrentUnit, DwarfContext);
2667 patchRangesForUnit(CurrentUnit, DwarfContext);
2668 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
2669 emitAcceleratorEntriesForUnit(CurrentUnit);
2672 // Emit all the compile unit's debug information.
2673 if (!ValidRelocs.empty() && !Options.NoOutput)
2674 for (auto &CurrentUnit : Units) {
2675 generateUnitRanges(CurrentUnit);
2676 CurrentUnit.fixupForwardReferences();
2677 Streamer->emitCompileUnitHeader(CurrentUnit);
2678 if (!CurrentUnit.getOutputUnitDIE())
2680 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
2683 if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
2684 patchFrameInfoForObject(*Obj, DwarfContext,
2685 Units[0].getOrigUnit().getAddressByteSize());
2687 // Clean-up before starting working on the next object.
2691 // Emit everything that's global.
2692 if (!Options.NoOutput) {
2693 Streamer->emitAbbrevs(Abbreviations);
2694 Streamer->emitStrings(StringPool);
2697 return Options.NoOutput ? true : Streamer->finish();
2701 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
2702 const LinkOptions &Options) {
2703 DwarfLinker Linker(OutputFilename, Options);
2704 return Linker.link(DM);