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 "MachOUtils.h"
14 #include "NonRelocatableStringpool.h"
15 #include "llvm/ADT/IntervalMap.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/DIE.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
22 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
23 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
24 #include "llvm/MC/MCAsmBackend.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCCodeEmitter.h"
28 #include "llvm/MC/MCDwarf.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/Object/MachO.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/LEB128.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetOptions.h"
48 template <typename KeyT, typename ValT>
49 using HalfOpenIntervalMap =
50 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
51 IntervalMapHalfOpenInfo<KeyT>>;
53 typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
55 // FIXME: Delete this structure.
56 struct PatchLocation {
57 DIE::value_iterator I;
59 PatchLocation() = default;
60 PatchLocation(DIE::value_iterator I) : I(I) {}
62 void set(uint64_t New) const {
65 assert(Old.getType() == DIEValue::isInteger);
66 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
69 uint64_t get() const {
71 return I->getDIEInteger().getValue();
78 /// A DeclContext is a named program scope that is used for ODR
79 /// uniquing of types.
80 /// The set of DeclContext for the ODR-subject parts of a Dwarf link
81 /// is expanded (and uniqued) with each new object file processed. We
82 /// need to determine the context of each DIE in an linked object file
83 /// to see if the corresponding type has already been emitted.
85 /// The contexts are conceptually organised as a tree (eg. a function
86 /// scope is contained in a namespace scope that contains other
87 /// scopes), but storing/accessing them in an actual tree is too
88 /// inefficient: we need to be able to very quickly query a context
89 /// for a given child context by name. Storing a StringMap in each
90 /// DeclContext would be too space inefficient.
91 /// The solution here is to give each DeclContext a link to its parent
92 /// (this allows to walk up the tree), but to query the existance of a
93 /// specific DeclContext using a separate DenseMap keyed on the hash
94 /// of the fully qualified name of the context.
96 unsigned QualifiedNameHash;
102 const DeclContext &Parent;
103 const DWARFDebugInfoEntryMinimal *LastSeenDIE;
104 uint32_t LastSeenCompileUnitID;
105 uint32_t CanonicalDIEOffset;
110 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
113 : QualifiedNameHash(0), Line(0), ByteSize(0),
114 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
115 LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
117 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
118 StringRef Name, StringRef File, const DeclContext &Parent,
119 const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
121 : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
122 Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
123 LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
125 uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
127 bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
129 uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
130 void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
132 uint16_t getTag() const { return Tag; }
133 StringRef getName() const { return Name; }
136 /// Info type for the DenseMap storing the DeclContext pointers.
137 struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
138 using DenseMapInfo<DeclContext *>::getEmptyKey;
139 using DenseMapInfo<DeclContext *>::getTombstoneKey;
141 static unsigned getHashValue(const DeclContext *Ctxt) {
142 return Ctxt->QualifiedNameHash;
145 static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
146 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
148 return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
149 LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
150 LHS->Name.data() == RHS->Name.data() &&
151 LHS->File.data() == RHS->File.data() &&
152 LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
156 /// This class gives a tree-like API to the DenseMap that stores the
157 /// DeclContext objects. It also holds the BumpPtrAllocator where
158 /// these objects will be allocated.
159 class DeclContextTree {
160 BumpPtrAllocator Allocator;
162 DeclContext::Map Contexts;
165 /// Get the child of \a Context described by \a DIE in \a Unit. The
166 /// required strings will be interned in \a StringPool.
167 /// \returns The child DeclContext along with one bit that is set if
168 /// this context is invalid.
169 /// FIXME: the invalid bit along the return value is to emulate some
170 /// dsymutil-classic functionality. See the fucntion definition for
171 /// a more thorough discussion of its use.
172 PointerIntPair<DeclContext *, 1>
173 getChildDeclContext(DeclContext &Context,
174 const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
175 NonRelocatableStringpool &StringPool);
177 DeclContext &getRoot() { return Root; }
180 /// \brief Stores all information relating to a compile unit, be it in
181 /// its original instance in the object file to its brand new cloned
182 /// and linked DIE tree.
185 /// \brief Information gathered about a DIE in the object file.
187 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
188 DeclContext *Ctxt; ///< ODR Declaration context.
189 DIE *Clone; ///< Cloned version of that DIE.
190 uint32_t ParentIdx; ///< The index of this DIE's parent.
191 bool Keep; ///< Is the DIE part of the linked output?
192 bool InDebugMap; ///< Was this DIE's entity found in the map?
195 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR)
196 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
198 Info.resize(OrigUnit.getNumDIEs());
200 const auto *CUDie = OrigUnit.getUnitDIE(false);
201 unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
202 &OrigUnit, dwarf::DW_AT_language, 0);
203 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
204 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
205 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
206 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
207 Lang == dwarf::DW_LANG_ObjC_plus_plus);
210 CompileUnit(CompileUnit &&RHS)
211 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
212 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
213 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
214 // The CompileUnit container has been 'reserve()'d with the right
215 // size. We cannot move the IntervalMap anyway.
216 llvm_unreachable("CompileUnits should not be moved.");
219 DWARFUnit &getOrigUnit() const { return OrigUnit; }
221 unsigned getUniqueID() const { return ID; }
223 DIE *getOutputUnitDIE() const { return CUDie; }
224 void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
226 bool hasODR() const { return HasODR; }
228 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
229 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
231 uint64_t getStartOffset() const { return StartOffset; }
232 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
233 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
235 uint64_t getLowPc() const { return LowPc; }
236 uint64_t getHighPc() const { return HighPc; }
238 Optional<PatchLocation> getUnitRangesAttribute() const {
239 return UnitRangeAttribute;
241 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
242 const std::vector<PatchLocation> &getRangesAttributes() const {
243 return RangeAttributes;
246 const std::vector<std::pair<PatchLocation, int64_t>> &
247 getLocationAttributes() const {
248 return LocationAttributes;
251 /// \brief Compute the end offset for this unit. Must be
252 /// called after the CU's DIEs have been cloned.
253 /// \returns the next unit offset (which is also the current
254 /// debug_info section size).
255 uint64_t computeNextUnitOffset();
257 /// \brief Keep track of a forward reference to DIE \p Die in \p
258 /// RefUnit by \p Attr. The attribute should be fixed up later to
259 /// point to the absolute offset of \p Die in the debug_info section
260 /// or to the canonical offset of \p Ctxt if it is non-null.
261 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
262 DeclContext *Ctxt, PatchLocation Attr);
264 /// \brief Apply all fixups recored by noteForwardReference().
265 void fixupForwardReferences();
267 /// \brief Add a function range [\p LowPC, \p HighPC) that is
268 /// relocatad by applying offset \p PCOffset.
269 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
271 /// \brief Keep track of a DW_AT_range attribute that we will need to
273 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
275 /// \brief Keep track of a location attribute pointing to a location
276 /// list in the debug_loc section.
277 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
279 /// \brief Add a name accelerator entry for \p Die with \p Name
280 /// which is stored in the string table at \p Offset.
281 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
282 bool SkipPubnamesSection = false);
284 /// \brief Add a type accelerator entry for \p Die with \p Name
285 /// which is stored in the string table at \p Offset.
286 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
289 StringRef Name; ///< Name of the entry.
290 const DIE *Die; ///< DIE this entry describes.
291 uint32_t NameOffset; ///< Offset of Name in the string pool.
292 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
294 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
295 bool SkipPubSection = false)
296 : Name(Name), Die(Die), NameOffset(NameOffset),
297 SkipPubSection(SkipPubSection) {}
300 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
301 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
303 /// Get the full path for file \a FileNum in the line table
304 const char *getResolvedPath(unsigned FileNum) {
305 if (FileNum >= ResolvedPaths.size())
307 return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
311 /// Set the fully resolved path for the line-table's file \a FileNum
313 void setResolvedPath(unsigned FileNum, const std::string &Path) {
314 if (ResolvedPaths.size() <= FileNum)
315 ResolvedPaths.resize(FileNum + 1);
316 ResolvedPaths[FileNum] = Path;
322 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
323 DIE *CUDie; ///< Root of the linked DIE tree.
325 uint64_t StartOffset;
326 uint64_t NextUnitOffset;
331 /// \brief A list of attributes to fixup with the absolute offset of
332 /// a DIE in the debug_info section.
334 /// The offsets for the attributes in this array couldn't be set while
335 /// cloning because for cross-cu forward refences the target DIE's
336 /// offset isn't known you emit the reference attribute.
337 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
338 PatchLocation>> ForwardDIEReferences;
340 FunctionIntervals::Allocator RangeAlloc;
341 /// \brief The ranges in that interval map are the PC ranges for
342 /// functions in this unit, associated with the PC offset to apply
343 /// to the addresses to get the linked address.
344 FunctionIntervals Ranges;
346 /// \brief DW_AT_ranges attributes to patch after we have gathered
347 /// all the unit's function addresses.
349 std::vector<PatchLocation> RangeAttributes;
350 Optional<PatchLocation> UnitRangeAttribute;
353 /// \brief Location attributes that need to be transfered from th
354 /// original debug_loc section to the liked one. They are stored
355 /// along with the PC offset that is to be applied to their
356 /// function's address.
357 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
359 /// \brief Accelerator entries for the unit, both for the pub*
360 /// sections and the apple* ones.
362 std::vector<AccelInfo> Pubnames;
363 std::vector<AccelInfo> Pubtypes;
366 /// Cached resolved paths from the line table.
367 std::vector<std::string> ResolvedPaths;
369 /// Is this unit subject to the ODR rule?
373 uint64_t CompileUnit::computeNextUnitOffset() {
374 NextUnitOffset = StartOffset + 11 /* Header size */;
375 // The root DIE might be null, meaning that the Unit had nothing to
376 // contribute to the linked output. In that case, we will emit the
377 // unit header without any actual DIE.
379 NextUnitOffset += CUDie->getSize();
380 return NextUnitOffset;
383 /// \brief Keep track of a forward cross-cu reference from this unit
384 /// to \p Die that lives in \p RefUnit.
385 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
386 DeclContext *Ctxt, PatchLocation Attr) {
387 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
390 /// \brief Apply all fixups recorded by noteForwardReference().
391 void CompileUnit::fixupForwardReferences() {
392 for (const auto &Ref : ForwardDIEReferences) {
394 const CompileUnit *RefUnit;
397 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
398 if (Ctxt && Ctxt->getCanonicalDIEOffset())
399 Attr.set(Ctxt->getCanonicalDIEOffset());
401 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
405 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
407 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
408 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
409 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
412 void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
413 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
414 RangeAttributes.push_back(Attr);
416 UnitRangeAttribute = Attr;
419 void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
420 LocationAttributes.emplace_back(Attr, PcOffset);
423 /// \brief Add a name accelerator entry for \p Die with \p Name
424 /// which is stored in the string table at \p Offset.
425 void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
426 uint32_t Offset, bool SkipPubSection) {
427 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
430 /// \brief Add a type accelerator entry for \p Die with \p Name
431 /// which is stored in the string table at \p Offset.
432 void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
434 Pubtypes.emplace_back(Name, Die, Offset, false);
437 /// \brief The Dwarf streaming logic
439 /// All interactions with the MC layer that is used to build the debug
440 /// information binary representation are handled in this class.
441 class DwarfStreamer {
442 /// \defgroup MCObjects MC layer objects constructed by the streamer
444 std::unique_ptr<MCRegisterInfo> MRI;
445 std::unique_ptr<MCAsmInfo> MAI;
446 std::unique_ptr<MCObjectFileInfo> MOFI;
447 std::unique_ptr<MCContext> MC;
448 MCAsmBackend *MAB; // Owned by MCStreamer
449 std::unique_ptr<MCInstrInfo> MII;
450 std::unique_ptr<MCSubtargetInfo> MSTI;
451 MCCodeEmitter *MCE; // Owned by MCStreamer
452 MCStreamer *MS; // Owned by AsmPrinter
453 std::unique_ptr<TargetMachine> TM;
454 std::unique_ptr<AsmPrinter> Asm;
457 /// \brief the file we stream the linked Dwarf to.
458 std::unique_ptr<raw_fd_ostream> OutFile;
460 uint32_t RangesSectionSize;
461 uint32_t LocSectionSize;
462 uint32_t LineSectionSize;
463 uint32_t FrameSectionSize;
465 /// \brief Emit the pubnames or pubtypes section contribution for \p
466 /// Unit into \p Sec. The data is provided in \p Names.
467 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
468 const CompileUnit &Unit,
469 const std::vector<CompileUnit::AccelInfo> &Names);
472 /// \brief Actually create the streamer and the ouptut file.
474 /// This could be done directly in the constructor, but it feels
475 /// more natural to handle errors through return value.
476 bool init(Triple TheTriple, StringRef OutputFilename);
478 /// \brief Dump the file to the disk.
479 bool finish(const DebugMap &);
481 AsmPrinter &getAsmPrinter() const { return *Asm; }
483 /// \brief Set the current output section to debug_info and change
484 /// the MC Dwarf version to \p DwarfVersion.
485 void switchToDebugInfoSection(unsigned DwarfVersion);
487 /// \brief Emit the compilation unit header for \p Unit in the
488 /// debug_info section.
490 /// As a side effect, this also switches the current Dwarf version
491 /// of the MC layer to the one of U.getOrigUnit().
492 void emitCompileUnitHeader(CompileUnit &Unit);
494 /// \brief Recursively emit the DIE tree rooted at \p Die.
495 void emitDIE(DIE &Die);
497 /// \brief Emit the abbreviation table \p Abbrevs to the
498 /// debug_abbrev section.
499 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
501 /// \brief Emit the string table described by \p Pool.
502 void emitStrings(const NonRelocatableStringpool &Pool);
504 /// \brief Emit debug_ranges for \p FuncRange by translating the
505 /// original \p Entries.
506 void emitRangesEntries(
507 int64_t UnitPcOffset, uint64_t OrigLowPc,
508 FunctionIntervals::const_iterator FuncRange,
509 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
510 unsigned AddressSize);
512 /// \brief Emit debug_aranges entries for \p Unit and if \p
513 /// DoRangesSection is true, also emit the debug_ranges entries for
514 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
515 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
517 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
519 /// \brief Emit the debug_loc contribution for \p Unit by copying
520 /// the entries from \p Dwarf and offseting them. Update the
521 /// location attributes to point to the new entries.
522 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
524 /// \brief Emit the line table described in \p Rows into the
525 /// debug_line section.
526 void emitLineTableForUnit(MCDwarfLineTableParams Params,
527 StringRef PrologueBytes, unsigned MinInstLength,
528 std::vector<DWARFDebugLine::Row> &Rows,
529 unsigned AdddressSize);
531 uint32_t getLineSectionSize() const { return LineSectionSize; }
533 /// \brief Emit the .debug_pubnames contribution for \p Unit.
534 void emitPubNamesForUnit(const CompileUnit &Unit);
536 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
537 void emitPubTypesForUnit(const CompileUnit &Unit);
539 /// \brief Emit a CIE.
540 void emitCIE(StringRef CIEBytes);
542 /// \brief Emit an FDE with data \p Bytes.
543 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
546 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
549 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
550 std::string ErrorStr;
551 std::string TripleName;
552 StringRef Context = "dwarf streamer init";
555 const Target *TheTarget =
556 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
558 return error(ErrorStr, Context);
559 TripleName = TheTriple.getTriple();
561 // Create all the MC Objects.
562 MRI.reset(TheTarget->createMCRegInfo(TripleName));
564 return error(Twine("no register info for target ") + TripleName, Context);
566 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
568 return error("no asm info for target " + TripleName, Context);
570 MOFI.reset(new MCObjectFileInfo);
571 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
572 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
575 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
577 return error("no asm backend for target " + TripleName, Context);
579 MII.reset(TheTarget->createMCInstrInfo());
581 return error("no instr info info for target " + TripleName, Context);
583 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
585 return error("no subtarget info for target " + TripleName, Context);
587 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
589 return error("no code emitter for target " + TripleName, Context);
591 // Create the output file.
594 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
596 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
598 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
600 /*DWARFMustBeAtTheEnd*/ false);
602 return error("no object streamer for target " + TripleName, Context);
604 // Finally create the AsmPrinter we'll use to emit the DIEs.
605 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
607 return error("no target machine for target " + TripleName, Context);
609 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
611 return error("no asm printer for target " + TripleName, Context);
613 RangesSectionSize = 0;
616 FrameSectionSize = 0;
621 bool DwarfStreamer::finish(const DebugMap &DM) {
622 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
623 return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
629 /// \brief Set the current output section to debug_info and change
630 /// the MC Dwarf version to \p DwarfVersion.
631 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
632 MS->SwitchSection(MOFI->getDwarfInfoSection());
633 MC->setDwarfVersion(DwarfVersion);
636 /// \brief Emit the compilation unit header for \p Unit in the
637 /// debug_info section.
639 /// A Dwarf scetion header is encoded as:
640 /// uint32_t Unit length (omiting this field)
642 /// uint32_t Abbreviation table offset
643 /// uint8_t Address size
645 /// Leading to a total of 11 bytes.
646 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
647 unsigned Version = Unit.getOrigUnit().getVersion();
648 switchToDebugInfoSection(Version);
650 // Emit size of content not including length itself. The size has
651 // already been computed in CompileUnit::computeOffsets(). Substract
652 // 4 to that size to account for the length field.
653 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
654 Asm->EmitInt16(Version);
655 // We share one abbreviations table across all units so it's always at the
656 // start of the section.
658 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
661 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
662 /// for the linked Dwarf file.
663 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
664 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
665 Asm->emitDwarfAbbrevs(Abbrevs);
668 /// \brief Recursively emit the DIE tree rooted at \p Die.
669 void DwarfStreamer::emitDIE(DIE &Die) {
670 MS->SwitchSection(MOFI->getDwarfInfoSection());
671 Asm->emitDwarfDIE(Die);
674 /// \brief Emit the debug_str section stored in \p Pool.
675 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
676 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
677 for (auto *Entry = Pool.getFirstEntry(); Entry;
678 Entry = Pool.getNextEntry(Entry))
679 Asm->OutStreamer->EmitBytes(
680 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
683 /// \brief Emit the debug_range section contents for \p FuncRange by
684 /// translating the original \p Entries. The debug_range section
685 /// format is totally trivial, consisting just of pairs of address
686 /// sized addresses describing the ranges.
687 void DwarfStreamer::emitRangesEntries(
688 int64_t UnitPcOffset, uint64_t OrigLowPc,
689 FunctionIntervals::const_iterator FuncRange,
690 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
691 unsigned AddressSize) {
692 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
694 // Offset each range by the right amount.
695 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
696 for (const auto &Range : Entries) {
697 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
698 warn("unsupported base address selection operation",
699 "emitting debug_ranges");
702 // Do not emit empty ranges.
703 if (Range.StartAddress == Range.EndAddress)
706 // All range entries should lie in the function range.
707 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
708 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
709 warn("inconsistent range data.", "emitting debug_ranges");
710 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
711 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
712 RangesSectionSize += 2 * AddressSize;
715 // Add the terminator entry.
716 MS->EmitIntValue(0, AddressSize);
717 MS->EmitIntValue(0, AddressSize);
718 RangesSectionSize += 2 * AddressSize;
721 /// \brief Emit the debug_aranges contribution of a unit and
722 /// if \p DoDebugRanges is true the debug_range contents for a
723 /// compile_unit level DW_AT_ranges attribute (Which are basically the
724 /// same thing with a different base address).
725 /// Just aggregate all the ranges gathered inside that unit.
726 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
727 bool DoDebugRanges) {
728 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
729 // Gather the ranges in a vector, so that we can simplify them. The
730 // IntervalMap will have coalesced the non-linked ranges, but here
731 // we want to coalesce the linked addresses.
732 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
733 const auto &FunctionRanges = Unit.getFunctionRanges();
734 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
735 Range != End; ++Range)
736 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
737 Range.stop() + Range.value()));
739 // The object addresses where sorted, but again, the linked
740 // addresses might end up in a different order.
741 std::sort(Ranges.begin(), Ranges.end());
743 if (!Ranges.empty()) {
744 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
746 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
747 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
749 unsigned HeaderSize =
750 sizeof(int32_t) + // Size of contents (w/o this field
751 sizeof(int16_t) + // DWARF ARange version number
752 sizeof(int32_t) + // Offset of CU in the .debug_info section
753 sizeof(int8_t) + // Pointer Size (in bytes)
754 sizeof(int8_t); // Segment Size (in bytes)
756 unsigned TupleSize = AddressSize * 2;
757 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
759 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
760 Asm->OutStreamer->EmitLabel(BeginLabel);
761 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
762 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
763 Asm->EmitInt8(AddressSize); // Address size
764 Asm->EmitInt8(0); // Segment size
766 Asm->OutStreamer->EmitFill(Padding, 0x0);
768 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
770 uint64_t RangeStart = Range->first;
771 MS->EmitIntValue(RangeStart, AddressSize);
772 while ((Range + 1) != End && Range->second == (Range + 1)->first)
774 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
778 Asm->OutStreamer->EmitIntValue(0, AddressSize);
779 Asm->OutStreamer->EmitIntValue(0, AddressSize);
780 Asm->OutStreamer->EmitLabel(EndLabel);
786 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
787 // Offset each range by the right amount.
788 int64_t PcOffset = -Unit.getLowPc();
789 // Emit coalesced ranges.
790 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
791 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
792 while (Range + 1 != End && Range->second == (Range + 1)->first)
794 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
795 RangesSectionSize += 2 * AddressSize;
798 // Add the terminator entry.
799 MS->EmitIntValue(0, AddressSize);
800 MS->EmitIntValue(0, AddressSize);
801 RangesSectionSize += 2 * AddressSize;
804 /// \brief Emit location lists for \p Unit and update attribtues to
805 /// point to the new entries.
806 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
807 DWARFContext &Dwarf) {
808 const auto &Attributes = Unit.getLocationAttributes();
810 if (Attributes.empty())
813 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
815 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
816 const DWARFSection &InputSec = Dwarf.getLocSection();
817 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
818 DWARFUnit &OrigUnit = Unit.getOrigUnit();
819 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
820 int64_t UnitPcOffset = 0;
821 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
822 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
823 if (OrigLowPc != -1ULL)
824 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
826 for (const auto &Attr : Attributes) {
827 uint32_t Offset = Attr.first.get();
828 Attr.first.set(LocSectionSize);
829 // This is the quantity to add to the old location address to get
830 // the correct address for the new one.
831 int64_t LocPcOffset = Attr.second + UnitPcOffset;
832 while (Data.isValidOffset(Offset)) {
833 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
834 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
835 LocSectionSize += 2 * AddressSize;
836 if (Low == 0 && High == 0) {
837 Asm->OutStreamer->EmitIntValue(0, AddressSize);
838 Asm->OutStreamer->EmitIntValue(0, AddressSize);
841 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
842 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
843 uint64_t Length = Data.getU16(&Offset);
844 Asm->OutStreamer->EmitIntValue(Length, 2);
845 // Just copy the bytes over.
846 Asm->OutStreamer->EmitBytes(
847 StringRef(InputSec.Data.substr(Offset, Length)));
849 LocSectionSize += Length + 2;
854 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
855 StringRef PrologueBytes,
856 unsigned MinInstLength,
857 std::vector<DWARFDebugLine::Row> &Rows,
858 unsigned PointerSize) {
859 // Switch to the section where the table will be emitted into.
860 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
861 MCSymbol *LineStartSym = MC->createTempSymbol();
862 MCSymbol *LineEndSym = MC->createTempSymbol();
864 // The first 4 bytes is the total length of the information for this
865 // compilation unit (not including these 4 bytes for the length).
866 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
867 Asm->OutStreamer->EmitLabel(LineStartSym);
869 MS->EmitBytes(PrologueBytes);
870 LineSectionSize += PrologueBytes.size() + 4;
872 SmallString<128> EncodingBuffer;
873 raw_svector_ostream EncodingOS(EncodingBuffer);
876 // We only have the dummy entry, dsymutil emits an entry with a 0
877 // address in that case.
878 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
879 MS->EmitBytes(EncodingOS.str());
880 LineSectionSize += EncodingBuffer.size();
881 MS->EmitLabel(LineEndSym);
885 // Line table state machine fields
886 unsigned FileNum = 1;
887 unsigned LastLine = 1;
889 unsigned IsStatement = 1;
891 uint64_t Address = -1ULL;
893 unsigned RowsSinceLastSequence = 0;
895 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
896 auto &Row = Rows[Idx];
898 int64_t AddressDelta;
899 if (Address == -1ULL) {
900 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
901 MS->EmitULEB128IntValue(PointerSize + 1);
902 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
903 MS->EmitIntValue(Row.Address, PointerSize);
904 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
907 AddressDelta = (Row.Address - Address) / MinInstLength;
910 // FIXME: code copied and transfromed from
911 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
912 // this code, but the current compatibility requirement with
913 // classic dsymutil makes it hard. Revisit that once this
914 // requirement is dropped.
916 if (FileNum != Row.File) {
918 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
919 MS->EmitULEB128IntValue(FileNum);
920 LineSectionSize += 1 + getULEB128Size(FileNum);
922 if (Column != Row.Column) {
924 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
925 MS->EmitULEB128IntValue(Column);
926 LineSectionSize += 1 + getULEB128Size(Column);
929 // FIXME: We should handle the discriminator here, but dsymutil
930 // doesn' consider it, thus ignore it for now.
932 if (Isa != Row.Isa) {
934 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
935 MS->EmitULEB128IntValue(Isa);
936 LineSectionSize += 1 + getULEB128Size(Isa);
938 if (IsStatement != Row.IsStmt) {
939 IsStatement = Row.IsStmt;
940 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
941 LineSectionSize += 1;
943 if (Row.BasicBlock) {
944 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
945 LineSectionSize += 1;
948 if (Row.PrologueEnd) {
949 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
950 LineSectionSize += 1;
953 if (Row.EpilogueBegin) {
954 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
955 LineSectionSize += 1;
958 int64_t LineDelta = int64_t(Row.Line) - LastLine;
959 if (!Row.EndSequence) {
960 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
961 MS->EmitBytes(EncodingOS.str());
962 LineSectionSize += EncodingBuffer.size();
963 EncodingBuffer.resize(0);
964 Address = Row.Address;
966 RowsSinceLastSequence++;
969 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
970 MS->EmitSLEB128IntValue(LineDelta);
971 LineSectionSize += 1 + getSLEB128Size(LineDelta);
974 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
975 MS->EmitULEB128IntValue(AddressDelta);
976 LineSectionSize += 1 + getULEB128Size(AddressDelta);
978 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
979 MS->EmitBytes(EncodingOS.str());
980 LineSectionSize += EncodingBuffer.size();
981 EncodingBuffer.resize(0);
983 LastLine = FileNum = IsStatement = 1;
984 RowsSinceLastSequence = Column = Isa = 0;
988 if (RowsSinceLastSequence) {
989 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
990 MS->EmitBytes(EncodingOS.str());
991 LineSectionSize += EncodingBuffer.size();
992 EncodingBuffer.resize(0);
995 MS->EmitLabel(LineEndSym);
998 /// \brief Emit the pubnames or pubtypes section contribution for \p
999 /// Unit into \p Sec. The data is provided in \p Names.
1000 void DwarfStreamer::emitPubSectionForUnit(
1001 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
1002 const std::vector<CompileUnit::AccelInfo> &Names) {
1006 // Start the dwarf pubnames section.
1007 Asm->OutStreamer->SwitchSection(Sec);
1008 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1009 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
1011 bool HeaderEmitted = false;
1012 // Emit the pubnames for this compilation unit.
1013 for (const auto &Name : Names) {
1014 if (Name.SkipPubSection)
1017 if (!HeaderEmitted) {
1019 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
1020 Asm->OutStreamer->EmitLabel(BeginLabel);
1021 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
1022 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
1023 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1024 HeaderEmitted = true;
1026 Asm->EmitInt32(Name.Die->getOffset());
1027 Asm->OutStreamer->EmitBytes(
1028 StringRef(Name.Name.data(), Name.Name.size() + 1));
1033 Asm->EmitInt32(0); // End marker.
1034 Asm->OutStreamer->EmitLabel(EndLabel);
1037 /// \brief Emit .debug_pubnames for \p Unit.
1038 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1039 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1040 "names", Unit, Unit.getPubnames());
1043 /// \brief Emit .debug_pubtypes for \p Unit.
1044 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1045 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1046 "types", Unit, Unit.getPubtypes());
1049 /// \brief Emit a CIE into the debug_frame section.
1050 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1051 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1053 MS->EmitBytes(CIEBytes);
1054 FrameSectionSize += CIEBytes.size();
1057 /// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1058 /// contains the FDE data without the length, CIE offset and address
1059 /// which will be replaced with the paramter values.
1060 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1061 uint32_t Address, StringRef FDEBytes) {
1062 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1064 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1065 MS->EmitIntValue(CIEOffset, 4);
1066 MS->EmitIntValue(Address, AddrSize);
1067 MS->EmitBytes(FDEBytes);
1068 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1071 /// \brief The core of the Dwarf linking logic.
1073 /// The link of the dwarf information from the object files will be
1074 /// driven by the selection of 'root DIEs', which are DIEs that
1075 /// describe variables or functions that are present in the linked
1076 /// binary (and thus have entries in the debug map). All the debug
1077 /// information that will be linked (the DIEs, but also the line
1078 /// tables, ranges, ...) is derived from that set of root DIEs.
1080 /// The root DIEs are identified because they contain relocations that
1081 /// correspond to a debug map entry at specific places (the low_pc for
1082 /// a function, the location for a variable). These relocations are
1083 /// called ValidRelocs in the DwarfLinker and are gathered as a very
1084 /// first step when we start processing a DebugMapObject.
1087 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1088 : OutputFilename(OutputFilename), Options(Options),
1089 BinHolder(Options.Verbose), LastCIEOffset(0) {}
1092 for (auto *Abbrev : Abbreviations)
1096 /// \brief Link the contents of the DebugMap.
1097 bool link(const DebugMap &);
1100 /// \brief Called at the start of a debug object link.
1101 void startDebugObject(DWARFContext &, DebugMapObject &);
1103 /// \brief Called at the end of a debug object link.
1104 void endDebugObject();
1106 /// Keeps track of relocations.
1107 class RelocationManager {
1112 const DebugMapObject::DebugMapEntry *Mapping;
1114 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1115 const DebugMapObject::DebugMapEntry *Mapping)
1116 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1118 bool operator<(const ValidReloc &RHS) const {
1119 return Offset < RHS.Offset;
1123 DwarfLinker &Linker;
1125 /// \brief The valid relocations for the current DebugMapObject.
1126 /// This vector is sorted by relocation offset.
1127 std::vector<ValidReloc> ValidRelocs;
1129 /// \brief Index into ValidRelocs of the next relocation to
1130 /// consider. As we walk the DIEs in acsending file offset and as
1131 /// ValidRelocs is sorted by file offset, keeping this index
1132 /// uptodate is all we have to do to have a cheap lookup during the
1133 /// root DIE selection and during DIE cloning.
1134 unsigned NextValidReloc;
1137 RelocationManager(DwarfLinker &Linker)
1138 : Linker(Linker), NextValidReloc(0) {}
1140 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1141 /// \brief Reset the NextValidReloc counter.
1142 void resetValidRelocs() { NextValidReloc = 0; }
1144 /// \defgroup FindValidRelocations Translate debug map into a list
1145 /// of relevant relocations
1148 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1149 const DebugMapObject &DMO);
1151 bool findValidRelocs(const object::SectionRef &Section,
1152 const object::ObjectFile &Obj,
1153 const DebugMapObject &DMO);
1155 void findValidRelocsMachO(const object::SectionRef &Section,
1156 const object::MachOObjectFile &Obj,
1157 const DebugMapObject &DMO);
1160 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1161 CompileUnit::DIEInfo &Info);
1163 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1164 bool isLittleEndian);
1167 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1170 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1171 /// keep. Store that information in \p CU's DIEInfo.
1172 void lookForDIEsToKeep(RelocationManager &RelocMgr,
1173 const DWARFDebugInfoEntryMinimal &DIE,
1174 const DebugMapObject &DMO, CompileUnit &CU,
1177 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1178 enum TravesalFlags {
1179 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1180 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1181 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1182 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1183 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
1184 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
1187 /// \brief Mark the passed DIE as well as all the ones it depends on
1189 void keepDIEAndDenpendencies(RelocationManager &RelocMgr,
1190 const DWARFDebugInfoEntryMinimal &DIE,
1191 CompileUnit::DIEInfo &MyInfo,
1192 const DebugMapObject &DMO, CompileUnit &CU,
1195 unsigned shouldKeepDIE(RelocationManager &RelocMgr,
1196 const DWARFDebugInfoEntryMinimal &DIE,
1197 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1200 unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
1201 const DWARFDebugInfoEntryMinimal &DIE,
1203 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1205 unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
1206 const DWARFDebugInfoEntryMinimal &DIE,
1208 CompileUnit::DIEInfo &MyInfo,
1211 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1212 CompileUnit::DIEInfo &Info);
1215 /// \defgroup Linking Methods used to link the debug information
1218 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1219 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1220 /// stripped out and addresses have been rewritten according to the
1223 /// \param OutOffset is the offset the cloned DIE in the output
1225 /// \param PCOffset (while cloning a function scope) is the offset
1226 /// applied to the entry point of the function to get the linked address.
1228 /// \returns the root of the cloned tree.
1229 DIE *cloneDIE(RelocationManager &RelocMgr,
1230 const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
1231 int64_t PCOffset, uint32_t OutOffset, unsigned Flags);
1233 /// Construct the output DIE tree by cloning the DIEs we chose to
1234 /// keep above. If there are no valid relocs, then there's nothing
1236 void cloneCompileUnit(RelocationManager &RelocMgr,
1237 MutableArrayRef<CompileUnit> CompileUnit,
1238 DWARFContextInMemory &DwarfContext);
1242 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1244 /// \brief Information gathered and exchanged between the various
1245 /// clone*Attributes helpers about the attributes of a particular DIE.
1246 struct AttributesInfo {
1247 const char *Name, *MangledName; ///< Names.
1248 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1250 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1251 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1252 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1254 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1255 bool IsDeclaration; ///< Is this DIE only a declaration?
1258 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1259 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1260 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1263 /// \brief Helper for cloneDIE.
1264 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1265 CompileUnit &U, const DWARFFormValue &Val,
1266 const AttributeSpec AttrSpec, unsigned AttrSize,
1267 AttributesInfo &AttrInfo);
1269 /// \brief Helper for cloneDIE.
1270 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1271 const DWARFFormValue &Val, const DWARFUnit &U);
1273 /// \brief Helper for cloneDIE.
1275 cloneDieReferenceAttribute(DIE &Die,
1276 const DWARFDebugInfoEntryMinimal &InputDIE,
1277 AttributeSpec AttrSpec, unsigned AttrSize,
1278 const DWARFFormValue &Val, CompileUnit &Unit);
1280 /// \brief Helper for cloneDIE.
1281 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1282 const DWARFFormValue &Val, unsigned AttrSize);
1284 /// \brief Helper for cloneDIE.
1285 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1286 const DWARFFormValue &Val,
1287 const CompileUnit &Unit, AttributesInfo &Info);
1289 /// \brief Helper for cloneDIE.
1290 unsigned cloneScalarAttribute(DIE &Die,
1291 const DWARFDebugInfoEntryMinimal &InputDIE,
1292 CompileUnit &U, AttributeSpec AttrSpec,
1293 const DWARFFormValue &Val, unsigned AttrSize,
1294 AttributesInfo &Info);
1296 /// \brief Assign an abbreviation number to \p Abbrev
1297 void AssignAbbrev(DIEAbbrev &Abbrev);
1299 /// Create a copy of abbreviation Abbrev.
1300 void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
1302 /// \brief FoldingSet that uniques the abbreviations.
1303 FoldingSet<DIEAbbrev> AbbreviationsSet;
1304 /// \brief Storage for the unique Abbreviations.
1305 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1306 /// be changed to a vecot of unique_ptrs.
1307 std::vector<DIEAbbrev *> Abbreviations;
1309 /// \brief Compute and emit debug_ranges section for \p Unit, and
1310 /// patch the attributes referencing it.
1311 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1313 /// \brief Generate and emit the DW_AT_ranges attribute for a
1314 /// compile_unit if it had one.
1315 void generateUnitRanges(CompileUnit &Unit) const;
1317 /// \brief Extract the line tables fromt he original dwarf, extract
1318 /// the relevant parts according to the linked function ranges and
1319 /// emit the result in the debug_line section.
1320 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1322 /// \brief Emit the accelerator entries for \p Unit.
1323 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1325 /// \brief Patch the frame info for an object file and emit it.
1326 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1327 unsigned AddressSize);
1329 /// \brief DIELoc objects that need to be destructed (but not freed!).
1330 std::vector<DIELoc *> DIELocs;
1331 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1332 std::vector<DIEBlock *> DIEBlocks;
1333 /// \brief Allocator used for all the DIEValue objects.
1334 BumpPtrAllocator DIEAlloc;
1337 /// ODR Contexts for that link.
1338 DeclContextTree ODRContexts;
1340 /// \defgroup Helpers Various helper methods.
1343 const DWARFDebugInfoEntryMinimal *
1344 resolveDIEReference(const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1345 const DWARFDebugInfoEntryMinimal &DIE,
1346 CompileUnit *&ReferencedCU);
1348 CompileUnit *getUnitForOffset(unsigned Offset);
1350 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1351 AttributesInfo &Info);
1353 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1354 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1356 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
1358 /// \brief Attempt to load a debug object from disk.
1359 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1360 DebugMapObject &Obj,
1361 const DebugMap &Map);
1365 std::string OutputFilename;
1366 LinkOptions Options;
1367 BinaryHolder BinHolder;
1368 std::unique_ptr<DwarfStreamer> Streamer;
1369 uint64_t OutputDebugInfoSize;
1371 /// The units of the current debug map object.
1372 std::vector<CompileUnit> Units;
1374 /// The debug map object curently under consideration.
1375 DebugMapObject *CurrentDebugObject;
1377 /// \brief The Dwarf string pool
1378 NonRelocatableStringpool StringPool;
1380 /// \brief This map is keyed by the entry PC of functions in that
1381 /// debug object and the associated value is a pair storing the
1382 /// corresponding end PC and the offset to apply to get the linked
1385 /// See startDebugObject() for a more complete description of its use.
1386 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1388 /// \brief The CIEs that have been emitted in the output
1389 /// section. The actual CIE data serves a the key to this StringMap,
1390 /// this takes care of comparing the semantics of CIEs defined in
1391 /// different object files.
1392 StringMap<uint32_t> EmittedCIEs;
1394 /// Offset of the last CIE that has been emitted in the output
1395 /// debug_frame section.
1396 uint32_t LastCIEOffset;
1399 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1400 /// returning our CompileUnit object instead.
1401 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1403 std::upper_bound(Units.begin(), Units.end(), Offset,
1404 [](uint32_t LHS, const CompileUnit &RHS) {
1405 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1407 return CU != Units.end() ? &*CU : nullptr;
1410 /// \brief Resolve the DIE attribute reference that has been
1411 /// extracted in \p RefValue. The resulting DIE migh be in another
1412 /// CompileUnit which is stored into \p ReferencedCU.
1413 /// \returns null if resolving fails for any reason.
1414 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1415 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1416 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1417 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1418 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1420 if ((RefCU = getUnitForOffset(RefOffset)))
1421 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1424 reportWarning("could not find referenced DIE", &Unit, &DIE);
1428 /// \returns whether the passed \a Attr type might contain a DIE
1429 /// reference suitable for ODR uniquing.
1430 static bool isODRAttribute(uint16_t Attr) {
1434 case dwarf::DW_AT_type:
1435 case dwarf::DW_AT_containing_type:
1436 case dwarf::DW_AT_specification:
1437 case dwarf::DW_AT_abstract_origin:
1438 case dwarf::DW_AT_import:
1441 llvm_unreachable("Improper attribute.");
1444 /// Set the last DIE/CU a context was seen in and, possibly invalidate
1445 /// the context if it is ambiguous.
1447 /// In the current implementation, we don't handle overloaded
1448 /// functions well, because the argument types are not taken into
1449 /// account when computing the DeclContext tree.
1451 /// Some of this is mitigated byt using mangled names that do contain
1452 /// the arguments types, but sometimes (eg. with function templates)
1453 /// we don't have that. In that case, just do not unique anything that
1454 /// refers to the contexts we are not able to distinguish.
1456 /// If a context that is not a namespace appears twice in the same CU,
1457 /// we know it is ambiguous. Make it invalid.
1458 bool DeclContext::setLastSeenDIE(CompileUnit &U,
1459 const DWARFDebugInfoEntryMinimal *Die) {
1460 if (LastSeenCompileUnitID == U.getUniqueID()) {
1461 DWARFUnit &OrigUnit = U.getOrigUnit();
1462 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1463 U.getInfo(FirstIdx).Ctxt = nullptr;
1467 LastSeenCompileUnitID = U.getUniqueID();
1472 /// Get the child context of \a Context corresponding to \a DIE.
1474 /// \returns the child context or null if we shouldn't track children
1475 /// contexts. It also returns an additional bit meaning 'invalid'. An
1476 /// invalid context means it shouldn't be considered for uniquing, but
1477 /// its not returning null, because some children of that context
1478 /// might be uniquing candidates.
1479 /// FIXME: this is for dsymutil-classic compatibility, I don't think
1480 /// it buys us much.
1481 PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1482 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1483 NonRelocatableStringpool &StringPool) {
1484 unsigned Tag = DIE->getTag();
1486 // FIXME: dsymutil-classic compat: We should bail out here if we
1487 // have a specification or an abstract_origin. We will get the
1488 // parent context wrong here.
1492 // By default stop gathering child contexts.
1493 return PointerIntPair<DeclContext *, 1>(nullptr);
1494 case dwarf::DW_TAG_compile_unit:
1495 // FIXME: Add support for DW_TAG_module.
1496 return PointerIntPair<DeclContext *, 1>(&Context);
1497 case dwarf::DW_TAG_subprogram:
1498 // Do not unique anything inside CU local functions.
1499 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1500 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1501 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1502 dwarf::DW_AT_external, 0))
1503 return PointerIntPair<DeclContext *, 1>(nullptr);
1505 case dwarf::DW_TAG_member:
1506 case dwarf::DW_TAG_namespace:
1507 case dwarf::DW_TAG_structure_type:
1508 case dwarf::DW_TAG_class_type:
1509 case dwarf::DW_TAG_union_type:
1510 case dwarf::DW_TAG_enumeration_type:
1511 case dwarf::DW_TAG_typedef:
1512 // Artificial things might be ambiguous, because they might be
1513 // created on demand. For example implicitely defined constructors
1514 // are ambiguous because of the way we identify contexts, and they
1515 // won't be generated everytime everywhere.
1516 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1517 dwarf::DW_AT_artificial, 0))
1518 return PointerIntPair<DeclContext *, 1>(nullptr);
1522 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1523 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1525 StringRef ShortNameRef;
1529 NameRef = StringPool.internString(Name);
1530 else if (Tag == dwarf::DW_TAG_namespace)
1531 // FIXME: For dsymutil-classic compatibility. I think uniquing
1532 // within anonymous namespaces is wrong. There is no ODR guarantee
1534 NameRef = StringPool.internString("(anonymous namespace)");
1536 if (ShortName && ShortName != Name)
1537 ShortNameRef = StringPool.internString(ShortName);
1539 ShortNameRef = NameRef;
1541 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1542 Tag != dwarf::DW_TAG_union_type &&
1543 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1544 return PointerIntPair<DeclContext *, 1>(nullptr);
1548 unsigned ByteSize = 0;
1550 // Gather some discriminating data about the DeclContext we will be
1551 // creating: File, line number and byte size. This shouldn't be
1552 // necessary, because the ODR is just about names, but given that we
1553 // do some approximations with overloaded functions and anonymous
1554 // namespaces, use these additional data points to make the process safer.
1555 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1556 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1557 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1558 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1559 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1560 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1561 &U.getOrigUnit())) {
1562 // FIXME: dsymutil-classic compatibility. I'd rather not
1563 // unique anything in anonymous namespaces, but if we do, then
1564 // verify that the file and line correspond.
1565 if (!Name && Tag == dwarf::DW_TAG_namespace)
1568 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1569 // instead of "" would allow more uniquing, but for now, do
1570 // it this way to match dsymutil-classic.
1571 if (LT->getFileNameByIndex(
1573 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1575 Line = DIE->getAttributeValueAsUnsignedConstant(
1576 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1577 #ifdef HAVE_REALPATH
1578 // Cache the resolved paths, because calling realpath is expansive.
1579 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1580 File = ResolvedPath;
1582 char RealPath[PATH_MAX + 1];
1583 RealPath[PATH_MAX] = 0;
1584 if (::realpath(File.c_str(), RealPath))
1586 U.setResolvedPath(FileNum, File);
1589 FileRef = StringPool.internString(File);
1595 if (!Line && NameRef.empty())
1596 return PointerIntPair<DeclContext *, 1>(nullptr);
1598 // FIXME: dsymutil-classic compat won't unique the same type
1599 // presented once as a struct and once as a class. Use the Tag in
1600 // the fully qualified name hash to get the same effect.
1601 // We hash NameRef, which is the mangled name, in order to get most
1602 // overloaded functions resolvec correctly.
1603 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1605 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1606 // use the filename.
1607 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1608 Hash = hash_combine(Hash, FileRef);
1610 // Now look if this context already exists.
1611 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1612 auto ContextIter = Contexts.find(&Key);
1614 if (ContextIter == Contexts.end()) {
1615 // The context wasn't found.
1617 DeclContext *NewContext =
1618 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1619 Context, DIE, U.getUniqueID());
1620 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1621 assert(Inserted && "Failed to insert DeclContext");
1623 } else if (Tag != dwarf::DW_TAG_namespace &&
1624 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1625 // The context was found, but it is ambiguous with another context
1626 // in the same file. Mark it invalid.
1627 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1630 assert(ContextIter != Contexts.end());
1631 // FIXME: dsymutil-classic compatibility. Union types aren't
1632 // uniques, but their children might be.
1633 if ((Tag == dwarf::DW_TAG_subprogram &&
1634 Context.getTag() != dwarf::DW_TAG_structure_type &&
1635 Context.getTag() != dwarf::DW_TAG_class_type) ||
1636 (Tag == dwarf::DW_TAG_union_type))
1637 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1639 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1642 /// \brief Get the potential name and mangled name for the entity
1643 /// described by \p Die and store them in \Info if they are not
1645 /// \returns is a name was found.
1646 bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1647 DWARFUnit &U, AttributesInfo &Info) {
1648 // FIXME: a bit wastefull as the first getName might return the
1650 if (!Info.MangledName &&
1651 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1652 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1654 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1655 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1657 return Info.Name || Info.MangledName;
1660 /// \brief Report a warning to the user, optionaly including
1661 /// information about a specific \p DIE related to the warning.
1662 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
1663 const DWARFDebugInfoEntryMinimal *DIE) const {
1664 StringRef Context = "<debug map>";
1665 if (CurrentDebugObject)
1666 Context = CurrentDebugObject->getObjectFilename();
1667 warn(Warning, Context);
1669 if (!Options.Verbose || !DIE)
1672 errs() << " in DIE:\n";
1673 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1677 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1678 if (Options.NoOutput)
1681 Streamer = llvm::make_unique<DwarfStreamer>();
1682 return Streamer->init(TheTriple, OutputFilename);
1685 /// \brief Recursive helper to gather the child->parent relationships in the
1686 /// original compile unit.
1687 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1688 unsigned ParentIdx, CompileUnit &CU,
1689 DeclContext *CurrentDeclContext,
1690 NonRelocatableStringpool &StringPool,
1691 DeclContextTree &Contexts) {
1692 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1693 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1695 Info.ParentIdx = ParentIdx;
1697 if (CurrentDeclContext) {
1698 auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1699 DIE, CU, StringPool);
1700 CurrentDeclContext = PtrInvalidPair.getPointer();
1702 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1704 Info.Ctxt = CurrentDeclContext = nullptr;
1707 if (DIE->hasChildren())
1708 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1709 Child = Child->getSibling())
1710 gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1714 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1718 case dwarf::DW_TAG_subprogram:
1719 case dwarf::DW_TAG_lexical_block:
1720 case dwarf::DW_TAG_subroutine_type:
1721 case dwarf::DW_TAG_structure_type:
1722 case dwarf::DW_TAG_class_type:
1723 case dwarf::DW_TAG_union_type:
1726 llvm_unreachable("Invalid Tag");
1729 static unsigned getRefAddrSize(const DWARFUnit &U) {
1730 if (U.getVersion() == 2)
1731 return U.getAddressByteSize();
1735 void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1736 Units.reserve(Dwarf.getNumCompileUnits());
1737 // Iterate over the debug map entries and put all the ones that are
1738 // functions (because they have a size) into the Ranges map. This
1739 // map is very similar to the FunctionRanges that are stored in each
1740 // unit, with 2 notable differences:
1741 // - obviously this one is global, while the other ones are per-unit.
1742 // - this one contains not only the functions described in the DIE
1743 // tree, but also the ones that are only in the debug map.
1744 // The latter information is required to reproduce dsymutil's logic
1745 // while linking line tables. The cases where this information
1746 // matters look like bugs that need to be investigated, but for now
1747 // we need to reproduce dsymutil's behavior.
1748 // FIXME: Once we understood exactly if that information is needed,
1749 // maybe totally remove this (or try to use it to do a real
1750 // -gline-tables-only on Darwin.
1751 for (const auto &Entry : Obj.symbols()) {
1752 const auto &Mapping = Entry.getValue();
1754 Ranges[Mapping.ObjectAddress] = std::make_pair(
1755 Mapping.ObjectAddress + Mapping.Size,
1756 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1760 void DwarfLinker::endDebugObject() {
1764 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1766 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1774 /// \brief Iterate over the relocations of the given \p Section and
1775 /// store the ones that correspond to debug map entries into the
1776 /// ValidRelocs array.
1777 void DwarfLinker::RelocationManager::
1778 findValidRelocsMachO(const object::SectionRef &Section,
1779 const object::MachOObjectFile &Obj,
1780 const DebugMapObject &DMO) {
1782 Section.getContents(Contents);
1783 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1785 for (const object::RelocationRef &Reloc : Section.relocations()) {
1786 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1787 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1788 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1789 uint64_t Offset64 = Reloc.getOffset();
1790 if ((RelocSize != 4 && RelocSize != 8)) {
1791 Linker.reportWarning(" unsupported relocation in debug_info section.");
1794 uint32_t Offset = Offset64;
1795 // Mach-o uses REL relocations, the addend is at the relocation offset.
1796 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1798 auto Sym = Reloc.getSymbol();
1799 if (Sym != Obj.symbol_end()) {
1800 ErrorOr<StringRef> SymbolName = Sym->getName();
1802 Linker.reportWarning("error getting relocation symbol name.");
1805 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
1806 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1807 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1808 // Do not store the addend. The addend was the address of the
1809 // symbol in the object file, the address in the binary that is
1810 // stored in the debug map doesn't need to be offseted.
1811 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1816 /// \brief Dispatch the valid relocation finding logic to the
1817 /// appropriate handler depending on the object file format.
1818 bool DwarfLinker::RelocationManager::findValidRelocs(
1819 const object::SectionRef &Section, const object::ObjectFile &Obj,
1820 const DebugMapObject &DMO) {
1821 // Dispatch to the right handler depending on the file type.
1822 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1823 findValidRelocsMachO(Section, *MachOObj, DMO);
1825 Linker.reportWarning(Twine("unsupported object file type: ") +
1828 if (ValidRelocs.empty())
1831 // Sort the relocations by offset. We will walk the DIEs linearly in
1832 // the file, this allows us to just keep an index in the relocation
1833 // array that we advance during our walk, rather than resorting to
1834 // some associative container. See DwarfLinker::NextValidReloc.
1835 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1839 /// \brief Look for relocations in the debug_info section that match
1840 /// entries in the debug map. These relocations will drive the Dwarf
1841 /// link by indicating which DIEs refer to symbols present in the
1843 /// \returns wether there are any valid relocations in the debug info.
1844 bool DwarfLinker::RelocationManager::
1845 findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1846 const DebugMapObject &DMO) {
1847 // Find the debug_info section.
1848 for (const object::SectionRef &Section : Obj.sections()) {
1849 StringRef SectionName;
1850 Section.getName(SectionName);
1851 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1852 if (SectionName != "debug_info")
1854 return findValidRelocs(Section, Obj, DMO);
1859 /// \brief Checks that there is a relocation against an actual debug
1860 /// map entry between \p StartOffset and \p NextOffset.
1862 /// This function must be called with offsets in strictly ascending
1863 /// order because it never looks back at relocations it already 'went past'.
1864 /// \returns true and sets Info.InDebugMap if it is the case.
1865 bool DwarfLinker::RelocationManager::
1866 hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1867 CompileUnit::DIEInfo &Info) {
1868 assert(NextValidReloc == 0 ||
1869 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1870 if (NextValidReloc >= ValidRelocs.size())
1873 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1875 // We might need to skip some relocs that we didn't consider. For
1876 // example the high_pc of a discarded DIE might contain a reloc that
1877 // is in the list because it actually corresponds to the start of a
1878 // function that is in the debug map.
1879 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1880 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1882 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1885 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1886 const auto &Mapping = ValidReloc.Mapping->getValue();
1887 if (Linker.Options.Verbose)
1888 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1889 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1890 uint64_t(Mapping.ObjectAddress),
1891 uint64_t(Mapping.BinaryAddress));
1893 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1894 Mapping.ObjectAddress;
1895 Info.InDebugMap = true;
1899 /// \brief Get the starting and ending (exclusive) offset for the
1900 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1901 /// supposed to point to the position of the first attribute described
1903 /// \return [StartOffset, EndOffset) as a pair.
1904 static std::pair<uint32_t, uint32_t>
1905 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1906 unsigned Offset, const DWARFUnit &Unit) {
1907 DataExtractor Data = Unit.getDebugInfoExtractor();
1909 for (unsigned i = 0; i < Idx; ++i)
1910 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1912 uint32_t End = Offset;
1913 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1915 return std::make_pair(Offset, End);
1918 /// \brief Check if a variable describing DIE should be kept.
1919 /// \returns updated TraversalFlags.
1920 unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
1921 const DWARFDebugInfoEntryMinimal &DIE,
1923 CompileUnit::DIEInfo &MyInfo,
1925 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1927 // Global variables with constant value can always be kept.
1928 if (!(Flags & TF_InFunctionScope) &&
1929 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1930 MyInfo.InDebugMap = true;
1931 return Flags | TF_Keep;
1934 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1935 if (LocationIdx == -1U)
1938 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1939 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1940 uint32_t LocationOffset, LocationEndOffset;
1941 std::tie(LocationOffset, LocationEndOffset) =
1942 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1944 // See if there is a relocation to a valid debug map entry inside
1945 // this variable's location. The order is important here. We want to
1946 // always check in the variable has a valid relocation, so that the
1947 // DIEInfo is filled. However, we don't want a static variable in a
1948 // function to force us to keep the enclosing function.
1949 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1950 (Flags & TF_InFunctionScope))
1953 if (Options.Verbose)
1954 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1956 return Flags | TF_Keep;
1959 /// \brief Check if a function describing DIE should be kept.
1960 /// \returns updated TraversalFlags.
1961 unsigned DwarfLinker::shouldKeepSubprogramDIE(
1962 RelocationManager &RelocMgr,
1963 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1964 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1965 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1967 Flags |= TF_InFunctionScope;
1969 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1970 if (LowPcIdx == -1U)
1973 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1974 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1975 uint32_t LowPcOffset, LowPcEndOffset;
1976 std::tie(LowPcOffset, LowPcEndOffset) =
1977 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1980 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1981 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1982 if (LowPc == -1ULL ||
1983 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1986 if (Options.Verbose)
1987 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1991 DWARFFormValue HighPcValue;
1992 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1993 reportWarning("Function without high_pc. Range will be discarded.\n",
1999 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2000 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2002 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2003 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2006 // Replace the debug map range with a more accurate one.
2007 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
2008 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2012 /// \brief Check if a DIE should be kept.
2013 /// \returns updated TraversalFlags.
2014 unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
2015 const DWARFDebugInfoEntryMinimal &DIE,
2017 CompileUnit::DIEInfo &MyInfo,
2019 switch (DIE.getTag()) {
2020 case dwarf::DW_TAG_constant:
2021 case dwarf::DW_TAG_variable:
2022 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
2023 case dwarf::DW_TAG_subprogram:
2024 return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
2025 case dwarf::DW_TAG_module:
2026 case dwarf::DW_TAG_imported_module:
2027 case dwarf::DW_TAG_imported_declaration:
2028 case dwarf::DW_TAG_imported_unit:
2029 // We always want to keep these.
2030 return Flags | TF_Keep;
2036 /// \brief Mark the passed DIE as well as all the ones it depends on
2039 /// This function is called by lookForDIEsToKeep on DIEs that are
2040 /// newly discovered to be needed in the link. It recursively calls
2041 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2042 /// TraversalFlags to inform it that it's not doing the primary DIE
2044 void DwarfLinker::keepDIEAndDenpendencies(RelocationManager &RelocMgr,
2045 const DWARFDebugInfoEntryMinimal &Die,
2046 CompileUnit::DIEInfo &MyInfo,
2047 const DebugMapObject &DMO,
2048 CompileUnit &CU, bool UseODR) {
2049 const DWARFUnit &Unit = CU.getOrigUnit();
2052 // First mark all the parent chain as kept.
2053 unsigned AncestorIdx = MyInfo.ParentIdx;
2054 while (!CU.getInfo(AncestorIdx).Keep) {
2055 unsigned ODRFlag = UseODR ? TF_ODR : 0;
2056 lookForDIEsToKeep(RelocMgr, *Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
2057 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
2058 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2061 // Then we need to mark all the DIEs referenced by this DIE's
2062 // attributes as kept.
2063 DataExtractor Data = Unit.getDebugInfoExtractor();
2064 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2065 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
2067 // Mark all DIEs referenced through atttributes as kept.
2068 for (const auto &AttrSpec : Abbrev->attributes()) {
2069 DWARFFormValue Val(AttrSpec.Form);
2071 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2072 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2076 Val.extractValue(Data, &Offset, &Unit);
2077 CompileUnit *ReferencedCU;
2078 if (const auto *RefDIE =
2079 resolveDIEReference(Val, Unit, Die, ReferencedCU)) {
2080 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2081 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2082 // If the referenced DIE has a DeclContext that has already been
2083 // emitted, then do not keep the one in this CU. We'll link to
2084 // the canonical DIE in cloneDieReferenceAttribute.
2085 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2086 // be necessary and could be advantageously replaced by
2087 // ReferencedCU->hasODR() && CU.hasODR().
2088 // FIXME: compatibility with dsymutil-classic. There is no
2089 // reason not to unique ref_addr references.
2090 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2091 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2092 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2095 unsigned ODRFlag = UseODR ? TF_ODR : 0;
2096 lookForDIEsToKeep(RelocMgr, *RefDIE, DMO, *ReferencedCU,
2097 TF_Keep | TF_DependencyWalk | ODRFlag);
2102 /// \brief Recursively walk the \p DIE tree and look for DIEs to
2103 /// keep. Store that information in \p CU's DIEInfo.
2105 /// This function is the entry point of the DIE selection
2106 /// algorithm. It is expected to walk the DIE tree in file order and
2107 /// (though the mediation of its helper) call hasValidRelocation() on
2108 /// each DIE that might be a 'root DIE' (See DwarfLinker class
2110 /// While walking the dependencies of root DIEs, this function is
2111 /// also called, but during these dependency walks the file order is
2112 /// not respected. The TF_DependencyWalk flag tells us which kind of
2113 /// traversal we are currently doing.
2114 void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
2115 const DWARFDebugInfoEntryMinimal &Die,
2116 const DebugMapObject &DMO, CompileUnit &CU,
2118 unsigned Idx = CU.getOrigUnit().getDIEIndex(&Die);
2119 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2120 bool AlreadyKept = MyInfo.Keep;
2122 // If the Keep flag is set, we are marking a required DIE's
2123 // dependencies. If our target is already marked as kept, we're all
2125 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2128 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
2129 // because it would screw up the relocation finding logic.
2130 if (!(Flags & TF_DependencyWalk))
2131 Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
2133 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
2134 if (!AlreadyKept && (Flags & TF_Keep)) {
2135 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2136 keepDIEAndDenpendencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
2138 // The TF_ParentWalk flag tells us that we are currently walking up
2139 // the parent chain of a required DIE, and we don't want to mark all
2140 // the children of the parents as kept (consider for example a
2141 // DW_TAG_namespace node in the parent chain). There are however a
2142 // set of DIE types for which we want to ignore that directive and still
2143 // walk their children.
2144 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
2145 Flags &= ~TF_ParentWalk;
2147 if (!Die.hasChildren() || (Flags & TF_ParentWalk))
2150 for (auto *Child = Die.getFirstChild(); Child && !Child->isNULL();
2151 Child = Child->getSibling())
2152 lookForDIEsToKeep(RelocMgr, *Child, DMO, CU, Flags);
2155 /// \brief Assign an abbreviation numer to \p Abbrev.
2157 /// Our DIEs get freed after every DebugMapObject has been processed,
2158 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2159 /// the instances hold by the DIEs. When we encounter an abbreviation
2160 /// that we don't know, we create a permanent copy of it.
2161 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2162 // Check the set for priors.
2163 FoldingSetNodeID ID;
2166 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2168 // If it's newly added.
2170 // Assign existing abbreviation number.
2171 Abbrev.setNumber(InSet->getNumber());
2173 // Add to abbreviation list.
2174 Abbreviations.push_back(
2175 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2176 for (const auto &Attr : Abbrev.getData())
2177 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2178 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2179 // Assign the unique abbreviation number.
2180 Abbrev.setNumber(Abbreviations.size());
2181 Abbreviations.back()->setNumber(Abbreviations.size());
2185 /// \brief Clone a string attribute described by \p AttrSpec and add
2187 /// \returns the size of the new attribute.
2188 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
2189 const DWARFFormValue &Val,
2190 const DWARFUnit &U) {
2191 // Switch everything to out of line strings.
2192 const char *String = *Val.getAsCString(&U);
2193 unsigned Offset = StringPool.getStringOffset(String);
2194 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
2195 DIEInteger(Offset));
2199 /// \brief Clone an attribute referencing another DIE and add
2201 /// \returns the size of the new attribute.
2202 unsigned DwarfLinker::cloneDieReferenceAttribute(
2203 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2204 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
2205 CompileUnit &Unit) {
2206 const DWARFUnit &U = Unit.getOrigUnit();
2207 uint32_t Ref = *Val.getAsReference(&U);
2208 DIE *NewRefDie = nullptr;
2209 CompileUnit *RefUnit = nullptr;
2210 DeclContext *Ctxt = nullptr;
2212 const DWARFDebugInfoEntryMinimal *RefDie =
2213 resolveDIEReference(Val, U, InputDIE, RefUnit);
2215 // If the referenced DIE is not found, drop the attribute.
2219 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2220 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
2222 // If we already have emitted an equivalent DeclContext, just point
2224 if (isODRAttribute(AttrSpec.Attr)) {
2225 Ctxt = RefInfo.Ctxt;
2226 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2227 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2228 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2229 dwarf::DW_FORM_ref_addr, Attr);
2230 return getRefAddrSize(U);
2234 if (!RefInfo.Clone) {
2235 assert(Ref > InputDIE.getOffset());
2236 // We haven't cloned this DIE yet. Just create an empty one and
2237 // store it. It'll get really cloned when we process it.
2238 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
2240 NewRefDie = RefInfo.Clone;
2242 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2243 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
2244 // We cannot currently rely on a DIEEntry to emit ref_addr
2245 // references, because the implementation calls back to DwarfDebug
2246 // to find the unit offset. (We don't have a DwarfDebug)
2247 // FIXME: we should be able to design DIEEntry reliance on
2250 if (Ref < InputDIE.getOffset()) {
2251 // We must have already cloned that DIE.
2252 uint32_t NewRefOffset =
2253 RefUnit->getStartOffset() + NewRefDie->getOffset();
2254 Attr = NewRefOffset;
2255 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2256 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
2258 // A forward reference. Note and fixup later.
2260 Unit.noteForwardReference(
2261 NewRefDie, RefUnit, Ctxt,
2262 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2263 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
2265 return getRefAddrSize(U);
2268 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2269 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
2273 /// \brief Clone an attribute of block form (locations, constants) and add
2275 /// \returns the size of the new attribute.
2276 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
2277 const DWARFFormValue &Val,
2278 unsigned AttrSize) {
2281 DIELoc *Loc = nullptr;
2282 DIEBlock *Block = nullptr;
2283 // Just copy the block data over.
2284 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
2285 Loc = new (DIEAlloc) DIELoc;
2286 DIELocs.push_back(Loc);
2288 Block = new (DIEAlloc) DIEBlock;
2289 DIEBlocks.push_back(Block);
2291 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2292 : static_cast<DIEValueList *>(Block);
2295 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2296 dwarf::Form(AttrSpec.Form), Loc);
2298 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2299 dwarf::Form(AttrSpec.Form), Block);
2300 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2301 for (auto Byte : Bytes)
2302 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2303 dwarf::DW_FORM_data1, DIEInteger(Byte));
2304 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2305 // the DIE class, this if could be replaced by
2306 // Attr->setSize(Bytes.size()).
2309 Loc->ComputeSize(&Streamer->getAsmPrinter());
2311 Block->ComputeSize(&Streamer->getAsmPrinter());
2313 Die.addValue(DIEAlloc, Value);
2317 /// \brief Clone an address attribute and add it to \p Die.
2318 /// \returns the size of the new attribute.
2319 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
2320 const DWARFFormValue &Val,
2321 const CompileUnit &Unit,
2322 AttributesInfo &Info) {
2323 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
2324 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2325 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2326 Die.getTag() == dwarf::DW_TAG_lexical_block)
2327 // The low_pc of a block or inline subroutine might get
2328 // relocated because it happens to match the low_pc of the
2329 // enclosing subprogram. To prevent issues with that, always use
2330 // the low_pc from the input DIE if relocations have been applied.
2331 Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2333 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2334 Addr = Unit.getLowPc();
2335 if (Addr == UINT64_MAX)
2338 Info.HasLowPc = true;
2339 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
2340 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2341 if (uint64_t HighPc = Unit.getHighPc())
2346 // If we have a high_pc recorded for the input DIE, use
2347 // it. Otherwise (when no relocations where applied) just use the
2348 // one we just decoded.
2349 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
2352 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
2353 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
2354 return Unit.getOrigUnit().getAddressByteSize();
2357 /// \brief Clone a scalar attribute and add it to \p Die.
2358 /// \returns the size of the new attribute.
2359 unsigned DwarfLinker::cloneScalarAttribute(
2360 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2361 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
2362 AttributesInfo &Info) {
2364 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2365 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2366 if (Unit.getLowPc() == -1ULL)
2368 // Dwarf >= 4 high_pc is an size, not an address.
2369 Value = Unit.getHighPc() - Unit.getLowPc();
2370 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
2371 Value = *Val.getAsSectionOffset();
2372 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2373 Value = *Val.getAsSignedConstant();
2374 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2375 Value = *OptionalValue;
2377 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
2378 &Unit.getOrigUnit(), &InputDIE);
2381 PatchLocation Patch =
2382 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2383 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
2384 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
2385 Unit.noteRangeAttribute(Die, Patch);
2387 // A more generic way to check for location attributes would be
2388 // nice, but it's very unlikely that any other attribute needs a
2390 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2391 AttrSpec.Attr == dwarf::DW_AT_frame_base)
2392 Unit.noteLocationAttribute(Patch, Info.PCOffset);
2393 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2394 Info.IsDeclaration = true;
2399 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2400 /// value \p Val, and add it to \p Die.
2401 /// \returns the size of the cloned attribute.
2402 unsigned DwarfLinker::cloneAttribute(DIE &Die,
2403 const DWARFDebugInfoEntryMinimal &InputDIE,
2405 const DWARFFormValue &Val,
2406 const AttributeSpec AttrSpec,
2407 unsigned AttrSize, AttributesInfo &Info) {
2408 const DWARFUnit &U = Unit.getOrigUnit();
2410 switch (AttrSpec.Form) {
2411 case dwarf::DW_FORM_strp:
2412 case dwarf::DW_FORM_string:
2413 return cloneStringAttribute(Die, AttrSpec, Val, U);
2414 case dwarf::DW_FORM_ref_addr:
2415 case dwarf::DW_FORM_ref1:
2416 case dwarf::DW_FORM_ref2:
2417 case dwarf::DW_FORM_ref4:
2418 case dwarf::DW_FORM_ref8:
2419 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
2421 case dwarf::DW_FORM_block:
2422 case dwarf::DW_FORM_block1:
2423 case dwarf::DW_FORM_block2:
2424 case dwarf::DW_FORM_block4:
2425 case dwarf::DW_FORM_exprloc:
2426 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2427 case dwarf::DW_FORM_addr:
2428 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
2429 case dwarf::DW_FORM_data1:
2430 case dwarf::DW_FORM_data2:
2431 case dwarf::DW_FORM_data4:
2432 case dwarf::DW_FORM_data8:
2433 case dwarf::DW_FORM_udata:
2434 case dwarf::DW_FORM_sdata:
2435 case dwarf::DW_FORM_sec_offset:
2436 case dwarf::DW_FORM_flag:
2437 case dwarf::DW_FORM_flag_present:
2438 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2441 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2448 /// \brief Apply the valid relocations found by findValidRelocs() to
2449 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
2450 /// in the debug_info section.
2452 /// Like for findValidRelocs(), this function must be called with
2453 /// monotonic \p BaseOffset values.
2455 /// \returns wether any reloc has been applied.
2456 bool DwarfLinker::RelocationManager::
2457 applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2458 bool isLittleEndian) {
2459 assert((NextValidReloc == 0 ||
2460 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2461 "BaseOffset should only be increasing.");
2462 if (NextValidReloc >= ValidRelocs.size())
2465 // Skip relocs that haven't been applied.
2466 while (NextValidReloc < ValidRelocs.size() &&
2467 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2470 bool Applied = false;
2471 uint64_t EndOffset = BaseOffset + Data.size();
2472 while (NextValidReloc < ValidRelocs.size() &&
2473 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2474 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2475 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2476 assert(ValidReloc.Offset - BaseOffset < Data.size());
2477 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2479 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2480 Value += ValidReloc.Addend;
2481 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2482 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2483 Buf[i] = uint8_t(Value >> (Index * 8));
2485 assert(ValidReloc.Size <= sizeof(Buf));
2486 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2493 static bool isTypeTag(uint16_t Tag) {
2495 case dwarf::DW_TAG_array_type:
2496 case dwarf::DW_TAG_class_type:
2497 case dwarf::DW_TAG_enumeration_type:
2498 case dwarf::DW_TAG_pointer_type:
2499 case dwarf::DW_TAG_reference_type:
2500 case dwarf::DW_TAG_string_type:
2501 case dwarf::DW_TAG_structure_type:
2502 case dwarf::DW_TAG_subroutine_type:
2503 case dwarf::DW_TAG_typedef:
2504 case dwarf::DW_TAG_union_type:
2505 case dwarf::DW_TAG_ptr_to_member_type:
2506 case dwarf::DW_TAG_set_type:
2507 case dwarf::DW_TAG_subrange_type:
2508 case dwarf::DW_TAG_base_type:
2509 case dwarf::DW_TAG_const_type:
2510 case dwarf::DW_TAG_constant:
2511 case dwarf::DW_TAG_file_type:
2512 case dwarf::DW_TAG_namelist:
2513 case dwarf::DW_TAG_packed_type:
2514 case dwarf::DW_TAG_volatile_type:
2515 case dwarf::DW_TAG_restrict_type:
2516 case dwarf::DW_TAG_interface_type:
2517 case dwarf::DW_TAG_unspecified_type:
2518 case dwarf::DW_TAG_shared_type:
2527 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2528 uint16_t Tag, bool InDebugMap, bool SkipPC,
2529 bool InFunctionScope) {
2530 switch (AttrSpec.Attr) {
2533 case dwarf::DW_AT_low_pc:
2534 case dwarf::DW_AT_high_pc:
2535 case dwarf::DW_AT_ranges:
2537 case dwarf::DW_AT_location:
2538 case dwarf::DW_AT_frame_base:
2539 // FIXME: for some reason dsymutil-classic keeps the location
2540 // attributes when they are of block type (ie. not location
2541 // lists). This is totally wrong for globals where we will keep a
2542 // wrong address. It is mostly harmless for locals, but there is
2543 // no point in keeping these anyway when the function wasn't linked.
2544 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2546 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2550 /// \brief Recursively clone \p InputDIE's subtrees that have been
2551 /// selected to appear in the linked output.
2553 /// \param OutOffset is the Offset where the newly created DIE will
2554 /// lie in the linked compile unit.
2556 /// \returns the cloned DIE object or null if nothing was selected.
2557 DIE *DwarfLinker::cloneDIE(RelocationManager &RelocMgr,
2558 const DWARFDebugInfoEntryMinimal &InputDIE,
2559 CompileUnit &Unit, int64_t PCOffset,
2560 uint32_t OutOffset, unsigned Flags) {
2561 DWARFUnit &U = Unit.getOrigUnit();
2562 unsigned Idx = U.getDIEIndex(&InputDIE);
2563 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2565 // Should the DIE appear in the output?
2566 if (!Unit.getInfo(Idx).Keep)
2569 uint32_t Offset = InputDIE.getOffset();
2570 // The DIE might have been already created by a forward reference
2571 // (see cloneDieReferenceAttribute()).
2572 DIE *Die = Info.Clone;
2574 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
2575 assert(Die->getTag() == InputDIE.getTag());
2576 Die->setOffset(OutOffset);
2577 if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2578 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2579 !Info.Ctxt->getCanonicalDIEOffset()) {
2580 // We are about to emit a DIE that is the root of its own valid
2581 // DeclContext tree. Make the current offset the canonical offset
2582 // for this context.
2583 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2586 // Extract and clone every attribute.
2587 DataExtractor Data = U.getDebugInfoExtractor();
2588 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
2589 AttributesInfo AttrInfo;
2591 // We could copy the data only if we need to aply a relocation to
2592 // it. After testing, it seems there is no performance downside to
2593 // doing the copy unconditionally, and it makes the code simpler.
2594 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2595 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2596 // Modify the copy with relocated addresses.
2597 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2598 // If we applied relocations, we store the value of high_pc that was
2599 // potentially stored in the input DIE. If high_pc is an address
2600 // (Dwarf version == 2), then it might have been relocated to a
2601 // totally unrelated value (because the end address in the object
2602 // file might be start address of another function which got moved
2603 // independantly by the linker). The computation of the actual
2604 // high_pc value is done in cloneAddressAttribute().
2605 AttrInfo.OrigHighPc =
2606 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2607 // Also store the low_pc. It might get relocated in an
2608 // inline_subprogram that happens at the beginning of its
2609 // inlining function.
2610 AttrInfo.OrigLowPc =
2611 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_low_pc, UINT64_MAX);
2614 // Reset the Offset to 0 as we will be working on the local copy of
2618 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2619 Offset += getULEB128Size(Abbrev->getCode());
2621 // We are entering a subprogram. Get and propagate the PCOffset.
2622 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2623 PCOffset = Info.AddrAdjust;
2624 AttrInfo.PCOffset = PCOffset;
2626 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2627 Flags |= TF_InFunctionScope;
2628 if (!Info.InDebugMap)
2632 bool Copied = false;
2633 for (const auto &AttrSpec : Abbrev->attributes()) {
2634 if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2635 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2636 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2637 // FIXME: dsymutil-classic keeps the old abbreviation around
2638 // even if it's not used. We can remove this (and the copyAbbrev
2639 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2641 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2647 DWARFFormValue Val(AttrSpec.Form);
2648 uint32_t AttrSize = Offset;
2649 Val.extractValue(Data, &Offset, &U);
2650 AttrSize = Offset - AttrSize;
2653 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2656 // Look for accelerator entries.
2657 uint16_t Tag = InputDIE.getTag();
2658 // FIXME: This is slightly wrong. An inline_subroutine without a
2659 // low_pc, but with AT_ranges might be interesting to get into the
2660 // accelerator tables too. For now stick with dsymutil's behavior.
2661 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2662 Tag != dwarf::DW_TAG_compile_unit &&
2663 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2664 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2665 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2666 AttrInfo.MangledNameOffset,
2667 Tag == dwarf::DW_TAG_inlined_subroutine);
2669 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2670 Tag == dwarf::DW_TAG_inlined_subroutine);
2671 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2672 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2673 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2676 DIEAbbrev NewAbbrev = Die->generateAbbrev();
2677 // If a scope DIE is kept, we must have kept at least one child. If
2678 // it's not the case, we'll just be emitting one wasteful end of
2679 // children marker, but things won't break.
2680 if (InputDIE.hasChildren())
2681 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2682 // Assign a permanent abbrev number
2683 AssignAbbrev(NewAbbrev);
2684 Die->setAbbrevNumber(NewAbbrev.getNumber());
2686 // Add the size of the abbreviation number to the output offset.
2687 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2689 if (!Abbrev->hasChildren()) {
2691 Die->setSize(OutOffset - Die->getOffset());
2695 // Recursively clone children.
2696 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2697 Child = Child->getSibling()) {
2699 cloneDIE(RelocMgr, *Child, Unit, PCOffset, OutOffset, Flags)) {
2700 Die->addChild(Clone);
2701 OutOffset = Clone->getOffset() + Clone->getSize();
2705 // Account for the end of children marker.
2706 OutOffset += sizeof(int8_t);
2708 Die->setSize(OutOffset - Die->getOffset());
2712 /// \brief Patch the input object file relevant debug_ranges entries
2713 /// and emit them in the output file. Update the relevant attributes
2714 /// to point at the new entries.
2715 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2716 DWARFContext &OrigDwarf) const {
2717 DWARFDebugRangeList RangeList;
2718 const auto &FunctionRanges = Unit.getFunctionRanges();
2719 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2720 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2721 OrigDwarf.isLittleEndian(), AddressSize);
2722 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2723 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2724 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
2725 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2726 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2727 // Ranges addresses are based on the unit's low_pc. Compute the
2728 // offset we need to apply to adapt to the the new unit's low_pc.
2729 int64_t UnitPcOffset = 0;
2730 if (OrigLowPc != -1ULL)
2731 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2733 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2734 uint32_t Offset = RangeAttribute.get();
2735 RangeAttribute.set(Streamer->getRangesSectionSize());
2736 RangeList.extract(RangeExtractor, &Offset);
2737 const auto &Entries = RangeList.getEntries();
2738 if (!Entries.empty()) {
2739 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2741 if (CurrRange == InvalidRange ||
2742 First.StartAddress + OrigLowPc < CurrRange.start() ||
2743 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2744 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2745 if (CurrRange == InvalidRange ||
2746 CurrRange.start() > First.StartAddress + OrigLowPc) {
2747 reportWarning("no mapping for range.");
2753 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2758 /// \brief Generate the debug_aranges entries for \p Unit and if the
2759 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2760 /// contribution for this attribute.
2761 /// FIXME: this could actually be done right in patchRangesForUnit,
2762 /// but for the sake of initial bit-for-bit compatibility with legacy
2763 /// dsymutil, we have to do it in a delayed pass.
2764 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2765 auto Attr = Unit.getUnitRangesAttribute();
2767 Attr->set(Streamer->getRangesSectionSize());
2768 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
2771 /// \brief Insert the new line info sequence \p Seq into the current
2772 /// set of already linked line info \p Rows.
2773 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2774 std::vector<DWARFDebugLine::Row> &Rows) {
2778 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2779 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2784 auto InsertPoint = std::lower_bound(
2785 Rows.begin(), Rows.end(), Seq.front(),
2786 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2787 return LHS.Address < RHS.Address;
2790 // FIXME: this only removes the unneeded end_sequence if the
2791 // sequences have been inserted in order. using a global sort like
2792 // described in patchLineTableForUnit() and delaying the end_sequene
2793 // elimination to emitLineTableForUnit() we can get rid of all of them.
2794 if (InsertPoint != Rows.end() &&
2795 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2796 *InsertPoint = Seq.front();
2797 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2799 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2805 static void patchStmtList(DIE &Die, DIEInteger Offset) {
2806 for (auto &V : Die.values())
2807 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2808 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2812 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2815 /// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2816 /// recreate a relocated version of these for the address ranges that
2817 /// are present in the binary.
2818 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2819 DWARFContext &OrigDwarf) {
2820 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
2821 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2822 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2823 if (StmtList == -1ULL)
2826 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2827 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2828 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
2830 // Parse the original line info for the unit.
2831 DWARFDebugLine::LineTable LineTable;
2832 uint32_t StmtOffset = StmtList;
2833 StringRef LineData = OrigDwarf.getLineSection().Data;
2834 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2835 Unit.getOrigUnit().getAddressByteSize());
2836 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2839 // This vector is the output line table.
2840 std::vector<DWARFDebugLine::Row> NewRows;
2841 NewRows.reserve(LineTable.Rows.size());
2843 // Current sequence of rows being extracted, before being inserted
2845 std::vector<DWARFDebugLine::Row> Seq;
2846 const auto &FunctionRanges = Unit.getFunctionRanges();
2847 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2849 // FIXME: This logic is meant to generate exactly the same output as
2850 // Darwin's classic dsynutil. There is a nicer way to implement this
2851 // by simply putting all the relocated line info in NewRows and simply
2852 // sorting NewRows before passing it to emitLineTableForUnit. This
2853 // should be correct as sequences for a function should stay
2854 // together in the sorted output. There are a few corner cases that
2855 // look suspicious though, and that required to implement the logic
2856 // this way. Revisit that once initial validation is finished.
2858 // Iterate over the object file line info and extract the sequences
2859 // that correspond to linked functions.
2860 for (auto &Row : LineTable.Rows) {
2861 // Check wether we stepped out of the range. The range is
2862 // half-open, but consider accept the end address of the range if
2863 // it is marked as end_sequence in the input (because in that
2864 // case, the relocation offset is accurate and that entry won't
2865 // serve as the start of another function).
2866 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2867 Row.Address > CurrRange.stop() ||
2868 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2869 // We just stepped out of a known range. Insert a end_sequence
2870 // corresponding to the end of the range.
2871 uint64_t StopAddress = CurrRange != InvalidRange
2872 ? CurrRange.stop() + CurrRange.value()
2874 CurrRange = FunctionRanges.find(Row.Address);
2875 bool CurrRangeValid =
2876 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2877 if (!CurrRangeValid) {
2878 CurrRange = InvalidRange;
2879 if (StopAddress != -1ULL) {
2880 // Try harder by looking in the DebugMapObject function
2881 // ranges map. There are corner cases where this finds a
2882 // valid entry. It's unclear if this is right or wrong, but
2883 // for now do as dsymutil.
2884 // FIXME: Understand exactly what cases this addresses and
2885 // potentially remove it along with the Ranges map.
2886 auto Range = Ranges.lower_bound(Row.Address);
2887 if (Range != Ranges.begin() && Range != Ranges.end())
2890 if (Range != Ranges.end() && Range->first <= Row.Address &&
2891 Range->second.first >= Row.Address) {
2892 StopAddress = Row.Address + Range->second.second;
2896 if (StopAddress != -1ULL && !Seq.empty()) {
2897 // Insert end sequence row with the computed end address, but
2898 // the same line as the previous one.
2899 auto NextLine = Seq.back();
2900 NextLine.Address = StopAddress;
2901 NextLine.EndSequence = 1;
2902 NextLine.PrologueEnd = 0;
2903 NextLine.BasicBlock = 0;
2904 NextLine.EpilogueBegin = 0;
2905 Seq.push_back(NextLine);
2906 insertLineSequence(Seq, NewRows);
2909 if (!CurrRangeValid)
2913 // Ignore empty sequences.
2914 if (Row.EndSequence && Seq.empty())
2917 // Relocate row address and add it to the current sequence.
2918 Row.Address += CurrRange.value();
2919 Seq.emplace_back(Row);
2921 if (Row.EndSequence)
2922 insertLineSequence(Seq, NewRows);
2925 // Finished extracting, now emit the line tables.
2926 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2927 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2928 // prologue over and that works because we act as both producer and
2929 // consumer. It would be nicer to have a real configurable line
2931 if (LineTable.Prologue.Version != 2 ||
2932 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2933 LineTable.Prologue.OpcodeBase > 13)
2934 reportWarning("line table paramters mismatch. Cannot emit.");
2936 MCDwarfLineTableParams Params;
2937 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
2938 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
2939 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
2940 Streamer->emitLineTableForUnit(Params,
2941 LineData.slice(StmtList + 4, PrologueEnd),
2942 LineTable.Prologue.MinInstLength, NewRows,
2943 Unit.getOrigUnit().getAddressByteSize());
2947 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2948 Streamer->emitPubNamesForUnit(Unit);
2949 Streamer->emitPubTypesForUnit(Unit);
2952 /// \brief Read the frame info stored in the object, and emit the
2953 /// patched frame descriptions for the linked binary.
2955 /// This is actually pretty easy as the data of the CIEs and FDEs can
2956 /// be considered as black boxes and moved as is. The only thing to do
2957 /// is to patch the addresses in the headers.
2958 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2959 DWARFContext &OrigDwarf,
2960 unsigned AddrSize) {
2961 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2962 if (FrameData.empty())
2965 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2966 uint32_t InputOffset = 0;
2968 // Store the data of the CIEs defined in this object, keyed by their
2970 DenseMap<uint32_t, StringRef> LocalCIES;
2972 while (Data.isValidOffset(InputOffset)) {
2973 uint32_t EntryOffset = InputOffset;
2974 uint32_t InitialLength = Data.getU32(&InputOffset);
2975 if (InitialLength == 0xFFFFFFFF)
2976 return reportWarning("Dwarf64 bits no supported");
2978 uint32_t CIEId = Data.getU32(&InputOffset);
2979 if (CIEId == 0xFFFFFFFF) {
2980 // This is a CIE, store it.
2981 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2982 LocalCIES[EntryOffset] = CIEData;
2983 // The -4 is to account for the CIEId we just read.
2984 InputOffset += InitialLength - 4;
2988 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2990 // Some compilers seem to emit frame info that doesn't start at
2991 // the function entry point, thus we can't just lookup the address
2992 // in the debug map. Use the linker's range map to see if the FDE
2993 // describes something that we can relocate.
2994 auto Range = Ranges.upper_bound(Loc);
2995 if (Range != Ranges.begin())
2997 if (Range == Ranges.end() || Range->first > Loc ||
2998 Range->second.first <= Loc) {
2999 // The +4 is to account for the size of the InitialLength field itself.
3000 InputOffset = EntryOffset + InitialLength + 4;
3004 // This is an FDE, and we have a mapping.
3005 // Have we already emitted a corresponding CIE?
3006 StringRef CIEData = LocalCIES[CIEId];
3007 if (CIEData.empty())
3008 return reportWarning("Inconsistent debug_frame content. Dropping.");
3010 // Look if we already emitted a CIE that corresponds to the
3011 // referenced one (the CIE data is the key of that lookup).
3012 auto IteratorInserted = EmittedCIEs.insert(
3013 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3014 // If there is no CIE yet for this ID, emit it.
3015 if (IteratorInserted.second ||
3016 // FIXME: dsymutil-classic only caches the last used CIE for
3017 // reuse. Mimic that behavior for now. Just removing that
3018 // second half of the condition and the LastCIEOffset variable
3019 // makes the code DTRT.
3020 LastCIEOffset != IteratorInserted.first->getValue()) {
3021 LastCIEOffset = Streamer->getFrameSectionSize();
3022 IteratorInserted.first->getValue() = LastCIEOffset;
3023 Streamer->emitCIE(CIEData);
3026 // Emit the FDE with updated address and CIE pointer.
3027 // (4 + AddrSize) is the size of the CIEId + initial_location
3028 // fields that will get reconstructed by emitFDE().
3029 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3030 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3031 Loc + Range->second.second,
3032 FrameData.substr(InputOffset, FDERemainingBytes));
3033 InputOffset += FDERemainingBytes;
3037 void DwarfLinker::copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev,
3039 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3040 dwarf::Form(Abbrev.hasChildren()));
3042 for (const auto &Attr : Abbrev.attributes()) {
3043 uint16_t Form = Attr.Form;
3044 if (hasODR && isODRAttribute(Attr.Attr))
3045 Form = dwarf::DW_FORM_ref_addr;
3046 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3052 ErrorOr<const object::ObjectFile &>
3053 DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3054 const DebugMap &Map) {
3056 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
3057 if (std::error_code EC = ErrOrObjs.getError()) {
3058 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3061 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3062 if (std::error_code EC = ErrOrObj.getError())
3063 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3067 void DwarfLinker::cloneCompileUnit(RelocationManager &RelocMgr,
3068 MutableArrayRef<CompileUnit> CompileUnits,
3069 DWARFContextInMemory &DwarfContext) {
3073 for (auto &CurrentUnit : CompileUnits) {
3074 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
3075 CurrentUnit.setStartOffset(OutputDebugInfoSize);
3076 DIE *OutputDIE = cloneDIE(RelocMgr, *InputDIE, CurrentUnit,
3077 0 /* PC offset */, 11 /* Unit Header size */, 0);
3078 CurrentUnit.setOutputUnitDIE(OutputDIE);
3079 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3080 if (Options.NoOutput)
3082 // FIXME: for compatibility with the classic dsymutil, we emit
3083 // an empty line table for the unit, even if the unit doesn't
3084 // actually exist in the DIE tree.
3085 patchLineTableForUnit(CurrentUnit, DwarfContext);
3088 patchRangesForUnit(CurrentUnit, DwarfContext);
3089 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3090 emitAcceleratorEntriesForUnit(CurrentUnit);
3093 if (Options.NoOutput)
3096 // Emit all the compile unit's debug information.
3097 for (auto &CurrentUnit : CompileUnits) {
3098 generateUnitRanges(CurrentUnit);
3099 CurrentUnit.fixupForwardReferences();
3100 Streamer->emitCompileUnitHeader(CurrentUnit);
3101 if (!CurrentUnit.getOutputUnitDIE())
3103 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
3107 bool DwarfLinker::link(const DebugMap &Map) {
3109 if (!createStreamer(Map.getTriple(), OutputFilename))
3112 // Size of the DIEs (and headers) generated for the linked output.
3113 OutputDebugInfoSize = 0;
3114 // A unique ID that identifies each compile unit.
3115 unsigned UnitID = 0;
3116 for (const auto &Obj : Map.objects()) {
3117 CurrentDebugObject = Obj.get();
3119 if (Options.Verbose)
3120 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
3121 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3125 // Look for relocations that correspond to debug map entries.
3126 RelocationManager RelocMgr(*this);
3127 if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
3128 if (Options.Verbose)
3129 outs() << "No valid relocations found. Skipping.\n";
3133 // Setup access to the debug info.
3134 DWARFContextInMemory DwarfContext(*ErrOrObj);
3135 startDebugObject(DwarfContext, *Obj);
3137 // In a first phase, just read in the debug info and store the DIE
3138 // parent links that we will use during the next phase.
3139 for (const auto &CU : DwarfContext.compile_units()) {
3140 auto *CUDie = CU->getUnitDIE(false);
3141 if (Options.Verbose) {
3142 outs() << "Input compilation unit:";
3143 CUDie->dump(outs(), CU.get(), 0);
3145 Units.emplace_back(*CU, UnitID++, !Options.NoODR);
3146 gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
3147 StringPool, ODRContexts);
3150 // Then mark all the DIEs that need to be present in the linked
3151 // output and collect some information about them. Note that this
3152 // loop can not be merged with the previous one becaue cross-cu
3153 // references require the ParentIdx to be setup for every CU in
3154 // the object file before calling this.
3155 for (auto &CurrentUnit : Units)
3156 lookForDIEsToKeep(RelocMgr, *CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
3159 // The calls to applyValidRelocs inside cloneDIE will walk the
3160 // reloc array again (in the same way findValidRelocsInDebugInfo()
3161 // did). We need to reset the NextValidReloc index to the beginning.
3162 RelocMgr.resetValidRelocs();
3163 if (RelocMgr.hasValidRelocs())
3164 cloneCompileUnit(RelocMgr, Units, DwarfContext);
3165 if (!Options.NoOutput && !Units.empty())
3166 patchFrameInfoForObject(*Obj, DwarfContext,
3167 Units[0].getOrigUnit().getAddressByteSize());
3169 // Clean-up before starting working on the next object.
3173 // Emit everything that's global.
3174 if (!Options.NoOutput) {
3175 Streamer->emitAbbrevs(Abbreviations);
3176 Streamer->emitStrings(StringPool);
3179 return Options.NoOutput ? true : Streamer->finish(Map);
3183 /// \brief Get the offset of string \p S in the string table. This
3184 /// can insert a new element or return the offset of a preexisitng
3186 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3187 if (S.empty() && !Strings.empty())
3190 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3194 // A non-empty string can't be at offset 0, so if we have an entry
3195 // with a 0 offset, it must be a previously interned string.
3196 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3197 if (Inserted || It->getValue().first == 0) {
3198 // Set offset and chain at the end of the entries list.
3199 It->getValue().first = CurrentEndOffset;
3200 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3201 Last->getValue().second = &*It;
3204 return It->getValue().first;
3207 /// \brief Put \p S into the StringMap so that it gets permanent
3208 /// storage, but do not actually link it in the chain of elements
3209 /// that go into the output section. A latter call to
3210 /// getStringOffset() with the same string will chain it though.
3211 StringRef NonRelocatableStringpool::internString(StringRef S) {
3212 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3213 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3214 return InsertResult.first->getKey();
3217 void warn(const Twine &Warning, const Twine &Context) {
3218 errs() << Twine("while processing ") + Context + ":\n";
3219 errs() << Twine("warning: ") + Warning + "\n";
3222 bool error(const Twine &Error, const Twine &Context) {
3223 errs() << Twine("while processing ") + Context + ":\n";
3224 errs() << Twine("error: ") + Error + "\n";
3228 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3229 const LinkOptions &Options) {
3230 DwarfLinker Linker(OutputFilename, Options);
3231 return Linker.link(DM);