1 //===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "BinaryHolder.h"
13 #include "llvm/ADT/IntervalMap.h"
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/DIE.h"
18 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
20 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
21 #include "llvm/MC/MCAsmBackend.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCCodeEmitter.h"
25 #include "llvm/MC/MCDwarf.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCObjectFileInfo.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/Object/MachO.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/Support/LEB128.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
45 void warn(const Twine &Warning, const Twine &Context) {
46 errs() << Twine("while processing ") + Context + ":\n";
47 errs() << Twine("warning: ") + Warning + "\n";
50 bool error(const Twine &Error, const Twine &Context) {
51 errs() << Twine("while processing ") + Context + ":\n";
52 errs() << Twine("error: ") + Error + "\n";
56 template <typename KeyT, typename ValT>
57 using HalfOpenIntervalMap =
58 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
59 IntervalMapHalfOpenInfo<KeyT>>;
61 typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
63 // FIXME: Delete this structure.
64 struct PatchLocation {
65 DIE::value_iterator I;
67 PatchLocation() = default;
68 PatchLocation(DIE::value_iterator I) : I(I) {}
70 void set(uint64_t New) const {
73 assert(Old.getType() == DIEValue::isInteger);
74 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
77 uint64_t get() const {
79 return I->getDIEInteger().getValue();
83 /// \brief Stores all information relating to a compile unit, be it in
84 /// its original instance in the object file to its brand new cloned
85 /// and linked DIE tree.
88 /// \brief Information gathered about a DIE in the object file.
90 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
91 DIE *Clone; ///< Cloned version of that DIE.
92 uint32_t ParentIdx; ///< The index of this DIE's parent.
93 bool Keep; ///< Is the DIE part of the linked output?
94 bool InDebugMap; ///< Was this DIE's entity found in the map?
97 CompileUnit(DWARFUnit &OrigUnit, unsigned ID)
98 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
100 Info.resize(OrigUnit.getNumDIEs());
103 CompileUnit(CompileUnit &&RHS)
104 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
105 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
106 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
107 // The CompileUnit container has been 'reserve()'d with the right
108 // size. We cannot move the IntervalMap anyway.
109 llvm_unreachable("CompileUnits should not be moved.");
112 DWARFUnit &getOrigUnit() const { return OrigUnit; }
114 unsigned getUniqueID() const { return ID; }
116 DIE *getOutputUnitDIE() const { return CUDie; }
117 void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
119 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
120 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
122 uint64_t getStartOffset() const { return StartOffset; }
123 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
124 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
126 uint64_t getLowPc() const { return LowPc; }
127 uint64_t getHighPc() const { return HighPc; }
129 Optional<PatchLocation> getUnitRangesAttribute() const {
130 return UnitRangeAttribute;
132 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
133 const std::vector<PatchLocation> &getRangesAttributes() const {
134 return RangeAttributes;
137 const std::vector<std::pair<PatchLocation, int64_t>> &
138 getLocationAttributes() const {
139 return LocationAttributes;
142 /// \brief Compute the end offset for this unit. Must be
143 /// called after the CU's DIEs have been cloned.
144 /// \returns the next unit offset (which is also the current
145 /// debug_info section size).
146 uint64_t computeNextUnitOffset();
148 /// \brief Keep track of a forward reference to DIE \p Die in \p
149 /// RefUnit by \p Attr. The attribute should be fixed up later to
150 /// point to the absolute offset of \p Die in the debug_info section.
151 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
154 /// \brief Apply all fixups recored by noteForwardReference().
155 void fixupForwardReferences();
157 /// \brief Add a function range [\p LowPC, \p HighPC) that is
158 /// relocatad by applying offset \p PCOffset.
159 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
161 /// \brief Keep track of a DW_AT_range attribute that we will need to
163 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
165 /// \brief Keep track of a location attribute pointing to a location
166 /// list in the debug_loc section.
167 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
169 /// \brief Add a name accelerator entry for \p Die with \p Name
170 /// which is stored in the string table at \p Offset.
171 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
172 bool SkipPubnamesSection = false);
174 /// \brief Add a type accelerator entry for \p Die with \p Name
175 /// which is stored in the string table at \p Offset.
176 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
179 StringRef Name; ///< Name of the entry.
180 const DIE *Die; ///< DIE this entry describes.
181 uint32_t NameOffset; ///< Offset of Name in the string pool.
182 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
184 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
185 bool SkipPubSection = false)
186 : Name(Name), Die(Die), NameOffset(NameOffset),
187 SkipPubSection(SkipPubSection) {}
190 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
191 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
196 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
197 DIE *CUDie; ///< Root of the linked DIE tree.
199 uint64_t StartOffset;
200 uint64_t NextUnitOffset;
205 /// \brief A list of attributes to fixup with the absolute offset of
206 /// a DIE in the debug_info section.
208 /// The offsets for the attributes in this array couldn't be set while
209 /// cloning because for cross-cu forward refences the target DIE's
210 /// offset isn't known you emit the reference attribute.
211 std::vector<std::tuple<DIE *, const CompileUnit *, PatchLocation>>
212 ForwardDIEReferences;
214 FunctionIntervals::Allocator RangeAlloc;
215 /// \brief The ranges in that interval map are the PC ranges for
216 /// functions in this unit, associated with the PC offset to apply
217 /// to the addresses to get the linked address.
218 FunctionIntervals Ranges;
220 /// \brief DW_AT_ranges attributes to patch after we have gathered
221 /// all the unit's function addresses.
223 std::vector<PatchLocation> RangeAttributes;
224 Optional<PatchLocation> UnitRangeAttribute;
227 /// \brief Location attributes that need to be transfered from th
228 /// original debug_loc section to the liked one. They are stored
229 /// along with the PC offset that is to be applied to their
230 /// function's address.
231 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
233 /// \brief Accelerator entries for the unit, both for the pub*
234 /// sections and the apple* ones.
236 std::vector<AccelInfo> Pubnames;
237 std::vector<AccelInfo> Pubtypes;
241 uint64_t CompileUnit::computeNextUnitOffset() {
242 NextUnitOffset = StartOffset + 11 /* Header size */;
243 // The root DIE might be null, meaning that the Unit had nothing to
244 // contribute to the linked output. In that case, we will emit the
245 // unit header without any actual DIE.
247 NextUnitOffset += CUDie->getSize();
248 return NextUnitOffset;
251 /// \brief Keep track of a forward cross-cu reference from this unit
252 /// to \p Die that lives in \p RefUnit.
253 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
254 PatchLocation Attr) {
255 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
258 /// \brief Apply all fixups recorded by noteForwardReference().
259 void CompileUnit::fixupForwardReferences() {
260 for (const auto &Ref : ForwardDIEReferences) {
262 const CompileUnit *RefUnit;
264 std::tie(RefDie, RefUnit, Attr) = Ref;
265 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
269 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
271 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
272 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
273 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
276 void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
277 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
278 RangeAttributes.push_back(Attr);
280 UnitRangeAttribute = Attr;
283 void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
284 LocationAttributes.emplace_back(Attr, PcOffset);
287 /// \brief Add a name accelerator entry for \p Die with \p Name
288 /// which is stored in the string table at \p Offset.
289 void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
290 uint32_t Offset, bool SkipPubSection) {
291 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
294 /// \brief Add a type accelerator entry for \p Die with \p Name
295 /// which is stored in the string table at \p Offset.
296 void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
298 Pubtypes.emplace_back(Name, Die, Offset, false);
301 /// \brief A string table that doesn't need relocations.
303 /// We are doing a final link, no need for a string table that
304 /// has relocation entries for every reference to it. This class
305 /// provides this ablitity by just associating offsets with
307 class NonRelocatableStringpool {
309 /// \brief Entries are stored into the StringMap and simply linked
310 /// together through the second element of this pair in order to
311 /// keep track of insertion order.
312 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
315 NonRelocatableStringpool()
316 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
317 // Legacy dsymutil puts an empty string at the start of the line
322 /// \brief Get the offset of string \p S in the string table. This
323 /// can insert a new element or return the offset of a preexisitng
325 uint32_t getStringOffset(StringRef S);
327 // \brief Return the first entry of the string table.
328 const MapTy::MapEntryTy *getFirstEntry() const {
329 return getNextEntry(&Sentinel);
332 // \brief Get the entry following \p E in the string table or null
333 // if \p E was the last entry.
334 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
335 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
338 uint64_t getSize() { return CurrentEndOffset; }
342 uint32_t CurrentEndOffset;
343 MapTy::MapEntryTy Sentinel, *Last;
346 /// \brief Get the offset of string \p S in the string table. This
347 /// can insert a new element or return the offset of a preexisitng
349 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
350 if (S.empty() && !Strings.empty())
353 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
357 // A non-empty string can't be at offset 0, so if we have an entry
358 // with a 0 offset, it must be a previously interned string.
359 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
360 if (Inserted || It->getValue().first == 0) {
361 // Set offset and chain at the end of the entries list.
362 It->getValue().first = CurrentEndOffset;
363 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
364 Last->getValue().second = &*It;
367 return It->getValue().first;
370 /// \brief The Dwarf streaming logic
372 /// All interactions with the MC layer that is used to build the debug
373 /// information binary representation are handled in this class.
374 class DwarfStreamer {
375 /// \defgroup MCObjects MC layer objects constructed by the streamer
377 std::unique_ptr<MCRegisterInfo> MRI;
378 std::unique_ptr<MCAsmInfo> MAI;
379 std::unique_ptr<MCObjectFileInfo> MOFI;
380 std::unique_ptr<MCContext> MC;
381 MCAsmBackend *MAB; // Owned by MCStreamer
382 std::unique_ptr<MCInstrInfo> MII;
383 std::unique_ptr<MCSubtargetInfo> MSTI;
384 MCCodeEmitter *MCE; // Owned by MCStreamer
385 MCStreamer *MS; // Owned by AsmPrinter
386 std::unique_ptr<TargetMachine> TM;
387 std::unique_ptr<AsmPrinter> Asm;
390 /// \brief the file we stream the linked Dwarf to.
391 std::unique_ptr<raw_fd_ostream> OutFile;
393 uint32_t RangesSectionSize;
394 uint32_t LocSectionSize;
395 uint32_t LineSectionSize;
396 uint32_t FrameSectionSize;
398 /// \brief Emit the pubnames or pubtypes section contribution for \p
399 /// Unit into \p Sec. The data is provided in \p Names.
400 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
401 const CompileUnit &Unit,
402 const std::vector<CompileUnit::AccelInfo> &Names);
405 /// \brief Actually create the streamer and the ouptut file.
407 /// This could be done directly in the constructor, but it feels
408 /// more natural to handle errors through return value.
409 bool init(Triple TheTriple, StringRef OutputFilename);
411 /// \brief Dump the file to the disk.
414 AsmPrinter &getAsmPrinter() const { return *Asm; }
416 /// \brief Set the current output section to debug_info and change
417 /// the MC Dwarf version to \p DwarfVersion.
418 void switchToDebugInfoSection(unsigned DwarfVersion);
420 /// \brief Emit the compilation unit header for \p Unit in the
421 /// debug_info section.
423 /// As a side effect, this also switches the current Dwarf version
424 /// of the MC layer to the one of U.getOrigUnit().
425 void emitCompileUnitHeader(CompileUnit &Unit);
427 /// \brief Recursively emit the DIE tree rooted at \p Die.
428 void emitDIE(DIE &Die);
430 /// \brief Emit the abbreviation table \p Abbrevs to the
431 /// debug_abbrev section.
432 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
434 /// \brief Emit the string table described by \p Pool.
435 void emitStrings(const NonRelocatableStringpool &Pool);
437 /// \brief Emit debug_ranges for \p FuncRange by translating the
438 /// original \p Entries.
439 void emitRangesEntries(
440 int64_t UnitPcOffset, uint64_t OrigLowPc,
441 FunctionIntervals::const_iterator FuncRange,
442 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
443 unsigned AddressSize);
445 /// \brief Emit debug_aranges entries for \p Unit and if \p
446 /// DoRangesSection is true, also emit the debug_ranges entries for
447 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
448 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
450 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
452 /// \brief Emit the debug_loc contribution for \p Unit by copying
453 /// the entries from \p Dwarf and offseting them. Update the
454 /// location attributes to point to the new entries.
455 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
457 /// \brief Emit the line table described in \p Rows into the
458 /// debug_line section.
459 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
460 std::vector<DWARFDebugLine::Row> &Rows,
461 unsigned AdddressSize);
463 uint32_t getLineSectionSize() const { return LineSectionSize; }
465 /// \brief Emit the .debug_pubnames contribution for \p Unit.
466 void emitPubNamesForUnit(const CompileUnit &Unit);
468 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
469 void emitPubTypesForUnit(const CompileUnit &Unit);
471 /// \brief Emit a CIE.
472 void emitCIE(StringRef CIEBytes);
474 /// \brief Emit an FDE with data \p Bytes.
475 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
478 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
481 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
482 std::string ErrorStr;
483 std::string TripleName;
484 StringRef Context = "dwarf streamer init";
487 const Target *TheTarget =
488 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
490 return error(ErrorStr, Context);
491 TripleName = TheTriple.getTriple();
493 // Create all the MC Objects.
494 MRI.reset(TheTarget->createMCRegInfo(TripleName));
496 return error(Twine("no register info for target ") + TripleName, Context);
498 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
500 return error("no asm info for target " + TripleName, Context);
502 MOFI.reset(new MCObjectFileInfo);
503 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
504 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
507 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
509 return error("no asm backend for target " + TripleName, Context);
511 MII.reset(TheTarget->createMCInstrInfo());
513 return error("no instr info info for target " + TripleName, Context);
515 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
517 return error("no subtarget info for target " + TripleName, Context);
519 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
521 return error("no code emitter for target " + TripleName, Context);
523 // Create the output file.
526 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
528 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
530 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
532 /*DWARFMustBeAtTheEnd*/ false);
534 return error("no object streamer for target " + TripleName, Context);
536 // Finally create the AsmPrinter we'll use to emit the DIEs.
537 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
539 return error("no target machine for target " + TripleName, Context);
541 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
543 return error("no asm printer for target " + TripleName, Context);
545 RangesSectionSize = 0;
548 FrameSectionSize = 0;
553 bool DwarfStreamer::finish() {
558 /// \brief Set the current output section to debug_info and change
559 /// the MC Dwarf version to \p DwarfVersion.
560 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
561 MS->SwitchSection(MOFI->getDwarfInfoSection());
562 MC->setDwarfVersion(DwarfVersion);
565 /// \brief Emit the compilation unit header for \p Unit in the
566 /// debug_info section.
568 /// A Dwarf scetion header is encoded as:
569 /// uint32_t Unit length (omiting this field)
571 /// uint32_t Abbreviation table offset
572 /// uint8_t Address size
574 /// Leading to a total of 11 bytes.
575 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
576 unsigned Version = Unit.getOrigUnit().getVersion();
577 switchToDebugInfoSection(Version);
579 // Emit size of content not including length itself. The size has
580 // already been computed in CompileUnit::computeOffsets(). Substract
581 // 4 to that size to account for the length field.
582 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
583 Asm->EmitInt16(Version);
584 // We share one abbreviations table across all units so it's always at the
585 // start of the section.
587 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
590 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
591 /// for the linked Dwarf file.
592 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
593 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
594 Asm->emitDwarfAbbrevs(Abbrevs);
597 /// \brief Recursively emit the DIE tree rooted at \p Die.
598 void DwarfStreamer::emitDIE(DIE &Die) {
599 MS->SwitchSection(MOFI->getDwarfInfoSection());
600 Asm->emitDwarfDIE(Die);
603 /// \brief Emit the debug_str section stored in \p Pool.
604 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
605 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
606 for (auto *Entry = Pool.getFirstEntry(); Entry;
607 Entry = Pool.getNextEntry(Entry))
608 Asm->OutStreamer->EmitBytes(
609 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
612 /// \brief Emit the debug_range section contents for \p FuncRange by
613 /// translating the original \p Entries. The debug_range section
614 /// format is totally trivial, consisting just of pairs of address
615 /// sized addresses describing the ranges.
616 void DwarfStreamer::emitRangesEntries(
617 int64_t UnitPcOffset, uint64_t OrigLowPc,
618 FunctionIntervals::const_iterator FuncRange,
619 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
620 unsigned AddressSize) {
621 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
623 // Offset each range by the right amount.
624 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
625 for (const auto &Range : Entries) {
626 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
627 warn("unsupported base address selection operation",
628 "emitting debug_ranges");
631 // Do not emit empty ranges.
632 if (Range.StartAddress == Range.EndAddress)
635 // All range entries should lie in the function range.
636 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
637 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
638 warn("inconsistent range data.", "emitting debug_ranges");
639 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
640 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
641 RangesSectionSize += 2 * AddressSize;
644 // Add the terminator entry.
645 MS->EmitIntValue(0, AddressSize);
646 MS->EmitIntValue(0, AddressSize);
647 RangesSectionSize += 2 * AddressSize;
650 /// \brief Emit the debug_aranges contribution of a unit and
651 /// if \p DoDebugRanges is true the debug_range contents for a
652 /// compile_unit level DW_AT_ranges attribute (Which are basically the
653 /// same thing with a different base address).
654 /// Just aggregate all the ranges gathered inside that unit.
655 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
656 bool DoDebugRanges) {
657 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
658 // Gather the ranges in a vector, so that we can simplify them. The
659 // IntervalMap will have coalesced the non-linked ranges, but here
660 // we want to coalesce the linked addresses.
661 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
662 const auto &FunctionRanges = Unit.getFunctionRanges();
663 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
664 Range != End; ++Range)
665 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
666 Range.stop() + Range.value()));
668 // The object addresses where sorted, but again, the linked
669 // addresses might end up in a different order.
670 std::sort(Ranges.begin(), Ranges.end());
672 if (!Ranges.empty()) {
673 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
675 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
676 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
678 unsigned HeaderSize =
679 sizeof(int32_t) + // Size of contents (w/o this field
680 sizeof(int16_t) + // DWARF ARange version number
681 sizeof(int32_t) + // Offset of CU in the .debug_info section
682 sizeof(int8_t) + // Pointer Size (in bytes)
683 sizeof(int8_t); // Segment Size (in bytes)
685 unsigned TupleSize = AddressSize * 2;
686 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
688 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
689 Asm->OutStreamer->EmitLabel(BeginLabel);
690 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
691 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
692 Asm->EmitInt8(AddressSize); // Address size
693 Asm->EmitInt8(0); // Segment size
695 Asm->OutStreamer->EmitFill(Padding, 0x0);
697 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
699 uint64_t RangeStart = Range->first;
700 MS->EmitIntValue(RangeStart, AddressSize);
701 while ((Range + 1) != End && Range->second == (Range + 1)->first)
703 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
707 Asm->OutStreamer->EmitIntValue(0, AddressSize);
708 Asm->OutStreamer->EmitIntValue(0, AddressSize);
709 Asm->OutStreamer->EmitLabel(EndLabel);
715 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
716 // Offset each range by the right amount.
717 int64_t PcOffset = -Unit.getLowPc();
718 // Emit coalesced ranges.
719 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
720 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
721 while (Range + 1 != End && Range->second == (Range + 1)->first)
723 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
724 RangesSectionSize += 2 * AddressSize;
727 // Add the terminator entry.
728 MS->EmitIntValue(0, AddressSize);
729 MS->EmitIntValue(0, AddressSize);
730 RangesSectionSize += 2 * AddressSize;
733 /// \brief Emit location lists for \p Unit and update attribtues to
734 /// point to the new entries.
735 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
736 DWARFContext &Dwarf) {
737 const auto &Attributes = Unit.getLocationAttributes();
739 if (Attributes.empty())
742 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
744 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
745 const DWARFSection &InputSec = Dwarf.getLocSection();
746 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
747 DWARFUnit &OrigUnit = Unit.getOrigUnit();
748 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
749 int64_t UnitPcOffset = 0;
750 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
751 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
752 if (OrigLowPc != -1ULL)
753 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
755 for (const auto &Attr : Attributes) {
756 uint32_t Offset = Attr.first.get();
757 Attr.first.set(LocSectionSize);
758 // This is the quantity to add to the old location address to get
759 // the correct address for the new one.
760 int64_t LocPcOffset = Attr.second + UnitPcOffset;
761 while (Data.isValidOffset(Offset)) {
762 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
763 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
764 LocSectionSize += 2 * AddressSize;
765 if (Low == 0 && High == 0) {
766 Asm->OutStreamer->EmitIntValue(0, AddressSize);
767 Asm->OutStreamer->EmitIntValue(0, AddressSize);
770 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
771 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
772 uint64_t Length = Data.getU16(&Offset);
773 Asm->OutStreamer->EmitIntValue(Length, 2);
774 // Just copy the bytes over.
775 Asm->OutStreamer->EmitBytes(
776 StringRef(InputSec.Data.substr(Offset, Length)));
778 LocSectionSize += Length + 2;
783 void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
784 unsigned MinInstLength,
785 std::vector<DWARFDebugLine::Row> &Rows,
786 unsigned PointerSize) {
787 // Switch to the section where the table will be emitted into.
788 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
789 MCSymbol *LineStartSym = MC->createTempSymbol();
790 MCSymbol *LineEndSym = MC->createTempSymbol();
792 // The first 4 bytes is the total length of the information for this
793 // compilation unit (not including these 4 bytes for the length).
794 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
795 Asm->OutStreamer->EmitLabel(LineStartSym);
797 MS->EmitBytes(PrologueBytes);
798 LineSectionSize += PrologueBytes.size() + 4;
800 SmallString<128> EncodingBuffer;
801 raw_svector_ostream EncodingOS(EncodingBuffer);
804 // We only have the dummy entry, dsymutil emits an entry with a 0
805 // address in that case.
806 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
807 MS->EmitBytes(EncodingOS.str());
808 LineSectionSize += EncodingBuffer.size();
809 MS->EmitLabel(LineEndSym);
813 // Line table state machine fields
814 unsigned FileNum = 1;
815 unsigned LastLine = 1;
817 unsigned IsStatement = 1;
819 uint64_t Address = -1ULL;
821 unsigned RowsSinceLastSequence = 0;
823 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
824 auto &Row = Rows[Idx];
826 int64_t AddressDelta;
827 if (Address == -1ULL) {
828 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
829 MS->EmitULEB128IntValue(PointerSize + 1);
830 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
831 MS->EmitIntValue(Row.Address, PointerSize);
832 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
835 AddressDelta = (Row.Address - Address) / MinInstLength;
838 // FIXME: code copied and transfromed from
839 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
840 // this code, but the current compatibility requirement with
841 // classic dsymutil makes it hard. Revisit that once this
842 // requirement is dropped.
844 if (FileNum != Row.File) {
846 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
847 MS->EmitULEB128IntValue(FileNum);
848 LineSectionSize += 1 + getULEB128Size(FileNum);
850 if (Column != Row.Column) {
852 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
853 MS->EmitULEB128IntValue(Column);
854 LineSectionSize += 1 + getULEB128Size(Column);
857 // FIXME: We should handle the discriminator here, but dsymutil
858 // doesn' consider it, thus ignore it for now.
860 if (Isa != Row.Isa) {
862 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
863 MS->EmitULEB128IntValue(Isa);
864 LineSectionSize += 1 + getULEB128Size(Isa);
866 if (IsStatement != Row.IsStmt) {
867 IsStatement = Row.IsStmt;
868 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
869 LineSectionSize += 1;
871 if (Row.BasicBlock) {
872 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
873 LineSectionSize += 1;
876 if (Row.PrologueEnd) {
877 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
878 LineSectionSize += 1;
881 if (Row.EpilogueBegin) {
882 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
883 LineSectionSize += 1;
886 int64_t LineDelta = int64_t(Row.Line) - LastLine;
887 if (!Row.EndSequence) {
888 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
889 MS->EmitBytes(EncodingOS.str());
890 LineSectionSize += EncodingBuffer.size();
891 EncodingBuffer.resize(0);
893 Address = Row.Address;
895 RowsSinceLastSequence++;
898 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
899 MS->EmitSLEB128IntValue(LineDelta);
900 LineSectionSize += 1 + getSLEB128Size(LineDelta);
903 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
904 MS->EmitULEB128IntValue(AddressDelta);
905 LineSectionSize += 1 + getULEB128Size(AddressDelta);
907 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
908 MS->EmitBytes(EncodingOS.str());
909 LineSectionSize += EncodingBuffer.size();
910 EncodingBuffer.resize(0);
913 LastLine = FileNum = IsStatement = 1;
914 RowsSinceLastSequence = Column = Isa = 0;
918 if (RowsSinceLastSequence) {
919 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
920 MS->EmitBytes(EncodingOS.str());
921 LineSectionSize += EncodingBuffer.size();
922 EncodingBuffer.resize(0);
926 MS->EmitLabel(LineEndSym);
929 /// \brief Emit the pubnames or pubtypes section contribution for \p
930 /// Unit into \p Sec. The data is provided in \p Names.
931 void DwarfStreamer::emitPubSectionForUnit(
932 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
933 const std::vector<CompileUnit::AccelInfo> &Names) {
937 // Start the dwarf pubnames section.
938 Asm->OutStreamer->SwitchSection(Sec);
939 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
940 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
942 bool HeaderEmitted = false;
943 // Emit the pubnames for this compilation unit.
944 for (const auto &Name : Names) {
945 if (Name.SkipPubSection)
948 if (!HeaderEmitted) {
950 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
951 Asm->OutStreamer->EmitLabel(BeginLabel);
952 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
953 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
954 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
955 HeaderEmitted = true;
957 Asm->EmitInt32(Name.Die->getOffset());
958 Asm->OutStreamer->EmitBytes(
959 StringRef(Name.Name.data(), Name.Name.size() + 1));
964 Asm->EmitInt32(0); // End marker.
965 Asm->OutStreamer->EmitLabel(EndLabel);
968 /// \brief Emit .debug_pubnames for \p Unit.
969 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
970 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
971 "names", Unit, Unit.getPubnames());
974 /// \brief Emit .debug_pubtypes for \p Unit.
975 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
976 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
977 "types", Unit, Unit.getPubtypes());
980 /// \brief Emit a CIE into the debug_frame section.
981 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
982 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
984 MS->EmitBytes(CIEBytes);
985 FrameSectionSize += CIEBytes.size();
988 /// \brief Emit a FDE into the debug_frame section. \p FDEBytes
989 /// contains the FDE data without the length, CIE offset and address
990 /// which will be replaced with the paramter values.
991 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
992 uint32_t Address, StringRef FDEBytes) {
993 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
995 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
996 MS->EmitIntValue(CIEOffset, 4);
997 MS->EmitIntValue(Address, AddrSize);
998 MS->EmitBytes(FDEBytes);
999 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1002 /// \brief The core of the Dwarf linking logic.
1004 /// The link of the dwarf information from the object files will be
1005 /// driven by the selection of 'root DIEs', which are DIEs that
1006 /// describe variables or functions that are present in the linked
1007 /// binary (and thus have entries in the debug map). All the debug
1008 /// information that will be linked (the DIEs, but also the line
1009 /// tables, ranges, ...) is derived from that set of root DIEs.
1011 /// The root DIEs are identified because they contain relocations that
1012 /// correspond to a debug map entry at specific places (the low_pc for
1013 /// a function, the location for a variable). These relocations are
1014 /// called ValidRelocs in the DwarfLinker and are gathered as a very
1015 /// first step when we start processing a DebugMapObject.
1018 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1019 : OutputFilename(OutputFilename), Options(Options),
1020 BinHolder(Options.Verbose), LastCIEOffset(0) {}
1023 for (auto *Abbrev : Abbreviations)
1027 /// \brief Link the contents of the DebugMap.
1028 bool link(const DebugMap &);
1031 /// \brief Called at the start of a debug object link.
1032 void startDebugObject(DWARFContext &, DebugMapObject &);
1034 /// \brief Called at the end of a debug object link.
1035 void endDebugObject();
1037 /// \defgroup FindValidRelocations Translate debug map into a list
1038 /// of relevant relocations
1045 const DebugMapObject::DebugMapEntry *Mapping;
1047 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1048 const DebugMapObject::DebugMapEntry *Mapping)
1049 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1051 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1054 /// \brief The valid relocations for the current DebugMapObject.
1055 /// This vector is sorted by relocation offset.
1056 std::vector<ValidReloc> ValidRelocs;
1058 /// \brief Index into ValidRelocs of the next relocation to
1059 /// consider. As we walk the DIEs in acsending file offset and as
1060 /// ValidRelocs is sorted by file offset, keeping this index
1061 /// uptodate is all we have to do to have a cheap lookup during the
1062 /// root DIE selection and during DIE cloning.
1063 unsigned NextValidReloc;
1065 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1066 const DebugMapObject &DMO);
1068 bool findValidRelocs(const object::SectionRef &Section,
1069 const object::ObjectFile &Obj,
1070 const DebugMapObject &DMO);
1072 void findValidRelocsMachO(const object::SectionRef &Section,
1073 const object::MachOObjectFile &Obj,
1074 const DebugMapObject &DMO);
1077 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1080 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1081 /// keep. Store that information in \p CU's DIEInfo.
1082 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1083 const DebugMapObject &DMO, CompileUnit &CU,
1086 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1087 enum TravesalFlags {
1088 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1089 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1090 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1091 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1094 /// \brief Mark the passed DIE as well as all the ones it depends on
1096 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1097 CompileUnit::DIEInfo &MyInfo,
1098 const DebugMapObject &DMO, CompileUnit &CU,
1101 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1102 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1105 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1107 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1109 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1111 CompileUnit::DIEInfo &MyInfo,
1114 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1115 CompileUnit::DIEInfo &Info);
1118 /// \defgroup Linking Methods used to link the debug information
1121 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1122 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1123 /// stripped out and addresses have been rewritten according to the
1126 /// \param OutOffset is the offset the cloned DIE in the output
1128 /// \param PCOffset (while cloning a function scope) is the offset
1129 /// applied to the entry point of the function to get the linked address.
1131 /// \returns the root of the cloned tree.
1132 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
1133 int64_t PCOffset, uint32_t OutOffset);
1135 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1137 /// \brief Information gathered and exchanged between the various
1138 /// clone*Attributes helpers about the attributes of a particular DIE.
1139 struct AttributesInfo {
1140 const char *Name, *MangledName; ///< Names.
1141 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1143 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1144 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1146 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1147 bool IsDeclaration; ///< Is this DIE only a declaration?
1150 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1151 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1152 IsDeclaration(false) {}
1155 /// \brief Helper for cloneDIE.
1156 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1157 CompileUnit &U, const DWARFFormValue &Val,
1158 const AttributeSpec AttrSpec, unsigned AttrSize,
1159 AttributesInfo &AttrInfo);
1161 /// \brief Helper for cloneDIE.
1162 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1163 const DWARFFormValue &Val, const DWARFUnit &U);
1165 /// \brief Helper for cloneDIE.
1167 cloneDieReferenceAttribute(DIE &Die,
1168 const DWARFDebugInfoEntryMinimal &InputDIE,
1169 AttributeSpec AttrSpec, unsigned AttrSize,
1170 const DWARFFormValue &Val, CompileUnit &Unit);
1172 /// \brief Helper for cloneDIE.
1173 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1174 const DWARFFormValue &Val, unsigned AttrSize);
1176 /// \brief Helper for cloneDIE.
1177 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1178 const DWARFFormValue &Val,
1179 const CompileUnit &Unit, AttributesInfo &Info);
1181 /// \brief Helper for cloneDIE.
1182 unsigned cloneScalarAttribute(DIE &Die,
1183 const DWARFDebugInfoEntryMinimal &InputDIE,
1184 CompileUnit &U, AttributeSpec AttrSpec,
1185 const DWARFFormValue &Val, unsigned AttrSize,
1186 AttributesInfo &Info);
1188 /// \brief Helper for cloneDIE.
1189 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1190 bool isLittleEndian);
1192 /// \brief Assign an abbreviation number to \p Abbrev
1193 void AssignAbbrev(DIEAbbrev &Abbrev);
1195 /// \brief FoldingSet that uniques the abbreviations.
1196 FoldingSet<DIEAbbrev> AbbreviationsSet;
1197 /// \brief Storage for the unique Abbreviations.
1198 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1199 /// be changed to a vecot of unique_ptrs.
1200 std::vector<DIEAbbrev *> Abbreviations;
1202 /// \brief Compute and emit debug_ranges section for \p Unit, and
1203 /// patch the attributes referencing it.
1204 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1206 /// \brief Generate and emit the DW_AT_ranges attribute for a
1207 /// compile_unit if it had one.
1208 void generateUnitRanges(CompileUnit &Unit) const;
1210 /// \brief Extract the line tables fromt he original dwarf, extract
1211 /// the relevant parts according to the linked function ranges and
1212 /// emit the result in the debug_line section.
1213 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1215 /// \brief Emit the accelerator entries for \p Unit.
1216 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1218 /// \brief Patch the frame info for an object file and emit it.
1219 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1220 unsigned AddressSize);
1222 /// \brief DIELoc objects that need to be destructed (but not freed!).
1223 std::vector<DIELoc *> DIELocs;
1224 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1225 std::vector<DIEBlock *> DIEBlocks;
1226 /// \brief Allocator used for all the DIEValue objects.
1227 BumpPtrAllocator DIEAlloc;
1230 /// \defgroup Helpers Various helper methods.
1233 const DWARFDebugInfoEntryMinimal *
1234 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
1235 const DWARFDebugInfoEntryMinimal &DIE,
1236 CompileUnit *&ReferencedCU);
1238 CompileUnit *getUnitForOffset(unsigned Offset);
1240 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1241 AttributesInfo &Info);
1243 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1244 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1246 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
1250 std::string OutputFilename;
1251 LinkOptions Options;
1252 BinaryHolder BinHolder;
1253 std::unique_ptr<DwarfStreamer> Streamer;
1255 /// The units of the current debug map object.
1256 std::vector<CompileUnit> Units;
1258 /// The debug map object curently under consideration.
1259 DebugMapObject *CurrentDebugObject;
1261 /// \brief The Dwarf string pool
1262 NonRelocatableStringpool StringPool;
1264 /// \brief This map is keyed by the entry PC of functions in that
1265 /// debug object and the associated value is a pair storing the
1266 /// corresponding end PC and the offset to apply to get the linked
1269 /// See startDebugObject() for a more complete description of its use.
1270 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1272 /// \brief The CIEs that have been emitted in the output
1273 /// section. The actual CIE data serves a the key to this StringMap,
1274 /// this takes care of comparing the semantics of CIEs defined in
1275 /// different object files.
1276 StringMap<uint32_t> EmittedCIEs;
1278 /// Offset of the last CIE that has been emitted in the output
1279 /// debug_frame section.
1280 uint32_t LastCIEOffset;
1283 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1284 /// returning our CompileUnit object instead.
1285 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1287 std::upper_bound(Units.begin(), Units.end(), Offset,
1288 [](uint32_t LHS, const CompileUnit &RHS) {
1289 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1291 return CU != Units.end() ? &*CU : nullptr;
1294 /// \brief Resolve the DIE attribute reference that has been
1295 /// extracted in \p RefValue. The resulting DIE migh be in another
1296 /// CompileUnit which is stored into \p ReferencedCU.
1297 /// \returns null if resolving fails for any reason.
1298 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1299 DWARFFormValue &RefValue, const DWARFUnit &Unit,
1300 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1301 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1302 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1304 if ((RefCU = getUnitForOffset(RefOffset)))
1305 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1308 reportWarning("could not find referenced DIE", &Unit, &DIE);
1312 /// \brief Get the potential name and mangled name for the entity
1313 /// described by \p Die and store them in \Info if they are not
1315 /// \returns is a name was found.
1316 bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1317 DWARFUnit &U, AttributesInfo &Info) {
1318 // FIXME: a bit wastefull as the first getName might return the
1320 if (!Info.MangledName &&
1321 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1322 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1324 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1325 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1327 return Info.Name || Info.MangledName;
1330 /// \brief Report a warning to the user, optionaly including
1331 /// information about a specific \p DIE related to the warning.
1332 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
1333 const DWARFDebugInfoEntryMinimal *DIE) const {
1334 StringRef Context = "<debug map>";
1335 if (CurrentDebugObject)
1336 Context = CurrentDebugObject->getObjectFilename();
1337 warn(Warning, Context);
1339 if (!Options.Verbose || !DIE)
1342 errs() << " in DIE:\n";
1343 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1347 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1348 if (Options.NoOutput)
1351 Streamer = llvm::make_unique<DwarfStreamer>();
1352 return Streamer->init(TheTriple, OutputFilename);
1355 /// \brief Recursive helper to gather the child->parent relationships in the
1356 /// original compile unit.
1357 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1358 unsigned ParentIdx, CompileUnit &CU) {
1359 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1360 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
1362 if (DIE->hasChildren())
1363 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1364 Child = Child->getSibling())
1365 gatherDIEParents(Child, MyIdx, CU);
1368 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1372 case dwarf::DW_TAG_subprogram:
1373 case dwarf::DW_TAG_lexical_block:
1374 case dwarf::DW_TAG_subroutine_type:
1375 case dwarf::DW_TAG_structure_type:
1376 case dwarf::DW_TAG_class_type:
1377 case dwarf::DW_TAG_union_type:
1380 llvm_unreachable("Invalid Tag");
1383 void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1384 Units.reserve(Dwarf.getNumCompileUnits());
1386 // Iterate over the debug map entries and put all the ones that are
1387 // functions (because they have a size) into the Ranges map. This
1388 // map is very similar to the FunctionRanges that are stored in each
1389 // unit, with 2 notable differences:
1390 // - obviously this one is global, while the other ones are per-unit.
1391 // - this one contains not only the functions described in the DIE
1392 // tree, but also the ones that are only in the debug map.
1393 // The latter information is required to reproduce dsymutil's logic
1394 // while linking line tables. The cases where this information
1395 // matters look like bugs that need to be investigated, but for now
1396 // we need to reproduce dsymutil's behavior.
1397 // FIXME: Once we understood exactly if that information is needed,
1398 // maybe totally remove this (or try to use it to do a real
1399 // -gline-tables-only on Darwin.
1400 for (const auto &Entry : Obj.symbols()) {
1401 const auto &Mapping = Entry.getValue();
1403 Ranges[Mapping.ObjectAddress] = std::make_pair(
1404 Mapping.ObjectAddress + Mapping.Size,
1405 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1409 void DwarfLinker::endDebugObject() {
1411 ValidRelocs.clear();
1414 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1416 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1424 /// \brief Iterate over the relocations of the given \p Section and
1425 /// store the ones that correspond to debug map entries into the
1426 /// ValidRelocs array.
1427 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1428 const object::MachOObjectFile &Obj,
1429 const DebugMapObject &DMO) {
1431 Section.getContents(Contents);
1432 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1434 for (const object::RelocationRef &Reloc : Section.relocations()) {
1435 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1436 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1437 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1438 uint64_t Offset64 = Reloc.getOffset();
1439 if ((RelocSize != 4 && RelocSize != 8)) {
1440 reportWarning(" unsupported relocation in debug_info section.");
1443 uint32_t Offset = Offset64;
1444 // Mach-o uses REL relocations, the addend is at the relocation offset.
1445 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1447 auto Sym = Reloc.getSymbol();
1448 if (Sym != Obj.symbol_end()) {
1449 ErrorOr<StringRef> SymbolName = Sym->getName();
1451 reportWarning("error getting relocation symbol name.");
1454 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
1455 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1456 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1457 // Do not store the addend. The addend was the address of the
1458 // symbol in the object file, the address in the binary that is
1459 // stored in the debug map doesn't need to be offseted.
1460 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1465 /// \brief Dispatch the valid relocation finding logic to the
1466 /// appropriate handler depending on the object file format.
1467 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1468 const object::ObjectFile &Obj,
1469 const DebugMapObject &DMO) {
1470 // Dispatch to the right handler depending on the file type.
1471 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1472 findValidRelocsMachO(Section, *MachOObj, DMO);
1474 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
1476 if (ValidRelocs.empty())
1479 // Sort the relocations by offset. We will walk the DIEs linearly in
1480 // the file, this allows us to just keep an index in the relocation
1481 // array that we advance during our walk, rather than resorting to
1482 // some associative container. See DwarfLinker::NextValidReloc.
1483 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1487 /// \brief Look for relocations in the debug_info section that match
1488 /// entries in the debug map. These relocations will drive the Dwarf
1489 /// link by indicating which DIEs refer to symbols present in the
1491 /// \returns wether there are any valid relocations in the debug info.
1492 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1493 const DebugMapObject &DMO) {
1494 // Find the debug_info section.
1495 for (const object::SectionRef &Section : Obj.sections()) {
1496 StringRef SectionName;
1497 Section.getName(SectionName);
1498 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1499 if (SectionName != "debug_info")
1501 return findValidRelocs(Section, Obj, DMO);
1506 /// \brief Checks that there is a relocation against an actual debug
1507 /// map entry between \p StartOffset and \p NextOffset.
1509 /// This function must be called with offsets in strictly ascending
1510 /// order because it never looks back at relocations it already 'went past'.
1511 /// \returns true and sets Info.InDebugMap if it is the case.
1512 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1513 CompileUnit::DIEInfo &Info) {
1514 assert(NextValidReloc == 0 ||
1515 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1516 if (NextValidReloc >= ValidRelocs.size())
1519 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1521 // We might need to skip some relocs that we didn't consider. For
1522 // example the high_pc of a discarded DIE might contain a reloc that
1523 // is in the list because it actually corresponds to the start of a
1524 // function that is in the debug map.
1525 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1526 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1528 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1531 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1532 const auto &Mapping = ValidReloc.Mapping->getValue();
1533 if (Options.Verbose)
1534 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1535 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1536 uint64_t(Mapping.ObjectAddress),
1537 uint64_t(Mapping.BinaryAddress));
1539 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1540 Mapping.ObjectAddress;
1541 Info.InDebugMap = true;
1545 /// \brief Get the starting and ending (exclusive) offset for the
1546 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1547 /// supposed to point to the position of the first attribute described
1549 /// \return [StartOffset, EndOffset) as a pair.
1550 static std::pair<uint32_t, uint32_t>
1551 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1552 unsigned Offset, const DWARFUnit &Unit) {
1553 DataExtractor Data = Unit.getDebugInfoExtractor();
1555 for (unsigned i = 0; i < Idx; ++i)
1556 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1558 uint32_t End = Offset;
1559 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1561 return std::make_pair(Offset, End);
1564 /// \brief Check if a variable describing DIE should be kept.
1565 /// \returns updated TraversalFlags.
1566 unsigned DwarfLinker::shouldKeepVariableDIE(
1567 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1568 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1569 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1571 // Global variables with constant value can always be kept.
1572 if (!(Flags & TF_InFunctionScope) &&
1573 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1574 MyInfo.InDebugMap = true;
1575 return Flags | TF_Keep;
1578 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1579 if (LocationIdx == -1U)
1582 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1583 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1584 uint32_t LocationOffset, LocationEndOffset;
1585 std::tie(LocationOffset, LocationEndOffset) =
1586 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1588 // See if there is a relocation to a valid debug map entry inside
1589 // this variable's location. The order is important here. We want to
1590 // always check in the variable has a valid relocation, so that the
1591 // DIEInfo is filled. However, we don't want a static variable in a
1592 // function to force us to keep the enclosing function.
1593 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1594 (Flags & TF_InFunctionScope))
1597 if (Options.Verbose)
1598 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1600 return Flags | TF_Keep;
1603 /// \brief Check if a function describing DIE should be kept.
1604 /// \returns updated TraversalFlags.
1605 unsigned DwarfLinker::shouldKeepSubprogramDIE(
1606 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1607 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1608 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1610 Flags |= TF_InFunctionScope;
1612 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1613 if (LowPcIdx == -1U)
1616 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1617 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1618 uint32_t LowPcOffset, LowPcEndOffset;
1619 std::tie(LowPcOffset, LowPcEndOffset) =
1620 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1623 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1624 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1625 if (LowPc == -1ULL ||
1626 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1629 if (Options.Verbose)
1630 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1634 DWARFFormValue HighPcValue;
1635 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1636 reportWarning("Function without high_pc. Range will be discarded.\n",
1642 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1643 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1645 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1646 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1649 // Replace the debug map range with a more accurate one.
1650 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
1651 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1655 /// \brief Check if a DIE should be kept.
1656 /// \returns updated TraversalFlags.
1657 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1659 CompileUnit::DIEInfo &MyInfo,
1661 switch (DIE.getTag()) {
1662 case dwarf::DW_TAG_constant:
1663 case dwarf::DW_TAG_variable:
1664 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1665 case dwarf::DW_TAG_subprogram:
1666 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1667 case dwarf::DW_TAG_module:
1668 case dwarf::DW_TAG_imported_module:
1669 case dwarf::DW_TAG_imported_declaration:
1670 case dwarf::DW_TAG_imported_unit:
1671 // We always want to keep these.
1672 return Flags | TF_Keep;
1678 /// \brief Mark the passed DIE as well as all the ones it depends on
1681 /// This function is called by lookForDIEsToKeep on DIEs that are
1682 /// newly discovered to be needed in the link. It recursively calls
1683 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1684 /// TraversalFlags to inform it that it's not doing the primary DIE
1686 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1687 CompileUnit::DIEInfo &MyInfo,
1688 const DebugMapObject &DMO,
1689 CompileUnit &CU, unsigned Flags) {
1690 const DWARFUnit &Unit = CU.getOrigUnit();
1693 // First mark all the parent chain as kept.
1694 unsigned AncestorIdx = MyInfo.ParentIdx;
1695 while (!CU.getInfo(AncestorIdx).Keep) {
1696 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1697 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1698 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1701 // Then we need to mark all the DIEs referenced by this DIE's
1702 // attributes as kept.
1703 DataExtractor Data = Unit.getDebugInfoExtractor();
1704 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1705 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1707 // Mark all DIEs referenced through atttributes as kept.
1708 for (const auto &AttrSpec : Abbrev->attributes()) {
1709 DWARFFormValue Val(AttrSpec.Form);
1711 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1712 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1716 Val.extractValue(Data, &Offset, &Unit);
1717 CompileUnit *ReferencedCU;
1718 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1719 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1720 TF_Keep | TF_DependencyWalk);
1724 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1725 /// keep. Store that information in \p CU's DIEInfo.
1727 /// This function is the entry point of the DIE selection
1728 /// algorithm. It is expected to walk the DIE tree in file order and
1729 /// (though the mediation of its helper) call hasValidRelocation() on
1730 /// each DIE that might be a 'root DIE' (See DwarfLinker class
1732 /// While walking the dependencies of root DIEs, this function is
1733 /// also called, but during these dependency walks the file order is
1734 /// not respected. The TF_DependencyWalk flag tells us which kind of
1735 /// traversal we are currently doing.
1736 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1737 const DebugMapObject &DMO, CompileUnit &CU,
1739 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1740 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1741 bool AlreadyKept = MyInfo.Keep;
1743 // If the Keep flag is set, we are marking a required DIE's
1744 // dependencies. If our target is already marked as kept, we're all
1746 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1749 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1750 // because it would screw up the relocation finding logic.
1751 if (!(Flags & TF_DependencyWalk))
1752 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1754 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1755 if (!AlreadyKept && (Flags & TF_Keep))
1756 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1758 // The TF_ParentWalk flag tells us that we are currently walking up
1759 // the parent chain of a required DIE, and we don't want to mark all
1760 // the children of the parents as kept (consider for example a
1761 // DW_TAG_namespace node in the parent chain). There are however a
1762 // set of DIE types for which we want to ignore that directive and still
1763 // walk their children.
1764 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1765 Flags &= ~TF_ParentWalk;
1767 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1770 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1771 Child = Child->getSibling())
1772 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1775 /// \brief Assign an abbreviation numer to \p Abbrev.
1777 /// Our DIEs get freed after every DebugMapObject has been processed,
1778 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1779 /// the instances hold by the DIEs. When we encounter an abbreviation
1780 /// that we don't know, we create a permanent copy of it.
1781 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1782 // Check the set for priors.
1783 FoldingSetNodeID ID;
1786 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1788 // If it's newly added.
1790 // Assign existing abbreviation number.
1791 Abbrev.setNumber(InSet->getNumber());
1793 // Add to abbreviation list.
1794 Abbreviations.push_back(
1795 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1796 for (const auto &Attr : Abbrev.getData())
1797 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1798 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1799 // Assign the unique abbreviation number.
1800 Abbrev.setNumber(Abbreviations.size());
1801 Abbreviations.back()->setNumber(Abbreviations.size());
1805 /// \brief Clone a string attribute described by \p AttrSpec and add
1807 /// \returns the size of the new attribute.
1808 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1809 const DWARFFormValue &Val,
1810 const DWARFUnit &U) {
1811 // Switch everything to out of line strings.
1812 const char *String = *Val.getAsCString(&U);
1813 unsigned Offset = StringPool.getStringOffset(String);
1814 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1815 DIEInteger(Offset));
1819 /// \brief Clone an attribute referencing another DIE and add
1821 /// \returns the size of the new attribute.
1822 unsigned DwarfLinker::cloneDieReferenceAttribute(
1823 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1824 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1825 CompileUnit &Unit) {
1826 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
1827 DIE *NewRefDie = nullptr;
1828 CompileUnit *RefUnit = nullptr;
1829 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1831 if (!(RefUnit = getUnitForOffset(Ref)) ||
1832 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1833 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1834 if (!AttributeString)
1835 AttributeString = "DW_AT_???";
1836 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1838 &Unit.getOrigUnit(), &InputDIE);
1842 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1843 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1844 if (!RefInfo.Clone) {
1845 assert(Ref > InputDIE.getOffset());
1846 // We haven't cloned this DIE yet. Just create an empty one and
1847 // store it. It'll get really cloned when we process it.
1848 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
1850 NewRefDie = RefInfo.Clone;
1852 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1853 // We cannot currently rely on a DIEEntry to emit ref_addr
1854 // references, because the implementation calls back to DwarfDebug
1855 // to find the unit offset. (We don't have a DwarfDebug)
1856 // FIXME: we should be able to design DIEEntry reliance on
1859 if (Ref < InputDIE.getOffset()) {
1860 // We must have already cloned that DIE.
1861 uint32_t NewRefOffset =
1862 RefUnit->getStartOffset() + NewRefDie->getOffset();
1863 Attr = NewRefOffset;
1864 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1865 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
1867 // A forward reference. Note and fixup later.
1869 Unit.noteForwardReference(
1871 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1872 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
1877 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1878 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
1882 /// \brief Clone an attribute of block form (locations, constants) and add
1884 /// \returns the size of the new attribute.
1885 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1886 const DWARFFormValue &Val,
1887 unsigned AttrSize) {
1890 DIELoc *Loc = nullptr;
1891 DIEBlock *Block = nullptr;
1892 // Just copy the block data over.
1893 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1894 Loc = new (DIEAlloc) DIELoc;
1895 DIELocs.push_back(Loc);
1897 Block = new (DIEAlloc) DIEBlock;
1898 DIEBlocks.push_back(Block);
1900 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1903 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1904 dwarf::Form(AttrSpec.Form), Loc);
1906 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1907 dwarf::Form(AttrSpec.Form), Block);
1908 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1909 for (auto Byte : Bytes)
1910 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
1911 dwarf::DW_FORM_data1, DIEInteger(Byte));
1912 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1913 // the DIE class, this if could be replaced by
1914 // Attr->setSize(Bytes.size()).
1917 Loc->ComputeSize(&Streamer->getAsmPrinter());
1919 Block->ComputeSize(&Streamer->getAsmPrinter());
1921 Die.addValue(DIEAlloc, Value);
1925 /// \brief Clone an address attribute and add it to \p Die.
1926 /// \returns the size of the new attribute.
1927 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1928 const DWARFFormValue &Val,
1929 const CompileUnit &Unit,
1930 AttributesInfo &Info) {
1931 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
1932 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1933 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1934 Die.getTag() == dwarf::DW_TAG_lexical_block)
1935 Addr += Info.PCOffset;
1936 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1937 Addr = Unit.getLowPc();
1938 if (Addr == UINT64_MAX)
1941 Info.HasLowPc = true;
1942 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1943 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1944 if (uint64_t HighPc = Unit.getHighPc())
1949 // If we have a high_pc recorded for the input DIE, use
1950 // it. Otherwise (when no relocations where applied) just use the
1951 // one we just decoded.
1952 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1955 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1956 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
1957 return Unit.getOrigUnit().getAddressByteSize();
1960 /// \brief Clone a scalar attribute and add it to \p Die.
1961 /// \returns the size of the new attribute.
1962 unsigned DwarfLinker::cloneScalarAttribute(
1963 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
1964 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
1965 AttributesInfo &Info) {
1967 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1968 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1969 if (Unit.getLowPc() == -1ULL)
1971 // Dwarf >= 4 high_pc is an size, not an address.
1972 Value = Unit.getHighPc() - Unit.getLowPc();
1973 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1974 Value = *Val.getAsSectionOffset();
1975 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1976 Value = *Val.getAsSignedConstant();
1977 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1978 Value = *OptionalValue;
1980 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1981 &Unit.getOrigUnit(), &InputDIE);
1984 PatchLocation Patch =
1985 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1986 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1987 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
1988 Unit.noteRangeAttribute(Die, Patch);
1989 // A more generic way to check for location attributes would be
1990 // nice, but it's very unlikely that any other attribute needs a
1992 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1993 AttrSpec.Attr == dwarf::DW_AT_frame_base)
1994 Unit.noteLocationAttribute(Patch, Info.PCOffset);
1995 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1996 Info.IsDeclaration = true;
2001 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2002 /// value \p Val, and add it to \p Die.
2003 /// \returns the size of the cloned attribute.
2004 unsigned DwarfLinker::cloneAttribute(DIE &Die,
2005 const DWARFDebugInfoEntryMinimal &InputDIE,
2007 const DWARFFormValue &Val,
2008 const AttributeSpec AttrSpec,
2009 unsigned AttrSize, AttributesInfo &Info) {
2010 const DWARFUnit &U = Unit.getOrigUnit();
2012 switch (AttrSpec.Form) {
2013 case dwarf::DW_FORM_strp:
2014 case dwarf::DW_FORM_string:
2015 return cloneStringAttribute(Die, AttrSpec, Val, U);
2016 case dwarf::DW_FORM_ref_addr:
2017 case dwarf::DW_FORM_ref1:
2018 case dwarf::DW_FORM_ref2:
2019 case dwarf::DW_FORM_ref4:
2020 case dwarf::DW_FORM_ref8:
2021 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
2023 case dwarf::DW_FORM_block:
2024 case dwarf::DW_FORM_block1:
2025 case dwarf::DW_FORM_block2:
2026 case dwarf::DW_FORM_block4:
2027 case dwarf::DW_FORM_exprloc:
2028 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2029 case dwarf::DW_FORM_addr:
2030 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
2031 case dwarf::DW_FORM_data1:
2032 case dwarf::DW_FORM_data2:
2033 case dwarf::DW_FORM_data4:
2034 case dwarf::DW_FORM_data8:
2035 case dwarf::DW_FORM_udata:
2036 case dwarf::DW_FORM_sdata:
2037 case dwarf::DW_FORM_sec_offset:
2038 case dwarf::DW_FORM_flag:
2039 case dwarf::DW_FORM_flag_present:
2040 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2043 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2050 /// \brief Apply the valid relocations found by findValidRelocs() to
2051 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
2052 /// in the debug_info section.
2054 /// Like for findValidRelocs(), this function must be called with
2055 /// monotonic \p BaseOffset values.
2057 /// \returns wether any reloc has been applied.
2058 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2059 uint32_t BaseOffset, bool isLittleEndian) {
2060 assert((NextValidReloc == 0 ||
2061 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2062 "BaseOffset should only be increasing.");
2063 if (NextValidReloc >= ValidRelocs.size())
2066 // Skip relocs that haven't been applied.
2067 while (NextValidReloc < ValidRelocs.size() &&
2068 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2071 bool Applied = false;
2072 uint64_t EndOffset = BaseOffset + Data.size();
2073 while (NextValidReloc < ValidRelocs.size() &&
2074 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2075 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2076 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2077 assert(ValidReloc.Offset - BaseOffset < Data.size());
2078 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2080 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2081 Value += ValidReloc.Addend;
2082 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2083 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2084 Buf[i] = uint8_t(Value >> (Index * 8));
2086 assert(ValidReloc.Size <= sizeof(Buf));
2087 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2094 static bool isTypeTag(uint16_t Tag) {
2096 case dwarf::DW_TAG_array_type:
2097 case dwarf::DW_TAG_class_type:
2098 case dwarf::DW_TAG_enumeration_type:
2099 case dwarf::DW_TAG_pointer_type:
2100 case dwarf::DW_TAG_reference_type:
2101 case dwarf::DW_TAG_string_type:
2102 case dwarf::DW_TAG_structure_type:
2103 case dwarf::DW_TAG_subroutine_type:
2104 case dwarf::DW_TAG_typedef:
2105 case dwarf::DW_TAG_union_type:
2106 case dwarf::DW_TAG_ptr_to_member_type:
2107 case dwarf::DW_TAG_set_type:
2108 case dwarf::DW_TAG_subrange_type:
2109 case dwarf::DW_TAG_base_type:
2110 case dwarf::DW_TAG_const_type:
2111 case dwarf::DW_TAG_constant:
2112 case dwarf::DW_TAG_file_type:
2113 case dwarf::DW_TAG_namelist:
2114 case dwarf::DW_TAG_packed_type:
2115 case dwarf::DW_TAG_volatile_type:
2116 case dwarf::DW_TAG_restrict_type:
2117 case dwarf::DW_TAG_interface_type:
2118 case dwarf::DW_TAG_unspecified_type:
2119 case dwarf::DW_TAG_shared_type:
2127 /// \brief Recursively clone \p InputDIE's subtrees that have been
2128 /// selected to appear in the linked output.
2130 /// \param OutOffset is the Offset where the newly created DIE will
2131 /// lie in the linked compile unit.
2133 /// \returns the cloned DIE object or null if nothing was selected.
2134 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
2135 CompileUnit &Unit, int64_t PCOffset,
2136 uint32_t OutOffset) {
2137 DWARFUnit &U = Unit.getOrigUnit();
2138 unsigned Idx = U.getDIEIndex(&InputDIE);
2139 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2141 // Should the DIE appear in the output?
2142 if (!Unit.getInfo(Idx).Keep)
2145 uint32_t Offset = InputDIE.getOffset();
2146 // The DIE might have been already created by a forward reference
2147 // (see cloneDieReferenceAttribute()).
2148 DIE *Die = Info.Clone;
2150 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
2151 assert(Die->getTag() == InputDIE.getTag());
2152 Die->setOffset(OutOffset);
2154 // Extract and clone every attribute.
2155 DataExtractor Data = U.getDebugInfoExtractor();
2156 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
2157 AttributesInfo AttrInfo;
2159 // We could copy the data only if we need to aply a relocation to
2160 // it. After testing, it seems there is no performance downside to
2161 // doing the copy unconditionally, and it makes the code simpler.
2162 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2163 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2164 // Modify the copy with relocated addresses.
2165 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2166 // If we applied relocations, we store the value of high_pc that was
2167 // potentially stored in the input DIE. If high_pc is an address
2168 // (Dwarf version == 2), then it might have been relocated to a
2169 // totally unrelated value (because the end address in the object
2170 // file might be start address of another function which got moved
2171 // independantly by the linker). The computation of the actual
2172 // high_pc value is done in cloneAddressAttribute().
2173 AttrInfo.OrigHighPc =
2174 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2177 // Reset the Offset to 0 as we will be working on the local copy of
2181 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2182 Offset += getULEB128Size(Abbrev->getCode());
2184 // We are entering a subprogram. Get and propagate the PCOffset.
2185 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2186 PCOffset = Info.AddrAdjust;
2187 AttrInfo.PCOffset = PCOffset;
2189 for (const auto &AttrSpec : Abbrev->attributes()) {
2190 DWARFFormValue Val(AttrSpec.Form);
2191 uint32_t AttrSize = Offset;
2192 Val.extractValue(Data, &Offset, &U);
2193 AttrSize = Offset - AttrSize;
2196 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2199 // Look for accelerator entries.
2200 uint16_t Tag = InputDIE.getTag();
2201 // FIXME: This is slightly wrong. An inline_subroutine without a
2202 // low_pc, but with AT_ranges might be interesting to get into the
2203 // accelerator tables too. For now stick with dsymutil's behavior.
2204 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2205 Tag != dwarf::DW_TAG_compile_unit &&
2206 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2207 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2208 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2209 AttrInfo.MangledNameOffset,
2210 Tag == dwarf::DW_TAG_inlined_subroutine);
2212 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2213 Tag == dwarf::DW_TAG_inlined_subroutine);
2214 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2215 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2216 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2219 DIEAbbrev NewAbbrev = Die->generateAbbrev();
2220 // If a scope DIE is kept, we must have kept at least one child. If
2221 // it's not the case, we'll just be emitting one wasteful end of
2222 // children marker, but things won't break.
2223 if (InputDIE.hasChildren())
2224 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2225 // Assign a permanent abbrev number
2226 AssignAbbrev(NewAbbrev);
2227 Die->setAbbrevNumber(NewAbbrev.getNumber());
2229 // Add the size of the abbreviation number to the output offset.
2230 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2232 if (!Abbrev->hasChildren()) {
2234 Die->setSize(OutOffset - Die->getOffset());
2238 // Recursively clone children.
2239 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2240 Child = Child->getSibling()) {
2241 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
2242 Die->addChild(Clone);
2243 OutOffset = Clone->getOffset() + Clone->getSize();
2247 // Account for the end of children marker.
2248 OutOffset += sizeof(int8_t);
2250 Die->setSize(OutOffset - Die->getOffset());
2254 /// \brief Patch the input object file relevant debug_ranges entries
2255 /// and emit them in the output file. Update the relevant attributes
2256 /// to point at the new entries.
2257 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2258 DWARFContext &OrigDwarf) const {
2259 DWARFDebugRangeList RangeList;
2260 const auto &FunctionRanges = Unit.getFunctionRanges();
2261 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2262 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2263 OrigDwarf.isLittleEndian(), AddressSize);
2264 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2265 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2266 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
2267 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2268 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2269 // Ranges addresses are based on the unit's low_pc. Compute the
2270 // offset we need to apply to adapt to the the new unit's low_pc.
2271 int64_t UnitPcOffset = 0;
2272 if (OrigLowPc != -1ULL)
2273 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2275 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2276 uint32_t Offset = RangeAttribute.get();
2277 RangeAttribute.set(Streamer->getRangesSectionSize());
2278 RangeList.extract(RangeExtractor, &Offset);
2279 const auto &Entries = RangeList.getEntries();
2280 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2282 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2283 First.StartAddress >= CurrRange.stop()) {
2284 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2285 if (CurrRange == InvalidRange ||
2286 CurrRange.start() > First.StartAddress + OrigLowPc) {
2287 reportWarning("no mapping for range.");
2292 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2297 /// \brief Generate the debug_aranges entries for \p Unit and if the
2298 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2299 /// contribution for this attribute.
2300 /// FIXME: this could actually be done right in patchRangesForUnit,
2301 /// but for the sake of initial bit-for-bit compatibility with legacy
2302 /// dsymutil, we have to do it in a delayed pass.
2303 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2304 auto Attr = Unit.getUnitRangesAttribute();
2306 Attr->set(Streamer->getRangesSectionSize());
2307 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
2310 /// \brief Insert the new line info sequence \p Seq into the current
2311 /// set of already linked line info \p Rows.
2312 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2313 std::vector<DWARFDebugLine::Row> &Rows) {
2317 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2318 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2323 auto InsertPoint = std::lower_bound(
2324 Rows.begin(), Rows.end(), Seq.front(),
2325 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2326 return LHS.Address < RHS.Address;
2329 // FIXME: this only removes the unneeded end_sequence if the
2330 // sequences have been inserted in order. using a global sort like
2331 // described in patchLineTableForUnit() and delaying the end_sequene
2332 // elimination to emitLineTableForUnit() we can get rid of all of them.
2333 if (InsertPoint != Rows.end() &&
2334 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2335 *InsertPoint = Seq.front();
2336 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2338 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2344 static void patchStmtList(DIE &Die, DIEInteger Offset) {
2345 for (auto &V : Die.values())
2346 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2347 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2351 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2354 /// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2355 /// recreate a relocated version of these for the address ranges that
2356 /// are present in the binary.
2357 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2358 DWARFContext &OrigDwarf) {
2359 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
2360 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2361 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2362 if (StmtList == -1ULL)
2365 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2366 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2367 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
2369 // Parse the original line info for the unit.
2370 DWARFDebugLine::LineTable LineTable;
2371 uint32_t StmtOffset = StmtList;
2372 StringRef LineData = OrigDwarf.getLineSection().Data;
2373 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2374 Unit.getOrigUnit().getAddressByteSize());
2375 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2378 // This vector is the output line table.
2379 std::vector<DWARFDebugLine::Row> NewRows;
2380 NewRows.reserve(LineTable.Rows.size());
2382 // Current sequence of rows being extracted, before being inserted
2384 std::vector<DWARFDebugLine::Row> Seq;
2385 const auto &FunctionRanges = Unit.getFunctionRanges();
2386 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2388 // FIXME: This logic is meant to generate exactly the same output as
2389 // Darwin's classic dsynutil. There is a nicer way to implement this
2390 // by simply putting all the relocated line info in NewRows and simply
2391 // sorting NewRows before passing it to emitLineTableForUnit. This
2392 // should be correct as sequences for a function should stay
2393 // together in the sorted output. There are a few corner cases that
2394 // look suspicious though, and that required to implement the logic
2395 // this way. Revisit that once initial validation is finished.
2397 // Iterate over the object file line info and extract the sequences
2398 // that correspond to linked functions.
2399 for (auto &Row : LineTable.Rows) {
2400 // Check wether we stepped out of the range. The range is
2401 // half-open, but consider accept the end address of the range if
2402 // it is marked as end_sequence in the input (because in that
2403 // case, the relocation offset is accurate and that entry won't
2404 // serve as the start of another function).
2405 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2406 Row.Address > CurrRange.stop() ||
2407 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2408 // We just stepped out of a known range. Insert a end_sequence
2409 // corresponding to the end of the range.
2410 uint64_t StopAddress = CurrRange != InvalidRange
2411 ? CurrRange.stop() + CurrRange.value()
2413 CurrRange = FunctionRanges.find(Row.Address);
2414 bool CurrRangeValid =
2415 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2416 if (!CurrRangeValid) {
2417 CurrRange = InvalidRange;
2418 if (StopAddress != -1ULL) {
2419 // Try harder by looking in the DebugMapObject function
2420 // ranges map. There are corner cases where this finds a
2421 // valid entry. It's unclear if this is right or wrong, but
2422 // for now do as dsymutil.
2423 // FIXME: Understand exactly what cases this addresses and
2424 // potentially remove it along with the Ranges map.
2425 auto Range = Ranges.lower_bound(Row.Address);
2426 if (Range != Ranges.begin() && Range != Ranges.end())
2429 if (Range != Ranges.end() && Range->first <= Row.Address &&
2430 Range->second.first >= Row.Address) {
2431 StopAddress = Row.Address + Range->second.second;
2435 if (StopAddress != -1ULL && !Seq.empty()) {
2436 // Insert end sequence row with the computed end address, but
2437 // the same line as the previous one.
2438 Seq.emplace_back(Seq.back());
2439 Seq.back().Address = StopAddress;
2440 Seq.back().EndSequence = 1;
2441 Seq.back().PrologueEnd = 0;
2442 Seq.back().BasicBlock = 0;
2443 Seq.back().EpilogueBegin = 0;
2444 insertLineSequence(Seq, NewRows);
2447 if (!CurrRangeValid)
2451 // Ignore empty sequences.
2452 if (Row.EndSequence && Seq.empty())
2455 // Relocate row address and add it to the current sequence.
2456 Row.Address += CurrRange.value();
2457 Seq.emplace_back(Row);
2459 if (Row.EndSequence)
2460 insertLineSequence(Seq, NewRows);
2463 // Finished extracting, now emit the line tables.
2464 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2465 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2466 // prologue over and that works because we act as both producer and
2467 // consumer. It would be nicer to have a real configurable line
2469 if (LineTable.Prologue.Version != 2 ||
2470 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2471 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2472 LineTable.Prologue.OpcodeBase != 13)
2473 reportWarning("line table paramters mismatch. Cannot emit.");
2475 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2476 LineTable.Prologue.MinInstLength, NewRows,
2477 Unit.getOrigUnit().getAddressByteSize());
2480 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2481 Streamer->emitPubNamesForUnit(Unit);
2482 Streamer->emitPubTypesForUnit(Unit);
2485 /// \brief Read the frame info stored in the object, and emit the
2486 /// patched frame descriptions for the linked binary.
2488 /// This is actually pretty easy as the data of the CIEs and FDEs can
2489 /// be considered as black boxes and moved as is. The only thing to do
2490 /// is to patch the addresses in the headers.
2491 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2492 DWARFContext &OrigDwarf,
2493 unsigned AddrSize) {
2494 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2495 if (FrameData.empty())
2498 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2499 uint32_t InputOffset = 0;
2501 // Store the data of the CIEs defined in this object, keyed by their
2503 DenseMap<uint32_t, StringRef> LocalCIES;
2505 while (Data.isValidOffset(InputOffset)) {
2506 uint32_t EntryOffset = InputOffset;
2507 uint32_t InitialLength = Data.getU32(&InputOffset);
2508 if (InitialLength == 0xFFFFFFFF)
2509 return reportWarning("Dwarf64 bits no supported");
2511 uint32_t CIEId = Data.getU32(&InputOffset);
2512 if (CIEId == 0xFFFFFFFF) {
2513 // This is a CIE, store it.
2514 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2515 LocalCIES[EntryOffset] = CIEData;
2516 // The -4 is to account for the CIEId we just read.
2517 InputOffset += InitialLength - 4;
2521 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2523 // Some compilers seem to emit frame info that doesn't start at
2524 // the function entry point, thus we can't just lookup the address
2525 // in the debug map. Use the linker's range map to see if the FDE
2526 // describes something that we can relocate.
2527 auto Range = Ranges.upper_bound(Loc);
2528 if (Range != Ranges.begin())
2530 if (Range == Ranges.end() || Range->first > Loc ||
2531 Range->second.first <= Loc) {
2532 // The +4 is to account for the size of the InitialLength field itself.
2533 InputOffset = EntryOffset + InitialLength + 4;
2537 // This is an FDE, and we have a mapping.
2538 // Have we already emitted a corresponding CIE?
2539 StringRef CIEData = LocalCIES[CIEId];
2540 if (CIEData.empty())
2541 return reportWarning("Inconsistent debug_frame content. Dropping.");
2543 // Look if we already emitted a CIE that corresponds to the
2544 // referenced one (the CIE data is the key of that lookup).
2545 auto IteratorInserted = EmittedCIEs.insert(
2546 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2547 // If there is no CIE yet for this ID, emit it.
2548 if (IteratorInserted.second ||
2549 // FIXME: dsymutil-classic only caches the last used CIE for
2550 // reuse. Mimic that behavior for now. Just removing that
2551 // second half of the condition and the LastCIEOffset variable
2552 // makes the code DTRT.
2553 LastCIEOffset != IteratorInserted.first->getValue()) {
2554 LastCIEOffset = Streamer->getFrameSectionSize();
2555 IteratorInserted.first->getValue() = LastCIEOffset;
2556 Streamer->emitCIE(CIEData);
2559 // Emit the FDE with updated address and CIE pointer.
2560 // (4 + AddrSize) is the size of the CIEId + initial_location
2561 // fields that will get reconstructed by emitFDE().
2562 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
2563 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
2564 Loc + Range->second.second,
2565 FrameData.substr(InputOffset, FDERemainingBytes));
2566 InputOffset += FDERemainingBytes;
2570 bool DwarfLinker::link(const DebugMap &Map) {
2572 if (Map.begin() == Map.end()) {
2573 errs() << "Empty debug map.\n";
2577 if (!createStreamer(Map.getTriple(), OutputFilename))
2580 // Size of the DIEs (and headers) generated for the linked output.
2581 uint64_t OutputDebugInfoSize = 0;
2582 // A unique ID that identifies each compile unit.
2583 unsigned UnitID = 0;
2584 for (const auto &Obj : Map.objects()) {
2585 CurrentDebugObject = Obj.get();
2587 if (Options.Verbose)
2588 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2589 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
2590 if (std::error_code EC = ErrOrObj.getError()) {
2591 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
2595 // Look for relocations that correspond to debug map entries.
2596 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
2597 if (Options.Verbose)
2598 outs() << "No valid relocations found. Skipping.\n";
2602 // Setup access to the debug info.
2603 DWARFContextInMemory DwarfContext(*ErrOrObj);
2604 startDebugObject(DwarfContext, *Obj);
2606 // In a first phase, just read in the debug info and store the DIE
2607 // parent links that we will use during the next phase.
2608 for (const auto &CU : DwarfContext.compile_units()) {
2609 auto *CUDie = CU->getUnitDIE(false);
2610 if (Options.Verbose) {
2611 outs() << "Input compilation unit:";
2612 CUDie->dump(outs(), CU.get(), 0);
2614 Units.emplace_back(*CU, UnitID++);
2615 gatherDIEParents(CUDie, 0, Units.back());
2618 // Then mark all the DIEs that need to be present in the linked
2619 // output and collect some information about them. Note that this
2620 // loop can not be merged with the previous one becaue cross-cu
2621 // references require the ParentIdx to be setup for every CU in
2622 // the object file before calling this.
2623 for (auto &CurrentUnit : Units)
2624 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
2627 // The calls to applyValidRelocs inside cloneDIE will walk the
2628 // reloc array again (in the same way findValidRelocsInDebugInfo()
2629 // did). We need to reset the NextValidReloc index to the beginning.
2632 // Construct the output DIE tree by cloning the DIEs we chose to
2633 // keep above. If there are no valid relocs, then there's nothing
2635 if (!ValidRelocs.empty())
2636 for (auto &CurrentUnit : Units) {
2637 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
2638 CurrentUnit.setStartOffset(OutputDebugInfoSize);
2639 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
2640 11 /* Unit Header size */);
2641 CurrentUnit.setOutputUnitDIE(OutputDIE);
2642 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
2643 if (Options.NoOutput)
2645 // FIXME: for compatibility with the classic dsymutil, we emit
2646 // an empty line table for the unit, even if the unit doesn't
2647 // actually exist in the DIE tree.
2648 patchLineTableForUnit(CurrentUnit, DwarfContext);
2651 patchRangesForUnit(CurrentUnit, DwarfContext);
2652 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
2653 emitAcceleratorEntriesForUnit(CurrentUnit);
2656 // Emit all the compile unit's debug information.
2657 if (!ValidRelocs.empty() && !Options.NoOutput)
2658 for (auto &CurrentUnit : Units) {
2659 generateUnitRanges(CurrentUnit);
2660 CurrentUnit.fixupForwardReferences();
2661 Streamer->emitCompileUnitHeader(CurrentUnit);
2662 if (!CurrentUnit.getOutputUnitDIE())
2664 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
2667 if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
2668 patchFrameInfoForObject(*Obj, DwarfContext,
2669 Units[0].getOrigUnit().getAddressByteSize());
2671 // Clean-up before starting working on the next object.
2675 // Emit everything that's global.
2676 if (!Options.NoOutput) {
2677 Streamer->emitAbbrevs(Abbreviations);
2678 Streamer->emitStrings(StringPool);
2681 return Options.NoOutput ? true : Streamer->finish();
2685 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
2686 const LinkOptions &Options) {
2687 DwarfLinker Linker(OutputFilename, Options);
2688 return Linker.link(DM);