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 "NonRelocatableStringpool.h"
14 #include "llvm/ADT/IntervalMap.h"
15 #include "llvm/ADT/StringMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/CodeGen/AsmPrinter.h"
18 #include "llvm/CodeGen/DIE.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
21 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
22 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
23 #include "llvm/MC/MCAsmBackend.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCCodeEmitter.h"
27 #include "llvm/MC/MCDwarf.h"
28 #include "llvm/MC/MCInstrInfo.h"
29 #include "llvm/MC/MCObjectFileInfo.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSubtargetInfo.h"
33 #include "llvm/Object/MachO.h"
34 #include "llvm/Support/Dwarf.h"
35 #include "llvm/Support/LEB128.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
47 template <typename KeyT, typename ValT>
48 using HalfOpenIntervalMap =
49 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
50 IntervalMapHalfOpenInfo<KeyT>>;
52 typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
54 // FIXME: Delete this structure.
55 struct PatchLocation {
56 DIE::value_iterator I;
58 PatchLocation() = default;
59 PatchLocation(DIE::value_iterator I) : I(I) {}
61 void set(uint64_t New) const {
64 assert(Old.getType() == DIEValue::isInteger);
65 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
68 uint64_t get() const {
70 return I->getDIEInteger().getValue();
77 /// A DeclContext is a named program scope that is used for ODR
78 /// uniquing of types.
79 /// The set of DeclContext for the ODR-subject parts of a Dwarf link
80 /// is expanded (and uniqued) with each new object file processed. We
81 /// need to determine the context of each DIE in an linked object file
82 /// to see if the corresponding type has already been emitted.
84 /// The contexts are conceptually organised as a tree (eg. a function
85 /// scope is contained in a namespace scope that contains other
86 /// scopes), but storing/accessing them in an actual tree is too
87 /// inefficient: we need to be able to very quickly query a context
88 /// for a given child context by name. Storing a StringMap in each
89 /// DeclContext would be too space inefficient.
90 /// The solution here is to give each DeclContext a link to its parent
91 /// (this allows to walk up the tree), but to query the existance of a
92 /// specific DeclContext using a separate DenseMap keyed on the hash
93 /// of the fully qualified name of the context.
95 unsigned QualifiedNameHash;
101 const DeclContext &Parent;
102 const DWARFDebugInfoEntryMinimal *LastSeenDIE;
103 uint32_t LastSeenCompileUnitID;
104 uint32_t CanonicalDIEOffset;
109 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
112 : QualifiedNameHash(0), Line(0), ByteSize(0),
113 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
114 LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
116 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
117 StringRef Name, StringRef File, const DeclContext &Parent,
118 const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
120 : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
121 Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
122 LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
124 uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
126 bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
128 uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
129 void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
131 uint16_t getTag() const { return Tag; }
132 StringRef getName() const { return Name; }
135 /// Info type for the DenseMap storing the DeclContext pointers.
136 struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
137 using DenseMapInfo<DeclContext *>::getEmptyKey;
138 using DenseMapInfo<DeclContext *>::getTombstoneKey;
140 static unsigned getHashValue(const DeclContext *Ctxt) {
141 return Ctxt->QualifiedNameHash;
144 static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
145 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
147 return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
148 LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
149 LHS->Name.data() == RHS->Name.data() &&
150 LHS->File.data() == RHS->File.data() &&
151 LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
155 /// This class gives a tree-like API to the DenseMap that stores the
156 /// DeclContext objects. It also holds the BumpPtrAllocator where
157 /// these objects will be allocated.
158 class DeclContextTree {
159 BumpPtrAllocator Allocator;
161 DeclContext::Map Contexts;
164 /// Get the child of \a Context described by \a DIE in \a Unit. The
165 /// required strings will be interned in \a StringPool.
166 /// \returns The child DeclContext along with one bit that is set if
167 /// this context is invalid.
168 /// FIXME: the invalid bit along the return value is to emulate some
169 /// dsymutil-classic functionality. See the fucntion definition for
170 /// a more thorough discussion of its use.
171 PointerIntPair<DeclContext *, 1>
172 getChildDeclContext(DeclContext &Context,
173 const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
174 NonRelocatableStringpool &StringPool);
176 DeclContext &getRoot() { return Root; }
179 /// \brief Stores all information relating to a compile unit, be it in
180 /// its original instance in the object file to its brand new cloned
181 /// and linked DIE tree.
184 /// \brief Information gathered about a DIE in the object file.
186 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
187 DeclContext *Ctxt; ///< ODR Declaration context.
188 DIE *Clone; ///< Cloned version of that DIE.
189 uint32_t ParentIdx; ///< The index of this DIE's parent.
190 bool Keep; ///< Is the DIE part of the linked output?
191 bool InDebugMap; ///< Was this DIE's entity found in the map?
194 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR)
195 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
197 Info.resize(OrigUnit.getNumDIEs());
199 const auto *CUDie = OrigUnit.getUnitDIE(false);
200 unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
201 &OrigUnit, dwarf::DW_AT_language, 0);
202 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
203 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
204 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
205 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
206 Lang == dwarf::DW_LANG_ObjC_plus_plus);
209 CompileUnit(CompileUnit &&RHS)
210 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
211 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
212 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
213 // The CompileUnit container has been 'reserve()'d with the right
214 // size. We cannot move the IntervalMap anyway.
215 llvm_unreachable("CompileUnits should not be moved.");
218 DWARFUnit &getOrigUnit() const { return OrigUnit; }
220 unsigned getUniqueID() const { return ID; }
222 DIE *getOutputUnitDIE() const { return CUDie; }
223 void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
225 bool hasODR() const { return HasODR; }
227 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
228 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
230 uint64_t getStartOffset() const { return StartOffset; }
231 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
232 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
234 uint64_t getLowPc() const { return LowPc; }
235 uint64_t getHighPc() const { return HighPc; }
237 Optional<PatchLocation> getUnitRangesAttribute() const {
238 return UnitRangeAttribute;
240 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
241 const std::vector<PatchLocation> &getRangesAttributes() const {
242 return RangeAttributes;
245 const std::vector<std::pair<PatchLocation, int64_t>> &
246 getLocationAttributes() const {
247 return LocationAttributes;
250 /// \brief Compute the end offset for this unit. Must be
251 /// called after the CU's DIEs have been cloned.
252 /// \returns the next unit offset (which is also the current
253 /// debug_info section size).
254 uint64_t computeNextUnitOffset();
256 /// \brief Keep track of a forward reference to DIE \p Die in \p
257 /// RefUnit by \p Attr. The attribute should be fixed up later to
258 /// point to the absolute offset of \p Die in the debug_info section
259 /// or to the canonical offset of \p Ctxt if it is non-null.
260 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
261 DeclContext *Ctxt, PatchLocation Attr);
263 /// \brief Apply all fixups recored by noteForwardReference().
264 void fixupForwardReferences();
266 /// \brief Add a function range [\p LowPC, \p HighPC) that is
267 /// relocatad by applying offset \p PCOffset.
268 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
270 /// \brief Keep track of a DW_AT_range attribute that we will need to
272 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
274 /// \brief Keep track of a location attribute pointing to a location
275 /// list in the debug_loc section.
276 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
278 /// \brief Add a name accelerator entry for \p Die with \p Name
279 /// which is stored in the string table at \p Offset.
280 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
281 bool SkipPubnamesSection = false);
283 /// \brief Add a type accelerator entry for \p Die with \p Name
284 /// which is stored in the string table at \p Offset.
285 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
288 StringRef Name; ///< Name of the entry.
289 const DIE *Die; ///< DIE this entry describes.
290 uint32_t NameOffset; ///< Offset of Name in the string pool.
291 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
293 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
294 bool SkipPubSection = false)
295 : Name(Name), Die(Die), NameOffset(NameOffset),
296 SkipPubSection(SkipPubSection) {}
299 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
300 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
302 /// Get the full path for file \a FileNum in the line table
303 const char *getResolvedPath(unsigned FileNum) {
304 if (FileNum >= ResolvedPaths.size())
306 return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
310 /// Set the fully resolved path for the line-table's file \a FileNum
312 void setResolvedPath(unsigned FileNum, const std::string &Path) {
313 if (ResolvedPaths.size() <= FileNum)
314 ResolvedPaths.resize(FileNum + 1);
315 ResolvedPaths[FileNum] = Path;
321 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
322 DIE *CUDie; ///< Root of the linked DIE tree.
324 uint64_t StartOffset;
325 uint64_t NextUnitOffset;
330 /// \brief A list of attributes to fixup with the absolute offset of
331 /// a DIE in the debug_info section.
333 /// The offsets for the attributes in this array couldn't be set while
334 /// cloning because for cross-cu forward refences the target DIE's
335 /// offset isn't known you emit the reference attribute.
336 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
337 PatchLocation>> ForwardDIEReferences;
339 FunctionIntervals::Allocator RangeAlloc;
340 /// \brief The ranges in that interval map are the PC ranges for
341 /// functions in this unit, associated with the PC offset to apply
342 /// to the addresses to get the linked address.
343 FunctionIntervals Ranges;
345 /// \brief DW_AT_ranges attributes to patch after we have gathered
346 /// all the unit's function addresses.
348 std::vector<PatchLocation> RangeAttributes;
349 Optional<PatchLocation> UnitRangeAttribute;
352 /// \brief Location attributes that need to be transfered from th
353 /// original debug_loc section to the liked one. They are stored
354 /// along with the PC offset that is to be applied to their
355 /// function's address.
356 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
358 /// \brief Accelerator entries for the unit, both for the pub*
359 /// sections and the apple* ones.
361 std::vector<AccelInfo> Pubnames;
362 std::vector<AccelInfo> Pubtypes;
365 /// Cached resolved paths from the line table.
366 std::vector<std::string> ResolvedPaths;
368 /// Is this unit subject to the ODR rule?
372 uint64_t CompileUnit::computeNextUnitOffset() {
373 NextUnitOffset = StartOffset + 11 /* Header size */;
374 // The root DIE might be null, meaning that the Unit had nothing to
375 // contribute to the linked output. In that case, we will emit the
376 // unit header without any actual DIE.
378 NextUnitOffset += CUDie->getSize();
379 return NextUnitOffset;
382 /// \brief Keep track of a forward cross-cu reference from this unit
383 /// to \p Die that lives in \p RefUnit.
384 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
385 DeclContext *Ctxt, PatchLocation Attr) {
386 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
389 /// \brief Apply all fixups recorded by noteForwardReference().
390 void CompileUnit::fixupForwardReferences() {
391 for (const auto &Ref : ForwardDIEReferences) {
393 const CompileUnit *RefUnit;
396 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
397 if (Ctxt && Ctxt->getCanonicalDIEOffset())
398 Attr.set(Ctxt->getCanonicalDIEOffset());
400 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
404 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
406 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
407 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
408 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
411 void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
412 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
413 RangeAttributes.push_back(Attr);
415 UnitRangeAttribute = Attr;
418 void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
419 LocationAttributes.emplace_back(Attr, PcOffset);
422 /// \brief Add a name accelerator entry for \p Die with \p Name
423 /// which is stored in the string table at \p Offset.
424 void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
425 uint32_t Offset, bool SkipPubSection) {
426 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
429 /// \brief Add a type accelerator entry for \p Die with \p Name
430 /// which is stored in the string table at \p Offset.
431 void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
433 Pubtypes.emplace_back(Name, Die, Offset, false);
436 /// \brief The Dwarf streaming logic
438 /// All interactions with the MC layer that is used to build the debug
439 /// information binary representation are handled in this class.
440 class DwarfStreamer {
441 /// \defgroup MCObjects MC layer objects constructed by the streamer
443 std::unique_ptr<MCRegisterInfo> MRI;
444 std::unique_ptr<MCAsmInfo> MAI;
445 std::unique_ptr<MCObjectFileInfo> MOFI;
446 std::unique_ptr<MCContext> MC;
447 MCAsmBackend *MAB; // Owned by MCStreamer
448 std::unique_ptr<MCInstrInfo> MII;
449 std::unique_ptr<MCSubtargetInfo> MSTI;
450 MCCodeEmitter *MCE; // Owned by MCStreamer
451 MCStreamer *MS; // Owned by AsmPrinter
452 std::unique_ptr<TargetMachine> TM;
453 std::unique_ptr<AsmPrinter> Asm;
456 /// \brief the file we stream the linked Dwarf to.
457 std::unique_ptr<raw_fd_ostream> OutFile;
459 uint32_t RangesSectionSize;
460 uint32_t LocSectionSize;
461 uint32_t LineSectionSize;
462 uint32_t FrameSectionSize;
464 /// \brief Emit the pubnames or pubtypes section contribution for \p
465 /// Unit into \p Sec. The data is provided in \p Names.
466 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
467 const CompileUnit &Unit,
468 const std::vector<CompileUnit::AccelInfo> &Names);
471 /// \brief Actually create the streamer and the ouptut file.
473 /// This could be done directly in the constructor, but it feels
474 /// more natural to handle errors through return value.
475 bool init(Triple TheTriple, StringRef OutputFilename);
477 /// \brief Dump the file to the disk.
480 AsmPrinter &getAsmPrinter() const { return *Asm; }
482 /// \brief Set the current output section to debug_info and change
483 /// the MC Dwarf version to \p DwarfVersion.
484 void switchToDebugInfoSection(unsigned DwarfVersion);
486 /// \brief Emit the compilation unit header for \p Unit in the
487 /// debug_info section.
489 /// As a side effect, this also switches the current Dwarf version
490 /// of the MC layer to the one of U.getOrigUnit().
491 void emitCompileUnitHeader(CompileUnit &Unit);
493 /// \brief Recursively emit the DIE tree rooted at \p Die.
494 void emitDIE(DIE &Die);
496 /// \brief Emit the abbreviation table \p Abbrevs to the
497 /// debug_abbrev section.
498 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
500 /// \brief Emit the string table described by \p Pool.
501 void emitStrings(const NonRelocatableStringpool &Pool);
503 /// \brief Emit debug_ranges for \p FuncRange by translating the
504 /// original \p Entries.
505 void emitRangesEntries(
506 int64_t UnitPcOffset, uint64_t OrigLowPc,
507 FunctionIntervals::const_iterator FuncRange,
508 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
509 unsigned AddressSize);
511 /// \brief Emit debug_aranges entries for \p Unit and if \p
512 /// DoRangesSection is true, also emit the debug_ranges entries for
513 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
514 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
516 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
518 /// \brief Emit the debug_loc contribution for \p Unit by copying
519 /// the entries from \p Dwarf and offseting them. Update the
520 /// location attributes to point to the new entries.
521 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
523 /// \brief Emit the line table described in \p Rows into the
524 /// debug_line section.
525 void emitLineTableForUnit(MCDwarfLineTableParams Params,
526 StringRef PrologueBytes, unsigned MinInstLength,
527 std::vector<DWARFDebugLine::Row> &Rows,
528 unsigned AdddressSize);
530 uint32_t getLineSectionSize() const { return LineSectionSize; }
532 /// \brief Emit the .debug_pubnames contribution for \p Unit.
533 void emitPubNamesForUnit(const CompileUnit &Unit);
535 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
536 void emitPubTypesForUnit(const CompileUnit &Unit);
538 /// \brief Emit a CIE.
539 void emitCIE(StringRef CIEBytes);
541 /// \brief Emit an FDE with data \p Bytes.
542 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
545 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
548 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
549 std::string ErrorStr;
550 std::string TripleName;
551 StringRef Context = "dwarf streamer init";
554 const Target *TheTarget =
555 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
557 return error(ErrorStr, Context);
558 TripleName = TheTriple.getTriple();
560 // Create all the MC Objects.
561 MRI.reset(TheTarget->createMCRegInfo(TripleName));
563 return error(Twine("no register info for target ") + TripleName, Context);
565 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
567 return error("no asm info for target " + TripleName, Context);
569 MOFI.reset(new MCObjectFileInfo);
570 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
571 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
574 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
576 return error("no asm backend for target " + TripleName, Context);
578 MII.reset(TheTarget->createMCInstrInfo());
580 return error("no instr info info for target " + TripleName, Context);
582 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
584 return error("no subtarget info for target " + TripleName, Context);
586 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
588 return error("no code emitter for target " + TripleName, Context);
590 // Create the output file.
593 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
595 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
597 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
599 /*DWARFMustBeAtTheEnd*/ false);
601 return error("no object streamer for target " + TripleName, Context);
603 // Finally create the AsmPrinter we'll use to emit the DIEs.
604 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
606 return error("no target machine for target " + TripleName, Context);
608 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
610 return error("no asm printer for target " + TripleName, Context);
612 RangesSectionSize = 0;
615 FrameSectionSize = 0;
620 bool DwarfStreamer::finish() {
625 /// \brief Set the current output section to debug_info and change
626 /// the MC Dwarf version to \p DwarfVersion.
627 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
628 MS->SwitchSection(MOFI->getDwarfInfoSection());
629 MC->setDwarfVersion(DwarfVersion);
632 /// \brief Emit the compilation unit header for \p Unit in the
633 /// debug_info section.
635 /// A Dwarf scetion header is encoded as:
636 /// uint32_t Unit length (omiting this field)
638 /// uint32_t Abbreviation table offset
639 /// uint8_t Address size
641 /// Leading to a total of 11 bytes.
642 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
643 unsigned Version = Unit.getOrigUnit().getVersion();
644 switchToDebugInfoSection(Version);
646 // Emit size of content not including length itself. The size has
647 // already been computed in CompileUnit::computeOffsets(). Substract
648 // 4 to that size to account for the length field.
649 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
650 Asm->EmitInt16(Version);
651 // We share one abbreviations table across all units so it's always at the
652 // start of the section.
654 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
657 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
658 /// for the linked Dwarf file.
659 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
660 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
661 Asm->emitDwarfAbbrevs(Abbrevs);
664 /// \brief Recursively emit the DIE tree rooted at \p Die.
665 void DwarfStreamer::emitDIE(DIE &Die) {
666 MS->SwitchSection(MOFI->getDwarfInfoSection());
667 Asm->emitDwarfDIE(Die);
670 /// \brief Emit the debug_str section stored in \p Pool.
671 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
672 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
673 for (auto *Entry = Pool.getFirstEntry(); Entry;
674 Entry = Pool.getNextEntry(Entry))
675 Asm->OutStreamer->EmitBytes(
676 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
679 /// \brief Emit the debug_range section contents for \p FuncRange by
680 /// translating the original \p Entries. The debug_range section
681 /// format is totally trivial, consisting just of pairs of address
682 /// sized addresses describing the ranges.
683 void DwarfStreamer::emitRangesEntries(
684 int64_t UnitPcOffset, uint64_t OrigLowPc,
685 FunctionIntervals::const_iterator FuncRange,
686 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
687 unsigned AddressSize) {
688 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
690 // Offset each range by the right amount.
691 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
692 for (const auto &Range : Entries) {
693 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
694 warn("unsupported base address selection operation",
695 "emitting debug_ranges");
698 // Do not emit empty ranges.
699 if (Range.StartAddress == Range.EndAddress)
702 // All range entries should lie in the function range.
703 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
704 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
705 warn("inconsistent range data.", "emitting debug_ranges");
706 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
707 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
708 RangesSectionSize += 2 * AddressSize;
711 // Add the terminator entry.
712 MS->EmitIntValue(0, AddressSize);
713 MS->EmitIntValue(0, AddressSize);
714 RangesSectionSize += 2 * AddressSize;
717 /// \brief Emit the debug_aranges contribution of a unit and
718 /// if \p DoDebugRanges is true the debug_range contents for a
719 /// compile_unit level DW_AT_ranges attribute (Which are basically the
720 /// same thing with a different base address).
721 /// Just aggregate all the ranges gathered inside that unit.
722 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
723 bool DoDebugRanges) {
724 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
725 // Gather the ranges in a vector, so that we can simplify them. The
726 // IntervalMap will have coalesced the non-linked ranges, but here
727 // we want to coalesce the linked addresses.
728 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
729 const auto &FunctionRanges = Unit.getFunctionRanges();
730 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
731 Range != End; ++Range)
732 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
733 Range.stop() + Range.value()));
735 // The object addresses where sorted, but again, the linked
736 // addresses might end up in a different order.
737 std::sort(Ranges.begin(), Ranges.end());
739 if (!Ranges.empty()) {
740 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
742 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
743 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
745 unsigned HeaderSize =
746 sizeof(int32_t) + // Size of contents (w/o this field
747 sizeof(int16_t) + // DWARF ARange version number
748 sizeof(int32_t) + // Offset of CU in the .debug_info section
749 sizeof(int8_t) + // Pointer Size (in bytes)
750 sizeof(int8_t); // Segment Size (in bytes)
752 unsigned TupleSize = AddressSize * 2;
753 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
755 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
756 Asm->OutStreamer->EmitLabel(BeginLabel);
757 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
758 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
759 Asm->EmitInt8(AddressSize); // Address size
760 Asm->EmitInt8(0); // Segment size
762 Asm->OutStreamer->EmitFill(Padding, 0x0);
764 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
766 uint64_t RangeStart = Range->first;
767 MS->EmitIntValue(RangeStart, AddressSize);
768 while ((Range + 1) != End && Range->second == (Range + 1)->first)
770 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
774 Asm->OutStreamer->EmitIntValue(0, AddressSize);
775 Asm->OutStreamer->EmitIntValue(0, AddressSize);
776 Asm->OutStreamer->EmitLabel(EndLabel);
782 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
783 // Offset each range by the right amount.
784 int64_t PcOffset = -Unit.getLowPc();
785 // Emit coalesced ranges.
786 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
787 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
788 while (Range + 1 != End && Range->second == (Range + 1)->first)
790 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
791 RangesSectionSize += 2 * AddressSize;
794 // Add the terminator entry.
795 MS->EmitIntValue(0, AddressSize);
796 MS->EmitIntValue(0, AddressSize);
797 RangesSectionSize += 2 * AddressSize;
800 /// \brief Emit location lists for \p Unit and update attribtues to
801 /// point to the new entries.
802 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
803 DWARFContext &Dwarf) {
804 const auto &Attributes = Unit.getLocationAttributes();
806 if (Attributes.empty())
809 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
811 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
812 const DWARFSection &InputSec = Dwarf.getLocSection();
813 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
814 DWARFUnit &OrigUnit = Unit.getOrigUnit();
815 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
816 int64_t UnitPcOffset = 0;
817 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
818 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
819 if (OrigLowPc != -1ULL)
820 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
822 for (const auto &Attr : Attributes) {
823 uint32_t Offset = Attr.first.get();
824 Attr.first.set(LocSectionSize);
825 // This is the quantity to add to the old location address to get
826 // the correct address for the new one.
827 int64_t LocPcOffset = Attr.second + UnitPcOffset;
828 while (Data.isValidOffset(Offset)) {
829 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
830 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
831 LocSectionSize += 2 * AddressSize;
832 if (Low == 0 && High == 0) {
833 Asm->OutStreamer->EmitIntValue(0, AddressSize);
834 Asm->OutStreamer->EmitIntValue(0, AddressSize);
837 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
838 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
839 uint64_t Length = Data.getU16(&Offset);
840 Asm->OutStreamer->EmitIntValue(Length, 2);
841 // Just copy the bytes over.
842 Asm->OutStreamer->EmitBytes(
843 StringRef(InputSec.Data.substr(Offset, Length)));
845 LocSectionSize += Length + 2;
850 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
851 StringRef PrologueBytes,
852 unsigned MinInstLength,
853 std::vector<DWARFDebugLine::Row> &Rows,
854 unsigned PointerSize) {
855 // Switch to the section where the table will be emitted into.
856 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
857 MCSymbol *LineStartSym = MC->createTempSymbol();
858 MCSymbol *LineEndSym = MC->createTempSymbol();
860 // The first 4 bytes is the total length of the information for this
861 // compilation unit (not including these 4 bytes for the length).
862 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
863 Asm->OutStreamer->EmitLabel(LineStartSym);
865 MS->EmitBytes(PrologueBytes);
866 LineSectionSize += PrologueBytes.size() + 4;
868 SmallString<128> EncodingBuffer;
869 raw_svector_ostream EncodingOS(EncodingBuffer);
872 // We only have the dummy entry, dsymutil emits an entry with a 0
873 // address in that case.
874 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
875 MS->EmitBytes(EncodingOS.str());
876 LineSectionSize += EncodingBuffer.size();
877 MS->EmitLabel(LineEndSym);
881 // Line table state machine fields
882 unsigned FileNum = 1;
883 unsigned LastLine = 1;
885 unsigned IsStatement = 1;
887 uint64_t Address = -1ULL;
889 unsigned RowsSinceLastSequence = 0;
891 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
892 auto &Row = Rows[Idx];
894 int64_t AddressDelta;
895 if (Address == -1ULL) {
896 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
897 MS->EmitULEB128IntValue(PointerSize + 1);
898 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
899 MS->EmitIntValue(Row.Address, PointerSize);
900 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
903 AddressDelta = (Row.Address - Address) / MinInstLength;
906 // FIXME: code copied and transfromed from
907 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
908 // this code, but the current compatibility requirement with
909 // classic dsymutil makes it hard. Revisit that once this
910 // requirement is dropped.
912 if (FileNum != Row.File) {
914 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
915 MS->EmitULEB128IntValue(FileNum);
916 LineSectionSize += 1 + getULEB128Size(FileNum);
918 if (Column != Row.Column) {
920 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
921 MS->EmitULEB128IntValue(Column);
922 LineSectionSize += 1 + getULEB128Size(Column);
925 // FIXME: We should handle the discriminator here, but dsymutil
926 // doesn' consider it, thus ignore it for now.
928 if (Isa != Row.Isa) {
930 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
931 MS->EmitULEB128IntValue(Isa);
932 LineSectionSize += 1 + getULEB128Size(Isa);
934 if (IsStatement != Row.IsStmt) {
935 IsStatement = Row.IsStmt;
936 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
937 LineSectionSize += 1;
939 if (Row.BasicBlock) {
940 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
941 LineSectionSize += 1;
944 if (Row.PrologueEnd) {
945 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
946 LineSectionSize += 1;
949 if (Row.EpilogueBegin) {
950 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
951 LineSectionSize += 1;
954 int64_t LineDelta = int64_t(Row.Line) - LastLine;
955 if (!Row.EndSequence) {
956 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
957 MS->EmitBytes(EncodingOS.str());
958 LineSectionSize += EncodingBuffer.size();
959 EncodingBuffer.resize(0);
960 Address = Row.Address;
962 RowsSinceLastSequence++;
965 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
966 MS->EmitSLEB128IntValue(LineDelta);
967 LineSectionSize += 1 + getSLEB128Size(LineDelta);
970 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
971 MS->EmitULEB128IntValue(AddressDelta);
972 LineSectionSize += 1 + getULEB128Size(AddressDelta);
974 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
975 MS->EmitBytes(EncodingOS.str());
976 LineSectionSize += EncodingBuffer.size();
977 EncodingBuffer.resize(0);
979 LastLine = FileNum = IsStatement = 1;
980 RowsSinceLastSequence = Column = Isa = 0;
984 if (RowsSinceLastSequence) {
985 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
986 MS->EmitBytes(EncodingOS.str());
987 LineSectionSize += EncodingBuffer.size();
988 EncodingBuffer.resize(0);
991 MS->EmitLabel(LineEndSym);
994 /// \brief Emit the pubnames or pubtypes section contribution for \p
995 /// Unit into \p Sec. The data is provided in \p Names.
996 void DwarfStreamer::emitPubSectionForUnit(
997 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
998 const std::vector<CompileUnit::AccelInfo> &Names) {
1002 // Start the dwarf pubnames section.
1003 Asm->OutStreamer->SwitchSection(Sec);
1004 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1005 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
1007 bool HeaderEmitted = false;
1008 // Emit the pubnames for this compilation unit.
1009 for (const auto &Name : Names) {
1010 if (Name.SkipPubSection)
1013 if (!HeaderEmitted) {
1015 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
1016 Asm->OutStreamer->EmitLabel(BeginLabel);
1017 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
1018 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
1019 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1020 HeaderEmitted = true;
1022 Asm->EmitInt32(Name.Die->getOffset());
1023 Asm->OutStreamer->EmitBytes(
1024 StringRef(Name.Name.data(), Name.Name.size() + 1));
1029 Asm->EmitInt32(0); // End marker.
1030 Asm->OutStreamer->EmitLabel(EndLabel);
1033 /// \brief Emit .debug_pubnames for \p Unit.
1034 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1035 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1036 "names", Unit, Unit.getPubnames());
1039 /// \brief Emit .debug_pubtypes for \p Unit.
1040 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1041 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1042 "types", Unit, Unit.getPubtypes());
1045 /// \brief Emit a CIE into the debug_frame section.
1046 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1047 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1049 MS->EmitBytes(CIEBytes);
1050 FrameSectionSize += CIEBytes.size();
1053 /// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1054 /// contains the FDE data without the length, CIE offset and address
1055 /// which will be replaced with the paramter values.
1056 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1057 uint32_t Address, StringRef FDEBytes) {
1058 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1060 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1061 MS->EmitIntValue(CIEOffset, 4);
1062 MS->EmitIntValue(Address, AddrSize);
1063 MS->EmitBytes(FDEBytes);
1064 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1067 /// \brief The core of the Dwarf linking logic.
1069 /// The link of the dwarf information from the object files will be
1070 /// driven by the selection of 'root DIEs', which are DIEs that
1071 /// describe variables or functions that are present in the linked
1072 /// binary (and thus have entries in the debug map). All the debug
1073 /// information that will be linked (the DIEs, but also the line
1074 /// tables, ranges, ...) is derived from that set of root DIEs.
1076 /// The root DIEs are identified because they contain relocations that
1077 /// correspond to a debug map entry at specific places (the low_pc for
1078 /// a function, the location for a variable). These relocations are
1079 /// called ValidRelocs in the DwarfLinker and are gathered as a very
1080 /// first step when we start processing a DebugMapObject.
1083 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1084 : OutputFilename(OutputFilename), Options(Options),
1085 BinHolder(Options.Verbose), LastCIEOffset(0) {}
1088 for (auto *Abbrev : Abbreviations)
1092 /// \brief Link the contents of the DebugMap.
1093 bool link(const DebugMap &);
1096 /// \brief Called at the start of a debug object link.
1097 void startDebugObject(DWARFContext &, DebugMapObject &);
1099 /// \brief Called at the end of a debug object link.
1100 void endDebugObject();
1102 /// \defgroup FindValidRelocations Translate debug map into a list
1103 /// of relevant relocations
1110 const DebugMapObject::DebugMapEntry *Mapping;
1112 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1113 const DebugMapObject::DebugMapEntry *Mapping)
1114 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1116 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1119 /// \brief The valid relocations for the current DebugMapObject.
1120 /// This vector is sorted by relocation offset.
1121 std::vector<ValidReloc> ValidRelocs;
1123 /// \brief Index into ValidRelocs of the next relocation to
1124 /// consider. As we walk the DIEs in acsending file offset and as
1125 /// ValidRelocs is sorted by file offset, keeping this index
1126 /// uptodate is all we have to do to have a cheap lookup during the
1127 /// root DIE selection and during DIE cloning.
1128 unsigned NextValidReloc;
1130 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1131 const DebugMapObject &DMO);
1133 bool findValidRelocs(const object::SectionRef &Section,
1134 const object::ObjectFile &Obj,
1135 const DebugMapObject &DMO);
1137 void findValidRelocsMachO(const object::SectionRef &Section,
1138 const object::MachOObjectFile &Obj,
1139 const DebugMapObject &DMO);
1142 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1145 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1146 /// keep. Store that information in \p CU's DIEInfo.
1147 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1148 const DebugMapObject &DMO, CompileUnit &CU,
1151 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1152 enum TravesalFlags {
1153 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1154 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1155 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1156 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1157 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
1160 /// \brief Mark the passed DIE as well as all the ones it depends on
1162 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1163 CompileUnit::DIEInfo &MyInfo,
1164 const DebugMapObject &DMO, CompileUnit &CU,
1167 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1168 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1171 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1173 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1175 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1177 CompileUnit::DIEInfo &MyInfo,
1180 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1181 CompileUnit::DIEInfo &Info);
1184 /// \defgroup Linking Methods used to link the debug information
1187 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1188 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1189 /// stripped out and addresses have been rewritten according to the
1192 /// \param OutOffset is the offset the cloned DIE in the output
1194 /// \param PCOffset (while cloning a function scope) is the offset
1195 /// applied to the entry point of the function to get the linked address.
1197 /// \returns the root of the cloned tree.
1198 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
1199 int64_t PCOffset, uint32_t OutOffset);
1201 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1203 /// \brief Information gathered and exchanged between the various
1204 /// clone*Attributes helpers about the attributes of a particular DIE.
1205 struct AttributesInfo {
1206 const char *Name, *MangledName; ///< Names.
1207 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1209 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1210 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1212 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1213 bool IsDeclaration; ///< Is this DIE only a declaration?
1216 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1217 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1218 IsDeclaration(false) {}
1221 /// \brief Helper for cloneDIE.
1222 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1223 CompileUnit &U, const DWARFFormValue &Val,
1224 const AttributeSpec AttrSpec, unsigned AttrSize,
1225 AttributesInfo &AttrInfo);
1227 /// \brief Helper for cloneDIE.
1228 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1229 const DWARFFormValue &Val, const DWARFUnit &U);
1231 /// \brief Helper for cloneDIE.
1233 cloneDieReferenceAttribute(DIE &Die,
1234 const DWARFDebugInfoEntryMinimal &InputDIE,
1235 AttributeSpec AttrSpec, unsigned AttrSize,
1236 const DWARFFormValue &Val, CompileUnit &Unit);
1238 /// \brief Helper for cloneDIE.
1239 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1240 const DWARFFormValue &Val, unsigned AttrSize);
1242 /// \brief Helper for cloneDIE.
1243 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1244 const DWARFFormValue &Val,
1245 const CompileUnit &Unit, AttributesInfo &Info);
1247 /// \brief Helper for cloneDIE.
1248 unsigned cloneScalarAttribute(DIE &Die,
1249 const DWARFDebugInfoEntryMinimal &InputDIE,
1250 CompileUnit &U, AttributeSpec AttrSpec,
1251 const DWARFFormValue &Val, unsigned AttrSize,
1252 AttributesInfo &Info);
1254 /// \brief Helper for cloneDIE.
1255 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1256 bool isLittleEndian);
1258 /// \brief Assign an abbreviation number to \p Abbrev
1259 void AssignAbbrev(DIEAbbrev &Abbrev);
1261 /// \brief FoldingSet that uniques the abbreviations.
1262 FoldingSet<DIEAbbrev> AbbreviationsSet;
1263 /// \brief Storage for the unique Abbreviations.
1264 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1265 /// be changed to a vecot of unique_ptrs.
1266 std::vector<DIEAbbrev *> Abbreviations;
1268 /// \brief Compute and emit debug_ranges section for \p Unit, and
1269 /// patch the attributes referencing it.
1270 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1272 /// \brief Generate and emit the DW_AT_ranges attribute for a
1273 /// compile_unit if it had one.
1274 void generateUnitRanges(CompileUnit &Unit) const;
1276 /// \brief Extract the line tables fromt he original dwarf, extract
1277 /// the relevant parts according to the linked function ranges and
1278 /// emit the result in the debug_line section.
1279 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1281 /// \brief Emit the accelerator entries for \p Unit.
1282 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1284 /// \brief Patch the frame info for an object file and emit it.
1285 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1286 unsigned AddressSize);
1288 /// \brief DIELoc objects that need to be destructed (but not freed!).
1289 std::vector<DIELoc *> DIELocs;
1290 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1291 std::vector<DIEBlock *> DIEBlocks;
1292 /// \brief Allocator used for all the DIEValue objects.
1293 BumpPtrAllocator DIEAlloc;
1296 /// ODR Contexts for that link.
1297 DeclContextTree ODRContexts;
1299 /// \defgroup Helpers Various helper methods.
1302 const DWARFDebugInfoEntryMinimal *
1303 resolveDIEReference(const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1304 const DWARFDebugInfoEntryMinimal &DIE,
1305 CompileUnit *&ReferencedCU);
1307 CompileUnit *getUnitForOffset(unsigned Offset);
1309 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1310 AttributesInfo &Info);
1312 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1313 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1315 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
1317 /// \brief Attempt to load a debug object from disk.
1318 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1319 DebugMapObject &Obj,
1320 const DebugMap &Map);
1324 std::string OutputFilename;
1325 LinkOptions Options;
1326 BinaryHolder BinHolder;
1327 std::unique_ptr<DwarfStreamer> Streamer;
1329 /// The units of the current debug map object.
1330 std::vector<CompileUnit> Units;
1332 /// The debug map object curently under consideration.
1333 DebugMapObject *CurrentDebugObject;
1335 /// \brief The Dwarf string pool
1336 NonRelocatableStringpool StringPool;
1338 /// \brief This map is keyed by the entry PC of functions in that
1339 /// debug object and the associated value is a pair storing the
1340 /// corresponding end PC and the offset to apply to get the linked
1343 /// See startDebugObject() for a more complete description of its use.
1344 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1346 /// \brief The CIEs that have been emitted in the output
1347 /// section. The actual CIE data serves a the key to this StringMap,
1348 /// this takes care of comparing the semantics of CIEs defined in
1349 /// different object files.
1350 StringMap<uint32_t> EmittedCIEs;
1352 /// Offset of the last CIE that has been emitted in the output
1353 /// debug_frame section.
1354 uint32_t LastCIEOffset;
1357 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1358 /// returning our CompileUnit object instead.
1359 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1361 std::upper_bound(Units.begin(), Units.end(), Offset,
1362 [](uint32_t LHS, const CompileUnit &RHS) {
1363 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1365 return CU != Units.end() ? &*CU : nullptr;
1368 /// \brief Resolve the DIE attribute reference that has been
1369 /// extracted in \p RefValue. The resulting DIE migh be in another
1370 /// CompileUnit which is stored into \p ReferencedCU.
1371 /// \returns null if resolving fails for any reason.
1372 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1373 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1374 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1375 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1376 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1378 if ((RefCU = getUnitForOffset(RefOffset)))
1379 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1382 reportWarning("could not find referenced DIE", &Unit, &DIE);
1386 /// \returns whether the passed \a Attr type might contain a DIE
1387 /// reference suitable for ODR uniquing.
1388 static bool isODRAttribute(uint16_t Attr) {
1392 case dwarf::DW_AT_type:
1393 case dwarf::DW_AT_containing_type:
1394 case dwarf::DW_AT_specification:
1395 case dwarf::DW_AT_abstract_origin:
1396 case dwarf::DW_AT_import:
1399 llvm_unreachable("Improper attribute.");
1402 /// Set the last DIE/CU a context was seen in and, possibly invalidate
1403 /// the context if it is ambiguous.
1405 /// In the current implementation, we don't handle overloaded
1406 /// functions well, because the argument types are not taken into
1407 /// account when computing the DeclContext tree.
1409 /// Some of this is mitigated byt using mangled names that do contain
1410 /// the arguments types, but sometimes (eg. with function templates)
1411 /// we don't have that. In that case, just do not unique anything that
1412 /// refers to the contexts we are not able to distinguish.
1414 /// If a context that is not a namespace appears twice in the same CU,
1415 /// we know it is ambiguous. Make it invalid.
1416 bool DeclContext::setLastSeenDIE(CompileUnit &U,
1417 const DWARFDebugInfoEntryMinimal *Die) {
1418 if (LastSeenCompileUnitID == U.getUniqueID()) {
1419 DWARFUnit &OrigUnit = U.getOrigUnit();
1420 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1421 U.getInfo(FirstIdx).Ctxt = nullptr;
1425 LastSeenCompileUnitID = U.getUniqueID();
1430 /// Get the child context of \a Context corresponding to \a DIE.
1432 /// \returns the child context or null if we shouldn't track children
1433 /// contexts. It also returns an additional bit meaning 'invalid'. An
1434 /// invalid context means it shouldn't be considered for uniquing, but
1435 /// its not returning null, because some children of that context
1436 /// might be uniquing candidates.
1437 /// FIXME: this is for dsymutil-classic compatibility, I don't think
1438 /// it buys us much.
1439 PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1440 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1441 NonRelocatableStringpool &StringPool) {
1442 unsigned Tag = DIE->getTag();
1444 // FIXME: dsymutil-classic compat: We should bail out here if we
1445 // have a specification or an abstract_origin. We will get the
1446 // parent context wrong here.
1450 // By default stop gathering child contexts.
1451 return PointerIntPair<DeclContext *, 1>(nullptr);
1452 case dwarf::DW_TAG_compile_unit:
1453 // FIXME: Add support for DW_TAG_module.
1454 return PointerIntPair<DeclContext *, 1>(&Context);
1455 case dwarf::DW_TAG_subprogram:
1456 // Do not unique anything inside CU local functions.
1457 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1458 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1459 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1460 dwarf::DW_AT_external, 0))
1461 return PointerIntPair<DeclContext *, 1>(nullptr);
1463 case dwarf::DW_TAG_member:
1464 case dwarf::DW_TAG_namespace:
1465 case dwarf::DW_TAG_structure_type:
1466 case dwarf::DW_TAG_class_type:
1467 case dwarf::DW_TAG_union_type:
1468 case dwarf::DW_TAG_enumeration_type:
1469 case dwarf::DW_TAG_typedef:
1470 // Artificial things might be ambiguous, because they might be
1471 // created on demand. For example implicitely defined constructors
1472 // are ambiguous because of the way we identify contexts, and they
1473 // won't be generated everytime everywhere.
1474 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1475 dwarf::DW_AT_artificial, 0))
1476 return PointerIntPair<DeclContext *, 1>(nullptr);
1480 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1481 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1483 StringRef ShortNameRef;
1487 NameRef = StringPool.internString(Name);
1488 else if (Tag == dwarf::DW_TAG_namespace)
1489 // FIXME: For dsymutil-classic compatibility. I think uniquing
1490 // within anonymous namespaces is wrong. There is no ODR guarantee
1492 NameRef = StringPool.internString("(anonymous namespace)");
1494 if (ShortName && ShortName != Name)
1495 ShortNameRef = StringPool.internString(ShortName);
1497 ShortNameRef = NameRef;
1499 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1500 Tag != dwarf::DW_TAG_union_type &&
1501 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1502 return PointerIntPair<DeclContext *, 1>(nullptr);
1506 unsigned ByteSize = 0;
1508 // Gather some discriminating data about the DeclContext we will be
1509 // creating: File, line number and byte size. This shouldn't be
1510 // necessary, because the ODR is just about names, but given that we
1511 // do some approximations with overloaded functions and anonymous
1512 // namespaces, use these additional data points to make the process safer.
1513 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1514 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1515 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1516 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1517 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1518 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1519 &U.getOrigUnit())) {
1520 // FIXME: dsymutil-classic compatibility. I'd rather not
1521 // unique anything in anonymous namespaces, but if we do, then
1522 // verify that the file and line correspond.
1523 if (!Name && Tag == dwarf::DW_TAG_namespace)
1526 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1527 // instead of "" would allow more uniquing, but for now, do
1528 // it this way to match dsymutil-classic.
1529 if (LT->getFileNameByIndex(
1531 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1533 Line = DIE->getAttributeValueAsUnsignedConstant(
1534 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1535 #ifdef HAVE_REALPATH
1536 // Cache the resolved paths, because calling realpath is expansive.
1537 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1538 File = ResolvedPath;
1540 char RealPath[PATH_MAX + 1];
1541 RealPath[PATH_MAX] = 0;
1542 if (::realpath(File.c_str(), RealPath))
1544 U.setResolvedPath(FileNum, File);
1547 FileRef = StringPool.internString(File);
1553 if (!Line && NameRef.empty())
1554 return PointerIntPair<DeclContext *, 1>(nullptr);
1556 // FIXME: dsymutil-classic compat won't unique the same type
1557 // presented once as a struct and once as a class. Use the Tag in
1558 // the fully qualified name hash to get the same effect.
1559 // We hash NameRef, which is the mangled name, in order to get most
1560 // overloaded functions resolvec correctly.
1561 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1563 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1564 // use the filename.
1565 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1566 Hash = hash_combine(Hash, FileRef);
1568 // Now look if this context already exists.
1569 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1570 auto ContextIter = Contexts.find(&Key);
1572 if (ContextIter == Contexts.end()) {
1573 // The context wasn't found.
1575 DeclContext *NewContext =
1576 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1577 Context, DIE, U.getUniqueID());
1578 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1579 assert(Inserted && "Failed to insert DeclContext");
1581 } else if (Tag != dwarf::DW_TAG_namespace &&
1582 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1583 // The context was found, but it is ambiguous with another context
1584 // in the same file. Mark it invalid.
1585 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1588 assert(ContextIter != Contexts.end());
1589 // FIXME: dsymutil-classic compatibility. Union types aren't
1590 // uniques, but their children might be.
1591 if ((Tag == dwarf::DW_TAG_subprogram &&
1592 Context.getTag() != dwarf::DW_TAG_structure_type &&
1593 Context.getTag() != dwarf::DW_TAG_class_type) ||
1594 (Tag == dwarf::DW_TAG_union_type))
1595 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1597 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1600 /// \brief Get the potential name and mangled name for the entity
1601 /// described by \p Die and store them in \Info if they are not
1603 /// \returns is a name was found.
1604 bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1605 DWARFUnit &U, AttributesInfo &Info) {
1606 // FIXME: a bit wastefull as the first getName might return the
1608 if (!Info.MangledName &&
1609 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1610 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1612 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1613 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1615 return Info.Name || Info.MangledName;
1618 /// \brief Report a warning to the user, optionaly including
1619 /// information about a specific \p DIE related to the warning.
1620 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
1621 const DWARFDebugInfoEntryMinimal *DIE) const {
1622 StringRef Context = "<debug map>";
1623 if (CurrentDebugObject)
1624 Context = CurrentDebugObject->getObjectFilename();
1625 warn(Warning, Context);
1627 if (!Options.Verbose || !DIE)
1630 errs() << " in DIE:\n";
1631 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1635 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1636 if (Options.NoOutput)
1639 Streamer = llvm::make_unique<DwarfStreamer>();
1640 return Streamer->init(TheTriple, OutputFilename);
1643 /// \brief Recursive helper to gather the child->parent relationships in the
1644 /// original compile unit.
1645 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1646 unsigned ParentIdx, CompileUnit &CU,
1647 DeclContext *CurrentDeclContext,
1648 NonRelocatableStringpool &StringPool,
1649 DeclContextTree &Contexts) {
1650 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1651 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1653 Info.ParentIdx = ParentIdx;
1655 if (CurrentDeclContext) {
1656 auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1657 DIE, CU, StringPool);
1658 CurrentDeclContext = PtrInvalidPair.getPointer();
1660 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1662 Info.Ctxt = CurrentDeclContext = nullptr;
1665 if (DIE->hasChildren())
1666 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1667 Child = Child->getSibling())
1668 gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1672 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1676 case dwarf::DW_TAG_subprogram:
1677 case dwarf::DW_TAG_lexical_block:
1678 case dwarf::DW_TAG_subroutine_type:
1679 case dwarf::DW_TAG_structure_type:
1680 case dwarf::DW_TAG_class_type:
1681 case dwarf::DW_TAG_union_type:
1684 llvm_unreachable("Invalid Tag");
1687 static unsigned getRefAddrSize(const DWARFUnit &U) {
1688 if (U.getVersion() == 2)
1689 return U.getAddressByteSize();
1693 void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1694 Units.reserve(Dwarf.getNumCompileUnits());
1696 // Iterate over the debug map entries and put all the ones that are
1697 // functions (because they have a size) into the Ranges map. This
1698 // map is very similar to the FunctionRanges that are stored in each
1699 // unit, with 2 notable differences:
1700 // - obviously this one is global, while the other ones are per-unit.
1701 // - this one contains not only the functions described in the DIE
1702 // tree, but also the ones that are only in the debug map.
1703 // The latter information is required to reproduce dsymutil's logic
1704 // while linking line tables. The cases where this information
1705 // matters look like bugs that need to be investigated, but for now
1706 // we need to reproduce dsymutil's behavior.
1707 // FIXME: Once we understood exactly if that information is needed,
1708 // maybe totally remove this (or try to use it to do a real
1709 // -gline-tables-only on Darwin.
1710 for (const auto &Entry : Obj.symbols()) {
1711 const auto &Mapping = Entry.getValue();
1713 Ranges[Mapping.ObjectAddress] = std::make_pair(
1714 Mapping.ObjectAddress + Mapping.Size,
1715 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1719 void DwarfLinker::endDebugObject() {
1721 ValidRelocs.clear();
1724 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1726 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1734 /// \brief Iterate over the relocations of the given \p Section and
1735 /// store the ones that correspond to debug map entries into the
1736 /// ValidRelocs array.
1737 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1738 const object::MachOObjectFile &Obj,
1739 const DebugMapObject &DMO) {
1741 Section.getContents(Contents);
1742 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1744 for (const object::RelocationRef &Reloc : Section.relocations()) {
1745 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1746 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1747 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1748 uint64_t Offset64 = Reloc.getOffset();
1749 if ((RelocSize != 4 && RelocSize != 8)) {
1750 reportWarning(" unsupported relocation in debug_info section.");
1753 uint32_t Offset = Offset64;
1754 // Mach-o uses REL relocations, the addend is at the relocation offset.
1755 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1757 auto Sym = Reloc.getSymbol();
1758 if (Sym != Obj.symbol_end()) {
1759 ErrorOr<StringRef> SymbolName = Sym->getName();
1761 reportWarning("error getting relocation symbol name.");
1764 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
1765 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1766 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1767 // Do not store the addend. The addend was the address of the
1768 // symbol in the object file, the address in the binary that is
1769 // stored in the debug map doesn't need to be offseted.
1770 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1775 /// \brief Dispatch the valid relocation finding logic to the
1776 /// appropriate handler depending on the object file format.
1777 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1778 const object::ObjectFile &Obj,
1779 const DebugMapObject &DMO) {
1780 // Dispatch to the right handler depending on the file type.
1781 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1782 findValidRelocsMachO(Section, *MachOObj, DMO);
1784 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
1786 if (ValidRelocs.empty())
1789 // Sort the relocations by offset. We will walk the DIEs linearly in
1790 // the file, this allows us to just keep an index in the relocation
1791 // array that we advance during our walk, rather than resorting to
1792 // some associative container. See DwarfLinker::NextValidReloc.
1793 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1797 /// \brief Look for relocations in the debug_info section that match
1798 /// entries in the debug map. These relocations will drive the Dwarf
1799 /// link by indicating which DIEs refer to symbols present in the
1801 /// \returns wether there are any valid relocations in the debug info.
1802 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1803 const DebugMapObject &DMO) {
1804 // Find the debug_info section.
1805 for (const object::SectionRef &Section : Obj.sections()) {
1806 StringRef SectionName;
1807 Section.getName(SectionName);
1808 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1809 if (SectionName != "debug_info")
1811 return findValidRelocs(Section, Obj, DMO);
1816 /// \brief Checks that there is a relocation against an actual debug
1817 /// map entry between \p StartOffset and \p NextOffset.
1819 /// This function must be called with offsets in strictly ascending
1820 /// order because it never looks back at relocations it already 'went past'.
1821 /// \returns true and sets Info.InDebugMap if it is the case.
1822 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1823 CompileUnit::DIEInfo &Info) {
1824 assert(NextValidReloc == 0 ||
1825 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1826 if (NextValidReloc >= ValidRelocs.size())
1829 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1831 // We might need to skip some relocs that we didn't consider. For
1832 // example the high_pc of a discarded DIE might contain a reloc that
1833 // is in the list because it actually corresponds to the start of a
1834 // function that is in the debug map.
1835 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1836 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1838 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1841 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1842 const auto &Mapping = ValidReloc.Mapping->getValue();
1843 if (Options.Verbose)
1844 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1845 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1846 uint64_t(Mapping.ObjectAddress),
1847 uint64_t(Mapping.BinaryAddress));
1849 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1850 Mapping.ObjectAddress;
1851 Info.InDebugMap = true;
1855 /// \brief Get the starting and ending (exclusive) offset for the
1856 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1857 /// supposed to point to the position of the first attribute described
1859 /// \return [StartOffset, EndOffset) as a pair.
1860 static std::pair<uint32_t, uint32_t>
1861 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1862 unsigned Offset, const DWARFUnit &Unit) {
1863 DataExtractor Data = Unit.getDebugInfoExtractor();
1865 for (unsigned i = 0; i < Idx; ++i)
1866 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1868 uint32_t End = Offset;
1869 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1871 return std::make_pair(Offset, End);
1874 /// \brief Check if a variable describing DIE should be kept.
1875 /// \returns updated TraversalFlags.
1876 unsigned DwarfLinker::shouldKeepVariableDIE(
1877 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1878 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1879 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1881 // Global variables with constant value can always be kept.
1882 if (!(Flags & TF_InFunctionScope) &&
1883 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1884 MyInfo.InDebugMap = true;
1885 return Flags | TF_Keep;
1888 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1889 if (LocationIdx == -1U)
1892 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1893 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1894 uint32_t LocationOffset, LocationEndOffset;
1895 std::tie(LocationOffset, LocationEndOffset) =
1896 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1898 // See if there is a relocation to a valid debug map entry inside
1899 // this variable's location. The order is important here. We want to
1900 // always check in the variable has a valid relocation, so that the
1901 // DIEInfo is filled. However, we don't want a static variable in a
1902 // function to force us to keep the enclosing function.
1903 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1904 (Flags & TF_InFunctionScope))
1907 if (Options.Verbose)
1908 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1910 return Flags | TF_Keep;
1913 /// \brief Check if a function describing DIE should be kept.
1914 /// \returns updated TraversalFlags.
1915 unsigned DwarfLinker::shouldKeepSubprogramDIE(
1916 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1917 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1918 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1920 Flags |= TF_InFunctionScope;
1922 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1923 if (LowPcIdx == -1U)
1926 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1927 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1928 uint32_t LowPcOffset, LowPcEndOffset;
1929 std::tie(LowPcOffset, LowPcEndOffset) =
1930 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1933 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1934 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1935 if (LowPc == -1ULL ||
1936 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1939 if (Options.Verbose)
1940 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1944 DWARFFormValue HighPcValue;
1945 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1946 reportWarning("Function without high_pc. Range will be discarded.\n",
1952 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1953 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1955 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1956 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1959 // Replace the debug map range with a more accurate one.
1960 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
1961 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1965 /// \brief Check if a DIE should be kept.
1966 /// \returns updated TraversalFlags.
1967 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1969 CompileUnit::DIEInfo &MyInfo,
1971 switch (DIE.getTag()) {
1972 case dwarf::DW_TAG_constant:
1973 case dwarf::DW_TAG_variable:
1974 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1975 case dwarf::DW_TAG_subprogram:
1976 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1977 case dwarf::DW_TAG_module:
1978 case dwarf::DW_TAG_imported_module:
1979 case dwarf::DW_TAG_imported_declaration:
1980 case dwarf::DW_TAG_imported_unit:
1981 // We always want to keep these.
1982 return Flags | TF_Keep;
1988 /// \brief Mark the passed DIE as well as all the ones it depends on
1991 /// This function is called by lookForDIEsToKeep on DIEs that are
1992 /// newly discovered to be needed in the link. It recursively calls
1993 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1994 /// TraversalFlags to inform it that it's not doing the primary DIE
1996 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1997 CompileUnit::DIEInfo &MyInfo,
1998 const DebugMapObject &DMO,
1999 CompileUnit &CU, bool UseODR) {
2000 const DWARFUnit &Unit = CU.getOrigUnit();
2003 // First mark all the parent chain as kept.
2004 unsigned AncestorIdx = MyInfo.ParentIdx;
2005 while (!CU.getInfo(AncestorIdx).Keep) {
2006 unsigned ODRFlag = UseODR ? TF_ODR : 0;
2007 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
2008 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
2009 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2012 // Then we need to mark all the DIEs referenced by this DIE's
2013 // attributes as kept.
2014 DataExtractor Data = Unit.getDebugInfoExtractor();
2015 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2016 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2018 // Mark all DIEs referenced through atttributes as kept.
2019 for (const auto &AttrSpec : Abbrev->attributes()) {
2020 DWARFFormValue Val(AttrSpec.Form);
2022 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2023 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2027 Val.extractValue(Data, &Offset, &Unit);
2028 CompileUnit *ReferencedCU;
2029 if (const auto *RefDIE =
2030 resolveDIEReference(Val, Unit, DIE, ReferencedCU)) {
2031 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2032 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2033 // If the referenced DIE has a DeclContext that has already been
2034 // emitted, then do not keep the one in this CU. We'll link to
2035 // the canonical DIE in cloneDieReferenceAttribute.
2036 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2037 // be necessary and could be advantageously replaced by
2038 // ReferencedCU->hasODR() && CU.hasODR().
2039 // FIXME: compatibility with dsymutil-classic. There is no
2040 // reason not to unique ref_addr references.
2041 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2042 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2043 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2046 unsigned ODRFlag = UseODR ? TF_ODR : 0;
2047 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
2048 TF_Keep | TF_DependencyWalk | ODRFlag);
2053 /// \brief Recursively walk the \p DIE tree and look for DIEs to
2054 /// keep. Store that information in \p CU's DIEInfo.
2056 /// This function is the entry point of the DIE selection
2057 /// algorithm. It is expected to walk the DIE tree in file order and
2058 /// (though the mediation of its helper) call hasValidRelocation() on
2059 /// each DIE that might be a 'root DIE' (See DwarfLinker class
2061 /// While walking the dependencies of root DIEs, this function is
2062 /// also called, but during these dependency walks the file order is
2063 /// not respected. The TF_DependencyWalk flag tells us which kind of
2064 /// traversal we are currently doing.
2065 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
2066 const DebugMapObject &DMO, CompileUnit &CU,
2068 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
2069 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2070 bool AlreadyKept = MyInfo.Keep;
2072 // If the Keep flag is set, we are marking a required DIE's
2073 // dependencies. If our target is already marked as kept, we're all
2075 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2078 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
2079 // because it would screw up the relocation finding logic.
2080 if (!(Flags & TF_DependencyWalk))
2081 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
2083 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
2084 if (!AlreadyKept && (Flags & TF_Keep)) {
2085 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2086 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, UseOdr);
2088 // The TF_ParentWalk flag tells us that we are currently walking up
2089 // the parent chain of a required DIE, and we don't want to mark all
2090 // the children of the parents as kept (consider for example a
2091 // DW_TAG_namespace node in the parent chain). There are however a
2092 // set of DIE types for which we want to ignore that directive and still
2093 // walk their children.
2094 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
2095 Flags &= ~TF_ParentWalk;
2097 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
2100 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
2101 Child = Child->getSibling())
2102 lookForDIEsToKeep(*Child, DMO, CU, Flags);
2105 /// \brief Assign an abbreviation numer to \p Abbrev.
2107 /// Our DIEs get freed after every DebugMapObject has been processed,
2108 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2109 /// the instances hold by the DIEs. When we encounter an abbreviation
2110 /// that we don't know, we create a permanent copy of it.
2111 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2112 // Check the set for priors.
2113 FoldingSetNodeID ID;
2116 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2118 // If it's newly added.
2120 // Assign existing abbreviation number.
2121 Abbrev.setNumber(InSet->getNumber());
2123 // Add to abbreviation list.
2124 Abbreviations.push_back(
2125 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2126 for (const auto &Attr : Abbrev.getData())
2127 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2128 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2129 // Assign the unique abbreviation number.
2130 Abbrev.setNumber(Abbreviations.size());
2131 Abbreviations.back()->setNumber(Abbreviations.size());
2135 /// \brief Clone a string attribute described by \p AttrSpec and add
2137 /// \returns the size of the new attribute.
2138 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
2139 const DWARFFormValue &Val,
2140 const DWARFUnit &U) {
2141 // Switch everything to out of line strings.
2142 const char *String = *Val.getAsCString(&U);
2143 unsigned Offset = StringPool.getStringOffset(String);
2144 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
2145 DIEInteger(Offset));
2149 /// \brief Clone an attribute referencing another DIE and add
2151 /// \returns the size of the new attribute.
2152 unsigned DwarfLinker::cloneDieReferenceAttribute(
2153 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2154 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
2155 CompileUnit &Unit) {
2156 const DWARFUnit &U = Unit.getOrigUnit();
2157 uint32_t Ref = *Val.getAsReference(&U);
2158 DIE *NewRefDie = nullptr;
2159 CompileUnit *RefUnit = nullptr;
2160 DeclContext *Ctxt = nullptr;
2162 const DWARFDebugInfoEntryMinimal *RefDie =
2163 resolveDIEReference(Val, U, InputDIE, RefUnit);
2165 // If the referenced DIE is not found, drop the attribute.
2169 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2170 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
2172 // If we already have emitted an equivalent DeclContext, just point
2174 if (isODRAttribute(AttrSpec.Attr)) {
2175 Ctxt = RefInfo.Ctxt;
2176 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2177 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2178 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2179 dwarf::DW_FORM_ref_addr, Attr);
2180 return getRefAddrSize(U);
2184 if (!RefInfo.Clone) {
2185 assert(Ref > InputDIE.getOffset());
2186 // We haven't cloned this DIE yet. Just create an empty one and
2187 // store it. It'll get really cloned when we process it.
2188 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
2190 NewRefDie = RefInfo.Clone;
2192 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2193 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
2194 // We cannot currently rely on a DIEEntry to emit ref_addr
2195 // references, because the implementation calls back to DwarfDebug
2196 // to find the unit offset. (We don't have a DwarfDebug)
2197 // FIXME: we should be able to design DIEEntry reliance on
2200 if (Ref < InputDIE.getOffset()) {
2201 // We must have already cloned that DIE.
2202 uint32_t NewRefOffset =
2203 RefUnit->getStartOffset() + NewRefDie->getOffset();
2204 Attr = NewRefOffset;
2205 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2206 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
2208 // A forward reference. Note and fixup later.
2210 Unit.noteForwardReference(
2211 NewRefDie, RefUnit, Ctxt,
2212 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2213 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
2215 return getRefAddrSize(U);
2218 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2219 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
2223 /// \brief Clone an attribute of block form (locations, constants) and add
2225 /// \returns the size of the new attribute.
2226 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
2227 const DWARFFormValue &Val,
2228 unsigned AttrSize) {
2231 DIELoc *Loc = nullptr;
2232 DIEBlock *Block = nullptr;
2233 // Just copy the block data over.
2234 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
2235 Loc = new (DIEAlloc) DIELoc;
2236 DIELocs.push_back(Loc);
2238 Block = new (DIEAlloc) DIEBlock;
2239 DIEBlocks.push_back(Block);
2241 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2242 : static_cast<DIEValueList *>(Block);
2245 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2246 dwarf::Form(AttrSpec.Form), Loc);
2248 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2249 dwarf::Form(AttrSpec.Form), Block);
2250 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2251 for (auto Byte : Bytes)
2252 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2253 dwarf::DW_FORM_data1, DIEInteger(Byte));
2254 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2255 // the DIE class, this if could be replaced by
2256 // Attr->setSize(Bytes.size()).
2259 Loc->ComputeSize(&Streamer->getAsmPrinter());
2261 Block->ComputeSize(&Streamer->getAsmPrinter());
2263 Die.addValue(DIEAlloc, Value);
2267 /// \brief Clone an address attribute and add it to \p Die.
2268 /// \returns the size of the new attribute.
2269 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
2270 const DWARFFormValue &Val,
2271 const CompileUnit &Unit,
2272 AttributesInfo &Info) {
2273 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
2274 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2275 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2276 Die.getTag() == dwarf::DW_TAG_lexical_block)
2277 Addr += Info.PCOffset;
2278 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2279 Addr = Unit.getLowPc();
2280 if (Addr == UINT64_MAX)
2283 Info.HasLowPc = true;
2284 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
2285 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2286 if (uint64_t HighPc = Unit.getHighPc())
2291 // If we have a high_pc recorded for the input DIE, use
2292 // it. Otherwise (when no relocations where applied) just use the
2293 // one we just decoded.
2294 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
2297 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
2298 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
2299 return Unit.getOrigUnit().getAddressByteSize();
2302 /// \brief Clone a scalar attribute and add it to \p Die.
2303 /// \returns the size of the new attribute.
2304 unsigned DwarfLinker::cloneScalarAttribute(
2305 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2306 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
2307 AttributesInfo &Info) {
2309 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2310 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2311 if (Unit.getLowPc() == -1ULL)
2313 // Dwarf >= 4 high_pc is an size, not an address.
2314 Value = Unit.getHighPc() - Unit.getLowPc();
2315 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
2316 Value = *Val.getAsSectionOffset();
2317 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2318 Value = *Val.getAsSignedConstant();
2319 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2320 Value = *OptionalValue;
2322 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
2323 &Unit.getOrigUnit(), &InputDIE);
2326 PatchLocation Patch =
2327 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2328 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
2329 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
2330 Unit.noteRangeAttribute(Die, Patch);
2331 // A more generic way to check for location attributes would be
2332 // nice, but it's very unlikely that any other attribute needs a
2334 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2335 AttrSpec.Attr == dwarf::DW_AT_frame_base)
2336 Unit.noteLocationAttribute(Patch, Info.PCOffset);
2337 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2338 Info.IsDeclaration = true;
2343 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2344 /// value \p Val, and add it to \p Die.
2345 /// \returns the size of the cloned attribute.
2346 unsigned DwarfLinker::cloneAttribute(DIE &Die,
2347 const DWARFDebugInfoEntryMinimal &InputDIE,
2349 const DWARFFormValue &Val,
2350 const AttributeSpec AttrSpec,
2351 unsigned AttrSize, AttributesInfo &Info) {
2352 const DWARFUnit &U = Unit.getOrigUnit();
2354 switch (AttrSpec.Form) {
2355 case dwarf::DW_FORM_strp:
2356 case dwarf::DW_FORM_string:
2357 return cloneStringAttribute(Die, AttrSpec, Val, U);
2358 case dwarf::DW_FORM_ref_addr:
2359 case dwarf::DW_FORM_ref1:
2360 case dwarf::DW_FORM_ref2:
2361 case dwarf::DW_FORM_ref4:
2362 case dwarf::DW_FORM_ref8:
2363 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
2365 case dwarf::DW_FORM_block:
2366 case dwarf::DW_FORM_block1:
2367 case dwarf::DW_FORM_block2:
2368 case dwarf::DW_FORM_block4:
2369 case dwarf::DW_FORM_exprloc:
2370 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2371 case dwarf::DW_FORM_addr:
2372 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
2373 case dwarf::DW_FORM_data1:
2374 case dwarf::DW_FORM_data2:
2375 case dwarf::DW_FORM_data4:
2376 case dwarf::DW_FORM_data8:
2377 case dwarf::DW_FORM_udata:
2378 case dwarf::DW_FORM_sdata:
2379 case dwarf::DW_FORM_sec_offset:
2380 case dwarf::DW_FORM_flag:
2381 case dwarf::DW_FORM_flag_present:
2382 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2385 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2392 /// \brief Apply the valid relocations found by findValidRelocs() to
2393 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
2394 /// in the debug_info section.
2396 /// Like for findValidRelocs(), this function must be called with
2397 /// monotonic \p BaseOffset values.
2399 /// \returns wether any reloc has been applied.
2400 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2401 uint32_t BaseOffset, bool isLittleEndian) {
2402 assert((NextValidReloc == 0 ||
2403 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2404 "BaseOffset should only be increasing.");
2405 if (NextValidReloc >= ValidRelocs.size())
2408 // Skip relocs that haven't been applied.
2409 while (NextValidReloc < ValidRelocs.size() &&
2410 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2413 bool Applied = false;
2414 uint64_t EndOffset = BaseOffset + Data.size();
2415 while (NextValidReloc < ValidRelocs.size() &&
2416 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2417 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2418 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2419 assert(ValidReloc.Offset - BaseOffset < Data.size());
2420 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2422 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2423 Value += ValidReloc.Addend;
2424 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2425 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2426 Buf[i] = uint8_t(Value >> (Index * 8));
2428 assert(ValidReloc.Size <= sizeof(Buf));
2429 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2436 static bool isTypeTag(uint16_t Tag) {
2438 case dwarf::DW_TAG_array_type:
2439 case dwarf::DW_TAG_class_type:
2440 case dwarf::DW_TAG_enumeration_type:
2441 case dwarf::DW_TAG_pointer_type:
2442 case dwarf::DW_TAG_reference_type:
2443 case dwarf::DW_TAG_string_type:
2444 case dwarf::DW_TAG_structure_type:
2445 case dwarf::DW_TAG_subroutine_type:
2446 case dwarf::DW_TAG_typedef:
2447 case dwarf::DW_TAG_union_type:
2448 case dwarf::DW_TAG_ptr_to_member_type:
2449 case dwarf::DW_TAG_set_type:
2450 case dwarf::DW_TAG_subrange_type:
2451 case dwarf::DW_TAG_base_type:
2452 case dwarf::DW_TAG_const_type:
2453 case dwarf::DW_TAG_constant:
2454 case dwarf::DW_TAG_file_type:
2455 case dwarf::DW_TAG_namelist:
2456 case dwarf::DW_TAG_packed_type:
2457 case dwarf::DW_TAG_volatile_type:
2458 case dwarf::DW_TAG_restrict_type:
2459 case dwarf::DW_TAG_interface_type:
2460 case dwarf::DW_TAG_unspecified_type:
2461 case dwarf::DW_TAG_shared_type:
2469 /// \brief Recursively clone \p InputDIE's subtrees that have been
2470 /// selected to appear in the linked output.
2472 /// \param OutOffset is the Offset where the newly created DIE will
2473 /// lie in the linked compile unit.
2475 /// \returns the cloned DIE object or null if nothing was selected.
2476 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
2477 CompileUnit &Unit, int64_t PCOffset,
2478 uint32_t OutOffset) {
2479 DWARFUnit &U = Unit.getOrigUnit();
2480 unsigned Idx = U.getDIEIndex(&InputDIE);
2481 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2483 // Should the DIE appear in the output?
2484 if (!Unit.getInfo(Idx).Keep)
2487 uint32_t Offset = InputDIE.getOffset();
2488 // The DIE might have been already created by a forward reference
2489 // (see cloneDieReferenceAttribute()).
2490 DIE *Die = Info.Clone;
2492 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
2493 assert(Die->getTag() == InputDIE.getTag());
2494 Die->setOffset(OutOffset);
2495 if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2496 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2497 !Info.Ctxt->getCanonicalDIEOffset()) {
2498 // We are about to emit a DIE that is the root of its own valid
2499 // DeclContext tree. Make the current offset the canonical offset
2500 // for this context.
2501 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2504 // Extract and clone every attribute.
2505 DataExtractor Data = U.getDebugInfoExtractor();
2506 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
2507 AttributesInfo AttrInfo;
2509 // We could copy the data only if we need to aply a relocation to
2510 // it. After testing, it seems there is no performance downside to
2511 // doing the copy unconditionally, and it makes the code simpler.
2512 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2513 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2514 // Modify the copy with relocated addresses.
2515 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2516 // If we applied relocations, we store the value of high_pc that was
2517 // potentially stored in the input DIE. If high_pc is an address
2518 // (Dwarf version == 2), then it might have been relocated to a
2519 // totally unrelated value (because the end address in the object
2520 // file might be start address of another function which got moved
2521 // independantly by the linker). The computation of the actual
2522 // high_pc value is done in cloneAddressAttribute().
2523 AttrInfo.OrigHighPc =
2524 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2527 // Reset the Offset to 0 as we will be working on the local copy of
2531 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2532 Offset += getULEB128Size(Abbrev->getCode());
2534 // We are entering a subprogram. Get and propagate the PCOffset.
2535 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2536 PCOffset = Info.AddrAdjust;
2537 AttrInfo.PCOffset = PCOffset;
2539 for (const auto &AttrSpec : Abbrev->attributes()) {
2540 DWARFFormValue Val(AttrSpec.Form);
2541 uint32_t AttrSize = Offset;
2542 Val.extractValue(Data, &Offset, &U);
2543 AttrSize = Offset - AttrSize;
2546 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2549 // Look for accelerator entries.
2550 uint16_t Tag = InputDIE.getTag();
2551 // FIXME: This is slightly wrong. An inline_subroutine without a
2552 // low_pc, but with AT_ranges might be interesting to get into the
2553 // accelerator tables too. For now stick with dsymutil's behavior.
2554 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2555 Tag != dwarf::DW_TAG_compile_unit &&
2556 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2557 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2558 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2559 AttrInfo.MangledNameOffset,
2560 Tag == dwarf::DW_TAG_inlined_subroutine);
2562 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2563 Tag == dwarf::DW_TAG_inlined_subroutine);
2564 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2565 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2566 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2569 DIEAbbrev NewAbbrev = Die->generateAbbrev();
2570 // If a scope DIE is kept, we must have kept at least one child. If
2571 // it's not the case, we'll just be emitting one wasteful end of
2572 // children marker, but things won't break.
2573 if (InputDIE.hasChildren())
2574 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2575 // Assign a permanent abbrev number
2576 AssignAbbrev(NewAbbrev);
2577 Die->setAbbrevNumber(NewAbbrev.getNumber());
2579 // Add the size of the abbreviation number to the output offset.
2580 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2582 if (!Abbrev->hasChildren()) {
2584 Die->setSize(OutOffset - Die->getOffset());
2588 // Recursively clone children.
2589 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2590 Child = Child->getSibling()) {
2591 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
2592 Die->addChild(Clone);
2593 OutOffset = Clone->getOffset() + Clone->getSize();
2597 // Account for the end of children marker.
2598 OutOffset += sizeof(int8_t);
2600 Die->setSize(OutOffset - Die->getOffset());
2604 /// \brief Patch the input object file relevant debug_ranges entries
2605 /// and emit them in the output file. Update the relevant attributes
2606 /// to point at the new entries.
2607 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2608 DWARFContext &OrigDwarf) const {
2609 DWARFDebugRangeList RangeList;
2610 const auto &FunctionRanges = Unit.getFunctionRanges();
2611 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2612 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2613 OrigDwarf.isLittleEndian(), AddressSize);
2614 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2615 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2616 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
2617 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2618 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2619 // Ranges addresses are based on the unit's low_pc. Compute the
2620 // offset we need to apply to adapt to the the new unit's low_pc.
2621 int64_t UnitPcOffset = 0;
2622 if (OrigLowPc != -1ULL)
2623 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2625 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2626 uint32_t Offset = RangeAttribute.get();
2627 RangeAttribute.set(Streamer->getRangesSectionSize());
2628 RangeList.extract(RangeExtractor, &Offset);
2629 const auto &Entries = RangeList.getEntries();
2630 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2632 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2633 First.StartAddress >= CurrRange.stop()) {
2634 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2635 if (CurrRange == InvalidRange ||
2636 CurrRange.start() > First.StartAddress + OrigLowPc) {
2637 reportWarning("no mapping for range.");
2642 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2647 /// \brief Generate the debug_aranges entries for \p Unit and if the
2648 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2649 /// contribution for this attribute.
2650 /// FIXME: this could actually be done right in patchRangesForUnit,
2651 /// but for the sake of initial bit-for-bit compatibility with legacy
2652 /// dsymutil, we have to do it in a delayed pass.
2653 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2654 auto Attr = Unit.getUnitRangesAttribute();
2656 Attr->set(Streamer->getRangesSectionSize());
2657 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
2660 /// \brief Insert the new line info sequence \p Seq into the current
2661 /// set of already linked line info \p Rows.
2662 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2663 std::vector<DWARFDebugLine::Row> &Rows) {
2667 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2668 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2673 auto InsertPoint = std::lower_bound(
2674 Rows.begin(), Rows.end(), Seq.front(),
2675 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2676 return LHS.Address < RHS.Address;
2679 // FIXME: this only removes the unneeded end_sequence if the
2680 // sequences have been inserted in order. using a global sort like
2681 // described in patchLineTableForUnit() and delaying the end_sequene
2682 // elimination to emitLineTableForUnit() we can get rid of all of them.
2683 if (InsertPoint != Rows.end() &&
2684 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2685 *InsertPoint = Seq.front();
2686 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2688 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2694 static void patchStmtList(DIE &Die, DIEInteger Offset) {
2695 for (auto &V : Die.values())
2696 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2697 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2701 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2704 /// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2705 /// recreate a relocated version of these for the address ranges that
2706 /// are present in the binary.
2707 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2708 DWARFContext &OrigDwarf) {
2709 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
2710 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2711 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2712 if (StmtList == -1ULL)
2715 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2716 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2717 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
2719 // Parse the original line info for the unit.
2720 DWARFDebugLine::LineTable LineTable;
2721 uint32_t StmtOffset = StmtList;
2722 StringRef LineData = OrigDwarf.getLineSection().Data;
2723 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2724 Unit.getOrigUnit().getAddressByteSize());
2725 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2728 // This vector is the output line table.
2729 std::vector<DWARFDebugLine::Row> NewRows;
2730 NewRows.reserve(LineTable.Rows.size());
2732 // Current sequence of rows being extracted, before being inserted
2734 std::vector<DWARFDebugLine::Row> Seq;
2735 const auto &FunctionRanges = Unit.getFunctionRanges();
2736 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2738 // FIXME: This logic is meant to generate exactly the same output as
2739 // Darwin's classic dsynutil. There is a nicer way to implement this
2740 // by simply putting all the relocated line info in NewRows and simply
2741 // sorting NewRows before passing it to emitLineTableForUnit. This
2742 // should be correct as sequences for a function should stay
2743 // together in the sorted output. There are a few corner cases that
2744 // look suspicious though, and that required to implement the logic
2745 // this way. Revisit that once initial validation is finished.
2747 // Iterate over the object file line info and extract the sequences
2748 // that correspond to linked functions.
2749 for (auto &Row : LineTable.Rows) {
2750 // Check wether we stepped out of the range. The range is
2751 // half-open, but consider accept the end address of the range if
2752 // it is marked as end_sequence in the input (because in that
2753 // case, the relocation offset is accurate and that entry won't
2754 // serve as the start of another function).
2755 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2756 Row.Address > CurrRange.stop() ||
2757 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2758 // We just stepped out of a known range. Insert a end_sequence
2759 // corresponding to the end of the range.
2760 uint64_t StopAddress = CurrRange != InvalidRange
2761 ? CurrRange.stop() + CurrRange.value()
2763 CurrRange = FunctionRanges.find(Row.Address);
2764 bool CurrRangeValid =
2765 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2766 if (!CurrRangeValid) {
2767 CurrRange = InvalidRange;
2768 if (StopAddress != -1ULL) {
2769 // Try harder by looking in the DebugMapObject function
2770 // ranges map. There are corner cases where this finds a
2771 // valid entry. It's unclear if this is right or wrong, but
2772 // for now do as dsymutil.
2773 // FIXME: Understand exactly what cases this addresses and
2774 // potentially remove it along with the Ranges map.
2775 auto Range = Ranges.lower_bound(Row.Address);
2776 if (Range != Ranges.begin() && Range != Ranges.end())
2779 if (Range != Ranges.end() && Range->first <= Row.Address &&
2780 Range->second.first >= Row.Address) {
2781 StopAddress = Row.Address + Range->second.second;
2785 if (StopAddress != -1ULL && !Seq.empty()) {
2786 // Insert end sequence row with the computed end address, but
2787 // the same line as the previous one.
2788 auto NextLine = Seq.back();
2789 NextLine.Address = StopAddress;
2790 NextLine.EndSequence = 1;
2791 NextLine.PrologueEnd = 0;
2792 NextLine.BasicBlock = 0;
2793 NextLine.EpilogueBegin = 0;
2794 Seq.push_back(NextLine);
2795 insertLineSequence(Seq, NewRows);
2798 if (!CurrRangeValid)
2802 // Ignore empty sequences.
2803 if (Row.EndSequence && Seq.empty())
2806 // Relocate row address and add it to the current sequence.
2807 Row.Address += CurrRange.value();
2808 Seq.emplace_back(Row);
2810 if (Row.EndSequence)
2811 insertLineSequence(Seq, NewRows);
2814 // Finished extracting, now emit the line tables.
2815 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2816 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2817 // prologue over and that works because we act as both producer and
2818 // consumer. It would be nicer to have a real configurable line
2820 if (LineTable.Prologue.Version != 2 ||
2821 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2822 LineTable.Prologue.OpcodeBase > 13)
2823 reportWarning("line table paramters mismatch. Cannot emit.");
2825 MCDwarfLineTableParams Params;
2826 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
2827 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
2828 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
2829 Streamer->emitLineTableForUnit(Params,
2830 LineData.slice(StmtList + 4, PrologueEnd),
2831 LineTable.Prologue.MinInstLength, NewRows,
2832 Unit.getOrigUnit().getAddressByteSize());
2836 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2837 Streamer->emitPubNamesForUnit(Unit);
2838 Streamer->emitPubTypesForUnit(Unit);
2841 /// \brief Read the frame info stored in the object, and emit the
2842 /// patched frame descriptions for the linked binary.
2844 /// This is actually pretty easy as the data of the CIEs and FDEs can
2845 /// be considered as black boxes and moved as is. The only thing to do
2846 /// is to patch the addresses in the headers.
2847 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2848 DWARFContext &OrigDwarf,
2849 unsigned AddrSize) {
2850 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2851 if (FrameData.empty())
2854 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2855 uint32_t InputOffset = 0;
2857 // Store the data of the CIEs defined in this object, keyed by their
2859 DenseMap<uint32_t, StringRef> LocalCIES;
2861 while (Data.isValidOffset(InputOffset)) {
2862 uint32_t EntryOffset = InputOffset;
2863 uint32_t InitialLength = Data.getU32(&InputOffset);
2864 if (InitialLength == 0xFFFFFFFF)
2865 return reportWarning("Dwarf64 bits no supported");
2867 uint32_t CIEId = Data.getU32(&InputOffset);
2868 if (CIEId == 0xFFFFFFFF) {
2869 // This is a CIE, store it.
2870 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2871 LocalCIES[EntryOffset] = CIEData;
2872 // The -4 is to account for the CIEId we just read.
2873 InputOffset += InitialLength - 4;
2877 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2879 // Some compilers seem to emit frame info that doesn't start at
2880 // the function entry point, thus we can't just lookup the address
2881 // in the debug map. Use the linker's range map to see if the FDE
2882 // describes something that we can relocate.
2883 auto Range = Ranges.upper_bound(Loc);
2884 if (Range != Ranges.begin())
2886 if (Range == Ranges.end() || Range->first > Loc ||
2887 Range->second.first <= Loc) {
2888 // The +4 is to account for the size of the InitialLength field itself.
2889 InputOffset = EntryOffset + InitialLength + 4;
2893 // This is an FDE, and we have a mapping.
2894 // Have we already emitted a corresponding CIE?
2895 StringRef CIEData = LocalCIES[CIEId];
2896 if (CIEData.empty())
2897 return reportWarning("Inconsistent debug_frame content. Dropping.");
2899 // Look if we already emitted a CIE that corresponds to the
2900 // referenced one (the CIE data is the key of that lookup).
2901 auto IteratorInserted = EmittedCIEs.insert(
2902 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2903 // If there is no CIE yet for this ID, emit it.
2904 if (IteratorInserted.second ||
2905 // FIXME: dsymutil-classic only caches the last used CIE for
2906 // reuse. Mimic that behavior for now. Just removing that
2907 // second half of the condition and the LastCIEOffset variable
2908 // makes the code DTRT.
2909 LastCIEOffset != IteratorInserted.first->getValue()) {
2910 LastCIEOffset = Streamer->getFrameSectionSize();
2911 IteratorInserted.first->getValue() = LastCIEOffset;
2912 Streamer->emitCIE(CIEData);
2915 // Emit the FDE with updated address and CIE pointer.
2916 // (4 + AddrSize) is the size of the CIEId + initial_location
2917 // fields that will get reconstructed by emitFDE().
2918 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
2919 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
2920 Loc + Range->second.second,
2921 FrameData.substr(InputOffset, FDERemainingBytes));
2922 InputOffset += FDERemainingBytes;
2926 ErrorOr<const object::ObjectFile &>
2927 DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
2928 const DebugMap &Map) {
2930 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
2931 if (std::error_code EC = ErrOrObjs.getError())
2932 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
2933 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
2934 if (std::error_code EC = ErrOrObj.getError())
2935 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
2939 bool DwarfLinker::link(const DebugMap &Map) {
2941 if (!createStreamer(Map.getTriple(), OutputFilename))
2944 // Size of the DIEs (and headers) generated for the linked output.
2945 uint64_t OutputDebugInfoSize = 0;
2946 // A unique ID that identifies each compile unit.
2947 unsigned UnitID = 0;
2948 for (const auto &Obj : Map.objects()) {
2949 CurrentDebugObject = Obj.get();
2951 if (Options.Verbose)
2952 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2953 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
2957 // Look for relocations that correspond to debug map entries.
2958 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
2959 if (Options.Verbose)
2960 outs() << "No valid relocations found. Skipping.\n";
2964 // Setup access to the debug info.
2965 DWARFContextInMemory DwarfContext(*ErrOrObj);
2966 startDebugObject(DwarfContext, *Obj);
2968 // In a first phase, just read in the debug info and store the DIE
2969 // parent links that we will use during the next phase.
2970 for (const auto &CU : DwarfContext.compile_units()) {
2971 auto *CUDie = CU->getUnitDIE(false);
2972 if (Options.Verbose) {
2973 outs() << "Input compilation unit:";
2974 CUDie->dump(outs(), CU.get(), 0);
2976 Units.emplace_back(*CU, UnitID++, !Options.NoODR);
2977 gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
2978 StringPool, ODRContexts);
2981 // Then mark all the DIEs that need to be present in the linked
2982 // output and collect some information about them. Note that this
2983 // loop can not be merged with the previous one becaue cross-cu
2984 // references require the ParentIdx to be setup for every CU in
2985 // the object file before calling this.
2986 for (auto &CurrentUnit : Units)
2987 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
2990 // The calls to applyValidRelocs inside cloneDIE will walk the
2991 // reloc array again (in the same way findValidRelocsInDebugInfo()
2992 // did). We need to reset the NextValidReloc index to the beginning.
2995 // Construct the output DIE tree by cloning the DIEs we chose to
2996 // keep above. If there are no valid relocs, then there's nothing
2998 if (!ValidRelocs.empty())
2999 for (auto &CurrentUnit : Units) {
3000 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
3001 CurrentUnit.setStartOffset(OutputDebugInfoSize);
3002 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
3003 11 /* Unit Header size */);
3004 CurrentUnit.setOutputUnitDIE(OutputDIE);
3005 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3006 if (Options.NoOutput)
3008 // FIXME: for compatibility with the classic dsymutil, we emit
3009 // an empty line table for the unit, even if the unit doesn't
3010 // actually exist in the DIE tree.
3011 patchLineTableForUnit(CurrentUnit, DwarfContext);
3014 patchRangesForUnit(CurrentUnit, DwarfContext);
3015 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3016 emitAcceleratorEntriesForUnit(CurrentUnit);
3019 // Emit all the compile unit's debug information.
3020 if (!ValidRelocs.empty() && !Options.NoOutput)
3021 for (auto &CurrentUnit : Units) {
3022 generateUnitRanges(CurrentUnit);
3023 CurrentUnit.fixupForwardReferences();
3024 Streamer->emitCompileUnitHeader(CurrentUnit);
3025 if (!CurrentUnit.getOutputUnitDIE())
3027 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
3030 if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
3031 patchFrameInfoForObject(*Obj, DwarfContext,
3032 Units[0].getOrigUnit().getAddressByteSize());
3034 // Clean-up before starting working on the next object.
3038 // Emit everything that's global.
3039 if (!Options.NoOutput) {
3040 Streamer->emitAbbrevs(Abbreviations);
3041 Streamer->emitStrings(StringPool);
3044 return Options.NoOutput ? true : Streamer->finish();
3048 /// \brief Get the offset of string \p S in the string table. This
3049 /// can insert a new element or return the offset of a preexisitng
3051 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3052 if (S.empty() && !Strings.empty())
3055 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3059 // A non-empty string can't be at offset 0, so if we have an entry
3060 // with a 0 offset, it must be a previously interned string.
3061 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3062 if (Inserted || It->getValue().first == 0) {
3063 // Set offset and chain at the end of the entries list.
3064 It->getValue().first = CurrentEndOffset;
3065 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3066 Last->getValue().second = &*It;
3069 return It->getValue().first;
3072 /// \brief Put \p S into the StringMap so that it gets permanent
3073 /// storage, but do not actually link it in the chain of elements
3074 /// that go into the output section. A latter call to
3075 /// getStringOffset() with the same string will chain it though.
3076 StringRef NonRelocatableStringpool::internString(StringRef S) {
3077 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3078 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3079 return InsertResult.first->getKey();
3082 void warn(const Twine &Warning, const Twine &Context) {
3083 errs() << Twine("while processing ") + Context + ":\n";
3084 errs() << Twine("warning: ") + Warning + "\n";
3087 bool error(const Twine &Error, const Twine &Context) {
3088 errs() << Twine("while processing ") + Context + ":\n";
3089 errs() << Twine("error: ") + Error + "\n";
3093 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3094 const LinkOptions &Options) {
3095 DwarfLinker Linker(OutputFilename, Options);
3096 return Linker.link(DM);