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 once DIE::Values has a stable iterator we can
65 struct PatchLocation {
69 PatchLocation() : Die(nullptr), Index(0) {}
70 PatchLocation(DIE &Die, unsigned Index) : Die(&Die), Index(Index) {}
72 void set(uint64_t New) const {
74 assert(Index < Die->getValues().size());
75 const auto &Old = Die->getValues()[Index];
76 assert(Old.getType() == DIEValue::isInteger);
78 DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New)));
81 uint64_t get() const {
83 assert(Index < Die->getValues().size());
84 assert(Die->getValues()[Index].getType() == DIEValue::isInteger);
85 return Die->getValues()[Index].getDIEInteger().getValue();
89 /// \brief Stores all information relating to a compile unit, be it in
90 /// its original instance in the object file to its brand new cloned
91 /// and linked DIE tree.
94 /// \brief Information gathered about a DIE in the object file.
96 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
97 DIE *Clone; ///< Cloned version of that DIE.
98 uint32_t ParentIdx; ///< The index of this DIE's parent.
99 bool Keep; ///< Is the DIE part of the linked output?
100 bool InDebugMap; ///< Was this DIE's entity found in the map?
103 CompileUnit(DWARFUnit &OrigUnit, unsigned ID)
104 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
106 Info.resize(OrigUnit.getNumDIEs());
109 CompileUnit(CompileUnit &&RHS)
110 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
111 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
112 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
113 // The CompileUnit container has been 'reserve()'d with the right
114 // size. We cannot move the IntervalMap anyway.
115 llvm_unreachable("CompileUnits should not be moved.");
118 DWARFUnit &getOrigUnit() const { return OrigUnit; }
120 unsigned getUniqueID() const { return ID; }
122 DIE *getOutputUnitDIE() const { return CUDie.get(); }
123 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
125 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
126 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
128 uint64_t getStartOffset() const { return StartOffset; }
129 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
130 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
132 uint64_t getLowPc() const { return LowPc; }
133 uint64_t getHighPc() const { return HighPc; }
135 Optional<PatchLocation> getUnitRangesAttribute() const {
136 return UnitRangeAttribute;
138 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
139 const std::vector<PatchLocation> &getRangesAttributes() const {
140 return RangeAttributes;
143 const std::vector<std::pair<PatchLocation, int64_t>> &
144 getLocationAttributes() const {
145 return LocationAttributes;
148 /// \brief Compute the end offset for this unit. Must be
149 /// called after the CU's DIEs have been cloned.
150 /// \returns the next unit offset (which is also the current
151 /// debug_info section size).
152 uint64_t computeNextUnitOffset();
154 /// \brief Keep track of a forward reference to DIE \p Die in \p
155 /// RefUnit by \p Attr. The attribute should be fixed up later to
156 /// point to the absolute offset of \p Die in the debug_info section.
157 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
160 /// \brief Apply all fixups recored by noteForwardReference().
161 void fixupForwardReferences();
163 /// \brief Add a function range [\p LowPC, \p HighPC) that is
164 /// relocatad by applying offset \p PCOffset.
165 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
167 /// \brief Keep track of a DW_AT_range attribute that we will need to
169 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
171 /// \brief Keep track of a location attribute pointing to a location
172 /// list in the debug_loc section.
173 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
175 /// \brief Add a name accelerator entry for \p Die with \p Name
176 /// which is stored in the string table at \p Offset.
177 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
178 bool SkipPubnamesSection = false);
180 /// \brief Add a type accelerator entry for \p Die with \p Name
181 /// which is stored in the string table at \p Offset.
182 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
185 StringRef Name; ///< Name of the entry.
186 const DIE *Die; ///< DIE this entry describes.
187 uint32_t NameOffset; ///< Offset of Name in the string pool.
188 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
190 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
191 bool SkipPubSection = false)
192 : Name(Name), Die(Die), NameOffset(NameOffset),
193 SkipPubSection(SkipPubSection) {}
196 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
197 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
202 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
203 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
205 uint64_t StartOffset;
206 uint64_t NextUnitOffset;
211 /// \brief A list of attributes to fixup with the absolute offset of
212 /// a DIE in the debug_info section.
214 /// The offsets for the attributes in this array couldn't be set while
215 /// cloning because for cross-cu forward refences the target DIE's
216 /// offset isn't known you emit the reference attribute.
217 std::vector<std::tuple<DIE *, const CompileUnit *, PatchLocation>>
218 ForwardDIEReferences;
220 FunctionIntervals::Allocator RangeAlloc;
221 /// \brief The ranges in that interval map are the PC ranges for
222 /// functions in this unit, associated with the PC offset to apply
223 /// to the addresses to get the linked address.
224 FunctionIntervals Ranges;
226 /// \brief DW_AT_ranges attributes to patch after we have gathered
227 /// all the unit's function addresses.
229 std::vector<PatchLocation> RangeAttributes;
230 Optional<PatchLocation> UnitRangeAttribute;
233 /// \brief Location attributes that need to be transfered from th
234 /// original debug_loc section to the liked one. They are stored
235 /// along with the PC offset that is to be applied to their
236 /// function's address.
237 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
239 /// \brief Accelerator entries for the unit, both for the pub*
240 /// sections and the apple* ones.
242 std::vector<AccelInfo> Pubnames;
243 std::vector<AccelInfo> Pubtypes;
247 uint64_t CompileUnit::computeNextUnitOffset() {
248 NextUnitOffset = StartOffset + 11 /* Header size */;
249 // The root DIE might be null, meaning that the Unit had nothing to
250 // contribute to the linked output. In that case, we will emit the
251 // unit header without any actual DIE.
253 NextUnitOffset += CUDie->getSize();
254 return NextUnitOffset;
257 /// \brief Keep track of a forward cross-cu reference from this unit
258 /// to \p Die that lives in \p RefUnit.
259 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
260 PatchLocation Attr) {
261 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
264 /// \brief Apply all fixups recorded by noteForwardReference().
265 void CompileUnit::fixupForwardReferences() {
266 for (const auto &Ref : ForwardDIEReferences) {
268 const CompileUnit *RefUnit;
270 std::tie(RefDie, RefUnit, Attr) = Ref;
271 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
275 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
277 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
278 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
279 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
282 void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
283 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
284 RangeAttributes.push_back(Attr);
286 UnitRangeAttribute = Attr;
289 void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
290 LocationAttributes.emplace_back(Attr, PcOffset);
293 /// \brief Add a name accelerator entry for \p Die with \p Name
294 /// which is stored in the string table at \p Offset.
295 void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
296 uint32_t Offset, bool SkipPubSection) {
297 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
300 /// \brief Add a type accelerator entry for \p Die with \p Name
301 /// which is stored in the string table at \p Offset.
302 void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
304 Pubtypes.emplace_back(Name, Die, Offset, false);
307 /// \brief A string table that doesn't need relocations.
309 /// We are doing a final link, no need for a string table that
310 /// has relocation entries for every reference to it. This class
311 /// provides this ablitity by just associating offsets with
313 class NonRelocatableStringpool {
315 /// \brief Entries are stored into the StringMap and simply linked
316 /// together through the second element of this pair in order to
317 /// keep track of insertion order.
318 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
321 NonRelocatableStringpool()
322 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
323 // Legacy dsymutil puts an empty string at the start of the line
328 /// \brief Get the offset of string \p S in the string table. This
329 /// can insert a new element or return the offset of a preexisitng
331 uint32_t getStringOffset(StringRef S);
333 /// \brief Get permanent storage for \p S (but do not necessarily
334 /// emit \p S in the output section).
335 /// \returns The StringRef that points to permanent storage to use
336 /// in place of \p S.
337 StringRef internString(StringRef S);
339 // \brief Return the first entry of the string table.
340 const MapTy::MapEntryTy *getFirstEntry() const {
341 return getNextEntry(&Sentinel);
344 // \brief Get the entry following \p E in the string table or null
345 // if \p E was the last entry.
346 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
347 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
350 uint64_t getSize() { return CurrentEndOffset; }
354 uint32_t CurrentEndOffset;
355 MapTy::MapEntryTy Sentinel, *Last;
358 /// \brief Get the offset of string \p S in the string table. This
359 /// can insert a new element or return the offset of a preexisitng
361 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
362 if (S.empty() && !Strings.empty())
365 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
369 // A non-empty string can't be at offset 0, so if we have an entry
370 // with a 0 offset, it must be a previously interned string.
371 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
372 if (Inserted || It->getValue().first == 0) {
373 // Set offset and chain at the end of the entries list.
374 It->getValue().first = CurrentEndOffset;
375 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
376 Last->getValue().second = &*It;
379 return It->getValue().first;
382 /// \brief Put \p S into the StringMap so that it gets permanent
383 /// storage, but do not actually link it in the chain of elements
384 /// that go into the output section. A latter call to
385 /// getStringOffset() with the same string will chain it though.
386 StringRef NonRelocatableStringpool::internString(StringRef S) {
387 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
388 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
389 return InsertResult.first->getKey();
392 /// \brief The Dwarf streaming logic
394 /// All interactions with the MC layer that is used to build the debug
395 /// information binary representation are handled in this class.
396 class DwarfStreamer {
397 /// \defgroup MCObjects MC layer objects constructed by the streamer
399 std::unique_ptr<MCRegisterInfo> MRI;
400 std::unique_ptr<MCAsmInfo> MAI;
401 std::unique_ptr<MCObjectFileInfo> MOFI;
402 std::unique_ptr<MCContext> MC;
403 MCAsmBackend *MAB; // Owned by MCStreamer
404 std::unique_ptr<MCInstrInfo> MII;
405 std::unique_ptr<MCSubtargetInfo> MSTI;
406 MCCodeEmitter *MCE; // Owned by MCStreamer
407 MCStreamer *MS; // Owned by AsmPrinter
408 std::unique_ptr<TargetMachine> TM;
409 std::unique_ptr<AsmPrinter> Asm;
412 /// \brief the file we stream the linked Dwarf to.
413 std::unique_ptr<raw_fd_ostream> OutFile;
415 uint32_t RangesSectionSize;
416 uint32_t LocSectionSize;
417 uint32_t LineSectionSize;
419 /// \brief Emit the pubnames or pubtypes section contribution for \p
420 /// Unit into \p Sec. The data is provided in \p Names.
421 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
422 const CompileUnit &Unit,
423 const std::vector<CompileUnit::AccelInfo> &Names);
426 /// \brief Actually create the streamer and the ouptut file.
428 /// This could be done directly in the constructor, but it feels
429 /// more natural to handle errors through return value.
430 bool init(Triple TheTriple, StringRef OutputFilename);
432 /// \brief Dump the file to the disk.
435 AsmPrinter &getAsmPrinter() const { return *Asm; }
437 /// \brief Set the current output section to debug_info and change
438 /// the MC Dwarf version to \p DwarfVersion.
439 void switchToDebugInfoSection(unsigned DwarfVersion);
441 /// \brief Emit the compilation unit header for \p Unit in the
442 /// debug_info section.
444 /// As a side effect, this also switches the current Dwarf version
445 /// of the MC layer to the one of U.getOrigUnit().
446 void emitCompileUnitHeader(CompileUnit &Unit);
448 /// \brief Recursively emit the DIE tree rooted at \p Die.
449 void emitDIE(DIE &Die);
451 /// \brief Emit the abbreviation table \p Abbrevs to the
452 /// debug_abbrev section.
453 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
455 /// \brief Emit the string table described by \p Pool.
456 void emitStrings(const NonRelocatableStringpool &Pool);
458 /// \brief Emit debug_ranges for \p FuncRange by translating the
459 /// original \p Entries.
460 void emitRangesEntries(
461 int64_t UnitPcOffset, uint64_t OrigLowPc,
462 FunctionIntervals::const_iterator FuncRange,
463 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
464 unsigned AddressSize);
466 /// \brief Emit debug_aranges entries for \p Unit and if \p
467 /// DoRangesSection is true, also emit the debug_ranges entries for
468 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
469 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
471 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
473 /// \brief Emit the debug_loc contribution for \p Unit by copying
474 /// the entries from \p Dwarf and offseting them. Update the
475 /// location attributes to point to the new entries.
476 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
478 /// \brief Emit the line table described in \p Rows into the
479 /// debug_line section.
480 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
481 std::vector<DWARFDebugLine::Row> &Rows,
482 unsigned AdddressSize);
484 uint32_t getLineSectionSize() const { return LineSectionSize; }
486 /// \brief Emit the .debug_pubnames contribution for \p Unit.
487 void emitPubNamesForUnit(const CompileUnit &Unit);
489 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
490 void emitPubTypesForUnit(const CompileUnit &Unit);
493 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
494 std::string ErrorStr;
495 std::string TripleName;
496 StringRef Context = "dwarf streamer init";
499 const Target *TheTarget =
500 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
502 return error(ErrorStr, Context);
503 TripleName = TheTriple.getTriple();
505 // Create all the MC Objects.
506 MRI.reset(TheTarget->createMCRegInfo(TripleName));
508 return error(Twine("no register info for target ") + TripleName, Context);
510 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
512 return error("no asm info for target " + TripleName, Context);
514 MOFI.reset(new MCObjectFileInfo);
515 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
516 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
519 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
521 return error("no asm backend for target " + TripleName, Context);
523 MII.reset(TheTarget->createMCInstrInfo());
525 return error("no instr info info for target " + TripleName, Context);
527 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
529 return error("no subtarget info for target " + TripleName, Context);
531 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
533 return error("no code emitter for target " + TripleName, Context);
535 // Create the output file.
538 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
540 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
542 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
544 /*DWARFMustBeAtTheEnd*/ false);
546 return error("no object streamer for target " + TripleName, Context);
548 // Finally create the AsmPrinter we'll use to emit the DIEs.
549 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
551 return error("no target machine for target " + TripleName, Context);
553 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
555 return error("no asm printer for target " + TripleName, Context);
557 RangesSectionSize = 0;
564 bool DwarfStreamer::finish() {
569 /// \brief Set the current output section to debug_info and change
570 /// the MC Dwarf version to \p DwarfVersion.
571 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
572 MS->SwitchSection(MOFI->getDwarfInfoSection());
573 MC->setDwarfVersion(DwarfVersion);
576 /// \brief Emit the compilation unit header for \p Unit in the
577 /// debug_info section.
579 /// A Dwarf scetion header is encoded as:
580 /// uint32_t Unit length (omiting this field)
582 /// uint32_t Abbreviation table offset
583 /// uint8_t Address size
585 /// Leading to a total of 11 bytes.
586 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
587 unsigned Version = Unit.getOrigUnit().getVersion();
588 switchToDebugInfoSection(Version);
590 // Emit size of content not including length itself. The size has
591 // already been computed in CompileUnit::computeOffsets(). Substract
592 // 4 to that size to account for the length field.
593 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
594 Asm->EmitInt16(Version);
595 // We share one abbreviations table across all units so it's always at the
596 // start of the section.
598 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
601 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
602 /// for the linked Dwarf file.
603 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
604 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
605 Asm->emitDwarfAbbrevs(Abbrevs);
608 /// \brief Recursively emit the DIE tree rooted at \p Die.
609 void DwarfStreamer::emitDIE(DIE &Die) {
610 MS->SwitchSection(MOFI->getDwarfInfoSection());
611 Asm->emitDwarfDIE(Die);
614 /// \brief Emit the debug_str section stored in \p Pool.
615 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
616 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
617 for (auto *Entry = Pool.getFirstEntry(); Entry;
618 Entry = Pool.getNextEntry(Entry))
619 Asm->OutStreamer->EmitBytes(
620 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
623 /// \brief Emit the debug_range section contents for \p FuncRange by
624 /// translating the original \p Entries. The debug_range section
625 /// format is totally trivial, consisting just of pairs of address
626 /// sized addresses describing the ranges.
627 void DwarfStreamer::emitRangesEntries(
628 int64_t UnitPcOffset, uint64_t OrigLowPc,
629 FunctionIntervals::const_iterator FuncRange,
630 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
631 unsigned AddressSize) {
632 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
634 // Offset each range by the right amount.
635 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
636 for (const auto &Range : Entries) {
637 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
638 warn("unsupported base address selection operation",
639 "emitting debug_ranges");
642 // Do not emit empty ranges.
643 if (Range.StartAddress == Range.EndAddress)
646 // All range entries should lie in the function range.
647 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
648 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
649 warn("inconsistent range data.", "emitting debug_ranges");
650 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
651 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
652 RangesSectionSize += 2 * AddressSize;
655 // Add the terminator entry.
656 MS->EmitIntValue(0, AddressSize);
657 MS->EmitIntValue(0, AddressSize);
658 RangesSectionSize += 2 * AddressSize;
661 /// \brief Emit the debug_aranges contribution of a unit and
662 /// if \p DoDebugRanges is true the debug_range contents for a
663 /// compile_unit level DW_AT_ranges attribute (Which are basically the
664 /// same thing with a different base address).
665 /// Just aggregate all the ranges gathered inside that unit.
666 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
667 bool DoDebugRanges) {
668 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
669 // Gather the ranges in a vector, so that we can simplify them. The
670 // IntervalMap will have coalesced the non-linked ranges, but here
671 // we want to coalesce the linked addresses.
672 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
673 const auto &FunctionRanges = Unit.getFunctionRanges();
674 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
675 Range != End; ++Range)
676 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
677 Range.stop() + Range.value()));
679 // The object addresses where sorted, but again, the linked
680 // addresses might end up in a different order.
681 std::sort(Ranges.begin(), Ranges.end());
683 if (!Ranges.empty()) {
684 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
686 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
687 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
689 unsigned HeaderSize =
690 sizeof(int32_t) + // Size of contents (w/o this field
691 sizeof(int16_t) + // DWARF ARange version number
692 sizeof(int32_t) + // Offset of CU in the .debug_info section
693 sizeof(int8_t) + // Pointer Size (in bytes)
694 sizeof(int8_t); // Segment Size (in bytes)
696 unsigned TupleSize = AddressSize * 2;
697 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
699 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
700 Asm->OutStreamer->EmitLabel(BeginLabel);
701 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
702 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
703 Asm->EmitInt8(AddressSize); // Address size
704 Asm->EmitInt8(0); // Segment size
706 Asm->OutStreamer->EmitFill(Padding, 0x0);
708 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
710 uint64_t RangeStart = Range->first;
711 MS->EmitIntValue(RangeStart, AddressSize);
712 while ((Range + 1) != End && Range->second == (Range + 1)->first)
714 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
718 Asm->OutStreamer->EmitIntValue(0, AddressSize);
719 Asm->OutStreamer->EmitIntValue(0, AddressSize);
720 Asm->OutStreamer->EmitLabel(EndLabel);
726 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
727 // Offset each range by the right amount.
728 int64_t PcOffset = -Unit.getLowPc();
729 // Emit coalesced ranges.
730 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
731 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
732 while (Range + 1 != End && Range->second == (Range + 1)->first)
734 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
735 RangesSectionSize += 2 * AddressSize;
738 // Add the terminator entry.
739 MS->EmitIntValue(0, AddressSize);
740 MS->EmitIntValue(0, AddressSize);
741 RangesSectionSize += 2 * AddressSize;
744 /// \brief Emit location lists for \p Unit and update attribtues to
745 /// point to the new entries.
746 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
747 DWARFContext &Dwarf) {
748 const auto &Attributes = Unit.getLocationAttributes();
750 if (Attributes.empty())
753 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
755 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
756 const DWARFSection &InputSec = Dwarf.getLocSection();
757 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
758 DWARFUnit &OrigUnit = Unit.getOrigUnit();
759 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
760 int64_t UnitPcOffset = 0;
761 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
762 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
763 if (OrigLowPc != -1ULL)
764 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
766 for (const auto &Attr : Attributes) {
767 uint32_t Offset = Attr.first.get();
768 Attr.first.set(LocSectionSize);
769 // This is the quantity to add to the old location address to get
770 // the correct address for the new one.
771 int64_t LocPcOffset = Attr.second + UnitPcOffset;
772 while (Data.isValidOffset(Offset)) {
773 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
774 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
775 LocSectionSize += 2 * AddressSize;
776 if (Low == 0 && High == 0) {
777 Asm->OutStreamer->EmitIntValue(0, AddressSize);
778 Asm->OutStreamer->EmitIntValue(0, AddressSize);
781 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
782 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
783 uint64_t Length = Data.getU16(&Offset);
784 Asm->OutStreamer->EmitIntValue(Length, 2);
785 // Just copy the bytes over.
786 Asm->OutStreamer->EmitBytes(
787 StringRef(InputSec.Data.substr(Offset, Length)));
789 LocSectionSize += Length + 2;
794 void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
795 unsigned MinInstLength,
796 std::vector<DWARFDebugLine::Row> &Rows,
797 unsigned PointerSize) {
798 // Switch to the section where the table will be emitted into.
799 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
800 MCSymbol *LineStartSym = MC->createTempSymbol();
801 MCSymbol *LineEndSym = MC->createTempSymbol();
803 // The first 4 bytes is the total length of the information for this
804 // compilation unit (not including these 4 bytes for the length).
805 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
806 Asm->OutStreamer->EmitLabel(LineStartSym);
808 MS->EmitBytes(PrologueBytes);
809 LineSectionSize += PrologueBytes.size() + 4;
811 SmallString<128> EncodingBuffer;
812 raw_svector_ostream EncodingOS(EncodingBuffer);
815 // We only have the dummy entry, dsymutil emits an entry with a 0
816 // address in that case.
817 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
818 MS->EmitBytes(EncodingOS.str());
819 LineSectionSize += EncodingBuffer.size();
820 MS->EmitLabel(LineEndSym);
824 // Line table state machine fields
825 unsigned FileNum = 1;
826 unsigned LastLine = 1;
828 unsigned IsStatement = 1;
830 uint64_t Address = -1ULL;
832 unsigned RowsSinceLastSequence = 0;
834 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
835 auto &Row = Rows[Idx];
837 int64_t AddressDelta;
838 if (Address == -1ULL) {
839 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
840 MS->EmitULEB128IntValue(PointerSize + 1);
841 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
842 MS->EmitIntValue(Row.Address, PointerSize);
843 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
846 AddressDelta = (Row.Address - Address) / MinInstLength;
849 // FIXME: code copied and transfromed from
850 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
851 // this code, but the current compatibility requirement with
852 // classic dsymutil makes it hard. Revisit that once this
853 // requirement is dropped.
855 if (FileNum != Row.File) {
857 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
858 MS->EmitULEB128IntValue(FileNum);
859 LineSectionSize += 1 + getULEB128Size(FileNum);
861 if (Column != Row.Column) {
863 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
864 MS->EmitULEB128IntValue(Column);
865 LineSectionSize += 1 + getULEB128Size(Column);
868 // FIXME: We should handle the discriminator here, but dsymutil
869 // doesn' consider it, thus ignore it for now.
871 if (Isa != Row.Isa) {
873 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
874 MS->EmitULEB128IntValue(Isa);
875 LineSectionSize += 1 + getULEB128Size(Isa);
877 if (IsStatement != Row.IsStmt) {
878 IsStatement = Row.IsStmt;
879 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
880 LineSectionSize += 1;
882 if (Row.BasicBlock) {
883 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
884 LineSectionSize += 1;
887 if (Row.PrologueEnd) {
888 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
889 LineSectionSize += 1;
892 if (Row.EpilogueBegin) {
893 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
894 LineSectionSize += 1;
897 int64_t LineDelta = int64_t(Row.Line) - LastLine;
898 if (!Row.EndSequence) {
899 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
900 MS->EmitBytes(EncodingOS.str());
901 LineSectionSize += EncodingBuffer.size();
902 EncodingBuffer.resize(0);
904 Address = Row.Address;
906 RowsSinceLastSequence++;
909 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
910 MS->EmitSLEB128IntValue(LineDelta);
911 LineSectionSize += 1 + getSLEB128Size(LineDelta);
914 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
915 MS->EmitULEB128IntValue(AddressDelta);
916 LineSectionSize += 1 + getULEB128Size(AddressDelta);
918 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
919 MS->EmitBytes(EncodingOS.str());
920 LineSectionSize += EncodingBuffer.size();
921 EncodingBuffer.resize(0);
924 LastLine = FileNum = IsStatement = 1;
925 RowsSinceLastSequence = Column = Isa = 0;
929 if (RowsSinceLastSequence) {
930 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
931 MS->EmitBytes(EncodingOS.str());
932 LineSectionSize += EncodingBuffer.size();
933 EncodingBuffer.resize(0);
937 MS->EmitLabel(LineEndSym);
940 /// \brief Emit the pubnames or pubtypes section contribution for \p
941 /// Unit into \p Sec. The data is provided in \p Names.
942 void DwarfStreamer::emitPubSectionForUnit(
943 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
944 const std::vector<CompileUnit::AccelInfo> &Names) {
948 // Start the dwarf pubnames section.
949 Asm->OutStreamer->SwitchSection(Sec);
950 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
951 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
953 bool HeaderEmitted = false;
954 // Emit the pubnames for this compilation unit.
955 for (const auto &Name : Names) {
956 if (Name.SkipPubSection)
959 if (!HeaderEmitted) {
961 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
962 Asm->OutStreamer->EmitLabel(BeginLabel);
963 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
964 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
965 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
966 HeaderEmitted = true;
968 Asm->EmitInt32(Name.Die->getOffset());
969 Asm->OutStreamer->EmitBytes(
970 StringRef(Name.Name.data(), Name.Name.size() + 1));
975 Asm->EmitInt32(0); // End marker.
976 Asm->OutStreamer->EmitLabel(EndLabel);
979 /// \brief Emit .debug_pubnames for \p Unit.
980 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
981 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
982 "names", Unit, Unit.getPubnames());
985 /// \brief Emit .debug_pubtypes for \p Unit.
986 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
987 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
988 "types", Unit, Unit.getPubtypes());
991 /// \brief The core of the Dwarf linking logic.
993 /// The link of the dwarf information from the object files will be
994 /// driven by the selection of 'root DIEs', which are DIEs that
995 /// describe variables or functions that are present in the linked
996 /// binary (and thus have entries in the debug map). All the debug
997 /// information that will be linked (the DIEs, but also the line
998 /// tables, ranges, ...) is derived from that set of root DIEs.
1000 /// The root DIEs are identified because they contain relocations that
1001 /// correspond to a debug map entry at specific places (the low_pc for
1002 /// a function, the location for a variable). These relocations are
1003 /// called ValidRelocs in the DwarfLinker and are gathered as a very
1004 /// first step when we start processing a DebugMapObject.
1007 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1008 : OutputFilename(OutputFilename), Options(Options),
1009 BinHolder(Options.Verbose) {}
1012 for (auto *Abbrev : Abbreviations)
1016 /// \brief Link the contents of the DebugMap.
1017 bool link(const DebugMap &);
1020 /// \brief Called at the start of a debug object link.
1021 void startDebugObject(DWARFContext &, DebugMapObject &);
1023 /// \brief Called at the end of a debug object link.
1024 void endDebugObject();
1026 /// \defgroup FindValidRelocations Translate debug map into a list
1027 /// of relevant relocations
1034 const DebugMapObject::DebugMapEntry *Mapping;
1036 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1037 const DebugMapObject::DebugMapEntry *Mapping)
1038 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1040 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1043 /// \brief The valid relocations for the current DebugMapObject.
1044 /// This vector is sorted by relocation offset.
1045 std::vector<ValidReloc> ValidRelocs;
1047 /// \brief Index into ValidRelocs of the next relocation to
1048 /// consider. As we walk the DIEs in acsending file offset and as
1049 /// ValidRelocs is sorted by file offset, keeping this index
1050 /// uptodate is all we have to do to have a cheap lookup during the
1051 /// root DIE selection and during DIE cloning.
1052 unsigned NextValidReloc;
1054 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1055 const DebugMapObject &DMO);
1057 bool findValidRelocs(const object::SectionRef &Section,
1058 const object::ObjectFile &Obj,
1059 const DebugMapObject &DMO);
1061 void findValidRelocsMachO(const object::SectionRef &Section,
1062 const object::MachOObjectFile &Obj,
1063 const DebugMapObject &DMO);
1066 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1069 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1070 /// keep. Store that information in \p CU's DIEInfo.
1071 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1072 const DebugMapObject &DMO, CompileUnit &CU,
1075 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1076 enum TravesalFlags {
1077 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1078 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1079 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1080 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1083 /// \brief Mark the passed DIE as well as all the ones it depends on
1085 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1086 CompileUnit::DIEInfo &MyInfo,
1087 const DebugMapObject &DMO, CompileUnit &CU,
1090 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1091 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1094 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1096 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1098 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1100 CompileUnit::DIEInfo &MyInfo,
1103 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1104 CompileUnit::DIEInfo &Info);
1107 /// \defgroup Linking Methods used to link the debug information
1110 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1111 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1112 /// stripped out and addresses have been rewritten according to the
1115 /// \param OutOffset is the offset the cloned DIE in the output
1117 /// \param PCOffset (while cloning a function scope) is the offset
1118 /// applied to the entry point of the function to get the linked address.
1120 /// \returns the root of the cloned tree.
1121 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
1122 int64_t PCOffset, uint32_t OutOffset);
1124 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1126 /// \brief Information gathered and exchanged between the various
1127 /// clone*Attributes helpers about the attributes of a particular DIE.
1128 struct AttributesInfo {
1129 const char *Name, *MangledName; ///< Names.
1130 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1132 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1133 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1135 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1136 bool IsDeclaration; ///< Is this DIE only a declaration?
1139 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1140 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1141 IsDeclaration(false) {}
1144 /// \brief Helper for cloneDIE.
1145 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1146 CompileUnit &U, const DWARFFormValue &Val,
1147 const AttributeSpec AttrSpec, unsigned AttrSize,
1148 AttributesInfo &AttrInfo);
1150 /// \brief Helper for cloneDIE.
1151 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1152 const DWARFFormValue &Val, const DWARFUnit &U);
1154 /// \brief Helper for cloneDIE.
1156 cloneDieReferenceAttribute(DIE &Die,
1157 const DWARFDebugInfoEntryMinimal &InputDIE,
1158 AttributeSpec AttrSpec, unsigned AttrSize,
1159 const DWARFFormValue &Val, CompileUnit &Unit);
1161 /// \brief Helper for cloneDIE.
1162 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1163 const DWARFFormValue &Val, unsigned AttrSize);
1165 /// \brief Helper for cloneDIE.
1166 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1167 const DWARFFormValue &Val,
1168 const CompileUnit &Unit, AttributesInfo &Info);
1170 /// \brief Helper for cloneDIE.
1171 unsigned cloneScalarAttribute(DIE &Die,
1172 const DWARFDebugInfoEntryMinimal &InputDIE,
1173 CompileUnit &U, AttributeSpec AttrSpec,
1174 const DWARFFormValue &Val, unsigned AttrSize,
1175 AttributesInfo &Info);
1177 /// \brief Helper for cloneDIE.
1178 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1179 bool isLittleEndian);
1181 /// \brief Assign an abbreviation number to \p Abbrev
1182 void AssignAbbrev(DIEAbbrev &Abbrev);
1184 /// \brief FoldingSet that uniques the abbreviations.
1185 FoldingSet<DIEAbbrev> AbbreviationsSet;
1186 /// \brief Storage for the unique Abbreviations.
1187 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1188 /// be changed to a vecot of unique_ptrs.
1189 std::vector<DIEAbbrev *> Abbreviations;
1191 /// \brief Compute and emit debug_ranges section for \p Unit, and
1192 /// patch the attributes referencing it.
1193 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1195 /// \brief Generate and emit the DW_AT_ranges attribute for a
1196 /// compile_unit if it had one.
1197 void generateUnitRanges(CompileUnit &Unit) const;
1199 /// \brief Extract the line tables fromt he original dwarf, extract
1200 /// the relevant parts according to the linked function ranges and
1201 /// emit the result in the debug_line section.
1202 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1204 /// \brief Emit the accelerator entries for \p Unit.
1205 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1207 /// \brief DIELoc objects that need to be destructed (but not freed!).
1208 std::vector<DIELoc *> DIELocs;
1209 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1210 std::vector<DIEBlock *> DIEBlocks;
1211 /// \brief Allocator used for all the DIEValue objects.
1212 BumpPtrAllocator DIEAlloc;
1215 /// \defgroup Helpers Various helper methods.
1218 const DWARFDebugInfoEntryMinimal *
1219 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
1220 const DWARFDebugInfoEntryMinimal &DIE,
1221 CompileUnit *&ReferencedCU);
1223 CompileUnit *getUnitForOffset(unsigned Offset);
1225 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1226 AttributesInfo &Info);
1228 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1229 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1231 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
1235 std::string OutputFilename;
1236 LinkOptions Options;
1237 BinaryHolder BinHolder;
1238 std::unique_ptr<DwarfStreamer> Streamer;
1240 /// The units of the current debug map object.
1241 std::vector<CompileUnit> Units;
1243 /// The debug map object curently under consideration.
1244 DebugMapObject *CurrentDebugObject;
1246 /// \brief The Dwarf string pool
1247 NonRelocatableStringpool StringPool;
1249 /// \brief This map is keyed by the entry PC of functions in that
1250 /// debug object and the associated value is a pair storing the
1251 /// corresponding end PC and the offset to apply to get the linked
1254 /// See startDebugObject() for a more complete description of its use.
1255 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1258 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1259 /// returning our CompileUnit object instead.
1260 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1262 std::upper_bound(Units.begin(), Units.end(), Offset,
1263 [](uint32_t LHS, const CompileUnit &RHS) {
1264 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1266 return CU != Units.end() ? &*CU : nullptr;
1269 /// \brief Resolve the DIE attribute reference that has been
1270 /// extracted in \p RefValue. The resulting DIE migh be in another
1271 /// CompileUnit which is stored into \p ReferencedCU.
1272 /// \returns null if resolving fails for any reason.
1273 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1274 DWARFFormValue &RefValue, const DWARFUnit &Unit,
1275 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1276 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1277 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1279 if ((RefCU = getUnitForOffset(RefOffset)))
1280 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1283 reportWarning("could not find referenced DIE", &Unit, &DIE);
1287 /// \brief Get the potential name and mangled name for the entity
1288 /// described by \p Die and store them in \Info if they are not
1290 /// \returns is a name was found.
1291 bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1292 DWARFUnit &U, AttributesInfo &Info) {
1293 // FIXME: a bit wastefull as the first getName might return the
1295 if (!Info.MangledName &&
1296 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1297 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1299 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1300 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1302 return Info.Name || Info.MangledName;
1305 /// \brief Report a warning to the user, optionaly including
1306 /// information about a specific \p DIE related to the warning.
1307 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
1308 const DWARFDebugInfoEntryMinimal *DIE) const {
1309 StringRef Context = "<debug map>";
1310 if (CurrentDebugObject)
1311 Context = CurrentDebugObject->getObjectFilename();
1312 warn(Warning, Context);
1314 if (!Options.Verbose || !DIE)
1317 errs() << " in DIE:\n";
1318 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1322 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1323 if (Options.NoOutput)
1326 Streamer = llvm::make_unique<DwarfStreamer>();
1327 return Streamer->init(TheTriple, OutputFilename);
1330 /// \brief Recursive helper to gather the child->parent relationships in the
1331 /// original compile unit.
1332 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1333 unsigned ParentIdx, CompileUnit &CU) {
1334 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1335 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
1337 if (DIE->hasChildren())
1338 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1339 Child = Child->getSibling())
1340 gatherDIEParents(Child, MyIdx, CU);
1343 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1347 case dwarf::DW_TAG_subprogram:
1348 case dwarf::DW_TAG_lexical_block:
1349 case dwarf::DW_TAG_subroutine_type:
1350 case dwarf::DW_TAG_structure_type:
1351 case dwarf::DW_TAG_class_type:
1352 case dwarf::DW_TAG_union_type:
1355 llvm_unreachable("Invalid Tag");
1358 void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1359 Units.reserve(Dwarf.getNumCompileUnits());
1361 // Iterate over the debug map entries and put all the ones that are
1362 // functions (because they have a size) into the Ranges map. This
1363 // map is very similar to the FunctionRanges that are stored in each
1364 // unit, with 2 notable differences:
1365 // - obviously this one is global, while the other ones are per-unit.
1366 // - this one contains not only the functions described in the DIE
1367 // tree, but also the ones that are only in the debug map.
1368 // The latter information is required to reproduce dsymutil's logic
1369 // while linking line tables. The cases where this information
1370 // matters look like bugs that need to be investigated, but for now
1371 // we need to reproduce dsymutil's behavior.
1372 // FIXME: Once we understood exactly if that information is needed,
1373 // maybe totally remove this (or try to use it to do a real
1374 // -gline-tables-only on Darwin.
1375 for (const auto &Entry : Obj.symbols()) {
1376 const auto &Mapping = Entry.getValue();
1378 Ranges[Mapping.ObjectAddress] = std::make_pair(
1379 Mapping.ObjectAddress + Mapping.Size,
1380 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1384 void DwarfLinker::endDebugObject() {
1386 ValidRelocs.clear();
1389 for (auto *Block : DIEBlocks)
1391 for (auto *Loc : DIELocs)
1399 /// \brief Iterate over the relocations of the given \p Section and
1400 /// store the ones that correspond to debug map entries into the
1401 /// ValidRelocs array.
1402 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1403 const object::MachOObjectFile &Obj,
1404 const DebugMapObject &DMO) {
1406 Section.getContents(Contents);
1407 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1409 for (const object::RelocationRef &Reloc : Section.relocations()) {
1410 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1411 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1412 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1414 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
1415 reportWarning(" unsupported relocation in debug_info section.");
1418 uint32_t Offset = Offset64;
1419 // Mach-o uses REL relocations, the addend is at the relocation offset.
1420 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1422 auto Sym = Reloc.getSymbol();
1423 if (Sym != Obj.symbol_end()) {
1424 StringRef SymbolName;
1425 if (Sym->getName(SymbolName)) {
1426 reportWarning("error getting relocation symbol name.");
1429 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
1430 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1431 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1432 // Do not store the addend. The addend was the address of the
1433 // symbol in the object file, the address in the binary that is
1434 // stored in the debug map doesn't need to be offseted.
1435 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1440 /// \brief Dispatch the valid relocation finding logic to the
1441 /// appropriate handler depending on the object file format.
1442 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1443 const object::ObjectFile &Obj,
1444 const DebugMapObject &DMO) {
1445 // Dispatch to the right handler depending on the file type.
1446 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1447 findValidRelocsMachO(Section, *MachOObj, DMO);
1449 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
1451 if (ValidRelocs.empty())
1454 // Sort the relocations by offset. We will walk the DIEs linearly in
1455 // the file, this allows us to just keep an index in the relocation
1456 // array that we advance during our walk, rather than resorting to
1457 // some associative container. See DwarfLinker::NextValidReloc.
1458 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1462 /// \brief Look for relocations in the debug_info section that match
1463 /// entries in the debug map. These relocations will drive the Dwarf
1464 /// link by indicating which DIEs refer to symbols present in the
1466 /// \returns wether there are any valid relocations in the debug info.
1467 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1468 const DebugMapObject &DMO) {
1469 // Find the debug_info section.
1470 for (const object::SectionRef &Section : Obj.sections()) {
1471 StringRef SectionName;
1472 Section.getName(SectionName);
1473 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1474 if (SectionName != "debug_info")
1476 return findValidRelocs(Section, Obj, DMO);
1481 /// \brief Checks that there is a relocation against an actual debug
1482 /// map entry between \p StartOffset and \p NextOffset.
1484 /// This function must be called with offsets in strictly ascending
1485 /// order because it never looks back at relocations it already 'went past'.
1486 /// \returns true and sets Info.InDebugMap if it is the case.
1487 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1488 CompileUnit::DIEInfo &Info) {
1489 assert(NextValidReloc == 0 ||
1490 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1491 if (NextValidReloc >= ValidRelocs.size())
1494 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1496 // We might need to skip some relocs that we didn't consider. For
1497 // example the high_pc of a discarded DIE might contain a reloc that
1498 // is in the list because it actually corresponds to the start of a
1499 // function that is in the debug map.
1500 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1501 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1503 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1506 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1507 if (Options.Verbose)
1508 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1509 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1510 ValidReloc.Mapping->getValue().ObjectAddress,
1511 ValidReloc.Mapping->getValue().BinaryAddress);
1513 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
1515 ValidReloc.Mapping->getValue().ObjectAddress;
1516 Info.InDebugMap = true;
1520 /// \brief Get the starting and ending (exclusive) offset for the
1521 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1522 /// supposed to point to the position of the first attribute described
1524 /// \return [StartOffset, EndOffset) as a pair.
1525 static std::pair<uint32_t, uint32_t>
1526 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1527 unsigned Offset, const DWARFUnit &Unit) {
1528 DataExtractor Data = Unit.getDebugInfoExtractor();
1530 for (unsigned i = 0; i < Idx; ++i)
1531 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1533 uint32_t End = Offset;
1534 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1536 return std::make_pair(Offset, End);
1539 /// \brief Check if a variable describing DIE should be kept.
1540 /// \returns updated TraversalFlags.
1541 unsigned DwarfLinker::shouldKeepVariableDIE(
1542 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1543 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1544 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1546 // Global variables with constant value can always be kept.
1547 if (!(Flags & TF_InFunctionScope) &&
1548 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1549 MyInfo.InDebugMap = true;
1550 return Flags | TF_Keep;
1553 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1554 if (LocationIdx == -1U)
1557 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1558 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1559 uint32_t LocationOffset, LocationEndOffset;
1560 std::tie(LocationOffset, LocationEndOffset) =
1561 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1563 // See if there is a relocation to a valid debug map entry inside
1564 // this variable's location. The order is important here. We want to
1565 // always check in the variable has a valid relocation, so that the
1566 // DIEInfo is filled. However, we don't want a static variable in a
1567 // function to force us to keep the enclosing function.
1568 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1569 (Flags & TF_InFunctionScope))
1572 if (Options.Verbose)
1573 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1575 return Flags | TF_Keep;
1578 /// \brief Check if a function describing DIE should be kept.
1579 /// \returns updated TraversalFlags.
1580 unsigned DwarfLinker::shouldKeepSubprogramDIE(
1581 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1582 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1583 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1585 Flags |= TF_InFunctionScope;
1587 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1588 if (LowPcIdx == -1U)
1591 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1592 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1593 uint32_t LowPcOffset, LowPcEndOffset;
1594 std::tie(LowPcOffset, LowPcEndOffset) =
1595 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1598 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1599 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1600 if (LowPc == -1ULL ||
1601 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1604 if (Options.Verbose)
1605 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1609 DWARFFormValue HighPcValue;
1610 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1611 reportWarning("Function without high_pc. Range will be discarded.\n",
1617 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1618 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1620 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1621 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1624 // Replace the debug map range with a more accurate one.
1625 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
1626 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1630 /// \brief Check if a DIE should be kept.
1631 /// \returns updated TraversalFlags.
1632 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1634 CompileUnit::DIEInfo &MyInfo,
1636 switch (DIE.getTag()) {
1637 case dwarf::DW_TAG_constant:
1638 case dwarf::DW_TAG_variable:
1639 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1640 case dwarf::DW_TAG_subprogram:
1641 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1642 case dwarf::DW_TAG_module:
1643 case dwarf::DW_TAG_imported_module:
1644 case dwarf::DW_TAG_imported_declaration:
1645 case dwarf::DW_TAG_imported_unit:
1646 // We always want to keep these.
1647 return Flags | TF_Keep;
1653 /// \brief Mark the passed DIE as well as all the ones it depends on
1656 /// This function is called by lookForDIEsToKeep on DIEs that are
1657 /// newly discovered to be needed in the link. It recursively calls
1658 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1659 /// TraversalFlags to inform it that it's not doing the primary DIE
1661 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1662 CompileUnit::DIEInfo &MyInfo,
1663 const DebugMapObject &DMO,
1664 CompileUnit &CU, unsigned Flags) {
1665 const DWARFUnit &Unit = CU.getOrigUnit();
1668 // First mark all the parent chain as kept.
1669 unsigned AncestorIdx = MyInfo.ParentIdx;
1670 while (!CU.getInfo(AncestorIdx).Keep) {
1671 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1672 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1673 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1676 // Then we need to mark all the DIEs referenced by this DIE's
1677 // attributes as kept.
1678 DataExtractor Data = Unit.getDebugInfoExtractor();
1679 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1680 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1682 // Mark all DIEs referenced through atttributes as kept.
1683 for (const auto &AttrSpec : Abbrev->attributes()) {
1684 DWARFFormValue Val(AttrSpec.Form);
1686 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1687 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1691 Val.extractValue(Data, &Offset, &Unit);
1692 CompileUnit *ReferencedCU;
1693 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1694 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1695 TF_Keep | TF_DependencyWalk);
1699 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1700 /// keep. Store that information in \p CU's DIEInfo.
1702 /// This function is the entry point of the DIE selection
1703 /// algorithm. It is expected to walk the DIE tree in file order and
1704 /// (though the mediation of its helper) call hasValidRelocation() on
1705 /// each DIE that might be a 'root DIE' (See DwarfLinker class
1707 /// While walking the dependencies of root DIEs, this function is
1708 /// also called, but during these dependency walks the file order is
1709 /// not respected. The TF_DependencyWalk flag tells us which kind of
1710 /// traversal we are currently doing.
1711 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1712 const DebugMapObject &DMO, CompileUnit &CU,
1714 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1715 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1716 bool AlreadyKept = MyInfo.Keep;
1718 // If the Keep flag is set, we are marking a required DIE's
1719 // dependencies. If our target is already marked as kept, we're all
1721 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1724 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1725 // because it would screw up the relocation finding logic.
1726 if (!(Flags & TF_DependencyWalk))
1727 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1729 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1730 if (!AlreadyKept && (Flags & TF_Keep))
1731 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1733 // The TF_ParentWalk flag tells us that we are currently walking up
1734 // the parent chain of a required DIE, and we don't want to mark all
1735 // the children of the parents as kept (consider for example a
1736 // DW_TAG_namespace node in the parent chain). There are however a
1737 // set of DIE types for which we want to ignore that directive and still
1738 // walk their children.
1739 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1740 Flags &= ~TF_ParentWalk;
1742 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1745 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1746 Child = Child->getSibling())
1747 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1750 /// \brief Assign an abbreviation numer to \p Abbrev.
1752 /// Our DIEs get freed after every DebugMapObject has been processed,
1753 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1754 /// the instances hold by the DIEs. When we encounter an abbreviation
1755 /// that we don't know, we create a permanent copy of it.
1756 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1757 // Check the set for priors.
1758 FoldingSetNodeID ID;
1761 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1763 // If it's newly added.
1765 // Assign existing abbreviation number.
1766 Abbrev.setNumber(InSet->getNumber());
1768 // Add to abbreviation list.
1769 Abbreviations.push_back(
1770 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1771 for (const auto &Attr : Abbrev.getData())
1772 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1773 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1774 // Assign the unique abbreviation number.
1775 Abbrev.setNumber(Abbreviations.size());
1776 Abbreviations.back()->setNumber(Abbreviations.size());
1780 /// \brief Clone a string attribute described by \p AttrSpec and add
1782 /// \returns the size of the new attribute.
1783 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1784 const DWARFFormValue &Val,
1785 const DWARFUnit &U) {
1786 // Switch everything to out of line strings.
1787 const char *String = *Val.getAsCString(&U);
1788 unsigned Offset = StringPool.getStringOffset(String);
1789 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1790 DIEInteger(Offset));
1794 /// \brief Clone an attribute referencing another DIE and add
1796 /// \returns the size of the new attribute.
1797 unsigned DwarfLinker::cloneDieReferenceAttribute(
1798 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1799 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1800 CompileUnit &Unit) {
1801 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
1802 DIE *NewRefDie = nullptr;
1803 CompileUnit *RefUnit = nullptr;
1804 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1806 if (!(RefUnit = getUnitForOffset(Ref)) ||
1807 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1808 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1809 if (!AttributeString)
1810 AttributeString = "DW_AT_???";
1811 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1813 &Unit.getOrigUnit(), &InputDIE);
1817 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1818 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1819 if (!RefInfo.Clone) {
1820 assert(Ref > InputDIE.getOffset());
1821 // We haven't cloned this DIE yet. Just create an empty one and
1822 // store it. It'll get really cloned when we process it.
1823 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1825 NewRefDie = RefInfo.Clone;
1827 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1828 // We cannot currently rely on a DIEEntry to emit ref_addr
1829 // references, because the implementation calls back to DwarfDebug
1830 // to find the unit offset. (We don't have a DwarfDebug)
1831 // FIXME: we should be able to design DIEEntry reliance on
1834 if (Ref < InputDIE.getOffset()) {
1835 // We must have already cloned that DIE.
1836 uint32_t NewRefOffset =
1837 RefUnit->getStartOffset() + NewRefDie->getOffset();
1838 Attr = NewRefOffset;
1840 // A forward reference. Note and fixup later.
1842 Unit.noteForwardReference(NewRefDie, RefUnit,
1843 PatchLocation(Die, Die.getValues().size()));
1845 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1850 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1851 DIEEntry(*NewRefDie));
1855 /// \brief Clone an attribute of block form (locations, constants) and add
1857 /// \returns the size of the new attribute.
1858 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1859 const DWARFFormValue &Val,
1860 unsigned AttrSize) {
1863 DIELoc *Loc = nullptr;
1864 DIEBlock *Block = nullptr;
1865 // Just copy the block data over.
1866 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1867 Loc = new (DIEAlloc) DIELoc;
1868 DIELocs.push_back(Loc);
1870 Block = new (DIEAlloc) DIEBlock;
1871 DIEBlocks.push_back(Block);
1873 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1876 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1877 dwarf::Form(AttrSpec.Form), Loc);
1879 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1880 dwarf::Form(AttrSpec.Form), Block);
1881 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1882 for (auto Byte : Bytes)
1883 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1885 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1886 // the DIE class, this if could be replaced by
1887 // Attr->setSize(Bytes.size()).
1890 Loc->ComputeSize(&Streamer->getAsmPrinter());
1892 Block->ComputeSize(&Streamer->getAsmPrinter());
1894 Die.addValue(Value);
1898 /// \brief Clone an address attribute and add it to \p Die.
1899 /// \returns the size of the new attribute.
1900 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1901 const DWARFFormValue &Val,
1902 const CompileUnit &Unit,
1903 AttributesInfo &Info) {
1904 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
1905 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1906 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1907 Die.getTag() == dwarf::DW_TAG_lexical_block)
1908 Addr += Info.PCOffset;
1909 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1910 Addr = Unit.getLowPc();
1911 if (Addr == UINT64_MAX)
1914 Info.HasLowPc = true;
1915 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1916 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1917 if (uint64_t HighPc = Unit.getHighPc())
1922 // If we have a high_pc recorded for the input DIE, use
1923 // it. Otherwise (when no relocations where applied) just use the
1924 // one we just decoded.
1925 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1928 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
1929 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
1930 return Unit.getOrigUnit().getAddressByteSize();
1933 /// \brief Clone a scalar attribute and add it to \p Die.
1934 /// \returns the size of the new attribute.
1935 unsigned DwarfLinker::cloneScalarAttribute(
1936 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
1937 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
1938 AttributesInfo &Info) {
1940 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1941 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1942 if (Unit.getLowPc() == -1ULL)
1944 // Dwarf >= 4 high_pc is an size, not an address.
1945 Value = Unit.getHighPc() - Unit.getLowPc();
1946 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1947 Value = *Val.getAsSectionOffset();
1948 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1949 Value = *Val.getAsSignedConstant();
1950 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1951 Value = *OptionalValue;
1953 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1954 &Unit.getOrigUnit(), &InputDIE);
1957 DIEInteger Attr(Value);
1958 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
1959 Unit.noteRangeAttribute(Die, PatchLocation(Die, Die.getValues().size()));
1960 // A more generic way to check for location attributes would be
1961 // nice, but it's very unlikely that any other attribute needs a
1963 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1964 AttrSpec.Attr == dwarf::DW_AT_frame_base)
1965 Unit.noteLocationAttribute(PatchLocation(Die, Die.getValues().size()),
1967 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1968 Info.IsDeclaration = true;
1970 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1975 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1976 /// value \p Val, and add it to \p Die.
1977 /// \returns the size of the cloned attribute.
1978 unsigned DwarfLinker::cloneAttribute(DIE &Die,
1979 const DWARFDebugInfoEntryMinimal &InputDIE,
1981 const DWARFFormValue &Val,
1982 const AttributeSpec AttrSpec,
1983 unsigned AttrSize, AttributesInfo &Info) {
1984 const DWARFUnit &U = Unit.getOrigUnit();
1986 switch (AttrSpec.Form) {
1987 case dwarf::DW_FORM_strp:
1988 case dwarf::DW_FORM_string:
1989 return cloneStringAttribute(Die, AttrSpec, Val, U);
1990 case dwarf::DW_FORM_ref_addr:
1991 case dwarf::DW_FORM_ref1:
1992 case dwarf::DW_FORM_ref2:
1993 case dwarf::DW_FORM_ref4:
1994 case dwarf::DW_FORM_ref8:
1995 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1997 case dwarf::DW_FORM_block:
1998 case dwarf::DW_FORM_block1:
1999 case dwarf::DW_FORM_block2:
2000 case dwarf::DW_FORM_block4:
2001 case dwarf::DW_FORM_exprloc:
2002 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2003 case dwarf::DW_FORM_addr:
2004 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
2005 case dwarf::DW_FORM_data1:
2006 case dwarf::DW_FORM_data2:
2007 case dwarf::DW_FORM_data4:
2008 case dwarf::DW_FORM_data8:
2009 case dwarf::DW_FORM_udata:
2010 case dwarf::DW_FORM_sdata:
2011 case dwarf::DW_FORM_sec_offset:
2012 case dwarf::DW_FORM_flag:
2013 case dwarf::DW_FORM_flag_present:
2014 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2017 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2024 /// \brief Apply the valid relocations found by findValidRelocs() to
2025 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
2026 /// in the debug_info section.
2028 /// Like for findValidRelocs(), this function must be called with
2029 /// monotonic \p BaseOffset values.
2031 /// \returns wether any reloc has been applied.
2032 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2033 uint32_t BaseOffset, bool isLittleEndian) {
2034 assert((NextValidReloc == 0 ||
2035 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2036 "BaseOffset should only be increasing.");
2037 if (NextValidReloc >= ValidRelocs.size())
2040 // Skip relocs that haven't been applied.
2041 while (NextValidReloc < ValidRelocs.size() &&
2042 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2045 bool Applied = false;
2046 uint64_t EndOffset = BaseOffset + Data.size();
2047 while (NextValidReloc < ValidRelocs.size() &&
2048 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2049 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2050 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2051 assert(ValidReloc.Offset - BaseOffset < Data.size());
2052 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2054 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2055 Value += ValidReloc.Addend;
2056 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2057 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2058 Buf[i] = uint8_t(Value >> (Index * 8));
2060 assert(ValidReloc.Size <= sizeof(Buf));
2061 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2068 static bool isTypeTag(uint16_t Tag) {
2070 case dwarf::DW_TAG_array_type:
2071 case dwarf::DW_TAG_class_type:
2072 case dwarf::DW_TAG_enumeration_type:
2073 case dwarf::DW_TAG_pointer_type:
2074 case dwarf::DW_TAG_reference_type:
2075 case dwarf::DW_TAG_string_type:
2076 case dwarf::DW_TAG_structure_type:
2077 case dwarf::DW_TAG_subroutine_type:
2078 case dwarf::DW_TAG_typedef:
2079 case dwarf::DW_TAG_union_type:
2080 case dwarf::DW_TAG_ptr_to_member_type:
2081 case dwarf::DW_TAG_set_type:
2082 case dwarf::DW_TAG_subrange_type:
2083 case dwarf::DW_TAG_base_type:
2084 case dwarf::DW_TAG_const_type:
2085 case dwarf::DW_TAG_constant:
2086 case dwarf::DW_TAG_file_type:
2087 case dwarf::DW_TAG_namelist:
2088 case dwarf::DW_TAG_packed_type:
2089 case dwarf::DW_TAG_volatile_type:
2090 case dwarf::DW_TAG_restrict_type:
2091 case dwarf::DW_TAG_interface_type:
2092 case dwarf::DW_TAG_unspecified_type:
2093 case dwarf::DW_TAG_shared_type:
2101 /// \brief Recursively clone \p InputDIE's subtrees that have been
2102 /// selected to appear in the linked output.
2104 /// \param OutOffset is the Offset where the newly created DIE will
2105 /// lie in the linked compile unit.
2107 /// \returns the cloned DIE object or null if nothing was selected.
2108 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
2109 CompileUnit &Unit, int64_t PCOffset,
2110 uint32_t OutOffset) {
2111 DWARFUnit &U = Unit.getOrigUnit();
2112 unsigned Idx = U.getDIEIndex(&InputDIE);
2113 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2115 // Should the DIE appear in the output?
2116 if (!Unit.getInfo(Idx).Keep)
2119 uint32_t Offset = InputDIE.getOffset();
2120 // The DIE might have been already created by a forward reference
2121 // (see cloneDieReferenceAttribute()).
2122 DIE *Die = Info.Clone;
2124 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
2125 assert(Die->getTag() == InputDIE.getTag());
2126 Die->setOffset(OutOffset);
2128 // Extract and clone every attribute.
2129 DataExtractor Data = U.getDebugInfoExtractor();
2130 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
2131 AttributesInfo AttrInfo;
2133 // We could copy the data only if we need to aply a relocation to
2134 // it. After testing, it seems there is no performance downside to
2135 // doing the copy unconditionally, and it makes the code simpler.
2136 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2137 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2138 // Modify the copy with relocated addresses.
2139 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2140 // If we applied relocations, we store the value of high_pc that was
2141 // potentially stored in the input DIE. If high_pc is an address
2142 // (Dwarf version == 2), then it might have been relocated to a
2143 // totally unrelated value (because the end address in the object
2144 // file might be start address of another function which got moved
2145 // independantly by the linker). The computation of the actual
2146 // high_pc value is done in cloneAddressAttribute().
2147 AttrInfo.OrigHighPc =
2148 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2151 // Reset the Offset to 0 as we will be working on the local copy of
2155 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2156 Offset += getULEB128Size(Abbrev->getCode());
2158 // We are entering a subprogram. Get and propagate the PCOffset.
2159 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2160 PCOffset = Info.AddrAdjust;
2161 AttrInfo.PCOffset = PCOffset;
2163 for (const auto &AttrSpec : Abbrev->attributes()) {
2164 DWARFFormValue Val(AttrSpec.Form);
2165 uint32_t AttrSize = Offset;
2166 Val.extractValue(Data, &Offset, &U);
2167 AttrSize = Offset - AttrSize;
2170 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2173 // Look for accelerator entries.
2174 uint16_t Tag = InputDIE.getTag();
2175 // FIXME: This is slightly wrong. An inline_subroutine without a
2176 // low_pc, but with AT_ranges might be interesting to get into the
2177 // accelerator tables too. For now stick with dsymutil's behavior.
2178 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2179 Tag != dwarf::DW_TAG_compile_unit &&
2180 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2181 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2182 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2183 AttrInfo.MangledNameOffset,
2184 Tag == dwarf::DW_TAG_inlined_subroutine);
2186 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2187 Tag == dwarf::DW_TAG_inlined_subroutine);
2188 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2189 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2190 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2193 DIEAbbrev NewAbbrev = Die->generateAbbrev();
2194 // If a scope DIE is kept, we must have kept at least one child. If
2195 // it's not the case, we'll just be emitting one wasteful end of
2196 // children marker, but things won't break.
2197 if (InputDIE.hasChildren())
2198 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2199 // Assign a permanent abbrev number
2200 AssignAbbrev(NewAbbrev);
2201 Die->setAbbrevNumber(NewAbbrev.getNumber());
2203 // Add the size of the abbreviation number to the output offset.
2204 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2206 if (!Abbrev->hasChildren()) {
2208 Die->setSize(OutOffset - Die->getOffset());
2212 // Recursively clone children.
2213 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2214 Child = Child->getSibling()) {
2215 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
2216 Die->addChild(std::unique_ptr<DIE>(Clone));
2217 OutOffset = Clone->getOffset() + Clone->getSize();
2221 // Account for the end of children marker.
2222 OutOffset += sizeof(int8_t);
2224 Die->setSize(OutOffset - Die->getOffset());
2228 /// \brief Patch the input object file relevant debug_ranges entries
2229 /// and emit them in the output file. Update the relevant attributes
2230 /// to point at the new entries.
2231 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2232 DWARFContext &OrigDwarf) const {
2233 DWARFDebugRangeList RangeList;
2234 const auto &FunctionRanges = Unit.getFunctionRanges();
2235 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2236 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2237 OrigDwarf.isLittleEndian(), AddressSize);
2238 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2239 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2240 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
2241 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2242 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2243 // Ranges addresses are based on the unit's low_pc. Compute the
2244 // offset we need to apply to adapt to the the new unit's low_pc.
2245 int64_t UnitPcOffset = 0;
2246 if (OrigLowPc != -1ULL)
2247 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2249 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2250 uint32_t Offset = RangeAttribute.get();
2251 RangeAttribute.set(Streamer->getRangesSectionSize());
2252 RangeList.extract(RangeExtractor, &Offset);
2253 const auto &Entries = RangeList.getEntries();
2254 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2256 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2257 First.StartAddress >= CurrRange.stop()) {
2258 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2259 if (CurrRange == InvalidRange ||
2260 CurrRange.start() > First.StartAddress + OrigLowPc) {
2261 reportWarning("no mapping for range.");
2266 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2271 /// \brief Generate the debug_aranges entries for \p Unit and if the
2272 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2273 /// contribution for this attribute.
2274 /// FIXME: this could actually be done right in patchRangesForUnit,
2275 /// but for the sake of initial bit-for-bit compatibility with legacy
2276 /// dsymutil, we have to do it in a delayed pass.
2277 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2278 auto Attr = Unit.getUnitRangesAttribute();
2280 Attr->set(Streamer->getRangesSectionSize());
2281 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
2284 /// \brief Insert the new line info sequence \p Seq into the current
2285 /// set of already linked line info \p Rows.
2286 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2287 std::vector<DWARFDebugLine::Row> &Rows) {
2291 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2292 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2297 auto InsertPoint = std::lower_bound(
2298 Rows.begin(), Rows.end(), Seq.front(),
2299 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2300 return LHS.Address < RHS.Address;
2303 // FIXME: this only removes the unneeded end_sequence if the
2304 // sequences have been inserted in order. using a global sort like
2305 // described in patchLineTableForUnit() and delaying the end_sequene
2306 // elimination to emitLineTableForUnit() we can get rid of all of them.
2307 if (InsertPoint != Rows.end() &&
2308 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2309 *InsertPoint = Seq.front();
2310 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2312 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2318 /// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2319 /// recreate a relocated version of these for the address ranges that
2320 /// are present in the binary.
2321 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2322 DWARFContext &OrigDwarf) {
2323 const DWARFDebugInfoEntryMinimal *CUDie =
2324 Unit.getOrigUnit().getUnitDIE();
2325 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2326 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2327 if (StmtList == -1ULL)
2330 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2331 if (auto *OutputDIE = Unit.getOutputUnitDIE()) {
2332 const auto &Values = OutputDIE->getValues();
2334 std::find_if(Values.begin(), Values.end(), [](const DIEValue &Value) {
2335 return Value.getAttribute() == dwarf::DW_AT_stmt_list;
2337 assert(Stmt < Values.end() && "Didn't find DW_AT_stmt_list in cloned DIE!");
2338 OutputDIE->setValue(Stmt - Values.begin(),
2339 DIEValue(Stmt->getAttribute(), Stmt->getForm(),
2340 DIEInteger(Streamer->getLineSectionSize())));
2343 // Parse the original line info for the unit.
2344 DWARFDebugLine::LineTable LineTable;
2345 uint32_t StmtOffset = StmtList;
2346 StringRef LineData = OrigDwarf.getLineSection().Data;
2347 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2348 Unit.getOrigUnit().getAddressByteSize());
2349 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2352 // This vector is the output line table.
2353 std::vector<DWARFDebugLine::Row> NewRows;
2354 NewRows.reserve(LineTable.Rows.size());
2356 // Current sequence of rows being extracted, before being inserted
2358 std::vector<DWARFDebugLine::Row> Seq;
2359 const auto &FunctionRanges = Unit.getFunctionRanges();
2360 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2362 // FIXME: This logic is meant to generate exactly the same output as
2363 // Darwin's classic dsynutil. There is a nicer way to implement this
2364 // by simply putting all the relocated line info in NewRows and simply
2365 // sorting NewRows before passing it to emitLineTableForUnit. This
2366 // should be correct as sequences for a function should stay
2367 // together in the sorted output. There are a few corner cases that
2368 // look suspicious though, and that required to implement the logic
2369 // this way. Revisit that once initial validation is finished.
2371 // Iterate over the object file line info and extract the sequences
2372 // that correspond to linked functions.
2373 for (auto &Row : LineTable.Rows) {
2374 // Check wether we stepped out of the range. The range is
2375 // half-open, but consider accept the end address of the range if
2376 // it is marked as end_sequence in the input (because in that
2377 // case, the relocation offset is accurate and that entry won't
2378 // serve as the start of another function).
2379 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2380 Row.Address > CurrRange.stop() ||
2381 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2382 // We just stepped out of a known range. Insert a end_sequence
2383 // corresponding to the end of the range.
2384 uint64_t StopAddress = CurrRange != InvalidRange
2385 ? CurrRange.stop() + CurrRange.value()
2387 CurrRange = FunctionRanges.find(Row.Address);
2388 bool CurrRangeValid =
2389 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2390 if (!CurrRangeValid) {
2391 CurrRange = InvalidRange;
2392 if (StopAddress != -1ULL) {
2393 // Try harder by looking in the DebugMapObject function
2394 // ranges map. There are corner cases where this finds a
2395 // valid entry. It's unclear if this is right or wrong, but
2396 // for now do as dsymutil.
2397 // FIXME: Understand exactly what cases this addresses and
2398 // potentially remove it along with the Ranges map.
2399 auto Range = Ranges.lower_bound(Row.Address);
2400 if (Range != Ranges.begin() && Range != Ranges.end())
2403 if (Range != Ranges.end() && Range->first <= Row.Address &&
2404 Range->second.first >= Row.Address) {
2405 StopAddress = Row.Address + Range->second.second;
2409 if (StopAddress != -1ULL && !Seq.empty()) {
2410 // Insert end sequence row with the computed end address, but
2411 // the same line as the previous one.
2412 Seq.emplace_back(Seq.back());
2413 Seq.back().Address = StopAddress;
2414 Seq.back().EndSequence = 1;
2415 Seq.back().PrologueEnd = 0;
2416 Seq.back().BasicBlock = 0;
2417 Seq.back().EpilogueBegin = 0;
2418 insertLineSequence(Seq, NewRows);
2421 if (!CurrRangeValid)
2425 // Ignore empty sequences.
2426 if (Row.EndSequence && Seq.empty())
2429 // Relocate row address and add it to the current sequence.
2430 Row.Address += CurrRange.value();
2431 Seq.emplace_back(Row);
2433 if (Row.EndSequence)
2434 insertLineSequence(Seq, NewRows);
2437 // Finished extracting, now emit the line tables.
2438 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2439 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2440 // prologue over and that works because we act as both producer and
2441 // consumer. It would be nicer to have a real configurable line
2443 if (LineTable.Prologue.Version != 2 ||
2444 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2445 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2446 LineTable.Prologue.OpcodeBase != 13)
2447 reportWarning("line table paramters mismatch. Cannot emit.");
2449 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2450 LineTable.Prologue.MinInstLength, NewRows,
2451 Unit.getOrigUnit().getAddressByteSize());
2454 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2455 Streamer->emitPubNamesForUnit(Unit);
2456 Streamer->emitPubTypesForUnit(Unit);
2459 bool DwarfLinker::link(const DebugMap &Map) {
2461 if (Map.begin() == Map.end()) {
2462 errs() << "Empty debug map.\n";
2466 if (!createStreamer(Map.getTriple(), OutputFilename))
2469 // Size of the DIEs (and headers) generated for the linked output.
2470 uint64_t OutputDebugInfoSize = 0;
2471 // A unique ID that identifies each compile unit.
2472 unsigned UnitID = 0;
2473 for (const auto &Obj : Map.objects()) {
2474 CurrentDebugObject = Obj.get();
2476 if (Options.Verbose)
2477 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2478 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
2479 if (std::error_code EC = ErrOrObj.getError()) {
2480 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
2484 // Look for relocations that correspond to debug map entries.
2485 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
2486 if (Options.Verbose)
2487 outs() << "No valid relocations found. Skipping.\n";
2491 // Setup access to the debug info.
2492 DWARFContextInMemory DwarfContext(*ErrOrObj);
2493 startDebugObject(DwarfContext, *Obj);
2495 // In a first phase, just read in the debug info and store the DIE
2496 // parent links that we will use during the next phase.
2497 for (const auto &CU : DwarfContext.compile_units()) {
2498 auto *CUDie = CU->getUnitDIE(false);
2499 if (Options.Verbose) {
2500 outs() << "Input compilation unit:";
2501 CUDie->dump(outs(), CU.get(), 0);
2503 Units.emplace_back(*CU, UnitID++);
2504 gatherDIEParents(CUDie, 0, Units.back());
2507 // Then mark all the DIEs that need to be present in the linked
2508 // output and collect some information about them. Note that this
2509 // loop can not be merged with the previous one becaue cross-cu
2510 // references require the ParentIdx to be setup for every CU in
2511 // the object file before calling this.
2512 for (auto &CurrentUnit : Units)
2513 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
2516 // The calls to applyValidRelocs inside cloneDIE will walk the
2517 // reloc array again (in the same way findValidRelocsInDebugInfo()
2518 // did). We need to reset the NextValidReloc index to the beginning.
2521 // Construct the output DIE tree by cloning the DIEs we chose to
2522 // keep above. If there are no valid relocs, then there's nothing
2524 if (!ValidRelocs.empty())
2525 for (auto &CurrentUnit : Units) {
2526 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
2527 CurrentUnit.setStartOffset(OutputDebugInfoSize);
2528 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
2529 11 /* Unit Header size */);
2530 CurrentUnit.setOutputUnitDIE(OutputDIE);
2531 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
2532 if (Options.NoOutput)
2534 // FIXME: for compatibility with the classic dsymutil, we emit
2535 // an empty line table for the unit, even if the unit doesn't
2536 // actually exist in the DIE tree.
2537 patchLineTableForUnit(CurrentUnit, DwarfContext);
2540 patchRangesForUnit(CurrentUnit, DwarfContext);
2541 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
2542 emitAcceleratorEntriesForUnit(CurrentUnit);
2545 // Emit all the compile unit's debug information.
2546 if (!ValidRelocs.empty() && !Options.NoOutput)
2547 for (auto &CurrentUnit : Units) {
2548 generateUnitRanges(CurrentUnit);
2549 CurrentUnit.fixupForwardReferences();
2550 Streamer->emitCompileUnitHeader(CurrentUnit);
2551 if (!CurrentUnit.getOutputUnitDIE())
2553 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
2556 // Clean-up before starting working on the next object.
2560 // Emit everything that's global.
2561 if (!Options.NoOutput) {
2562 Streamer->emitAbbrevs(Abbreviations);
2563 Streamer->emitStrings(StringPool);
2566 return Options.NoOutput ? true : Streamer->finish();
2570 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
2571 const LinkOptions &Options) {
2572 DwarfLinker Linker(OutputFilename, Options);
2573 return Linker.link(DM);