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/Config/config.h"
19 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
20 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
21 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
22 #include "llvm/MC/MCAsmBackend.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCCodeEmitter.h"
26 #include "llvm/MC/MCDwarf.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCObjectFileInfo.h"
29 #include "llvm/MC/MCRegisterInfo.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/Object/MachO.h"
33 #include "llvm/Support/Dwarf.h"
34 #include "llvm/Support/LEB128.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
46 void warn(const Twine &Warning, const Twine &Context) {
47 errs() << Twine("while processing ") + Context + ":\n";
48 errs() << Twine("warning: ") + Warning + "\n";
51 bool error(const Twine &Error, const Twine &Context) {
52 errs() << Twine("while processing ") + Context + ":\n";
53 errs() << Twine("error: ") + Error + "\n";
57 template <typename KeyT, typename ValT>
58 using HalfOpenIntervalMap =
59 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
60 IntervalMapHalfOpenInfo<KeyT>>;
62 typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
64 // FIXME: Delete this structure.
65 struct PatchLocation {
66 DIE::value_iterator I;
68 PatchLocation() = default;
69 PatchLocation(DIE::value_iterator I) : I(I) {}
71 void set(uint64_t New) const {
74 assert(Old.getType() == DIEValue::isInteger);
75 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
78 uint64_t get() const {
80 return I->getDIEInteger().getValue();
86 class NonRelocatableStringpool;
88 /// A DeclContext is a named program scope that is used for ODR
89 /// uniquing of types.
90 /// The set of DeclContext for the ODR-subject parts of a Dwarf link
91 /// is expanded (and uniqued) with each new object file processed. We
92 /// need to determine the context of each DIE in an linked object file
93 /// to see if the corresponding type has already been emitted.
95 /// The contexts are conceptually organised as a tree (eg. a function
96 /// scope is contained in a namespace scope that contains other
97 /// scopes), but storing/accessing them in an actual tree is too
98 /// inefficient: we need to be able to very quickly query a context
99 /// for a given child context by name. Storing a StringMap in each
100 /// DeclContext would be too space inefficient.
101 /// The solution here is to give each DeclContext a link to its parent
102 /// (this allows to walk up the tree), but to query the existance of a
103 /// specific DeclContext using a separate DenseMap keyed on the hash
104 /// of the fully qualified name of the context.
106 unsigned QualifiedNameHash;
112 const DeclContext &Parent;
113 const DWARFDebugInfoEntryMinimal *LastSeenDIE;
114 uint32_t LastSeenCompileUnitID;
115 uint32_t CanonicalDIEOffset;
120 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
123 : QualifiedNameHash(0), Line(0), ByteSize(0),
124 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
125 LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
127 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
128 StringRef Name, StringRef File, const DeclContext &Parent,
129 const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
131 : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
132 Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
133 LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
135 uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
137 bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
139 uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
140 void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
142 uint16_t getTag() const { return Tag; }
143 StringRef getName() const { return Name; }
146 /// Info type for the DenseMap storing the DeclContext pointers.
147 struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
148 using DenseMapInfo<DeclContext *>::getEmptyKey;
149 using DenseMapInfo<DeclContext *>::getTombstoneKey;
151 static unsigned getHashValue(const DeclContext *Ctxt) {
152 return Ctxt->QualifiedNameHash;
155 static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
156 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
158 return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
159 LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
160 LHS->Name.data() == RHS->Name.data() &&
161 LHS->File.data() == RHS->File.data() &&
162 LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
166 /// This class gives a tree-like API to the DenseMap that stores the
167 /// DeclContext objects. It also holds the BumpPtrAllocator where
168 /// these objects will be allocated.
169 class DeclContextTree {
170 BumpPtrAllocator Allocator;
172 DeclContext::Map Contexts;
175 /// Get the child of \a Context described by \a DIE in \a Unit. The
176 /// required strings will be interned in \a StringPool.
177 /// \returns The child DeclContext along with one bit that is set if
178 /// this context is invalid.
179 /// FIXME: the invalid bit along the return value is to emulate some
180 /// dsymutil-classic functionality. See the fucntion definition for
181 /// a more thorough discussion of its use.
182 PointerIntPair<DeclContext *, 1>
183 getChildDeclContext(DeclContext &Context,
184 const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
185 NonRelocatableStringpool &StringPool);
187 DeclContext &getRoot() { return Root; }
190 /// \brief Stores all information relating to a compile unit, be it in
191 /// its original instance in the object file to its brand new cloned
192 /// and linked DIE tree.
195 /// \brief Information gathered about a DIE in the object file.
197 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
198 DeclContext *Ctxt; ///< ODR Declaration context.
199 DIE *Clone; ///< Cloned version of that DIE.
200 uint32_t ParentIdx; ///< The index of this DIE's parent.
201 bool Keep; ///< Is the DIE part of the linked output?
202 bool InDebugMap; ///< Was this DIE's entity found in the map?
205 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR)
206 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
208 Info.resize(OrigUnit.getNumDIEs());
210 const auto *CUDie = OrigUnit.getUnitDIE(false);
211 unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
212 &OrigUnit, dwarf::DW_AT_language, 0);
213 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
214 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
215 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
216 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
217 Lang == dwarf::DW_LANG_ObjC_plus_plus);
220 CompileUnit(CompileUnit &&RHS)
221 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
222 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
223 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
224 // The CompileUnit container has been 'reserve()'d with the right
225 // size. We cannot move the IntervalMap anyway.
226 llvm_unreachable("CompileUnits should not be moved.");
229 DWARFUnit &getOrigUnit() const { return OrigUnit; }
231 unsigned getUniqueID() const { return ID; }
233 DIE *getOutputUnitDIE() const { return CUDie; }
234 void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
236 bool hasODR() const { return HasODR; }
238 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
239 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
241 uint64_t getStartOffset() const { return StartOffset; }
242 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
243 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
245 uint64_t getLowPc() const { return LowPc; }
246 uint64_t getHighPc() const { return HighPc; }
248 Optional<PatchLocation> getUnitRangesAttribute() const {
249 return UnitRangeAttribute;
251 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
252 const std::vector<PatchLocation> &getRangesAttributes() const {
253 return RangeAttributes;
256 const std::vector<std::pair<PatchLocation, int64_t>> &
257 getLocationAttributes() const {
258 return LocationAttributes;
261 /// \brief Compute the end offset for this unit. Must be
262 /// called after the CU's DIEs have been cloned.
263 /// \returns the next unit offset (which is also the current
264 /// debug_info section size).
265 uint64_t computeNextUnitOffset();
267 /// \brief Keep track of a forward reference to DIE \p Die in \p
268 /// RefUnit by \p Attr. The attribute should be fixed up later to
269 /// point to the absolute offset of \p Die in the debug_info section
270 /// or to the canonical offset of \p Ctxt if it is non-null.
271 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
272 DeclContext *Ctxt, PatchLocation Attr);
274 /// \brief Apply all fixups recored by noteForwardReference().
275 void fixupForwardReferences();
277 /// \brief Add a function range [\p LowPC, \p HighPC) that is
278 /// relocatad by applying offset \p PCOffset.
279 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
281 /// \brief Keep track of a DW_AT_range attribute that we will need to
283 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
285 /// \brief Keep track of a location attribute pointing to a location
286 /// list in the debug_loc section.
287 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
289 /// \brief Add a name accelerator entry for \p Die with \p Name
290 /// which is stored in the string table at \p Offset.
291 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
292 bool SkipPubnamesSection = false);
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 addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
299 StringRef Name; ///< Name of the entry.
300 const DIE *Die; ///< DIE this entry describes.
301 uint32_t NameOffset; ///< Offset of Name in the string pool.
302 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
304 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
305 bool SkipPubSection = false)
306 : Name(Name), Die(Die), NameOffset(NameOffset),
307 SkipPubSection(SkipPubSection) {}
310 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
311 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
313 /// Get the full path for file \a FileNum in the line table
314 const char *getResolvedPath(unsigned FileNum) {
315 if (FileNum >= ResolvedPaths.size())
317 return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
321 /// Set the fully resolved path for the line-table's file \a FileNum
323 void setResolvedPath(unsigned FileNum, const std::string &Path) {
324 if (ResolvedPaths.size() <= FileNum)
325 ResolvedPaths.resize(FileNum + 1);
326 ResolvedPaths[FileNum] = Path;
332 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
333 DIE *CUDie; ///< Root of the linked DIE tree.
335 uint64_t StartOffset;
336 uint64_t NextUnitOffset;
341 /// \brief A list of attributes to fixup with the absolute offset of
342 /// a DIE in the debug_info section.
344 /// The offsets for the attributes in this array couldn't be set while
345 /// cloning because for cross-cu forward refences the target DIE's
346 /// offset isn't known you emit the reference attribute.
347 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
348 PatchLocation>> ForwardDIEReferences;
350 FunctionIntervals::Allocator RangeAlloc;
351 /// \brief The ranges in that interval map are the PC ranges for
352 /// functions in this unit, associated with the PC offset to apply
353 /// to the addresses to get the linked address.
354 FunctionIntervals Ranges;
356 /// \brief DW_AT_ranges attributes to patch after we have gathered
357 /// all the unit's function addresses.
359 std::vector<PatchLocation> RangeAttributes;
360 Optional<PatchLocation> UnitRangeAttribute;
363 /// \brief Location attributes that need to be transfered from th
364 /// original debug_loc section to the liked one. They are stored
365 /// along with the PC offset that is to be applied to their
366 /// function's address.
367 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
369 /// \brief Accelerator entries for the unit, both for the pub*
370 /// sections and the apple* ones.
372 std::vector<AccelInfo> Pubnames;
373 std::vector<AccelInfo> Pubtypes;
376 /// Cached resolved paths from the line table.
377 std::vector<std::string> ResolvedPaths;
379 /// Is this unit subject to the ODR rule?
383 uint64_t CompileUnit::computeNextUnitOffset() {
384 NextUnitOffset = StartOffset + 11 /* Header size */;
385 // The root DIE might be null, meaning that the Unit had nothing to
386 // contribute to the linked output. In that case, we will emit the
387 // unit header without any actual DIE.
389 NextUnitOffset += CUDie->getSize();
390 return NextUnitOffset;
393 /// \brief Keep track of a forward cross-cu reference from this unit
394 /// to \p Die that lives in \p RefUnit.
395 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
396 DeclContext *Ctxt, PatchLocation Attr) {
397 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
400 /// \brief Apply all fixups recorded by noteForwardReference().
401 void CompileUnit::fixupForwardReferences() {
402 for (const auto &Ref : ForwardDIEReferences) {
404 const CompileUnit *RefUnit;
407 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
408 if (Ctxt && Ctxt->getCanonicalDIEOffset())
409 Attr.set(Ctxt->getCanonicalDIEOffset());
411 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
415 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
417 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
418 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
419 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
422 void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
423 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
424 RangeAttributes.push_back(Attr);
426 UnitRangeAttribute = Attr;
429 void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
430 LocationAttributes.emplace_back(Attr, PcOffset);
433 /// \brief Add a name accelerator entry for \p Die with \p Name
434 /// which is stored in the string table at \p Offset.
435 void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
436 uint32_t Offset, bool SkipPubSection) {
437 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
440 /// \brief Add a type accelerator entry for \p Die with \p Name
441 /// which is stored in the string table at \p Offset.
442 void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
444 Pubtypes.emplace_back(Name, Die, Offset, false);
447 /// \brief A string table that doesn't need relocations.
449 /// We are doing a final link, no need for a string table that
450 /// has relocation entries for every reference to it. This class
451 /// provides this ablitity by just associating offsets with
453 class NonRelocatableStringpool {
455 /// \brief Entries are stored into the StringMap and simply linked
456 /// together through the second element of this pair in order to
457 /// keep track of insertion order.
458 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
461 NonRelocatableStringpool()
462 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
463 // Legacy dsymutil puts an empty string at the start of the line
468 /// \brief Get the offset of string \p S in the string table. This
469 /// can insert a new element or return the offset of a preexisitng
471 uint32_t getStringOffset(StringRef S);
473 /// \brief Get permanent storage for \p S (but do not necessarily
474 /// emit \p S in the output section).
475 /// \returns The StringRef that points to permanent storage to use
476 /// in place of \p S.
477 StringRef internString(StringRef S);
479 // \brief Return the first entry of the string table.
480 const MapTy::MapEntryTy *getFirstEntry() const {
481 return getNextEntry(&Sentinel);
484 // \brief Get the entry following \p E in the string table or null
485 // if \p E was the last entry.
486 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
487 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
490 uint64_t getSize() { return CurrentEndOffset; }
494 uint32_t CurrentEndOffset;
495 MapTy::MapEntryTy Sentinel, *Last;
498 /// \brief Get the offset of string \p S in the string table. This
499 /// can insert a new element or return the offset of a preexisitng
501 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
502 if (S.empty() && !Strings.empty())
505 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
509 // A non-empty string can't be at offset 0, so if we have an entry
510 // with a 0 offset, it must be a previously interned string.
511 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
512 if (Inserted || It->getValue().first == 0) {
513 // Set offset and chain at the end of the entries list.
514 It->getValue().first = CurrentEndOffset;
515 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
516 Last->getValue().second = &*It;
519 return It->getValue().first;
522 /// \brief Put \p S into the StringMap so that it gets permanent
523 /// storage, but do not actually link it in the chain of elements
524 /// that go into the output section. A latter call to
525 /// getStringOffset() with the same string will chain it though.
526 StringRef NonRelocatableStringpool::internString(StringRef S) {
527 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
528 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
529 return InsertResult.first->getKey();
532 /// \brief The Dwarf streaming logic
534 /// All interactions with the MC layer that is used to build the debug
535 /// information binary representation are handled in this class.
536 class DwarfStreamer {
537 /// \defgroup MCObjects MC layer objects constructed by the streamer
539 std::unique_ptr<MCRegisterInfo> MRI;
540 std::unique_ptr<MCAsmInfo> MAI;
541 std::unique_ptr<MCObjectFileInfo> MOFI;
542 std::unique_ptr<MCContext> MC;
543 MCAsmBackend *MAB; // Owned by MCStreamer
544 std::unique_ptr<MCInstrInfo> MII;
545 std::unique_ptr<MCSubtargetInfo> MSTI;
546 MCCodeEmitter *MCE; // Owned by MCStreamer
547 MCStreamer *MS; // Owned by AsmPrinter
548 std::unique_ptr<TargetMachine> TM;
549 std::unique_ptr<AsmPrinter> Asm;
552 /// \brief the file we stream the linked Dwarf to.
553 std::unique_ptr<raw_fd_ostream> OutFile;
555 uint32_t RangesSectionSize;
556 uint32_t LocSectionSize;
557 uint32_t LineSectionSize;
558 uint32_t FrameSectionSize;
560 /// \brief Emit the pubnames or pubtypes section contribution for \p
561 /// Unit into \p Sec. The data is provided in \p Names.
562 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
563 const CompileUnit &Unit,
564 const std::vector<CompileUnit::AccelInfo> &Names);
567 /// \brief Actually create the streamer and the ouptut file.
569 /// This could be done directly in the constructor, but it feels
570 /// more natural to handle errors through return value.
571 bool init(Triple TheTriple, StringRef OutputFilename);
573 /// \brief Dump the file to the disk.
576 AsmPrinter &getAsmPrinter() const { return *Asm; }
578 /// \brief Set the current output section to debug_info and change
579 /// the MC Dwarf version to \p DwarfVersion.
580 void switchToDebugInfoSection(unsigned DwarfVersion);
582 /// \brief Emit the compilation unit header for \p Unit in the
583 /// debug_info section.
585 /// As a side effect, this also switches the current Dwarf version
586 /// of the MC layer to the one of U.getOrigUnit().
587 void emitCompileUnitHeader(CompileUnit &Unit);
589 /// \brief Recursively emit the DIE tree rooted at \p Die.
590 void emitDIE(DIE &Die);
592 /// \brief Emit the abbreviation table \p Abbrevs to the
593 /// debug_abbrev section.
594 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
596 /// \brief Emit the string table described by \p Pool.
597 void emitStrings(const NonRelocatableStringpool &Pool);
599 /// \brief Emit debug_ranges for \p FuncRange by translating the
600 /// original \p Entries.
601 void emitRangesEntries(
602 int64_t UnitPcOffset, uint64_t OrigLowPc,
603 FunctionIntervals::const_iterator FuncRange,
604 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
605 unsigned AddressSize);
607 /// \brief Emit debug_aranges entries for \p Unit and if \p
608 /// DoRangesSection is true, also emit the debug_ranges entries for
609 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
610 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
612 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
614 /// \brief Emit the debug_loc contribution for \p Unit by copying
615 /// the entries from \p Dwarf and offseting them. Update the
616 /// location attributes to point to the new entries.
617 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
619 /// \brief Emit the line table described in \p Rows into the
620 /// debug_line section.
621 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
622 std::vector<DWARFDebugLine::Row> &Rows,
623 unsigned AdddressSize);
625 uint32_t getLineSectionSize() const { return LineSectionSize; }
627 /// \brief Emit the .debug_pubnames contribution for \p Unit.
628 void emitPubNamesForUnit(const CompileUnit &Unit);
630 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
631 void emitPubTypesForUnit(const CompileUnit &Unit);
633 /// \brief Emit a CIE.
634 void emitCIE(StringRef CIEBytes);
636 /// \brief Emit an FDE with data \p Bytes.
637 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
640 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
643 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
644 std::string ErrorStr;
645 std::string TripleName;
646 StringRef Context = "dwarf streamer init";
649 const Target *TheTarget =
650 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
652 return error(ErrorStr, Context);
653 TripleName = TheTriple.getTriple();
655 // Create all the MC Objects.
656 MRI.reset(TheTarget->createMCRegInfo(TripleName));
658 return error(Twine("no register info for target ") + TripleName, Context);
660 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
662 return error("no asm info for target " + TripleName, Context);
664 MOFI.reset(new MCObjectFileInfo);
665 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
666 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
669 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
671 return error("no asm backend for target " + TripleName, Context);
673 MII.reset(TheTarget->createMCInstrInfo());
675 return error("no instr info info for target " + TripleName, Context);
677 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
679 return error("no subtarget info for target " + TripleName, Context);
681 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
683 return error("no code emitter for target " + TripleName, Context);
685 // Create the output file.
688 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
690 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
692 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
694 /*DWARFMustBeAtTheEnd*/ false);
696 return error("no object streamer for target " + TripleName, Context);
698 // Finally create the AsmPrinter we'll use to emit the DIEs.
699 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
701 return error("no target machine for target " + TripleName, Context);
703 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
705 return error("no asm printer for target " + TripleName, Context);
707 RangesSectionSize = 0;
710 FrameSectionSize = 0;
715 bool DwarfStreamer::finish() {
720 /// \brief Set the current output section to debug_info and change
721 /// the MC Dwarf version to \p DwarfVersion.
722 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
723 MS->SwitchSection(MOFI->getDwarfInfoSection());
724 MC->setDwarfVersion(DwarfVersion);
727 /// \brief Emit the compilation unit header for \p Unit in the
728 /// debug_info section.
730 /// A Dwarf scetion header is encoded as:
731 /// uint32_t Unit length (omiting this field)
733 /// uint32_t Abbreviation table offset
734 /// uint8_t Address size
736 /// Leading to a total of 11 bytes.
737 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
738 unsigned Version = Unit.getOrigUnit().getVersion();
739 switchToDebugInfoSection(Version);
741 // Emit size of content not including length itself. The size has
742 // already been computed in CompileUnit::computeOffsets(). Substract
743 // 4 to that size to account for the length field.
744 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
745 Asm->EmitInt16(Version);
746 // We share one abbreviations table across all units so it's always at the
747 // start of the section.
749 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
752 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
753 /// for the linked Dwarf file.
754 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
755 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
756 Asm->emitDwarfAbbrevs(Abbrevs);
759 /// \brief Recursively emit the DIE tree rooted at \p Die.
760 void DwarfStreamer::emitDIE(DIE &Die) {
761 MS->SwitchSection(MOFI->getDwarfInfoSection());
762 Asm->emitDwarfDIE(Die);
765 /// \brief Emit the debug_str section stored in \p Pool.
766 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
767 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
768 for (auto *Entry = Pool.getFirstEntry(); Entry;
769 Entry = Pool.getNextEntry(Entry))
770 Asm->OutStreamer->EmitBytes(
771 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
774 /// \brief Emit the debug_range section contents for \p FuncRange by
775 /// translating the original \p Entries. The debug_range section
776 /// format is totally trivial, consisting just of pairs of address
777 /// sized addresses describing the ranges.
778 void DwarfStreamer::emitRangesEntries(
779 int64_t UnitPcOffset, uint64_t OrigLowPc,
780 FunctionIntervals::const_iterator FuncRange,
781 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
782 unsigned AddressSize) {
783 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
785 // Offset each range by the right amount.
786 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
787 for (const auto &Range : Entries) {
788 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
789 warn("unsupported base address selection operation",
790 "emitting debug_ranges");
793 // Do not emit empty ranges.
794 if (Range.StartAddress == Range.EndAddress)
797 // All range entries should lie in the function range.
798 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
799 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
800 warn("inconsistent range data.", "emitting debug_ranges");
801 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
802 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
803 RangesSectionSize += 2 * AddressSize;
806 // Add the terminator entry.
807 MS->EmitIntValue(0, AddressSize);
808 MS->EmitIntValue(0, AddressSize);
809 RangesSectionSize += 2 * AddressSize;
812 /// \brief Emit the debug_aranges contribution of a unit and
813 /// if \p DoDebugRanges is true the debug_range contents for a
814 /// compile_unit level DW_AT_ranges attribute (Which are basically the
815 /// same thing with a different base address).
816 /// Just aggregate all the ranges gathered inside that unit.
817 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
818 bool DoDebugRanges) {
819 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
820 // Gather the ranges in a vector, so that we can simplify them. The
821 // IntervalMap will have coalesced the non-linked ranges, but here
822 // we want to coalesce the linked addresses.
823 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
824 const auto &FunctionRanges = Unit.getFunctionRanges();
825 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
826 Range != End; ++Range)
827 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
828 Range.stop() + Range.value()));
830 // The object addresses where sorted, but again, the linked
831 // addresses might end up in a different order.
832 std::sort(Ranges.begin(), Ranges.end());
834 if (!Ranges.empty()) {
835 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
837 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
838 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
840 unsigned HeaderSize =
841 sizeof(int32_t) + // Size of contents (w/o this field
842 sizeof(int16_t) + // DWARF ARange version number
843 sizeof(int32_t) + // Offset of CU in the .debug_info section
844 sizeof(int8_t) + // Pointer Size (in bytes)
845 sizeof(int8_t); // Segment Size (in bytes)
847 unsigned TupleSize = AddressSize * 2;
848 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
850 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
851 Asm->OutStreamer->EmitLabel(BeginLabel);
852 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
853 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
854 Asm->EmitInt8(AddressSize); // Address size
855 Asm->EmitInt8(0); // Segment size
857 Asm->OutStreamer->EmitFill(Padding, 0x0);
859 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
861 uint64_t RangeStart = Range->first;
862 MS->EmitIntValue(RangeStart, AddressSize);
863 while ((Range + 1) != End && Range->second == (Range + 1)->first)
865 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
869 Asm->OutStreamer->EmitIntValue(0, AddressSize);
870 Asm->OutStreamer->EmitIntValue(0, AddressSize);
871 Asm->OutStreamer->EmitLabel(EndLabel);
877 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
878 // Offset each range by the right amount.
879 int64_t PcOffset = -Unit.getLowPc();
880 // Emit coalesced ranges.
881 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
882 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
883 while (Range + 1 != End && Range->second == (Range + 1)->first)
885 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
886 RangesSectionSize += 2 * AddressSize;
889 // Add the terminator entry.
890 MS->EmitIntValue(0, AddressSize);
891 MS->EmitIntValue(0, AddressSize);
892 RangesSectionSize += 2 * AddressSize;
895 /// \brief Emit location lists for \p Unit and update attribtues to
896 /// point to the new entries.
897 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
898 DWARFContext &Dwarf) {
899 const auto &Attributes = Unit.getLocationAttributes();
901 if (Attributes.empty())
904 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
906 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
907 const DWARFSection &InputSec = Dwarf.getLocSection();
908 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
909 DWARFUnit &OrigUnit = Unit.getOrigUnit();
910 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
911 int64_t UnitPcOffset = 0;
912 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
913 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
914 if (OrigLowPc != -1ULL)
915 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
917 for (const auto &Attr : Attributes) {
918 uint32_t Offset = Attr.first.get();
919 Attr.first.set(LocSectionSize);
920 // This is the quantity to add to the old location address to get
921 // the correct address for the new one.
922 int64_t LocPcOffset = Attr.second + UnitPcOffset;
923 while (Data.isValidOffset(Offset)) {
924 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
925 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
926 LocSectionSize += 2 * AddressSize;
927 if (Low == 0 && High == 0) {
928 Asm->OutStreamer->EmitIntValue(0, AddressSize);
929 Asm->OutStreamer->EmitIntValue(0, AddressSize);
932 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
933 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
934 uint64_t Length = Data.getU16(&Offset);
935 Asm->OutStreamer->EmitIntValue(Length, 2);
936 // Just copy the bytes over.
937 Asm->OutStreamer->EmitBytes(
938 StringRef(InputSec.Data.substr(Offset, Length)));
940 LocSectionSize += Length + 2;
945 void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
946 unsigned MinInstLength,
947 std::vector<DWARFDebugLine::Row> &Rows,
948 unsigned PointerSize) {
949 // Switch to the section where the table will be emitted into.
950 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
951 MCSymbol *LineStartSym = MC->createTempSymbol();
952 MCSymbol *LineEndSym = MC->createTempSymbol();
954 // The first 4 bytes is the total length of the information for this
955 // compilation unit (not including these 4 bytes for the length).
956 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
957 Asm->OutStreamer->EmitLabel(LineStartSym);
959 MS->EmitBytes(PrologueBytes);
960 LineSectionSize += PrologueBytes.size() + 4;
962 SmallString<128> EncodingBuffer;
963 raw_svector_ostream EncodingOS(EncodingBuffer);
966 // We only have the dummy entry, dsymutil emits an entry with a 0
967 // address in that case.
968 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
969 MS->EmitBytes(EncodingOS.str());
970 LineSectionSize += EncodingBuffer.size();
971 MS->EmitLabel(LineEndSym);
975 // Line table state machine fields
976 unsigned FileNum = 1;
977 unsigned LastLine = 1;
979 unsigned IsStatement = 1;
981 uint64_t Address = -1ULL;
983 unsigned RowsSinceLastSequence = 0;
985 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
986 auto &Row = Rows[Idx];
988 int64_t AddressDelta;
989 if (Address == -1ULL) {
990 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
991 MS->EmitULEB128IntValue(PointerSize + 1);
992 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
993 MS->EmitIntValue(Row.Address, PointerSize);
994 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
997 AddressDelta = (Row.Address - Address) / MinInstLength;
1000 // FIXME: code copied and transfromed from
1001 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
1002 // this code, but the current compatibility requirement with
1003 // classic dsymutil makes it hard. Revisit that once this
1004 // requirement is dropped.
1006 if (FileNum != Row.File) {
1008 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
1009 MS->EmitULEB128IntValue(FileNum);
1010 LineSectionSize += 1 + getULEB128Size(FileNum);
1012 if (Column != Row.Column) {
1013 Column = Row.Column;
1014 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
1015 MS->EmitULEB128IntValue(Column);
1016 LineSectionSize += 1 + getULEB128Size(Column);
1019 // FIXME: We should handle the discriminator here, but dsymutil
1020 // doesn' consider it, thus ignore it for now.
1022 if (Isa != Row.Isa) {
1024 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
1025 MS->EmitULEB128IntValue(Isa);
1026 LineSectionSize += 1 + getULEB128Size(Isa);
1028 if (IsStatement != Row.IsStmt) {
1029 IsStatement = Row.IsStmt;
1030 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
1031 LineSectionSize += 1;
1033 if (Row.BasicBlock) {
1034 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
1035 LineSectionSize += 1;
1038 if (Row.PrologueEnd) {
1039 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
1040 LineSectionSize += 1;
1043 if (Row.EpilogueBegin) {
1044 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
1045 LineSectionSize += 1;
1048 int64_t LineDelta = int64_t(Row.Line) - LastLine;
1049 if (!Row.EndSequence) {
1050 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
1051 MS->EmitBytes(EncodingOS.str());
1052 LineSectionSize += EncodingBuffer.size();
1053 EncodingBuffer.resize(0);
1054 EncodingOS.resync();
1055 Address = Row.Address;
1056 LastLine = Row.Line;
1057 RowsSinceLastSequence++;
1060 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
1061 MS->EmitSLEB128IntValue(LineDelta);
1062 LineSectionSize += 1 + getSLEB128Size(LineDelta);
1065 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
1066 MS->EmitULEB128IntValue(AddressDelta);
1067 LineSectionSize += 1 + getULEB128Size(AddressDelta);
1069 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
1070 MS->EmitBytes(EncodingOS.str());
1071 LineSectionSize += EncodingBuffer.size();
1072 EncodingBuffer.resize(0);
1073 EncodingOS.resync();
1075 LastLine = FileNum = IsStatement = 1;
1076 RowsSinceLastSequence = Column = Isa = 0;
1080 if (RowsSinceLastSequence) {
1081 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
1082 MS->EmitBytes(EncodingOS.str());
1083 LineSectionSize += EncodingBuffer.size();
1084 EncodingBuffer.resize(0);
1085 EncodingOS.resync();
1088 MS->EmitLabel(LineEndSym);
1091 /// \brief Emit the pubnames or pubtypes section contribution for \p
1092 /// Unit into \p Sec. The data is provided in \p Names.
1093 void DwarfStreamer::emitPubSectionForUnit(
1094 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
1095 const std::vector<CompileUnit::AccelInfo> &Names) {
1099 // Start the dwarf pubnames section.
1100 Asm->OutStreamer->SwitchSection(Sec);
1101 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1102 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
1104 bool HeaderEmitted = false;
1105 // Emit the pubnames for this compilation unit.
1106 for (const auto &Name : Names) {
1107 if (Name.SkipPubSection)
1110 if (!HeaderEmitted) {
1112 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
1113 Asm->OutStreamer->EmitLabel(BeginLabel);
1114 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
1115 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
1116 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1117 HeaderEmitted = true;
1119 Asm->EmitInt32(Name.Die->getOffset());
1120 Asm->OutStreamer->EmitBytes(
1121 StringRef(Name.Name.data(), Name.Name.size() + 1));
1126 Asm->EmitInt32(0); // End marker.
1127 Asm->OutStreamer->EmitLabel(EndLabel);
1130 /// \brief Emit .debug_pubnames for \p Unit.
1131 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1132 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1133 "names", Unit, Unit.getPubnames());
1136 /// \brief Emit .debug_pubtypes for \p Unit.
1137 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1138 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1139 "types", Unit, Unit.getPubtypes());
1142 /// \brief Emit a CIE into the debug_frame section.
1143 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1144 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1146 MS->EmitBytes(CIEBytes);
1147 FrameSectionSize += CIEBytes.size();
1150 /// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1151 /// contains the FDE data without the length, CIE offset and address
1152 /// which will be replaced with the paramter values.
1153 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1154 uint32_t Address, StringRef FDEBytes) {
1155 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1157 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1158 MS->EmitIntValue(CIEOffset, 4);
1159 MS->EmitIntValue(Address, AddrSize);
1160 MS->EmitBytes(FDEBytes);
1161 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1164 /// \brief The core of the Dwarf linking logic.
1166 /// The link of the dwarf information from the object files will be
1167 /// driven by the selection of 'root DIEs', which are DIEs that
1168 /// describe variables or functions that are present in the linked
1169 /// binary (and thus have entries in the debug map). All the debug
1170 /// information that will be linked (the DIEs, but also the line
1171 /// tables, ranges, ...) is derived from that set of root DIEs.
1173 /// The root DIEs are identified because they contain relocations that
1174 /// correspond to a debug map entry at specific places (the low_pc for
1175 /// a function, the location for a variable). These relocations are
1176 /// called ValidRelocs in the DwarfLinker and are gathered as a very
1177 /// first step when we start processing a DebugMapObject.
1180 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1181 : OutputFilename(OutputFilename), Options(Options),
1182 BinHolder(Options.Verbose), LastCIEOffset(0) {}
1185 for (auto *Abbrev : Abbreviations)
1189 /// \brief Link the contents of the DebugMap.
1190 bool link(const DebugMap &);
1193 /// \brief Called at the start of a debug object link.
1194 void startDebugObject(DWARFContext &, DebugMapObject &);
1196 /// \brief Called at the end of a debug object link.
1197 void endDebugObject();
1199 /// \defgroup FindValidRelocations Translate debug map into a list
1200 /// of relevant relocations
1207 const DebugMapObject::DebugMapEntry *Mapping;
1209 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1210 const DebugMapObject::DebugMapEntry *Mapping)
1211 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1213 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1216 /// \brief The valid relocations for the current DebugMapObject.
1217 /// This vector is sorted by relocation offset.
1218 std::vector<ValidReloc> ValidRelocs;
1220 /// \brief Index into ValidRelocs of the next relocation to
1221 /// consider. As we walk the DIEs in acsending file offset and as
1222 /// ValidRelocs is sorted by file offset, keeping this index
1223 /// uptodate is all we have to do to have a cheap lookup during the
1224 /// root DIE selection and during DIE cloning.
1225 unsigned NextValidReloc;
1227 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1228 const DebugMapObject &DMO);
1230 bool findValidRelocs(const object::SectionRef &Section,
1231 const object::ObjectFile &Obj,
1232 const DebugMapObject &DMO);
1234 void findValidRelocsMachO(const object::SectionRef &Section,
1235 const object::MachOObjectFile &Obj,
1236 const DebugMapObject &DMO);
1239 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1242 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1243 /// keep. Store that information in \p CU's DIEInfo.
1244 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1245 const DebugMapObject &DMO, CompileUnit &CU,
1248 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1249 enum TravesalFlags {
1250 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1251 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1252 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1253 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1254 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
1257 /// \brief Mark the passed DIE as well as all the ones it depends on
1259 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1260 CompileUnit::DIEInfo &MyInfo,
1261 const DebugMapObject &DMO, CompileUnit &CU,
1264 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1265 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1268 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1270 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1272 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1274 CompileUnit::DIEInfo &MyInfo,
1277 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1278 CompileUnit::DIEInfo &Info);
1281 /// \defgroup Linking Methods used to link the debug information
1284 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1285 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1286 /// stripped out and addresses have been rewritten according to the
1289 /// \param OutOffset is the offset the cloned DIE in the output
1291 /// \param PCOffset (while cloning a function scope) is the offset
1292 /// applied to the entry point of the function to get the linked address.
1294 /// \returns the root of the cloned tree.
1295 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
1296 int64_t PCOffset, uint32_t OutOffset);
1298 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1300 /// \brief Information gathered and exchanged between the various
1301 /// clone*Attributes helpers about the attributes of a particular DIE.
1302 struct AttributesInfo {
1303 const char *Name, *MangledName; ///< Names.
1304 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1306 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1307 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1309 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1310 bool IsDeclaration; ///< Is this DIE only a declaration?
1313 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1314 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1315 IsDeclaration(false) {}
1318 /// \brief Helper for cloneDIE.
1319 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1320 CompileUnit &U, const DWARFFormValue &Val,
1321 const AttributeSpec AttrSpec, unsigned AttrSize,
1322 AttributesInfo &AttrInfo);
1324 /// \brief Helper for cloneDIE.
1325 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1326 const DWARFFormValue &Val, const DWARFUnit &U);
1328 /// \brief Helper for cloneDIE.
1330 cloneDieReferenceAttribute(DIE &Die,
1331 const DWARFDebugInfoEntryMinimal &InputDIE,
1332 AttributeSpec AttrSpec, unsigned AttrSize,
1333 const DWARFFormValue &Val, CompileUnit &Unit);
1335 /// \brief Helper for cloneDIE.
1336 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1337 const DWARFFormValue &Val, unsigned AttrSize);
1339 /// \brief Helper for cloneDIE.
1340 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1341 const DWARFFormValue &Val,
1342 const CompileUnit &Unit, AttributesInfo &Info);
1344 /// \brief Helper for cloneDIE.
1345 unsigned cloneScalarAttribute(DIE &Die,
1346 const DWARFDebugInfoEntryMinimal &InputDIE,
1347 CompileUnit &U, AttributeSpec AttrSpec,
1348 const DWARFFormValue &Val, unsigned AttrSize,
1349 AttributesInfo &Info);
1351 /// \brief Helper for cloneDIE.
1352 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1353 bool isLittleEndian);
1355 /// \brief Assign an abbreviation number to \p Abbrev
1356 void AssignAbbrev(DIEAbbrev &Abbrev);
1358 /// \brief FoldingSet that uniques the abbreviations.
1359 FoldingSet<DIEAbbrev> AbbreviationsSet;
1360 /// \brief Storage for the unique Abbreviations.
1361 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1362 /// be changed to a vecot of unique_ptrs.
1363 std::vector<DIEAbbrev *> Abbreviations;
1365 /// \brief Compute and emit debug_ranges section for \p Unit, and
1366 /// patch the attributes referencing it.
1367 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1369 /// \brief Generate and emit the DW_AT_ranges attribute for a
1370 /// compile_unit if it had one.
1371 void generateUnitRanges(CompileUnit &Unit) const;
1373 /// \brief Extract the line tables fromt he original dwarf, extract
1374 /// the relevant parts according to the linked function ranges and
1375 /// emit the result in the debug_line section.
1376 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1378 /// \brief Emit the accelerator entries for \p Unit.
1379 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1381 /// \brief Patch the frame info for an object file and emit it.
1382 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1383 unsigned AddressSize);
1385 /// \brief DIELoc objects that need to be destructed (but not freed!).
1386 std::vector<DIELoc *> DIELocs;
1387 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1388 std::vector<DIEBlock *> DIEBlocks;
1389 /// \brief Allocator used for all the DIEValue objects.
1390 BumpPtrAllocator DIEAlloc;
1393 /// ODR Contexts for that link.
1394 DeclContextTree ODRContexts;
1396 /// \defgroup Helpers Various helper methods.
1399 const DWARFDebugInfoEntryMinimal *
1400 resolveDIEReference(const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1401 const DWARFDebugInfoEntryMinimal &DIE,
1402 CompileUnit *&ReferencedCU);
1404 CompileUnit *getUnitForOffset(unsigned Offset);
1406 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1407 AttributesInfo &Info);
1409 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1410 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1412 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
1414 /// \brief Attempt to load a debug object from disk.
1415 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1416 DebugMapObject &Obj,
1417 const DebugMap &Map);
1421 std::string OutputFilename;
1422 LinkOptions Options;
1423 BinaryHolder BinHolder;
1424 std::unique_ptr<DwarfStreamer> Streamer;
1426 /// The units of the current debug map object.
1427 std::vector<CompileUnit> Units;
1429 /// The debug map object curently under consideration.
1430 DebugMapObject *CurrentDebugObject;
1432 /// \brief The Dwarf string pool
1433 NonRelocatableStringpool StringPool;
1435 /// \brief This map is keyed by the entry PC of functions in that
1436 /// debug object and the associated value is a pair storing the
1437 /// corresponding end PC and the offset to apply to get the linked
1440 /// See startDebugObject() for a more complete description of its use.
1441 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1443 /// \brief The CIEs that have been emitted in the output
1444 /// section. The actual CIE data serves a the key to this StringMap,
1445 /// this takes care of comparing the semantics of CIEs defined in
1446 /// different object files.
1447 StringMap<uint32_t> EmittedCIEs;
1449 /// Offset of the last CIE that has been emitted in the output
1450 /// debug_frame section.
1451 uint32_t LastCIEOffset;
1454 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1455 /// returning our CompileUnit object instead.
1456 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1458 std::upper_bound(Units.begin(), Units.end(), Offset,
1459 [](uint32_t LHS, const CompileUnit &RHS) {
1460 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1462 return CU != Units.end() ? &*CU : nullptr;
1465 /// \brief Resolve the DIE attribute reference that has been
1466 /// extracted in \p RefValue. The resulting DIE migh be in another
1467 /// CompileUnit which is stored into \p ReferencedCU.
1468 /// \returns null if resolving fails for any reason.
1469 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1470 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1471 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1472 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1473 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1475 if ((RefCU = getUnitForOffset(RefOffset)))
1476 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1479 reportWarning("could not find referenced DIE", &Unit, &DIE);
1483 /// \returns whether the passed \a Attr type might contain a DIE
1484 /// reference suitable for ODR uniquing.
1485 static bool isODRAttribute(uint16_t Attr) {
1489 case dwarf::DW_AT_type:
1490 case dwarf::DW_AT_containing_type:
1491 case dwarf::DW_AT_specification:
1492 case dwarf::DW_AT_abstract_origin:
1493 case dwarf::DW_AT_import:
1496 llvm_unreachable("Improper attribute.");
1499 /// Set the last DIE/CU a context was seen in and, possibly invalidate
1500 /// the context if it is ambiguous.
1502 /// In the current implementation, we don't handle overloaded
1503 /// functions well, because the argument types are not taken into
1504 /// account when computing the DeclContext tree.
1506 /// Some of this is mitigated byt using mangled names that do contain
1507 /// the arguments types, but sometimes (eg. with function templates)
1508 /// we don't have that. In that case, just do not unique anything that
1509 /// refers to the contexts we are not able to distinguish.
1511 /// If a context that is not a namespace appears twice in the same CU,
1512 /// we know it is ambiguous. Make it invalid.
1513 bool DeclContext::setLastSeenDIE(CompileUnit &U,
1514 const DWARFDebugInfoEntryMinimal *Die) {
1515 if (LastSeenCompileUnitID == U.getUniqueID()) {
1516 DWARFUnit &OrigUnit = U.getOrigUnit();
1517 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1518 U.getInfo(FirstIdx).Ctxt = nullptr;
1522 LastSeenCompileUnitID = U.getUniqueID();
1527 /// Get the child context of \a Context corresponding to \a DIE.
1529 /// \returns the child context or null if we shouldn't track children
1530 /// contexts. It also returns an additional bit meaning 'invalid'. An
1531 /// invalid context means it shouldn't be considered for uniquing, but
1532 /// its not returning null, because some children of that context
1533 /// might be uniquing candidates.
1534 /// FIXME: this is for dsymutil-classic compatibility, I don't think
1535 /// it buys us much.
1536 PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1537 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1538 NonRelocatableStringpool &StringPool) {
1539 unsigned Tag = DIE->getTag();
1541 // FIXME: dsymutil-classic compat: We should bail out here if we
1542 // have a specification or an abstract_origin. We will get the
1543 // parent context wrong here.
1547 // By default stop gathering child contexts.
1548 return PointerIntPair<DeclContext *, 1>(nullptr);
1549 case dwarf::DW_TAG_compile_unit:
1550 // FIXME: Add support for DW_TAG_module.
1551 return PointerIntPair<DeclContext *, 1>(&Context);
1552 case dwarf::DW_TAG_subprogram:
1553 // Do not unique anything inside CU local functions.
1554 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1555 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1556 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1557 dwarf::DW_AT_external, 0))
1558 return PointerIntPair<DeclContext *, 1>(nullptr);
1560 case dwarf::DW_TAG_member:
1561 case dwarf::DW_TAG_namespace:
1562 case dwarf::DW_TAG_structure_type:
1563 case dwarf::DW_TAG_class_type:
1564 case dwarf::DW_TAG_union_type:
1565 case dwarf::DW_TAG_enumeration_type:
1566 case dwarf::DW_TAG_typedef:
1567 // Artificial things might be ambiguous, because they might be
1568 // created on demand. For example implicitely defined constructors
1569 // are ambiguous because of the way we identify contexts, and they
1570 // won't be generated everytime everywhere.
1571 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1572 dwarf::DW_AT_artificial, 0))
1573 return PointerIntPair<DeclContext *, 1>(nullptr);
1577 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1578 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1580 StringRef ShortNameRef;
1584 NameRef = StringPool.internString(Name);
1585 else if (Tag == dwarf::DW_TAG_namespace)
1586 // FIXME: For dsymutil-classic compatibility. I think uniquing
1587 // within anonymous namespaces is wrong. There is no ODR guarantee
1589 NameRef = StringPool.internString("(anonymous namespace)");
1591 if (ShortName && ShortName != Name)
1592 ShortNameRef = StringPool.internString(ShortName);
1594 ShortNameRef = NameRef;
1596 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1597 Tag != dwarf::DW_TAG_union_type &&
1598 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1599 return PointerIntPair<DeclContext *, 1>(nullptr);
1603 unsigned ByteSize = 0;
1605 // Gather some discriminating data about the DeclContext we will be
1606 // creating: File, line number and byte size. This shouldn't be
1607 // necessary, because the ODR is just about names, but given that we
1608 // do some approximations with overloaded functions and anonymous
1609 // namespaces, use these additional data points to make the process safer.
1610 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1611 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1612 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1613 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1614 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1615 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1616 &U.getOrigUnit())) {
1617 // FIXME: dsymutil-classic compatibility. I'd rather not
1618 // unique anything in anonymous namespaces, but if we do, then
1619 // verify that the file and line correspond.
1620 if (!Name && Tag == dwarf::DW_TAG_namespace)
1623 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1624 // instead of "" would allow more uniquing, but for now, do
1625 // it this way to match dsymutil-classic.
1626 if (LT->getFileNameByIndex(
1628 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1630 Line = DIE->getAttributeValueAsUnsignedConstant(
1631 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1632 #ifdef HAVE_REALPATH
1633 // Cache the resolved paths, because calling realpath is expansive.
1634 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1635 File = ResolvedPath;
1637 char RealPath[PATH_MAX + 1];
1638 RealPath[PATH_MAX] = 0;
1639 if (::realpath(File.c_str(), RealPath))
1641 U.setResolvedPath(FileNum, File);
1644 FileRef = StringPool.internString(File);
1650 if (!Line && NameRef.empty())
1651 return PointerIntPair<DeclContext *, 1>(nullptr);
1653 // FIXME: dsymutil-classic compat won't unique the same type
1654 // presented once as a struct and once as a class. Use the Tag in
1655 // the fully qualified name hash to get the same effect.
1656 // We hash NameRef, which is the mangled name, in order to get most
1657 // overloaded functions resolvec correctly.
1658 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1660 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1661 // use the filename.
1662 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1663 Hash = hash_combine(Hash, FileRef);
1665 // Now look if this context already exists.
1666 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1667 auto ContextIter = Contexts.find(&Key);
1669 if (ContextIter == Contexts.end()) {
1670 // The context wasn't found.
1672 DeclContext *NewContext =
1673 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1674 Context, DIE, U.getUniqueID());
1675 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1676 assert(Inserted && "Failed to insert DeclContext");
1678 } else if (Tag != dwarf::DW_TAG_namespace &&
1679 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1680 // The context was found, but it is ambiguous with another context
1681 // in the same file. Mark it invalid.
1682 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1685 assert(ContextIter != Contexts.end());
1686 // FIXME: dsymutil-classic compatibility. Union types aren't
1687 // uniques, but their children might be.
1688 if ((Tag == dwarf::DW_TAG_subprogram &&
1689 Context.getTag() != dwarf::DW_TAG_structure_type &&
1690 Context.getTag() != dwarf::DW_TAG_class_type) ||
1691 (Tag == dwarf::DW_TAG_union_type))
1692 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1694 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1697 /// \brief Get the potential name and mangled name for the entity
1698 /// described by \p Die and store them in \Info if they are not
1700 /// \returns is a name was found.
1701 bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1702 DWARFUnit &U, AttributesInfo &Info) {
1703 // FIXME: a bit wastefull as the first getName might return the
1705 if (!Info.MangledName &&
1706 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1707 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1709 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1710 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1712 return Info.Name || Info.MangledName;
1715 /// \brief Report a warning to the user, optionaly including
1716 /// information about a specific \p DIE related to the warning.
1717 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
1718 const DWARFDebugInfoEntryMinimal *DIE) const {
1719 StringRef Context = "<debug map>";
1720 if (CurrentDebugObject)
1721 Context = CurrentDebugObject->getObjectFilename();
1722 warn(Warning, Context);
1724 if (!Options.Verbose || !DIE)
1727 errs() << " in DIE:\n";
1728 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1732 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1733 if (Options.NoOutput)
1736 Streamer = llvm::make_unique<DwarfStreamer>();
1737 return Streamer->init(TheTriple, OutputFilename);
1740 /// \brief Recursive helper to gather the child->parent relationships in the
1741 /// original compile unit.
1742 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1743 unsigned ParentIdx, CompileUnit &CU,
1744 DeclContext *CurrentDeclContext,
1745 NonRelocatableStringpool &StringPool,
1746 DeclContextTree &Contexts) {
1747 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1748 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1750 Info.ParentIdx = ParentIdx;
1752 if (CurrentDeclContext) {
1753 auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1754 DIE, CU, StringPool);
1755 CurrentDeclContext = PtrInvalidPair.getPointer();
1757 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1759 Info.Ctxt = CurrentDeclContext = nullptr;
1762 if (DIE->hasChildren())
1763 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1764 Child = Child->getSibling())
1765 gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1769 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1773 case dwarf::DW_TAG_subprogram:
1774 case dwarf::DW_TAG_lexical_block:
1775 case dwarf::DW_TAG_subroutine_type:
1776 case dwarf::DW_TAG_structure_type:
1777 case dwarf::DW_TAG_class_type:
1778 case dwarf::DW_TAG_union_type:
1781 llvm_unreachable("Invalid Tag");
1784 static unsigned getRefAddrSize(const DWARFUnit &U) {
1785 if (U.getVersion() == 2)
1786 return U.getAddressByteSize();
1790 void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1791 Units.reserve(Dwarf.getNumCompileUnits());
1793 // Iterate over the debug map entries and put all the ones that are
1794 // functions (because they have a size) into the Ranges map. This
1795 // map is very similar to the FunctionRanges that are stored in each
1796 // unit, with 2 notable differences:
1797 // - obviously this one is global, while the other ones are per-unit.
1798 // - this one contains not only the functions described in the DIE
1799 // tree, but also the ones that are only in the debug map.
1800 // The latter information is required to reproduce dsymutil's logic
1801 // while linking line tables. The cases where this information
1802 // matters look like bugs that need to be investigated, but for now
1803 // we need to reproduce dsymutil's behavior.
1804 // FIXME: Once we understood exactly if that information is needed,
1805 // maybe totally remove this (or try to use it to do a real
1806 // -gline-tables-only on Darwin.
1807 for (const auto &Entry : Obj.symbols()) {
1808 const auto &Mapping = Entry.getValue();
1810 Ranges[Mapping.ObjectAddress] = std::make_pair(
1811 Mapping.ObjectAddress + Mapping.Size,
1812 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1816 void DwarfLinker::endDebugObject() {
1818 ValidRelocs.clear();
1821 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1823 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1831 /// \brief Iterate over the relocations of the given \p Section and
1832 /// store the ones that correspond to debug map entries into the
1833 /// ValidRelocs array.
1834 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1835 const object::MachOObjectFile &Obj,
1836 const DebugMapObject &DMO) {
1838 Section.getContents(Contents);
1839 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1841 for (const object::RelocationRef &Reloc : Section.relocations()) {
1842 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1843 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1844 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1845 uint64_t Offset64 = Reloc.getOffset();
1846 if ((RelocSize != 4 && RelocSize != 8)) {
1847 reportWarning(" unsupported relocation in debug_info section.");
1850 uint32_t Offset = Offset64;
1851 // Mach-o uses REL relocations, the addend is at the relocation offset.
1852 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1854 auto Sym = Reloc.getSymbol();
1855 if (Sym != Obj.symbol_end()) {
1856 ErrorOr<StringRef> SymbolName = Sym->getName();
1858 reportWarning("error getting relocation symbol name.");
1861 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
1862 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1863 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1864 // Do not store the addend. The addend was the address of the
1865 // symbol in the object file, the address in the binary that is
1866 // stored in the debug map doesn't need to be offseted.
1867 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1872 /// \brief Dispatch the valid relocation finding logic to the
1873 /// appropriate handler depending on the object file format.
1874 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1875 const object::ObjectFile &Obj,
1876 const DebugMapObject &DMO) {
1877 // Dispatch to the right handler depending on the file type.
1878 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1879 findValidRelocsMachO(Section, *MachOObj, DMO);
1881 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
1883 if (ValidRelocs.empty())
1886 // Sort the relocations by offset. We will walk the DIEs linearly in
1887 // the file, this allows us to just keep an index in the relocation
1888 // array that we advance during our walk, rather than resorting to
1889 // some associative container. See DwarfLinker::NextValidReloc.
1890 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1894 /// \brief Look for relocations in the debug_info section that match
1895 /// entries in the debug map. These relocations will drive the Dwarf
1896 /// link by indicating which DIEs refer to symbols present in the
1898 /// \returns wether there are any valid relocations in the debug info.
1899 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1900 const DebugMapObject &DMO) {
1901 // Find the debug_info section.
1902 for (const object::SectionRef &Section : Obj.sections()) {
1903 StringRef SectionName;
1904 Section.getName(SectionName);
1905 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1906 if (SectionName != "debug_info")
1908 return findValidRelocs(Section, Obj, DMO);
1913 /// \brief Checks that there is a relocation against an actual debug
1914 /// map entry between \p StartOffset and \p NextOffset.
1916 /// This function must be called with offsets in strictly ascending
1917 /// order because it never looks back at relocations it already 'went past'.
1918 /// \returns true and sets Info.InDebugMap if it is the case.
1919 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1920 CompileUnit::DIEInfo &Info) {
1921 assert(NextValidReloc == 0 ||
1922 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1923 if (NextValidReloc >= ValidRelocs.size())
1926 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1928 // We might need to skip some relocs that we didn't consider. For
1929 // example the high_pc of a discarded DIE might contain a reloc that
1930 // is in the list because it actually corresponds to the start of a
1931 // function that is in the debug map.
1932 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1933 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1935 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1938 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1939 const auto &Mapping = ValidReloc.Mapping->getValue();
1940 if (Options.Verbose)
1941 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1942 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1943 uint64_t(Mapping.ObjectAddress),
1944 uint64_t(Mapping.BinaryAddress));
1946 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1947 Mapping.ObjectAddress;
1948 Info.InDebugMap = true;
1952 /// \brief Get the starting and ending (exclusive) offset for the
1953 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1954 /// supposed to point to the position of the first attribute described
1956 /// \return [StartOffset, EndOffset) as a pair.
1957 static std::pair<uint32_t, uint32_t>
1958 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1959 unsigned Offset, const DWARFUnit &Unit) {
1960 DataExtractor Data = Unit.getDebugInfoExtractor();
1962 for (unsigned i = 0; i < Idx; ++i)
1963 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1965 uint32_t End = Offset;
1966 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1968 return std::make_pair(Offset, End);
1971 /// \brief Check if a variable describing DIE should be kept.
1972 /// \returns updated TraversalFlags.
1973 unsigned DwarfLinker::shouldKeepVariableDIE(
1974 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1975 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1976 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1978 // Global variables with constant value can always be kept.
1979 if (!(Flags & TF_InFunctionScope) &&
1980 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1981 MyInfo.InDebugMap = true;
1982 return Flags | TF_Keep;
1985 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1986 if (LocationIdx == -1U)
1989 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1990 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1991 uint32_t LocationOffset, LocationEndOffset;
1992 std::tie(LocationOffset, LocationEndOffset) =
1993 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1995 // See if there is a relocation to a valid debug map entry inside
1996 // this variable's location. The order is important here. We want to
1997 // always check in the variable has a valid relocation, so that the
1998 // DIEInfo is filled. However, we don't want a static variable in a
1999 // function to force us to keep the enclosing function.
2000 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
2001 (Flags & TF_InFunctionScope))
2004 if (Options.Verbose)
2005 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2007 return Flags | TF_Keep;
2010 /// \brief Check if a function describing DIE should be kept.
2011 /// \returns updated TraversalFlags.
2012 unsigned DwarfLinker::shouldKeepSubprogramDIE(
2013 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2014 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2015 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2017 Flags |= TF_InFunctionScope;
2019 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2020 if (LowPcIdx == -1U)
2023 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2024 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2025 uint32_t LowPcOffset, LowPcEndOffset;
2026 std::tie(LowPcOffset, LowPcEndOffset) =
2027 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2030 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2031 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2032 if (LowPc == -1ULL ||
2033 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
2036 if (Options.Verbose)
2037 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2041 DWARFFormValue HighPcValue;
2042 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2043 reportWarning("Function without high_pc. Range will be discarded.\n",
2049 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2050 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2052 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2053 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2056 // Replace the debug map range with a more accurate one.
2057 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
2058 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2062 /// \brief Check if a DIE should be kept.
2063 /// \returns updated TraversalFlags.
2064 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
2066 CompileUnit::DIEInfo &MyInfo,
2068 switch (DIE.getTag()) {
2069 case dwarf::DW_TAG_constant:
2070 case dwarf::DW_TAG_variable:
2071 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
2072 case dwarf::DW_TAG_subprogram:
2073 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
2074 case dwarf::DW_TAG_module:
2075 case dwarf::DW_TAG_imported_module:
2076 case dwarf::DW_TAG_imported_declaration:
2077 case dwarf::DW_TAG_imported_unit:
2078 // We always want to keep these.
2079 return Flags | TF_Keep;
2085 /// \brief Mark the passed DIE as well as all the ones it depends on
2088 /// This function is called by lookForDIEsToKeep on DIEs that are
2089 /// newly discovered to be needed in the link. It recursively calls
2090 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2091 /// TraversalFlags to inform it that it's not doing the primary DIE
2093 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
2094 CompileUnit::DIEInfo &MyInfo,
2095 const DebugMapObject &DMO,
2096 CompileUnit &CU, bool UseODR) {
2097 const DWARFUnit &Unit = CU.getOrigUnit();
2100 // First mark all the parent chain as kept.
2101 unsigned AncestorIdx = MyInfo.ParentIdx;
2102 while (!CU.getInfo(AncestorIdx).Keep) {
2103 unsigned ODRFlag = UseODR ? TF_ODR : 0;
2104 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
2105 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
2106 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2109 // Then we need to mark all the DIEs referenced by this DIE's
2110 // attributes as kept.
2111 DataExtractor Data = Unit.getDebugInfoExtractor();
2112 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2113 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2115 // Mark all DIEs referenced through atttributes as kept.
2116 for (const auto &AttrSpec : Abbrev->attributes()) {
2117 DWARFFormValue Val(AttrSpec.Form);
2119 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2120 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2124 Val.extractValue(Data, &Offset, &Unit);
2125 CompileUnit *ReferencedCU;
2126 if (const auto *RefDIE =
2127 resolveDIEReference(Val, Unit, DIE, ReferencedCU)) {
2128 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2129 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2130 // If the referenced DIE has a DeclContext that has already been
2131 // emitted, then do not keep the one in this CU. We'll link to
2132 // the canonical DIE in cloneDieReferenceAttribute.
2133 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2134 // be necessary and could be advantageously replaced by
2135 // ReferencedCU->hasODR() && CU.hasODR().
2136 // FIXME: compatibility with dsymutil-classic. There is no
2137 // reason not to unique ref_addr references.
2138 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2139 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2140 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2143 unsigned ODRFlag = UseODR ? TF_ODR : 0;
2144 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
2145 TF_Keep | TF_DependencyWalk | ODRFlag);
2150 /// \brief Recursively walk the \p DIE tree and look for DIEs to
2151 /// keep. Store that information in \p CU's DIEInfo.
2153 /// This function is the entry point of the DIE selection
2154 /// algorithm. It is expected to walk the DIE tree in file order and
2155 /// (though the mediation of its helper) call hasValidRelocation() on
2156 /// each DIE that might be a 'root DIE' (See DwarfLinker class
2158 /// While walking the dependencies of root DIEs, this function is
2159 /// also called, but during these dependency walks the file order is
2160 /// not respected. The TF_DependencyWalk flag tells us which kind of
2161 /// traversal we are currently doing.
2162 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
2163 const DebugMapObject &DMO, CompileUnit &CU,
2165 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
2166 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2167 bool AlreadyKept = MyInfo.Keep;
2169 // If the Keep flag is set, we are marking a required DIE's
2170 // dependencies. If our target is already marked as kept, we're all
2172 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2175 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
2176 // because it would screw up the relocation finding logic.
2177 if (!(Flags & TF_DependencyWalk))
2178 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
2180 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
2181 if (!AlreadyKept && (Flags & TF_Keep)) {
2182 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2183 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, UseOdr);
2185 // The TF_ParentWalk flag tells us that we are currently walking up
2186 // the parent chain of a required DIE, and we don't want to mark all
2187 // the children of the parents as kept (consider for example a
2188 // DW_TAG_namespace node in the parent chain). There are however a
2189 // set of DIE types for which we want to ignore that directive and still
2190 // walk their children.
2191 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
2192 Flags &= ~TF_ParentWalk;
2194 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
2197 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
2198 Child = Child->getSibling())
2199 lookForDIEsToKeep(*Child, DMO, CU, Flags);
2202 /// \brief Assign an abbreviation numer to \p Abbrev.
2204 /// Our DIEs get freed after every DebugMapObject has been processed,
2205 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2206 /// the instances hold by the DIEs. When we encounter an abbreviation
2207 /// that we don't know, we create a permanent copy of it.
2208 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2209 // Check the set for priors.
2210 FoldingSetNodeID ID;
2213 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2215 // If it's newly added.
2217 // Assign existing abbreviation number.
2218 Abbrev.setNumber(InSet->getNumber());
2220 // Add to abbreviation list.
2221 Abbreviations.push_back(
2222 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2223 for (const auto &Attr : Abbrev.getData())
2224 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2225 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2226 // Assign the unique abbreviation number.
2227 Abbrev.setNumber(Abbreviations.size());
2228 Abbreviations.back()->setNumber(Abbreviations.size());
2232 /// \brief Clone a string attribute described by \p AttrSpec and add
2234 /// \returns the size of the new attribute.
2235 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
2236 const DWARFFormValue &Val,
2237 const DWARFUnit &U) {
2238 // Switch everything to out of line strings.
2239 const char *String = *Val.getAsCString(&U);
2240 unsigned Offset = StringPool.getStringOffset(String);
2241 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
2242 DIEInteger(Offset));
2246 /// \brief Clone an attribute referencing another DIE and add
2248 /// \returns the size of the new attribute.
2249 unsigned DwarfLinker::cloneDieReferenceAttribute(
2250 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2251 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
2252 CompileUnit &Unit) {
2253 const DWARFUnit &U = Unit.getOrigUnit();
2254 uint32_t Ref = *Val.getAsReference(&U);
2255 DIE *NewRefDie = nullptr;
2256 CompileUnit *RefUnit = nullptr;
2257 DeclContext *Ctxt = nullptr;
2259 const DWARFDebugInfoEntryMinimal *RefDie =
2260 resolveDIEReference(Val, U, InputDIE, RefUnit);
2262 // If the referenced DIE is not found, drop the attribute.
2266 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2267 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
2269 // If we already have emitted an equivalent DeclContext, just point
2271 if (isODRAttribute(AttrSpec.Attr)) {
2272 Ctxt = RefInfo.Ctxt;
2273 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2274 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2275 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2276 dwarf::DW_FORM_ref_addr, Attr);
2277 return getRefAddrSize(U);
2281 if (!RefInfo.Clone) {
2282 assert(Ref > InputDIE.getOffset());
2283 // We haven't cloned this DIE yet. Just create an empty one and
2284 // store it. It'll get really cloned when we process it.
2285 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
2287 NewRefDie = RefInfo.Clone;
2289 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2290 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
2291 // We cannot currently rely on a DIEEntry to emit ref_addr
2292 // references, because the implementation calls back to DwarfDebug
2293 // to find the unit offset. (We don't have a DwarfDebug)
2294 // FIXME: we should be able to design DIEEntry reliance on
2297 if (Ref < InputDIE.getOffset()) {
2298 // We must have already cloned that DIE.
2299 uint32_t NewRefOffset =
2300 RefUnit->getStartOffset() + NewRefDie->getOffset();
2301 Attr = NewRefOffset;
2302 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2303 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
2305 // A forward reference. Note and fixup later.
2307 Unit.noteForwardReference(
2308 NewRefDie, RefUnit, Ctxt,
2309 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2310 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
2312 return getRefAddrSize(U);
2315 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2316 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
2320 /// \brief Clone an attribute of block form (locations, constants) and add
2322 /// \returns the size of the new attribute.
2323 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
2324 const DWARFFormValue &Val,
2325 unsigned AttrSize) {
2328 DIELoc *Loc = nullptr;
2329 DIEBlock *Block = nullptr;
2330 // Just copy the block data over.
2331 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
2332 Loc = new (DIEAlloc) DIELoc;
2333 DIELocs.push_back(Loc);
2335 Block = new (DIEAlloc) DIEBlock;
2336 DIEBlocks.push_back(Block);
2338 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
2341 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2342 dwarf::Form(AttrSpec.Form), Loc);
2344 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2345 dwarf::Form(AttrSpec.Form), Block);
2346 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2347 for (auto Byte : Bytes)
2348 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2349 dwarf::DW_FORM_data1, DIEInteger(Byte));
2350 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2351 // the DIE class, this if could be replaced by
2352 // Attr->setSize(Bytes.size()).
2355 Loc->ComputeSize(&Streamer->getAsmPrinter());
2357 Block->ComputeSize(&Streamer->getAsmPrinter());
2359 Die.addValue(DIEAlloc, Value);
2363 /// \brief Clone an address attribute and add it to \p Die.
2364 /// \returns the size of the new attribute.
2365 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
2366 const DWARFFormValue &Val,
2367 const CompileUnit &Unit,
2368 AttributesInfo &Info) {
2369 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
2370 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2371 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2372 Die.getTag() == dwarf::DW_TAG_lexical_block)
2373 Addr += Info.PCOffset;
2374 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2375 Addr = Unit.getLowPc();
2376 if (Addr == UINT64_MAX)
2379 Info.HasLowPc = true;
2380 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
2381 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2382 if (uint64_t HighPc = Unit.getHighPc())
2387 // If we have a high_pc recorded for the input DIE, use
2388 // it. Otherwise (when no relocations where applied) just use the
2389 // one we just decoded.
2390 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
2393 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
2394 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
2395 return Unit.getOrigUnit().getAddressByteSize();
2398 /// \brief Clone a scalar attribute and add it to \p Die.
2399 /// \returns the size of the new attribute.
2400 unsigned DwarfLinker::cloneScalarAttribute(
2401 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2402 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
2403 AttributesInfo &Info) {
2405 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2406 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2407 if (Unit.getLowPc() == -1ULL)
2409 // Dwarf >= 4 high_pc is an size, not an address.
2410 Value = Unit.getHighPc() - Unit.getLowPc();
2411 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
2412 Value = *Val.getAsSectionOffset();
2413 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2414 Value = *Val.getAsSignedConstant();
2415 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2416 Value = *OptionalValue;
2418 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
2419 &Unit.getOrigUnit(), &InputDIE);
2422 PatchLocation Patch =
2423 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2424 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
2425 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
2426 Unit.noteRangeAttribute(Die, Patch);
2427 // A more generic way to check for location attributes would be
2428 // nice, but it's very unlikely that any other attribute needs a
2430 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2431 AttrSpec.Attr == dwarf::DW_AT_frame_base)
2432 Unit.noteLocationAttribute(Patch, Info.PCOffset);
2433 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2434 Info.IsDeclaration = true;
2439 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2440 /// value \p Val, and add it to \p Die.
2441 /// \returns the size of the cloned attribute.
2442 unsigned DwarfLinker::cloneAttribute(DIE &Die,
2443 const DWARFDebugInfoEntryMinimal &InputDIE,
2445 const DWARFFormValue &Val,
2446 const AttributeSpec AttrSpec,
2447 unsigned AttrSize, AttributesInfo &Info) {
2448 const DWARFUnit &U = Unit.getOrigUnit();
2450 switch (AttrSpec.Form) {
2451 case dwarf::DW_FORM_strp:
2452 case dwarf::DW_FORM_string:
2453 return cloneStringAttribute(Die, AttrSpec, Val, U);
2454 case dwarf::DW_FORM_ref_addr:
2455 case dwarf::DW_FORM_ref1:
2456 case dwarf::DW_FORM_ref2:
2457 case dwarf::DW_FORM_ref4:
2458 case dwarf::DW_FORM_ref8:
2459 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
2461 case dwarf::DW_FORM_block:
2462 case dwarf::DW_FORM_block1:
2463 case dwarf::DW_FORM_block2:
2464 case dwarf::DW_FORM_block4:
2465 case dwarf::DW_FORM_exprloc:
2466 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2467 case dwarf::DW_FORM_addr:
2468 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
2469 case dwarf::DW_FORM_data1:
2470 case dwarf::DW_FORM_data2:
2471 case dwarf::DW_FORM_data4:
2472 case dwarf::DW_FORM_data8:
2473 case dwarf::DW_FORM_udata:
2474 case dwarf::DW_FORM_sdata:
2475 case dwarf::DW_FORM_sec_offset:
2476 case dwarf::DW_FORM_flag:
2477 case dwarf::DW_FORM_flag_present:
2478 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2481 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2488 /// \brief Apply the valid relocations found by findValidRelocs() to
2489 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
2490 /// in the debug_info section.
2492 /// Like for findValidRelocs(), this function must be called with
2493 /// monotonic \p BaseOffset values.
2495 /// \returns wether any reloc has been applied.
2496 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2497 uint32_t BaseOffset, bool isLittleEndian) {
2498 assert((NextValidReloc == 0 ||
2499 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2500 "BaseOffset should only be increasing.");
2501 if (NextValidReloc >= ValidRelocs.size())
2504 // Skip relocs that haven't been applied.
2505 while (NextValidReloc < ValidRelocs.size() &&
2506 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2509 bool Applied = false;
2510 uint64_t EndOffset = BaseOffset + Data.size();
2511 while (NextValidReloc < ValidRelocs.size() &&
2512 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2513 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2514 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2515 assert(ValidReloc.Offset - BaseOffset < Data.size());
2516 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2518 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2519 Value += ValidReloc.Addend;
2520 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2521 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2522 Buf[i] = uint8_t(Value >> (Index * 8));
2524 assert(ValidReloc.Size <= sizeof(Buf));
2525 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2532 static bool isTypeTag(uint16_t Tag) {
2534 case dwarf::DW_TAG_array_type:
2535 case dwarf::DW_TAG_class_type:
2536 case dwarf::DW_TAG_enumeration_type:
2537 case dwarf::DW_TAG_pointer_type:
2538 case dwarf::DW_TAG_reference_type:
2539 case dwarf::DW_TAG_string_type:
2540 case dwarf::DW_TAG_structure_type:
2541 case dwarf::DW_TAG_subroutine_type:
2542 case dwarf::DW_TAG_typedef:
2543 case dwarf::DW_TAG_union_type:
2544 case dwarf::DW_TAG_ptr_to_member_type:
2545 case dwarf::DW_TAG_set_type:
2546 case dwarf::DW_TAG_subrange_type:
2547 case dwarf::DW_TAG_base_type:
2548 case dwarf::DW_TAG_const_type:
2549 case dwarf::DW_TAG_constant:
2550 case dwarf::DW_TAG_file_type:
2551 case dwarf::DW_TAG_namelist:
2552 case dwarf::DW_TAG_packed_type:
2553 case dwarf::DW_TAG_volatile_type:
2554 case dwarf::DW_TAG_restrict_type:
2555 case dwarf::DW_TAG_interface_type:
2556 case dwarf::DW_TAG_unspecified_type:
2557 case dwarf::DW_TAG_shared_type:
2565 /// \brief Recursively clone \p InputDIE's subtrees that have been
2566 /// selected to appear in the linked output.
2568 /// \param OutOffset is the Offset where the newly created DIE will
2569 /// lie in the linked compile unit.
2571 /// \returns the cloned DIE object or null if nothing was selected.
2572 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
2573 CompileUnit &Unit, int64_t PCOffset,
2574 uint32_t OutOffset) {
2575 DWARFUnit &U = Unit.getOrigUnit();
2576 unsigned Idx = U.getDIEIndex(&InputDIE);
2577 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2579 // Should the DIE appear in the output?
2580 if (!Unit.getInfo(Idx).Keep)
2583 uint32_t Offset = InputDIE.getOffset();
2584 // The DIE might have been already created by a forward reference
2585 // (see cloneDieReferenceAttribute()).
2586 DIE *Die = Info.Clone;
2588 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
2589 assert(Die->getTag() == InputDIE.getTag());
2590 Die->setOffset(OutOffset);
2591 if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2592 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2593 !Info.Ctxt->getCanonicalDIEOffset()) {
2594 // We are about to emit a DIE that is the root of its own valid
2595 // DeclContext tree. Make the current offset the canonical offset
2596 // for this context.
2597 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2600 // Extract and clone every attribute.
2601 DataExtractor Data = U.getDebugInfoExtractor();
2602 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
2603 AttributesInfo AttrInfo;
2605 // We could copy the data only if we need to aply a relocation to
2606 // it. After testing, it seems there is no performance downside to
2607 // doing the copy unconditionally, and it makes the code simpler.
2608 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2609 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2610 // Modify the copy with relocated addresses.
2611 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2612 // If we applied relocations, we store the value of high_pc that was
2613 // potentially stored in the input DIE. If high_pc is an address
2614 // (Dwarf version == 2), then it might have been relocated to a
2615 // totally unrelated value (because the end address in the object
2616 // file might be start address of another function which got moved
2617 // independantly by the linker). The computation of the actual
2618 // high_pc value is done in cloneAddressAttribute().
2619 AttrInfo.OrigHighPc =
2620 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2623 // Reset the Offset to 0 as we will be working on the local copy of
2627 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2628 Offset += getULEB128Size(Abbrev->getCode());
2630 // We are entering a subprogram. Get and propagate the PCOffset.
2631 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2632 PCOffset = Info.AddrAdjust;
2633 AttrInfo.PCOffset = PCOffset;
2635 for (const auto &AttrSpec : Abbrev->attributes()) {
2636 DWARFFormValue Val(AttrSpec.Form);
2637 uint32_t AttrSize = Offset;
2638 Val.extractValue(Data, &Offset, &U);
2639 AttrSize = Offset - AttrSize;
2642 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2645 // Look for accelerator entries.
2646 uint16_t Tag = InputDIE.getTag();
2647 // FIXME: This is slightly wrong. An inline_subroutine without a
2648 // low_pc, but with AT_ranges might be interesting to get into the
2649 // accelerator tables too. For now stick with dsymutil's behavior.
2650 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2651 Tag != dwarf::DW_TAG_compile_unit &&
2652 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2653 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2654 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2655 AttrInfo.MangledNameOffset,
2656 Tag == dwarf::DW_TAG_inlined_subroutine);
2658 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2659 Tag == dwarf::DW_TAG_inlined_subroutine);
2660 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2661 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2662 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2665 DIEAbbrev NewAbbrev = Die->generateAbbrev();
2666 // If a scope DIE is kept, we must have kept at least one child. If
2667 // it's not the case, we'll just be emitting one wasteful end of
2668 // children marker, but things won't break.
2669 if (InputDIE.hasChildren())
2670 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2671 // Assign a permanent abbrev number
2672 AssignAbbrev(NewAbbrev);
2673 Die->setAbbrevNumber(NewAbbrev.getNumber());
2675 // Add the size of the abbreviation number to the output offset.
2676 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2678 if (!Abbrev->hasChildren()) {
2680 Die->setSize(OutOffset - Die->getOffset());
2684 // Recursively clone children.
2685 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2686 Child = Child->getSibling()) {
2687 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
2688 Die->addChild(Clone);
2689 OutOffset = Clone->getOffset() + Clone->getSize();
2693 // Account for the end of children marker.
2694 OutOffset += sizeof(int8_t);
2696 Die->setSize(OutOffset - Die->getOffset());
2700 /// \brief Patch the input object file relevant debug_ranges entries
2701 /// and emit them in the output file. Update the relevant attributes
2702 /// to point at the new entries.
2703 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2704 DWARFContext &OrigDwarf) const {
2705 DWARFDebugRangeList RangeList;
2706 const auto &FunctionRanges = Unit.getFunctionRanges();
2707 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2708 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2709 OrigDwarf.isLittleEndian(), AddressSize);
2710 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2711 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2712 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
2713 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2714 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2715 // Ranges addresses are based on the unit's low_pc. Compute the
2716 // offset we need to apply to adapt to the the new unit's low_pc.
2717 int64_t UnitPcOffset = 0;
2718 if (OrigLowPc != -1ULL)
2719 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2721 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2722 uint32_t Offset = RangeAttribute.get();
2723 RangeAttribute.set(Streamer->getRangesSectionSize());
2724 RangeList.extract(RangeExtractor, &Offset);
2725 const auto &Entries = RangeList.getEntries();
2726 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2728 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2729 First.StartAddress >= CurrRange.stop()) {
2730 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2731 if (CurrRange == InvalidRange ||
2732 CurrRange.start() > First.StartAddress + OrigLowPc) {
2733 reportWarning("no mapping for range.");
2738 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2743 /// \brief Generate the debug_aranges entries for \p Unit and if the
2744 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2745 /// contribution for this attribute.
2746 /// FIXME: this could actually be done right in patchRangesForUnit,
2747 /// but for the sake of initial bit-for-bit compatibility with legacy
2748 /// dsymutil, we have to do it in a delayed pass.
2749 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2750 auto Attr = Unit.getUnitRangesAttribute();
2752 Attr->set(Streamer->getRangesSectionSize());
2753 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
2756 /// \brief Insert the new line info sequence \p Seq into the current
2757 /// set of already linked line info \p Rows.
2758 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2759 std::vector<DWARFDebugLine::Row> &Rows) {
2763 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2764 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2769 auto InsertPoint = std::lower_bound(
2770 Rows.begin(), Rows.end(), Seq.front(),
2771 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2772 return LHS.Address < RHS.Address;
2775 // FIXME: this only removes the unneeded end_sequence if the
2776 // sequences have been inserted in order. using a global sort like
2777 // described in patchLineTableForUnit() and delaying the end_sequene
2778 // elimination to emitLineTableForUnit() we can get rid of all of them.
2779 if (InsertPoint != Rows.end() &&
2780 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2781 *InsertPoint = Seq.front();
2782 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2784 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2790 static void patchStmtList(DIE &Die, DIEInteger Offset) {
2791 for (auto &V : Die.values())
2792 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2793 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2797 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2800 /// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2801 /// recreate a relocated version of these for the address ranges that
2802 /// are present in the binary.
2803 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2804 DWARFContext &OrigDwarf) {
2805 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
2806 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2807 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2808 if (StmtList == -1ULL)
2811 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2812 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2813 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
2815 // Parse the original line info for the unit.
2816 DWARFDebugLine::LineTable LineTable;
2817 uint32_t StmtOffset = StmtList;
2818 StringRef LineData = OrigDwarf.getLineSection().Data;
2819 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2820 Unit.getOrigUnit().getAddressByteSize());
2821 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2824 // This vector is the output line table.
2825 std::vector<DWARFDebugLine::Row> NewRows;
2826 NewRows.reserve(LineTable.Rows.size());
2828 // Current sequence of rows being extracted, before being inserted
2830 std::vector<DWARFDebugLine::Row> Seq;
2831 const auto &FunctionRanges = Unit.getFunctionRanges();
2832 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2834 // FIXME: This logic is meant to generate exactly the same output as
2835 // Darwin's classic dsynutil. There is a nicer way to implement this
2836 // by simply putting all the relocated line info in NewRows and simply
2837 // sorting NewRows before passing it to emitLineTableForUnit. This
2838 // should be correct as sequences for a function should stay
2839 // together in the sorted output. There are a few corner cases that
2840 // look suspicious though, and that required to implement the logic
2841 // this way. Revisit that once initial validation is finished.
2843 // Iterate over the object file line info and extract the sequences
2844 // that correspond to linked functions.
2845 for (auto &Row : LineTable.Rows) {
2846 // Check wether we stepped out of the range. The range is
2847 // half-open, but consider accept the end address of the range if
2848 // it is marked as end_sequence in the input (because in that
2849 // case, the relocation offset is accurate and that entry won't
2850 // serve as the start of another function).
2851 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2852 Row.Address > CurrRange.stop() ||
2853 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2854 // We just stepped out of a known range. Insert a end_sequence
2855 // corresponding to the end of the range.
2856 uint64_t StopAddress = CurrRange != InvalidRange
2857 ? CurrRange.stop() + CurrRange.value()
2859 CurrRange = FunctionRanges.find(Row.Address);
2860 bool CurrRangeValid =
2861 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2862 if (!CurrRangeValid) {
2863 CurrRange = InvalidRange;
2864 if (StopAddress != -1ULL) {
2865 // Try harder by looking in the DebugMapObject function
2866 // ranges map. There are corner cases where this finds a
2867 // valid entry. It's unclear if this is right or wrong, but
2868 // for now do as dsymutil.
2869 // FIXME: Understand exactly what cases this addresses and
2870 // potentially remove it along with the Ranges map.
2871 auto Range = Ranges.lower_bound(Row.Address);
2872 if (Range != Ranges.begin() && Range != Ranges.end())
2875 if (Range != Ranges.end() && Range->first <= Row.Address &&
2876 Range->second.first >= Row.Address) {
2877 StopAddress = Row.Address + Range->second.second;
2881 if (StopAddress != -1ULL && !Seq.empty()) {
2882 // Insert end sequence row with the computed end address, but
2883 // the same line as the previous one.
2884 Seq.emplace_back(Seq.back());
2885 Seq.back().Address = StopAddress;
2886 Seq.back().EndSequence = 1;
2887 Seq.back().PrologueEnd = 0;
2888 Seq.back().BasicBlock = 0;
2889 Seq.back().EpilogueBegin = 0;
2890 insertLineSequence(Seq, NewRows);
2893 if (!CurrRangeValid)
2897 // Ignore empty sequences.
2898 if (Row.EndSequence && Seq.empty())
2901 // Relocate row address and add it to the current sequence.
2902 Row.Address += CurrRange.value();
2903 Seq.emplace_back(Row);
2905 if (Row.EndSequence)
2906 insertLineSequence(Seq, NewRows);
2909 // Finished extracting, now emit the line tables.
2910 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2911 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2912 // prologue over and that works because we act as both producer and
2913 // consumer. It would be nicer to have a real configurable line
2915 if (LineTable.Prologue.Version != 2 ||
2916 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2917 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2918 LineTable.Prologue.OpcodeBase != 13)
2919 reportWarning("line table paramters mismatch. Cannot emit.");
2921 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2922 LineTable.Prologue.MinInstLength, NewRows,
2923 Unit.getOrigUnit().getAddressByteSize());
2926 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2927 Streamer->emitPubNamesForUnit(Unit);
2928 Streamer->emitPubTypesForUnit(Unit);
2931 /// \brief Read the frame info stored in the object, and emit the
2932 /// patched frame descriptions for the linked binary.
2934 /// This is actually pretty easy as the data of the CIEs and FDEs can
2935 /// be considered as black boxes and moved as is. The only thing to do
2936 /// is to patch the addresses in the headers.
2937 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2938 DWARFContext &OrigDwarf,
2939 unsigned AddrSize) {
2940 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2941 if (FrameData.empty())
2944 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2945 uint32_t InputOffset = 0;
2947 // Store the data of the CIEs defined in this object, keyed by their
2949 DenseMap<uint32_t, StringRef> LocalCIES;
2951 while (Data.isValidOffset(InputOffset)) {
2952 uint32_t EntryOffset = InputOffset;
2953 uint32_t InitialLength = Data.getU32(&InputOffset);
2954 if (InitialLength == 0xFFFFFFFF)
2955 return reportWarning("Dwarf64 bits no supported");
2957 uint32_t CIEId = Data.getU32(&InputOffset);
2958 if (CIEId == 0xFFFFFFFF) {
2959 // This is a CIE, store it.
2960 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2961 LocalCIES[EntryOffset] = CIEData;
2962 // The -4 is to account for the CIEId we just read.
2963 InputOffset += InitialLength - 4;
2967 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2969 // Some compilers seem to emit frame info that doesn't start at
2970 // the function entry point, thus we can't just lookup the address
2971 // in the debug map. Use the linker's range map to see if the FDE
2972 // describes something that we can relocate.
2973 auto Range = Ranges.upper_bound(Loc);
2974 if (Range != Ranges.begin())
2976 if (Range == Ranges.end() || Range->first > Loc ||
2977 Range->second.first <= Loc) {
2978 // The +4 is to account for the size of the InitialLength field itself.
2979 InputOffset = EntryOffset + InitialLength + 4;
2983 // This is an FDE, and we have a mapping.
2984 // Have we already emitted a corresponding CIE?
2985 StringRef CIEData = LocalCIES[CIEId];
2986 if (CIEData.empty())
2987 return reportWarning("Inconsistent debug_frame content. Dropping.");
2989 // Look if we already emitted a CIE that corresponds to the
2990 // referenced one (the CIE data is the key of that lookup).
2991 auto IteratorInserted = EmittedCIEs.insert(
2992 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2993 // If there is no CIE yet for this ID, emit it.
2994 if (IteratorInserted.second ||
2995 // FIXME: dsymutil-classic only caches the last used CIE for
2996 // reuse. Mimic that behavior for now. Just removing that
2997 // second half of the condition and the LastCIEOffset variable
2998 // makes the code DTRT.
2999 LastCIEOffset != IteratorInserted.first->getValue()) {
3000 LastCIEOffset = Streamer->getFrameSectionSize();
3001 IteratorInserted.first->getValue() = LastCIEOffset;
3002 Streamer->emitCIE(CIEData);
3005 // Emit the FDE with updated address and CIE pointer.
3006 // (4 + AddrSize) is the size of the CIEId + initial_location
3007 // fields that will get reconstructed by emitFDE().
3008 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3009 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3010 Loc + Range->second.second,
3011 FrameData.substr(InputOffset, FDERemainingBytes));
3012 InputOffset += FDERemainingBytes;
3016 ErrorOr<const object::ObjectFile &>
3017 DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3018 const DebugMap &Map) {
3020 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
3021 if (std::error_code EC = ErrOrObjs.getError())
3022 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3023 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3024 if (std::error_code EC = ErrOrObj.getError())
3025 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3029 bool DwarfLinker::link(const DebugMap &Map) {
3031 if (Map.begin() == Map.end()) {
3032 errs() << "Empty debug map.\n";
3036 if (!createStreamer(Map.getTriple(), OutputFilename))
3039 // Size of the DIEs (and headers) generated for the linked output.
3040 uint64_t OutputDebugInfoSize = 0;
3041 // A unique ID that identifies each compile unit.
3042 unsigned UnitID = 0;
3043 for (const auto &Obj : Map.objects()) {
3044 CurrentDebugObject = Obj.get();
3046 if (Options.Verbose)
3047 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
3048 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3052 // Look for relocations that correspond to debug map entries.
3053 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
3054 if (Options.Verbose)
3055 outs() << "No valid relocations found. Skipping.\n";
3059 // Setup access to the debug info.
3060 DWARFContextInMemory DwarfContext(*ErrOrObj);
3061 startDebugObject(DwarfContext, *Obj);
3063 // In a first phase, just read in the debug info and store the DIE
3064 // parent links that we will use during the next phase.
3065 for (const auto &CU : DwarfContext.compile_units()) {
3066 auto *CUDie = CU->getUnitDIE(false);
3067 if (Options.Verbose) {
3068 outs() << "Input compilation unit:";
3069 CUDie->dump(outs(), CU.get(), 0);
3071 Units.emplace_back(*CU, UnitID++, !Options.NoODR);
3072 gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
3073 StringPool, ODRContexts);
3076 // Then mark all the DIEs that need to be present in the linked
3077 // output and collect some information about them. Note that this
3078 // loop can not be merged with the previous one becaue cross-cu
3079 // references require the ParentIdx to be setup for every CU in
3080 // the object file before calling this.
3081 for (auto &CurrentUnit : Units)
3082 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
3085 // The calls to applyValidRelocs inside cloneDIE will walk the
3086 // reloc array again (in the same way findValidRelocsInDebugInfo()
3087 // did). We need to reset the NextValidReloc index to the beginning.
3090 // Construct the output DIE tree by cloning the DIEs we chose to
3091 // keep above. If there are no valid relocs, then there's nothing
3093 if (!ValidRelocs.empty())
3094 for (auto &CurrentUnit : Units) {
3095 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
3096 CurrentUnit.setStartOffset(OutputDebugInfoSize);
3097 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
3098 11 /* Unit Header size */);
3099 CurrentUnit.setOutputUnitDIE(OutputDIE);
3100 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3101 if (Options.NoOutput)
3103 // FIXME: for compatibility with the classic dsymutil, we emit
3104 // an empty line table for the unit, even if the unit doesn't
3105 // actually exist in the DIE tree.
3106 patchLineTableForUnit(CurrentUnit, DwarfContext);
3109 patchRangesForUnit(CurrentUnit, DwarfContext);
3110 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3111 emitAcceleratorEntriesForUnit(CurrentUnit);
3114 // Emit all the compile unit's debug information.
3115 if (!ValidRelocs.empty() && !Options.NoOutput)
3116 for (auto &CurrentUnit : Units) {
3117 generateUnitRanges(CurrentUnit);
3118 CurrentUnit.fixupForwardReferences();
3119 Streamer->emitCompileUnitHeader(CurrentUnit);
3120 if (!CurrentUnit.getOutputUnitDIE())
3122 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
3125 if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
3126 patchFrameInfoForObject(*Obj, DwarfContext,
3127 Units[0].getOrigUnit().getAddressByteSize());
3129 // Clean-up before starting working on the next object.
3133 // Emit everything that's global.
3134 if (!Options.NoOutput) {
3135 Streamer->emitAbbrevs(Abbreviations);
3136 Streamer->emitStrings(StringPool);
3139 return Options.NoOutput ? true : Streamer->finish();
3143 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3144 const LinkOptions &Options) {
3145 DwarfLinker Linker(OutputFilename, Options);
3146 return Linker.link(DM);