1 //===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "BinaryHolder.h"
13 #include "MachOUtils.h"
14 #include "NonRelocatableStringpool.h"
15 #include "llvm/ADT/IntervalMap.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/DIE.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
22 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
23 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
24 #include "llvm/MC/MCAsmBackend.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCCodeEmitter.h"
28 #include "llvm/MC/MCDwarf.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
35 #include "llvm/Object/MachO.h"
36 #include "llvm/Support/Dwarf.h"
37 #include "llvm/Support/LEB128.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
50 template <typename KeyT, typename ValT>
51 using HalfOpenIntervalMap =
52 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
53 IntervalMapHalfOpenInfo<KeyT>>;
55 typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
57 // FIXME: Delete this structure.
58 struct PatchLocation {
59 DIE::value_iterator I;
61 PatchLocation() = default;
62 PatchLocation(DIE::value_iterator I) : I(I) {}
64 void set(uint64_t New) const {
67 assert(Old.getType() == DIEValue::isInteger);
68 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
71 uint64_t get() const {
73 return I->getDIEInteger().getValue();
80 /// A DeclContext is a named program scope that is used for ODR
81 /// uniquing of types.
82 /// The set of DeclContext for the ODR-subject parts of a Dwarf link
83 /// is expanded (and uniqued) with each new object file processed. We
84 /// need to determine the context of each DIE in an linked object file
85 /// to see if the corresponding type has already been emitted.
87 /// The contexts are conceptually organised as a tree (eg. a function
88 /// scope is contained in a namespace scope that contains other
89 /// scopes), but storing/accessing them in an actual tree is too
90 /// inefficient: we need to be able to very quickly query a context
91 /// for a given child context by name. Storing a StringMap in each
92 /// DeclContext would be too space inefficient.
93 /// The solution here is to give each DeclContext a link to its parent
94 /// (this allows to walk up the tree), but to query the existance of a
95 /// specific DeclContext using a separate DenseMap keyed on the hash
96 /// of the fully qualified name of the context.
98 unsigned QualifiedNameHash;
104 const DeclContext &Parent;
105 DWARFDie LastSeenDIE;
106 uint32_t LastSeenCompileUnitID;
107 uint32_t CanonicalDIEOffset;
112 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
115 : QualifiedNameHash(0), Line(0), ByteSize(0),
116 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
117 LastSeenDIE(), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
119 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
120 StringRef Name, StringRef File, const DeclContext &Parent,
121 DWARFDie LastSeenDIE = DWARFDie(), unsigned CUId = 0)
122 : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
123 Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
124 LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
126 uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
128 bool setLastSeenDIE(CompileUnit &U, const DWARFDie &Die);
130 uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
131 void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
133 uint16_t getTag() const { return Tag; }
134 StringRef getName() const { return Name; }
137 /// Info type for the DenseMap storing the DeclContext pointers.
138 struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
139 using DenseMapInfo<DeclContext *>::getEmptyKey;
140 using DenseMapInfo<DeclContext *>::getTombstoneKey;
142 static unsigned getHashValue(const DeclContext *Ctxt) {
143 return Ctxt->QualifiedNameHash;
146 static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
147 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
149 return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
150 LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
151 LHS->Name.data() == RHS->Name.data() &&
152 LHS->File.data() == RHS->File.data() &&
153 LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
157 /// This class gives a tree-like API to the DenseMap that stores the
158 /// DeclContext objects. It also holds the BumpPtrAllocator where
159 /// these objects will be allocated.
160 class DeclContextTree {
161 BumpPtrAllocator Allocator;
163 DeclContext::Map Contexts;
166 /// Get the child of \a Context described by \a DIE in \a Unit. The
167 /// required strings will be interned in \a StringPool.
168 /// \returns The child DeclContext along with one bit that is set if
169 /// this context is invalid.
170 /// An invalid context means it shouldn't be considered for uniquing, but its
171 /// not returning null, because some children of that context might be
172 /// uniquing candidates. FIXME: The invalid bit along the return value is to
173 /// emulate some dsymutil-classic functionality.
174 PointerIntPair<DeclContext *, 1>
175 getChildDeclContext(DeclContext &Context,
176 const DWARFDie &DIE, CompileUnit &Unit,
177 NonRelocatableStringpool &StringPool, bool InClangModule);
179 DeclContext &getRoot() { return Root; }
182 /// \brief Stores all information relating to a compile unit, be it in
183 /// its original instance in the object file to its brand new cloned
184 /// and linked DIE tree.
187 /// \brief Information gathered about a DIE in the object file.
189 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
190 DeclContext *Ctxt; ///< ODR Declaration context.
191 DIE *Clone; ///< Cloned version of that DIE.
192 uint32_t ParentIdx; ///< The index of this DIE's parent.
193 bool Keep : 1; ///< Is the DIE part of the linked output?
194 bool InDebugMap : 1;///< Was this DIE's entity found in the map?
195 bool Prune : 1; ///< Is this a pure forward declaration we can strip?
198 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR,
199 StringRef ClangModuleName)
200 : OrigUnit(OrigUnit), ID(ID), NewUnit(OrigUnit.getVersion(),
201 OrigUnit.getAddressByteSize(),
202 OrigUnit.getUnitDIE().getTag()),
203 LowPc(UINT64_MAX), HighPc(0), RangeAlloc(), Ranges(RangeAlloc),
204 ClangModuleName(ClangModuleName) {
205 Info.resize(OrigUnit.getNumDIEs());
207 auto CUDie = OrigUnit.getUnitDIE(false);
208 unsigned Lang = CUDie.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_language, 0);
209 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
210 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
211 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
212 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
213 Lang == dwarf::DW_LANG_ObjC_plus_plus);
216 DWARFUnit &getOrigUnit() const { return OrigUnit; }
218 unsigned getUniqueID() const { return ID; }
220 DIE *getOutputUnitDIE() const {
221 return &const_cast<DIEUnit &>(NewUnit).getUnitDie();
224 bool hasODR() const { return HasODR; }
225 bool isClangModule() const { return !ClangModuleName.empty(); }
226 const std::string &getClangModuleName() const { return ClangModuleName; }
228 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
229 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
231 uint64_t getStartOffset() const { return StartOffset; }
232 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
233 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
235 uint64_t getLowPc() const { return LowPc; }
236 uint64_t getHighPc() const { return HighPc; }
238 Optional<PatchLocation> getUnitRangesAttribute() const {
239 return UnitRangeAttribute;
241 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
242 const std::vector<PatchLocation> &getRangesAttributes() const {
243 return RangeAttributes;
246 const std::vector<std::pair<PatchLocation, int64_t>> &
247 getLocationAttributes() const {
248 return LocationAttributes;
251 void setHasInterestingContent() { HasInterestingContent = true; }
252 bool hasInterestingContent() { return HasInterestingContent; }
254 /// Mark every DIE in this unit as kept. This function also
255 /// marks variables as InDebugMap so that they appear in the
256 /// reconstructed accelerator tables.
257 void markEverythingAsKept();
259 /// \brief Compute the end offset for this unit. Must be
260 /// called after the CU's DIEs have been cloned.
261 /// \returns the next unit offset (which is also the current
262 /// debug_info section size).
263 uint64_t computeNextUnitOffset();
265 /// \brief Keep track of a forward reference to DIE \p Die in \p
266 /// RefUnit by \p Attr. The attribute should be fixed up later to
267 /// point to the absolute offset of \p Die in the debug_info section
268 /// or to the canonical offset of \p Ctxt if it is non-null.
269 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
270 DeclContext *Ctxt, PatchLocation Attr);
272 /// \brief Apply all fixups recored by noteForwardReference().
273 void fixupForwardReferences();
275 /// \brief Add a function range [\p LowPC, \p HighPC) that is
276 /// relocatad by applying offset \p PCOffset.
277 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
279 /// \brief Keep track of a DW_AT_range attribute that we will need to
281 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
283 /// \brief Keep track of a location attribute pointing to a location
284 /// list in the debug_loc section.
285 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
287 /// \brief Add a name accelerator entry for \p Die with \p Name
288 /// which is stored in the string table at \p Offset.
289 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
290 bool SkipPubnamesSection = false);
292 /// \brief Add a type accelerator entry for \p Die with \p Name
293 /// which is stored in the string table at \p Offset.
294 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
297 StringRef Name; ///< Name of the entry.
298 const DIE *Die; ///< DIE this entry describes.
299 uint32_t NameOffset; ///< Offset of Name in the string pool.
300 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
302 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
303 bool SkipPubSection = false)
304 : Name(Name), Die(Die), NameOffset(NameOffset),
305 SkipPubSection(SkipPubSection) {}
308 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
309 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
311 /// Get the full path for file \a FileNum in the line table
312 StringRef getResolvedPath(unsigned FileNum) {
313 if (FileNum >= ResolvedPaths.size())
315 return ResolvedPaths[FileNum];
318 /// Set the fully resolved path for the line-table's file \a FileNum
320 void setResolvedPath(unsigned FileNum, StringRef Path) {
321 if (ResolvedPaths.size() <= FileNum)
322 ResolvedPaths.resize(FileNum + 1);
323 ResolvedPaths[FileNum] = Path;
329 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
332 uint64_t StartOffset;
333 uint64_t NextUnitOffset;
338 /// \brief A list of attributes to fixup with the absolute offset of
339 /// a DIE in the debug_info section.
341 /// The offsets for the attributes in this array couldn't be set while
342 /// cloning because for cross-cu forward refences the target DIE's
343 /// offset isn't known you emit the reference attribute.
344 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
345 PatchLocation>> ForwardDIEReferences;
347 FunctionIntervals::Allocator RangeAlloc;
348 /// \brief The ranges in that interval map are the PC ranges for
349 /// functions in this unit, associated with the PC offset to apply
350 /// to the addresses to get the linked address.
351 FunctionIntervals Ranges;
353 /// \brief DW_AT_ranges attributes to patch after we have gathered
354 /// all the unit's function addresses.
356 std::vector<PatchLocation> RangeAttributes;
357 Optional<PatchLocation> UnitRangeAttribute;
360 /// \brief Location attributes that need to be transfered from th
361 /// original debug_loc section to the liked one. They are stored
362 /// along with the PC offset that is to be applied to their
363 /// function's address.
364 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
366 /// \brief Accelerator entries for the unit, both for the pub*
367 /// sections and the apple* ones.
369 std::vector<AccelInfo> Pubnames;
370 std::vector<AccelInfo> Pubtypes;
373 /// Cached resolved paths from the line table.
374 /// Note, the StringRefs here point in to the intern (uniquing) string pool.
375 /// This means that a StringRef returned here doesn't need to then be uniqued
376 /// for the purposes of getting a unique address for each string.
377 std::vector<StringRef> ResolvedPaths;
379 /// Is this unit subject to the ODR rule?
381 /// Did a DIE actually contain a valid reloc?
382 bool HasInterestingContent;
383 /// If this is a Clang module, this holds the module's name.
384 std::string ClangModuleName;
387 void CompileUnit::markEverythingAsKept() {
389 // Mark everything that wasn't explicity marked for pruning.
393 uint64_t CompileUnit::computeNextUnitOffset() {
394 NextUnitOffset = StartOffset + 11 /* Header size */;
395 // The root DIE might be null, meaning that the Unit had nothing to
396 // contribute to the linked output. In that case, we will emit the
397 // unit header without any actual DIE.
398 NextUnitOffset += NewUnit.getUnitDie().getSize();
399 return NextUnitOffset;
402 /// \brief Keep track of a forward cross-cu reference from this unit
403 /// to \p Die that lives in \p RefUnit.
404 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
405 DeclContext *Ctxt, PatchLocation Attr) {
406 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
409 /// \brief Apply all fixups recorded by noteForwardReference().
410 void CompileUnit::fixupForwardReferences() {
411 for (const auto &Ref : ForwardDIEReferences) {
413 const CompileUnit *RefUnit;
416 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
417 if (Ctxt && Ctxt->getCanonicalDIEOffset())
418 Attr.set(Ctxt->getCanonicalDIEOffset());
420 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
424 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
426 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
427 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
428 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
431 void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
432 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
433 RangeAttributes.push_back(Attr);
435 UnitRangeAttribute = Attr;
438 void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
439 LocationAttributes.emplace_back(Attr, PcOffset);
442 /// \brief Add a name accelerator entry for \p Die with \p Name
443 /// which is stored in the string table at \p Offset.
444 void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
445 uint32_t Offset, bool SkipPubSection) {
446 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
449 /// \brief Add a type accelerator entry for \p Die with \p Name
450 /// which is stored in the string table at \p Offset.
451 void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
453 Pubtypes.emplace_back(Name, Die, Offset, false);
456 /// \brief The Dwarf streaming logic
458 /// All interactions with the MC layer that is used to build the debug
459 /// information binary representation are handled in this class.
460 class DwarfStreamer {
461 /// \defgroup MCObjects MC layer objects constructed by the streamer
463 std::unique_ptr<MCRegisterInfo> MRI;
464 std::unique_ptr<MCAsmInfo> MAI;
465 std::unique_ptr<MCObjectFileInfo> MOFI;
466 std::unique_ptr<MCContext> MC;
467 MCAsmBackend *MAB; // Owned by MCStreamer
468 std::unique_ptr<MCInstrInfo> MII;
469 std::unique_ptr<MCSubtargetInfo> MSTI;
470 MCCodeEmitter *MCE; // Owned by MCStreamer
471 MCStreamer *MS; // Owned by AsmPrinter
472 std::unique_ptr<TargetMachine> TM;
473 std::unique_ptr<AsmPrinter> Asm;
476 /// \brief the file we stream the linked Dwarf to.
477 std::unique_ptr<raw_fd_ostream> OutFile;
479 uint32_t RangesSectionSize;
480 uint32_t LocSectionSize;
481 uint32_t LineSectionSize;
482 uint32_t FrameSectionSize;
484 /// \brief Emit the pubnames or pubtypes section contribution for \p
485 /// Unit into \p Sec. The data is provided in \p Names.
486 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
487 const CompileUnit &Unit,
488 const std::vector<CompileUnit::AccelInfo> &Names);
491 /// \brief Actually create the streamer and the ouptut file.
493 /// This could be done directly in the constructor, but it feels
494 /// more natural to handle errors through return value.
495 bool init(Triple TheTriple, StringRef OutputFilename);
497 /// \brief Dump the file to the disk.
498 bool finish(const DebugMap &);
500 AsmPrinter &getAsmPrinter() const { return *Asm; }
502 /// \brief Set the current output section to debug_info and change
503 /// the MC Dwarf version to \p DwarfVersion.
504 void switchToDebugInfoSection(unsigned DwarfVersion);
506 /// \brief Emit the compilation unit header for \p Unit in the
507 /// debug_info section.
509 /// As a side effect, this also switches the current Dwarf version
510 /// of the MC layer to the one of U.getOrigUnit().
511 void emitCompileUnitHeader(CompileUnit &Unit);
513 /// \brief Recursively emit the DIE tree rooted at \p Die.
514 void emitDIE(DIE &Die);
516 /// \brief Emit the abbreviation table \p Abbrevs to the
517 /// debug_abbrev section.
518 void emitAbbrevs(const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs);
520 /// \brief Emit the string table described by \p Pool.
521 void emitStrings(const NonRelocatableStringpool &Pool);
523 /// \brief Emit debug_ranges for \p FuncRange by translating the
524 /// original \p Entries.
525 void emitRangesEntries(
526 int64_t UnitPcOffset, uint64_t OrigLowPc,
527 const FunctionIntervals::const_iterator &FuncRange,
528 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
529 unsigned AddressSize);
531 /// \brief Emit debug_aranges entries for \p Unit and if \p
532 /// DoRangesSection is true, also emit the debug_ranges entries for
533 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
534 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
536 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
538 /// \brief Emit the debug_loc contribution for \p Unit by copying
539 /// the entries from \p Dwarf and offseting them. Update the
540 /// location attributes to point to the new entries.
541 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
543 /// \brief Emit the line table described in \p Rows into the
544 /// debug_line section.
545 void emitLineTableForUnit(MCDwarfLineTableParams Params,
546 StringRef PrologueBytes, unsigned MinInstLength,
547 std::vector<DWARFDebugLine::Row> &Rows,
548 unsigned AdddressSize);
550 uint32_t getLineSectionSize() const { return LineSectionSize; }
552 /// \brief Emit the .debug_pubnames contribution for \p Unit.
553 void emitPubNamesForUnit(const CompileUnit &Unit);
555 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
556 void emitPubTypesForUnit(const CompileUnit &Unit);
558 /// \brief Emit a CIE.
559 void emitCIE(StringRef CIEBytes);
561 /// \brief Emit an FDE with data \p Bytes.
562 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
565 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
568 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
569 std::string ErrorStr;
570 std::string TripleName;
571 StringRef Context = "dwarf streamer init";
574 const Target *TheTarget =
575 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
577 return error(ErrorStr, Context);
578 TripleName = TheTriple.getTriple();
580 // Create all the MC Objects.
581 MRI.reset(TheTarget->createMCRegInfo(TripleName));
583 return error(Twine("no register info for target ") + TripleName, Context);
585 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
587 return error("no asm info for target " + TripleName, Context);
589 MOFI.reset(new MCObjectFileInfo);
590 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
591 MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, CodeModel::Default, *MC);
593 MCTargetOptions Options;
594 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "", Options);
596 return error("no asm backend for target " + TripleName, Context);
598 MII.reset(TheTarget->createMCInstrInfo());
600 return error("no instr info info for target " + TripleName, Context);
602 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
604 return error("no subtarget info for target " + TripleName, Context);
606 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
608 return error("no code emitter for target " + TripleName, Context);
610 // Create the output file.
613 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
615 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
617 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
618 MS = TheTarget->createMCObjectStreamer(
619 TheTriple, *MC, *MAB, *OutFile, MCE, *MSTI, MCOptions.MCRelaxAll,
620 MCOptions.MCIncrementalLinkerCompatible,
621 /*DWARFMustBeAtTheEnd*/ false);
623 return error("no object streamer for target " + TripleName, Context);
625 // Finally create the AsmPrinter we'll use to emit the DIEs.
626 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
629 return error("no target machine for target " + TripleName, Context);
631 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
633 return error("no asm printer for target " + TripleName, Context);
635 RangesSectionSize = 0;
638 FrameSectionSize = 0;
643 bool DwarfStreamer::finish(const DebugMap &DM) {
644 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
645 return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
651 /// \brief Set the current output section to debug_info and change
652 /// the MC Dwarf version to \p DwarfVersion.
653 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
654 MS->SwitchSection(MOFI->getDwarfInfoSection());
655 MC->setDwarfVersion(DwarfVersion);
658 /// \brief Emit the compilation unit header for \p Unit in the
659 /// debug_info section.
661 /// A Dwarf scetion header is encoded as:
662 /// uint32_t Unit length (omiting this field)
664 /// uint32_t Abbreviation table offset
665 /// uint8_t Address size
667 /// Leading to a total of 11 bytes.
668 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
669 unsigned Version = Unit.getOrigUnit().getVersion();
670 switchToDebugInfoSection(Version);
672 // Emit size of content not including length itself. The size has
673 // already been computed in CompileUnit::computeOffsets(). Substract
674 // 4 to that size to account for the length field.
675 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
676 Asm->EmitInt16(Version);
677 // We share one abbreviations table across all units so it's always at the
678 // start of the section.
680 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
683 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
684 /// for the linked Dwarf file.
685 void DwarfStreamer::emitAbbrevs(
686 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs) {
687 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
688 Asm->emitDwarfAbbrevs(Abbrevs);
691 /// \brief Recursively emit the DIE tree rooted at \p Die.
692 void DwarfStreamer::emitDIE(DIE &Die) {
693 MS->SwitchSection(MOFI->getDwarfInfoSection());
694 Asm->emitDwarfDIE(Die);
697 /// \brief Emit the debug_str section stored in \p Pool.
698 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
699 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
700 for (auto *Entry = Pool.getFirstEntry(); Entry;
701 Entry = Pool.getNextEntry(Entry))
702 Asm->OutStreamer->EmitBytes(
703 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
706 /// \brief Emit the debug_range section contents for \p FuncRange by
707 /// translating the original \p Entries. The debug_range section
708 /// format is totally trivial, consisting just of pairs of address
709 /// sized addresses describing the ranges.
710 void DwarfStreamer::emitRangesEntries(
711 int64_t UnitPcOffset, uint64_t OrigLowPc,
712 const FunctionIntervals::const_iterator &FuncRange,
713 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
714 unsigned AddressSize) {
715 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
717 // Offset each range by the right amount.
718 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
719 for (const auto &Range : Entries) {
720 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
721 warn("unsupported base address selection operation",
722 "emitting debug_ranges");
725 // Do not emit empty ranges.
726 if (Range.StartAddress == Range.EndAddress)
729 // All range entries should lie in the function range.
730 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
731 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
732 warn("inconsistent range data.", "emitting debug_ranges");
733 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
734 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
735 RangesSectionSize += 2 * AddressSize;
738 // Add the terminator entry.
739 MS->EmitIntValue(0, AddressSize);
740 MS->EmitIntValue(0, AddressSize);
741 RangesSectionSize += 2 * AddressSize;
744 /// \brief Emit the debug_aranges contribution of a unit and
745 /// if \p DoDebugRanges is true the debug_range contents for a
746 /// compile_unit level DW_AT_ranges attribute (Which are basically the
747 /// same thing with a different base address).
748 /// Just aggregate all the ranges gathered inside that unit.
749 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
750 bool DoDebugRanges) {
751 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
752 // Gather the ranges in a vector, so that we can simplify them. The
753 // IntervalMap will have coalesced the non-linked ranges, but here
754 // we want to coalesce the linked addresses.
755 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
756 const auto &FunctionRanges = Unit.getFunctionRanges();
757 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
758 Range != End; ++Range)
759 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
760 Range.stop() + Range.value()));
762 // The object addresses where sorted, but again, the linked
763 // addresses might end up in a different order.
764 std::sort(Ranges.begin(), Ranges.end());
766 if (!Ranges.empty()) {
767 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
769 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
770 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
772 unsigned HeaderSize =
773 sizeof(int32_t) + // Size of contents (w/o this field
774 sizeof(int16_t) + // DWARF ARange version number
775 sizeof(int32_t) + // Offset of CU in the .debug_info section
776 sizeof(int8_t) + // Pointer Size (in bytes)
777 sizeof(int8_t); // Segment Size (in bytes)
779 unsigned TupleSize = AddressSize * 2;
780 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
782 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
783 Asm->OutStreamer->EmitLabel(BeginLabel);
784 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
785 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
786 Asm->EmitInt8(AddressSize); // Address size
787 Asm->EmitInt8(0); // Segment size
789 Asm->OutStreamer->emitFill(Padding, 0x0);
791 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
793 uint64_t RangeStart = Range->first;
794 MS->EmitIntValue(RangeStart, AddressSize);
795 while ((Range + 1) != End && Range->second == (Range + 1)->first)
797 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
801 Asm->OutStreamer->EmitIntValue(0, AddressSize);
802 Asm->OutStreamer->EmitIntValue(0, AddressSize);
803 Asm->OutStreamer->EmitLabel(EndLabel);
809 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
810 // Offset each range by the right amount.
811 int64_t PcOffset = -Unit.getLowPc();
812 // Emit coalesced ranges.
813 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
814 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
815 while (Range + 1 != End && Range->second == (Range + 1)->first)
817 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
818 RangesSectionSize += 2 * AddressSize;
821 // Add the terminator entry.
822 MS->EmitIntValue(0, AddressSize);
823 MS->EmitIntValue(0, AddressSize);
824 RangesSectionSize += 2 * AddressSize;
827 /// \brief Emit location lists for \p Unit and update attribtues to
828 /// point to the new entries.
829 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
830 DWARFContext &Dwarf) {
831 const auto &Attributes = Unit.getLocationAttributes();
833 if (Attributes.empty())
836 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
838 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
839 const DWARFSection &InputSec = Dwarf.getLocSection();
840 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
841 DWARFUnit &OrigUnit = Unit.getOrigUnit();
842 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
843 int64_t UnitPcOffset = 0;
844 auto OrigLowPc = OrigUnitDie.getAttributeValueAsAddress(dwarf::DW_AT_low_pc);
846 UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc();
848 for (const auto &Attr : Attributes) {
849 uint32_t Offset = Attr.first.get();
850 Attr.first.set(LocSectionSize);
851 // This is the quantity to add to the old location address to get
852 // the correct address for the new one.
853 int64_t LocPcOffset = Attr.second + UnitPcOffset;
854 while (Data.isValidOffset(Offset)) {
855 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
856 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
857 LocSectionSize += 2 * AddressSize;
858 if (Low == 0 && High == 0) {
859 Asm->OutStreamer->EmitIntValue(0, AddressSize);
860 Asm->OutStreamer->EmitIntValue(0, AddressSize);
863 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
864 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
865 uint64_t Length = Data.getU16(&Offset);
866 Asm->OutStreamer->EmitIntValue(Length, 2);
867 // Just copy the bytes over.
868 Asm->OutStreamer->EmitBytes(
869 StringRef(InputSec.Data.substr(Offset, Length)));
871 LocSectionSize += Length + 2;
876 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
877 StringRef PrologueBytes,
878 unsigned MinInstLength,
879 std::vector<DWARFDebugLine::Row> &Rows,
880 unsigned PointerSize) {
881 // Switch to the section where the table will be emitted into.
882 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
883 MCSymbol *LineStartSym = MC->createTempSymbol();
884 MCSymbol *LineEndSym = MC->createTempSymbol();
886 // The first 4 bytes is the total length of the information for this
887 // compilation unit (not including these 4 bytes for the length).
888 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
889 Asm->OutStreamer->EmitLabel(LineStartSym);
891 MS->EmitBytes(PrologueBytes);
892 LineSectionSize += PrologueBytes.size() + 4;
894 SmallString<128> EncodingBuffer;
895 raw_svector_ostream EncodingOS(EncodingBuffer);
898 // We only have the dummy entry, dsymutil emits an entry with a 0
899 // address in that case.
900 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
901 MS->EmitBytes(EncodingOS.str());
902 LineSectionSize += EncodingBuffer.size();
903 MS->EmitLabel(LineEndSym);
907 // Line table state machine fields
908 unsigned FileNum = 1;
909 unsigned LastLine = 1;
911 unsigned IsStatement = 1;
913 uint64_t Address = -1ULL;
915 unsigned RowsSinceLastSequence = 0;
917 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
918 auto &Row = Rows[Idx];
920 int64_t AddressDelta;
921 if (Address == -1ULL) {
922 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
923 MS->EmitULEB128IntValue(PointerSize + 1);
924 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
925 MS->EmitIntValue(Row.Address, PointerSize);
926 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
929 AddressDelta = (Row.Address - Address) / MinInstLength;
932 // FIXME: code copied and transfromed from
933 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
934 // this code, but the current compatibility requirement with
935 // classic dsymutil makes it hard. Revisit that once this
936 // requirement is dropped.
938 if (FileNum != Row.File) {
940 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
941 MS->EmitULEB128IntValue(FileNum);
942 LineSectionSize += 1 + getULEB128Size(FileNum);
944 if (Column != Row.Column) {
946 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
947 MS->EmitULEB128IntValue(Column);
948 LineSectionSize += 1 + getULEB128Size(Column);
951 // FIXME: We should handle the discriminator here, but dsymutil
952 // doesn' consider it, thus ignore it for now.
954 if (Isa != Row.Isa) {
956 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
957 MS->EmitULEB128IntValue(Isa);
958 LineSectionSize += 1 + getULEB128Size(Isa);
960 if (IsStatement != Row.IsStmt) {
961 IsStatement = Row.IsStmt;
962 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
963 LineSectionSize += 1;
965 if (Row.BasicBlock) {
966 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
967 LineSectionSize += 1;
970 if (Row.PrologueEnd) {
971 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
972 LineSectionSize += 1;
975 if (Row.EpilogueBegin) {
976 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
977 LineSectionSize += 1;
980 int64_t LineDelta = int64_t(Row.Line) - LastLine;
981 if (!Row.EndSequence) {
982 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
983 MS->EmitBytes(EncodingOS.str());
984 LineSectionSize += EncodingBuffer.size();
985 EncodingBuffer.resize(0);
986 Address = Row.Address;
988 RowsSinceLastSequence++;
991 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
992 MS->EmitSLEB128IntValue(LineDelta);
993 LineSectionSize += 1 + getSLEB128Size(LineDelta);
996 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
997 MS->EmitULEB128IntValue(AddressDelta);
998 LineSectionSize += 1 + getULEB128Size(AddressDelta);
1000 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
1001 MS->EmitBytes(EncodingOS.str());
1002 LineSectionSize += EncodingBuffer.size();
1003 EncodingBuffer.resize(0);
1005 LastLine = FileNum = IsStatement = 1;
1006 RowsSinceLastSequence = Column = Isa = 0;
1010 if (RowsSinceLastSequence) {
1011 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
1012 MS->EmitBytes(EncodingOS.str());
1013 LineSectionSize += EncodingBuffer.size();
1014 EncodingBuffer.resize(0);
1017 MS->EmitLabel(LineEndSym);
1020 /// \brief Emit the pubnames or pubtypes section contribution for \p
1021 /// Unit into \p Sec. The data is provided in \p Names.
1022 void DwarfStreamer::emitPubSectionForUnit(
1023 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
1024 const std::vector<CompileUnit::AccelInfo> &Names) {
1028 // Start the dwarf pubnames section.
1029 Asm->OutStreamer->SwitchSection(Sec);
1030 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1031 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
1033 bool HeaderEmitted = false;
1034 // Emit the pubnames for this compilation unit.
1035 for (const auto &Name : Names) {
1036 if (Name.SkipPubSection)
1039 if (!HeaderEmitted) {
1041 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
1042 Asm->OutStreamer->EmitLabel(BeginLabel);
1043 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
1044 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
1045 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1046 HeaderEmitted = true;
1048 Asm->EmitInt32(Name.Die->getOffset());
1049 Asm->OutStreamer->EmitBytes(
1050 StringRef(Name.Name.data(), Name.Name.size() + 1));
1055 Asm->EmitInt32(0); // End marker.
1056 Asm->OutStreamer->EmitLabel(EndLabel);
1059 /// \brief Emit .debug_pubnames for \p Unit.
1060 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1061 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1062 "names", Unit, Unit.getPubnames());
1065 /// \brief Emit .debug_pubtypes for \p Unit.
1066 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1067 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1068 "types", Unit, Unit.getPubtypes());
1071 /// \brief Emit a CIE into the debug_frame section.
1072 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1073 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1075 MS->EmitBytes(CIEBytes);
1076 FrameSectionSize += CIEBytes.size();
1079 /// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1080 /// contains the FDE data without the length, CIE offset and address
1081 /// which will be replaced with the paramter values.
1082 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1083 uint32_t Address, StringRef FDEBytes) {
1084 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1086 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1087 MS->EmitIntValue(CIEOffset, 4);
1088 MS->EmitIntValue(Address, AddrSize);
1089 MS->EmitBytes(FDEBytes);
1090 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1093 /// \brief The core of the Dwarf linking logic.
1095 /// The link of the dwarf information from the object files will be
1096 /// driven by the selection of 'root DIEs', which are DIEs that
1097 /// describe variables or functions that are present in the linked
1098 /// binary (and thus have entries in the debug map). All the debug
1099 /// information that will be linked (the DIEs, but also the line
1100 /// tables, ranges, ...) is derived from that set of root DIEs.
1102 /// The root DIEs are identified because they contain relocations that
1103 /// correspond to a debug map entry at specific places (the low_pc for
1104 /// a function, the location for a variable). These relocations are
1105 /// called ValidRelocs in the DwarfLinker and are gathered as a very
1106 /// first step when we start processing a DebugMapObject.
1109 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1110 : OutputFilename(OutputFilename), Options(Options),
1111 BinHolder(Options.Verbose), LastCIEOffset(0) {}
1113 /// \brief Link the contents of the DebugMap.
1114 bool link(const DebugMap &);
1116 void reportWarning(const Twine &Warning,
1117 const DWARFDie *DIE = nullptr) const;
1120 /// \brief Called at the start of a debug object link.
1121 void startDebugObject(DWARFContext &, DebugMapObject &);
1123 /// \brief Called at the end of a debug object link.
1124 void endDebugObject();
1126 /// Keeps track of relocations.
1127 class RelocationManager {
1132 const DebugMapObject::DebugMapEntry *Mapping;
1134 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1135 const DebugMapObject::DebugMapEntry *Mapping)
1136 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1138 bool operator<(const ValidReloc &RHS) const {
1139 return Offset < RHS.Offset;
1143 DwarfLinker &Linker;
1145 /// \brief The valid relocations for the current DebugMapObject.
1146 /// This vector is sorted by relocation offset.
1147 std::vector<ValidReloc> ValidRelocs;
1149 /// \brief Index into ValidRelocs of the next relocation to
1150 /// consider. As we walk the DIEs in acsending file offset and as
1151 /// ValidRelocs is sorted by file offset, keeping this index
1152 /// uptodate is all we have to do to have a cheap lookup during the
1153 /// root DIE selection and during DIE cloning.
1154 unsigned NextValidReloc;
1157 RelocationManager(DwarfLinker &Linker)
1158 : Linker(Linker), NextValidReloc(0) {}
1160 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1161 /// \brief Reset the NextValidReloc counter.
1162 void resetValidRelocs() { NextValidReloc = 0; }
1164 /// \defgroup FindValidRelocations Translate debug map into a list
1165 /// of relevant relocations
1168 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1169 const DebugMapObject &DMO);
1171 bool findValidRelocs(const object::SectionRef &Section,
1172 const object::ObjectFile &Obj,
1173 const DebugMapObject &DMO);
1175 void findValidRelocsMachO(const object::SectionRef &Section,
1176 const object::MachOObjectFile &Obj,
1177 const DebugMapObject &DMO);
1180 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1181 CompileUnit::DIEInfo &Info);
1183 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1184 bool isLittleEndian);
1187 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1190 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1191 /// keep. Store that information in \p CU's DIEInfo.
1192 void lookForDIEsToKeep(RelocationManager &RelocMgr,
1193 const DWARFDie &DIE,
1194 const DebugMapObject &DMO, CompileUnit &CU,
1197 /// If this compile unit is really a skeleton CU that points to a
1198 /// clang module, register it in ClangModules and return true.
1200 /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
1201 /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
1203 bool registerModuleReference(const DWARFDie &CUDie,
1204 const DWARFUnit &Unit, DebugMap &ModuleMap,
1205 unsigned Indent = 0);
1207 /// Recursively add the debug info in this clang module .pcm
1208 /// file (and all the modules imported by it in a bottom-up fashion)
1210 void loadClangModule(StringRef Filename, StringRef ModulePath,
1211 StringRef ModuleName, uint64_t DwoId,
1212 DebugMap &ModuleMap, unsigned Indent = 0);
1214 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1215 enum TravesalFlags {
1216 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1217 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1218 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1219 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1220 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
1221 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
1224 /// \brief Mark the passed DIE as well as all the ones it depends on
1226 void keepDIEAndDependencies(RelocationManager &RelocMgr,
1227 const DWARFDie &DIE,
1228 CompileUnit::DIEInfo &MyInfo,
1229 const DebugMapObject &DMO, CompileUnit &CU,
1232 unsigned shouldKeepDIE(RelocationManager &RelocMgr,
1233 const DWARFDie &DIE,
1234 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1237 unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
1238 const DWARFDie &DIE,
1240 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1242 unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
1243 const DWARFDie &DIE,
1245 CompileUnit::DIEInfo &MyInfo,
1248 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1249 CompileUnit::DIEInfo &Info);
1252 /// \defgroup Linking Methods used to link the debug information
1257 DwarfLinker &Linker;
1258 RelocationManager &RelocMgr;
1259 /// Allocator used for all the DIEValue objects.
1260 BumpPtrAllocator &DIEAlloc;
1261 std::vector<std::unique_ptr<CompileUnit>> &CompileUnits;
1262 LinkOptions Options;
1265 DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1266 BumpPtrAllocator &DIEAlloc,
1267 std::vector<std::unique_ptr<CompileUnit>> &CompileUnits,
1268 LinkOptions &Options)
1269 : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1270 CompileUnits(CompileUnits), Options(Options) {}
1272 /// Recursively clone \p InputDIE into an tree of DIE objects
1273 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1274 /// stripped out and addresses have been rewritten according to the
1277 /// \param OutOffset is the offset the cloned DIE in the output
1279 /// \param PCOffset (while cloning a function scope) is the offset
1280 /// applied to the entry point of the function to get the linked address.
1281 /// \param Die the output DIE to use, pass NULL to create one.
1282 /// \returns the root of the cloned tree or null if nothing was selected.
1283 DIE *cloneDIE(const DWARFDie &InputDIE, CompileUnit &U,
1284 int64_t PCOffset, uint32_t OutOffset, unsigned Flags,
1285 DIE *Die = nullptr);
1287 /// Construct the output DIE tree by cloning the DIEs we
1288 /// chose to keep above. If there are no valid relocs, then there's
1289 /// nothing to clone/emit.
1290 void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
1293 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1295 /// Information gathered and exchanged between the various
1296 /// clone*Attributes helpers about the attributes of a particular DIE.
1297 struct AttributesInfo {
1298 const char *Name, *MangledName; ///< Names.
1299 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1301 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1302 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1303 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1305 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1306 bool IsDeclaration; ///< Is this DIE only a declaration?
1309 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1310 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1311 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1314 /// Helper for cloneDIE.
1315 unsigned cloneAttribute(DIE &Die,
1316 const DWARFDie &InputDIE,
1317 CompileUnit &U, const DWARFFormValue &Val,
1318 const AttributeSpec AttrSpec, unsigned AttrSize,
1319 AttributesInfo &AttrInfo);
1321 /// Clone a string attribute described by \p AttrSpec and add
1323 /// \returns the size of the new attribute.
1324 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1325 const DWARFFormValue &Val,
1326 const DWARFUnit &U);
1328 /// Clone an attribute referencing another DIE and add
1330 /// \returns the size of the new attribute.
1332 cloneDieReferenceAttribute(DIE &Die,
1333 const DWARFDie &InputDIE,
1334 AttributeSpec AttrSpec, unsigned AttrSize,
1335 const DWARFFormValue &Val, CompileUnit &Unit);
1337 /// Clone an attribute referencing another DIE and add
1339 /// \returns the size of the new attribute.
1340 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1341 const DWARFFormValue &Val, unsigned AttrSize);
1343 /// Clone an attribute referencing another DIE and add
1345 /// \returns the size of the new attribute.
1346 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1347 const DWARFFormValue &Val,
1348 const CompileUnit &Unit,
1349 AttributesInfo &Info);
1351 /// Clone a scalar attribute and add it to \p Die.
1352 /// \returns the size of the new attribute.
1353 unsigned cloneScalarAttribute(DIE &Die,
1354 const DWARFDie &InputDIE,
1355 CompileUnit &U, AttributeSpec AttrSpec,
1356 const DWARFFormValue &Val, unsigned AttrSize,
1357 AttributesInfo &Info);
1359 /// Get the potential name and mangled name for the entity
1360 /// described by \p Die and store them in \Info if they are not
1362 /// \returns is a name was found.
1363 bool getDIENames(const DWARFDie &Die, AttributesInfo &Info);
1365 /// Create a copy of abbreviation Abbrev.
1366 void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
1369 /// \brief Assign an abbreviation number to \p Abbrev
1370 void AssignAbbrev(DIEAbbrev &Abbrev);
1372 /// \brief FoldingSet that uniques the abbreviations.
1373 FoldingSet<DIEAbbrev> AbbreviationsSet;
1374 /// \brief Storage for the unique Abbreviations.
1375 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1376 /// be changed to a vecot of unique_ptrs.
1377 std::vector<std::unique_ptr<DIEAbbrev>> Abbreviations;
1379 /// \brief Compute and emit debug_ranges section for \p Unit, and
1380 /// patch the attributes referencing it.
1381 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1383 /// \brief Generate and emit the DW_AT_ranges attribute for a
1384 /// compile_unit if it had one.
1385 void generateUnitRanges(CompileUnit &Unit) const;
1387 /// \brief Extract the line tables fromt he original dwarf, extract
1388 /// the relevant parts according to the linked function ranges and
1389 /// emit the result in the debug_line section.
1390 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1392 /// \brief Emit the accelerator entries for \p Unit.
1393 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1395 /// \brief Patch the frame info for an object file and emit it.
1396 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1397 unsigned AddressSize);
1399 /// \brief DIELoc objects that need to be destructed (but not freed!).
1400 std::vector<DIELoc *> DIELocs;
1401 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1402 std::vector<DIEBlock *> DIEBlocks;
1403 /// \brief Allocator used for all the DIEValue objects.
1404 BumpPtrAllocator DIEAlloc;
1407 /// ODR Contexts for that link.
1408 DeclContextTree ODRContexts;
1410 /// \defgroup Helpers Various helper methods.
1413 bool createStreamer(const Triple &TheTriple, StringRef OutputFilename);
1415 /// \brief Attempt to load a debug object from disk.
1416 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1417 DebugMapObject &Obj,
1418 const DebugMap &Map);
1421 std::string OutputFilename;
1422 LinkOptions Options;
1423 BinaryHolder BinHolder;
1424 std::unique_ptr<DwarfStreamer> Streamer;
1425 uint64_t OutputDebugInfoSize;
1426 unsigned UnitID; ///< A unique ID that identifies each compile unit.
1428 /// The units of the current debug map object.
1429 std::vector<std::unique_ptr<CompileUnit>> Units;
1432 /// The debug map object currently under consideration.
1433 DebugMapObject *CurrentDebugObject;
1435 /// \brief The Dwarf string pool
1436 NonRelocatableStringpool StringPool;
1438 /// \brief This map is keyed by the entry PC of functions in that
1439 /// debug object and the associated value is a pair storing the
1440 /// corresponding end PC and the offset to apply to get the linked
1443 /// See startDebugObject() for a more complete description of its use.
1444 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1446 /// \brief The CIEs that have been emitted in the output
1447 /// section. The actual CIE data serves a the key to this StringMap,
1448 /// this takes care of comparing the semantics of CIEs defined in
1449 /// different object files.
1450 StringMap<uint32_t> EmittedCIEs;
1452 /// Offset of the last CIE that has been emitted in the output
1453 /// debug_frame section.
1454 uint32_t LastCIEOffset;
1456 /// Mapping the PCM filename to the DwoId.
1457 StringMap<uint64_t> ClangModules;
1459 bool ModuleCacheHintDisplayed = false;
1460 bool ArchiveHintDisplayed = false;
1463 /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
1464 /// CompileUnit object instead.
1465 static CompileUnit *getUnitForOffset(
1466 std::vector<std::unique_ptr<CompileUnit>> &Units, unsigned Offset) {
1468 std::upper_bound(Units.begin(), Units.end(), Offset,
1469 [](uint32_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
1470 return LHS < RHS->getOrigUnit().getNextUnitOffset();
1472 return CU != Units.end() ? CU->get() : nullptr;
1475 /// Resolve the DIE attribute reference that has been
1476 /// extracted in \p RefValue. The resulting DIE migh be in another
1477 /// CompileUnit which is stored into \p ReferencedCU.
1478 /// \returns null if resolving fails for any reason.
1479 static DWARFDie resolveDIEReference(
1480 const DwarfLinker &Linker, std::vector<std::unique_ptr<CompileUnit>> &Units,
1481 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1482 const DWARFDie &DIE, CompileUnit *&RefCU) {
1483 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1484 uint64_t RefOffset = *RefValue.getAsReference();
1486 if ((RefCU = getUnitForOffset(Units, RefOffset)))
1487 if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1490 Linker.reportWarning("could not find referenced DIE", &DIE);
1494 /// \returns whether the passed \a Attr type might contain a DIE
1495 /// reference suitable for ODR uniquing.
1496 static bool isODRAttribute(uint16_t Attr) {
1500 case dwarf::DW_AT_type:
1501 case dwarf::DW_AT_containing_type:
1502 case dwarf::DW_AT_specification:
1503 case dwarf::DW_AT_abstract_origin:
1504 case dwarf::DW_AT_import:
1507 llvm_unreachable("Improper attribute.");
1510 /// Set the last DIE/CU a context was seen in and, possibly invalidate
1511 /// the context if it is ambiguous.
1513 /// In the current implementation, we don't handle overloaded
1514 /// functions well, because the argument types are not taken into
1515 /// account when computing the DeclContext tree.
1517 /// Some of this is mitigated byt using mangled names that do contain
1518 /// the arguments types, but sometimes (eg. with function templates)
1519 /// we don't have that. In that case, just do not unique anything that
1520 /// refers to the contexts we are not able to distinguish.
1522 /// If a context that is not a namespace appears twice in the same CU,
1523 /// we know it is ambiguous. Make it invalid.
1524 bool DeclContext::setLastSeenDIE(CompileUnit &U,
1525 const DWARFDie &Die) {
1526 if (LastSeenCompileUnitID == U.getUniqueID()) {
1527 DWARFUnit &OrigUnit = U.getOrigUnit();
1528 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1529 U.getInfo(FirstIdx).Ctxt = nullptr;
1533 LastSeenCompileUnitID = U.getUniqueID();
1538 PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1539 DeclContext &Context, const DWARFDie &DIE, CompileUnit &U,
1540 NonRelocatableStringpool &StringPool, bool InClangModule) {
1541 unsigned Tag = DIE.getTag();
1543 // FIXME: dsymutil-classic compat: We should bail out here if we
1544 // have a specification or an abstract_origin. We will get the
1545 // parent context wrong here.
1549 // By default stop gathering child contexts.
1550 return PointerIntPair<DeclContext *, 1>(nullptr);
1551 case dwarf::DW_TAG_module:
1553 case dwarf::DW_TAG_compile_unit:
1554 return PointerIntPair<DeclContext *, 1>(&Context);
1555 case dwarf::DW_TAG_subprogram:
1556 // Do not unique anything inside CU local functions.
1557 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1558 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1559 !DIE.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_external, 0))
1560 return PointerIntPair<DeclContext *, 1>(nullptr);
1562 case dwarf::DW_TAG_member:
1563 case dwarf::DW_TAG_namespace:
1564 case dwarf::DW_TAG_structure_type:
1565 case dwarf::DW_TAG_class_type:
1566 case dwarf::DW_TAG_union_type:
1567 case dwarf::DW_TAG_enumeration_type:
1568 case dwarf::DW_TAG_typedef:
1569 // Artificial things might be ambiguous, because they might be
1570 // created on demand. For example implicitely defined constructors
1571 // are ambiguous because of the way we identify contexts, and they
1572 // won't be generated everytime everywhere.
1573 if (DIE.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_artificial, 0))
1574 return PointerIntPair<DeclContext *, 1>(nullptr);
1578 const char *Name = DIE.getName(DINameKind::LinkageName);
1579 const char *ShortName = DIE.getName(DINameKind::ShortName);
1581 StringRef ShortNameRef;
1585 NameRef = StringPool.internString(Name);
1586 else if (Tag == dwarf::DW_TAG_namespace)
1587 // FIXME: For dsymutil-classic compatibility. I think uniquing
1588 // within anonymous namespaces is wrong. There is no ODR guarantee
1590 NameRef = StringPool.internString("(anonymous namespace)");
1592 if (ShortName && ShortName != Name)
1593 ShortNameRef = StringPool.internString(ShortName);
1595 ShortNameRef = NameRef;
1597 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1598 Tag != dwarf::DW_TAG_union_type &&
1599 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1600 return PointerIntPair<DeclContext *, 1>(nullptr);
1603 unsigned ByteSize = UINT32_MAX;
1605 if (!InClangModule) {
1606 // Gather some discriminating data about the DeclContext we will be
1607 // creating: File, line number and byte size. This shouldn't be
1608 // necessary, because the ODR is just about names, but given that we
1609 // do some approximations with overloaded functions and anonymous
1610 // namespaces, use these additional data points to make the process
1611 // safer. This is disabled for clang modules, because forward
1612 // declarations of module-defined types do not have a file and line.
1613 ByteSize = DIE.getAttributeValueAsUnsignedConstant(
1614 dwarf::DW_AT_byte_size, UINT64_MAX);
1615 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1616 if (unsigned FileNum = DIE.getAttributeValueAsUnsignedConstant(
1617 dwarf::DW_AT_decl_file, 0)) {
1618 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1619 &U.getOrigUnit())) {
1620 // FIXME: dsymutil-classic compatibility. I'd rather not
1621 // unique anything in anonymous namespaces, but if we do, then
1622 // verify that the file and line correspond.
1623 if (!Name && Tag == dwarf::DW_TAG_namespace)
1626 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1627 // instead of "" would allow more uniquing, but for now, do
1628 // it this way to match dsymutil-classic.
1629 if (LT->hasFileAtIndex(FileNum)) {
1630 Line = DIE.getAttributeValueAsUnsignedConstant(
1631 dwarf::DW_AT_decl_line, 0);
1632 // Cache the resolved paths, because calling realpath is expansive.
1633 StringRef ResolvedPath = U.getResolvedPath(FileNum);
1634 if (!ResolvedPath.empty()) {
1635 FileRef = ResolvedPath;
1639 LT->getFileNameByIndex(FileNum, "",
1640 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1643 assert(gotFileName && "Must get file name from line table");
1644 #ifdef HAVE_REALPATH
1645 char RealPath[PATH_MAX + 1];
1646 RealPath[PATH_MAX] = 0;
1647 if (::realpath(File.c_str(), RealPath))
1650 FileRef = StringPool.internString(File);
1651 U.setResolvedPath(FileNum, FileRef);
1659 if (!Line && NameRef.empty())
1660 return PointerIntPair<DeclContext *, 1>(nullptr);
1662 // We hash NameRef, which is the mangled name, in order to get most
1663 // overloaded functions resolve correctly.
1665 // Strictly speaking, hashing the Tag is only necessary for a
1666 // DW_TAG_module, to prevent uniquing of a module and a namespace
1667 // with the same name.
1669 // FIXME: dsymutil-classic won't unique the same type presented
1670 // once as a struct and once as a class. Using the Tag in the fully
1671 // qualified name hash to get the same effect.
1672 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1674 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1675 // use the filename.
1676 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1677 Hash = hash_combine(Hash, FileRef);
1679 // Now look if this context already exists.
1680 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1681 auto ContextIter = Contexts.find(&Key);
1683 if (ContextIter == Contexts.end()) {
1684 // The context wasn't found.
1686 DeclContext *NewContext =
1687 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1688 Context, DIE, U.getUniqueID());
1689 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1690 assert(Inserted && "Failed to insert DeclContext");
1692 } else if (Tag != dwarf::DW_TAG_namespace &&
1693 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1694 // The context was found, but it is ambiguous with another context
1695 // in the same file. Mark it invalid.
1696 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1699 assert(ContextIter != Contexts.end());
1700 // FIXME: dsymutil-classic compatibility. Union types aren't
1701 // uniques, but their children might be.
1702 if ((Tag == dwarf::DW_TAG_subprogram &&
1703 Context.getTag() != dwarf::DW_TAG_structure_type &&
1704 Context.getTag() != dwarf::DW_TAG_class_type) ||
1705 (Tag == dwarf::DW_TAG_union_type))
1706 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1708 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1711 bool DwarfLinker::DIECloner::getDIENames(const DWARFDie &Die,
1712 AttributesInfo &Info) {
1713 // FIXME: a bit wasteful as the first getName might return the
1715 if (!Info.MangledName &&
1716 (Info.MangledName = Die.getName(DINameKind::LinkageName)))
1717 Info.MangledNameOffset =
1718 Linker.StringPool.getStringOffset(Info.MangledName);
1720 if (!Info.Name && (Info.Name = Die.getName(DINameKind::ShortName)))
1721 Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
1723 return Info.Name || Info.MangledName;
1726 /// \brief Report a warning to the user, optionaly including
1727 /// information about a specific \p DIE related to the warning.
1728 void DwarfLinker::reportWarning(const Twine &Warning,
1729 const DWARFDie *DIE) const {
1730 StringRef Context = "<debug map>";
1731 if (CurrentDebugObject)
1732 Context = CurrentDebugObject->getObjectFilename();
1733 warn(Warning, Context);
1735 if (!Options.Verbose || !DIE)
1738 errs() << " in DIE:\n";
1739 DIE->dump(errs(), 0 /* RecurseDepth */, 6 /* Indent */);
1742 bool DwarfLinker::createStreamer(const Triple &TheTriple,
1743 StringRef OutputFilename) {
1744 if (Options.NoOutput)
1747 Streamer = llvm::make_unique<DwarfStreamer>();
1748 return Streamer->init(TheTriple, OutputFilename);
1751 /// Recursive helper to build the global DeclContext information and
1752 /// gather the child->parent relationships in the original compile unit.
1754 /// \return true when this DIE and all of its children are only
1755 /// forward declarations to types defined in external clang modules
1756 /// (i.e., forward declarations that are children of a DW_TAG_module).
1757 static bool analyzeContextInfo(const DWARFDie &DIE,
1758 unsigned ParentIdx, CompileUnit &CU,
1759 DeclContext *CurrentDeclContext,
1760 NonRelocatableStringpool &StringPool,
1761 DeclContextTree &Contexts,
1762 bool InImportedModule = false) {
1763 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1764 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1766 // Clang imposes an ODR on modules(!) regardless of the language:
1767 // "The module-id should consist of only a single identifier,
1768 // which provides the name of the module being defined. Each
1769 // module shall have a single definition."
1771 // This does not extend to the types inside the modules:
1772 // "[I]n C, this implies that if two structs are defined in
1773 // different submodules with the same name, those two types are
1774 // distinct types (but may be compatible types if their
1775 // definitions match)."
1777 // We treat non-C++ modules like namespaces for this reason.
1778 if (DIE.getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
1779 DIE.getAttributeValueAsString(dwarf::DW_AT_name,
1780 "") != CU.getClangModuleName()) {
1781 InImportedModule = true;
1784 Info.ParentIdx = ParentIdx;
1785 bool InClangModule = CU.isClangModule() || InImportedModule;
1786 if (CU.hasODR() || InClangModule) {
1787 if (CurrentDeclContext) {
1788 auto PtrInvalidPair = Contexts.getChildDeclContext(
1789 *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
1790 CurrentDeclContext = PtrInvalidPair.getPointer();
1792 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1794 Info.Ctxt = CurrentDeclContext = nullptr;
1797 Info.Prune = InImportedModule;
1798 if (DIE.hasChildren())
1799 for (auto Child: DIE.children())
1800 Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
1801 StringPool, Contexts, InImportedModule);
1803 // Prune this DIE if it is either a forward declaration inside a
1804 // DW_TAG_module or a DW_TAG_module that contains nothing but
1805 // forward declarations.
1806 Info.Prune &= (DIE.getTag() == dwarf::DW_TAG_module) ||
1807 DIE.getAttributeValueAsUnsignedConstant(
1808 dwarf::DW_AT_declaration, 0);
1810 // Don't prune it if there is no definition for the DIE.
1811 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
1816 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1820 case dwarf::DW_TAG_subprogram:
1821 case dwarf::DW_TAG_lexical_block:
1822 case dwarf::DW_TAG_subroutine_type:
1823 case dwarf::DW_TAG_structure_type:
1824 case dwarf::DW_TAG_class_type:
1825 case dwarf::DW_TAG_union_type:
1828 llvm_unreachable("Invalid Tag");
1831 void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1832 // Iterate over the debug map entries and put all the ones that are
1833 // functions (because they have a size) into the Ranges map. This
1834 // map is very similar to the FunctionRanges that are stored in each
1835 // unit, with 2 notable differences:
1836 // - obviously this one is global, while the other ones are per-unit.
1837 // - this one contains not only the functions described in the DIE
1838 // tree, but also the ones that are only in the debug map.
1839 // The latter information is required to reproduce dsymutil's logic
1840 // while linking line tables. The cases where this information
1841 // matters look like bugs that need to be investigated, but for now
1842 // we need to reproduce dsymutil's behavior.
1843 // FIXME: Once we understood exactly if that information is needed,
1844 // maybe totally remove this (or try to use it to do a real
1845 // -gline-tables-only on Darwin.
1846 for (const auto &Entry : Obj.symbols()) {
1847 const auto &Mapping = Entry.getValue();
1848 if (Mapping.Size && Mapping.ObjectAddress)
1849 Ranges[*Mapping.ObjectAddress] = std::make_pair(
1850 *Mapping.ObjectAddress + Mapping.Size,
1851 int64_t(Mapping.BinaryAddress) - *Mapping.ObjectAddress);
1855 void DwarfLinker::endDebugObject() {
1859 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1861 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1869 static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
1872 return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
1873 RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
1874 case Triple::x86_64:
1875 return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
1878 return RelocType == MachO::ARM_RELOC_SECTDIFF ||
1879 RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1880 RelocType == MachO::ARM_RELOC_HALF ||
1881 RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
1882 case Triple::aarch64:
1883 return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
1889 /// \brief Iterate over the relocations of the given \p Section and
1890 /// store the ones that correspond to debug map entries into the
1891 /// ValidRelocs array.
1892 void DwarfLinker::RelocationManager::
1893 findValidRelocsMachO(const object::SectionRef &Section,
1894 const object::MachOObjectFile &Obj,
1895 const DebugMapObject &DMO) {
1897 Section.getContents(Contents);
1898 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1899 bool SkipNext = false;
1901 for (const object::RelocationRef &Reloc : Section.relocations()) {
1907 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1908 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1910 if (isMachOPairedReloc(Obj.getAnyRelocationType(MachOReloc),
1913 Linker.reportWarning(" unsupported relocation in debug_info section.");
1917 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1918 uint64_t Offset64 = Reloc.getOffset();
1919 if ((RelocSize != 4 && RelocSize != 8)) {
1920 Linker.reportWarning(" unsupported relocation in debug_info section.");
1923 uint32_t Offset = Offset64;
1924 // Mach-o uses REL relocations, the addend is at the relocation offset.
1925 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1926 uint64_t SymAddress;
1929 if (Obj.isRelocationScattered(MachOReloc)) {
1930 // The address of the base symbol for scattered relocations is
1931 // stored in the reloc itself. The actual addend will store the
1932 // base address plus the offset.
1933 SymAddress = Obj.getScatteredRelocationValue(MachOReloc);
1934 SymOffset = int64_t(Addend) - SymAddress;
1936 SymAddress = Addend;
1940 auto Sym = Reloc.getSymbol();
1941 if (Sym != Obj.symbol_end()) {
1942 Expected<StringRef> SymbolName = Sym->getName();
1944 consumeError(SymbolName.takeError());
1945 Linker.reportWarning("error getting relocation symbol name.");
1948 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
1949 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1950 } else if (const auto *Mapping = DMO.lookupObjectAddress(SymAddress)) {
1951 // Do not store the addend. The addend was the address of the
1952 // symbol in the object file, the address in the binary that is
1953 // stored in the debug map doesn't need to be offseted.
1954 ValidRelocs.emplace_back(Offset64, RelocSize, SymOffset, Mapping);
1959 /// \brief Dispatch the valid relocation finding logic to the
1960 /// appropriate handler depending on the object file format.
1961 bool DwarfLinker::RelocationManager::findValidRelocs(
1962 const object::SectionRef &Section, const object::ObjectFile &Obj,
1963 const DebugMapObject &DMO) {
1964 // Dispatch to the right handler depending on the file type.
1965 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1966 findValidRelocsMachO(Section, *MachOObj, DMO);
1968 Linker.reportWarning(Twine("unsupported object file type: ") +
1971 if (ValidRelocs.empty())
1974 // Sort the relocations by offset. We will walk the DIEs linearly in
1975 // the file, this allows us to just keep an index in the relocation
1976 // array that we advance during our walk, rather than resorting to
1977 // some associative container. See DwarfLinker::NextValidReloc.
1978 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1982 /// \brief Look for relocations in the debug_info section that match
1983 /// entries in the debug map. These relocations will drive the Dwarf
1984 /// link by indicating which DIEs refer to symbols present in the
1986 /// \returns wether there are any valid relocations in the debug info.
1987 bool DwarfLinker::RelocationManager::
1988 findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1989 const DebugMapObject &DMO) {
1990 // Find the debug_info section.
1991 for (const object::SectionRef &Section : Obj.sections()) {
1992 StringRef SectionName;
1993 Section.getName(SectionName);
1994 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1995 if (SectionName != "debug_info")
1997 return findValidRelocs(Section, Obj, DMO);
2002 /// \brief Checks that there is a relocation against an actual debug
2003 /// map entry between \p StartOffset and \p NextOffset.
2005 /// This function must be called with offsets in strictly ascending
2006 /// order because it never looks back at relocations it already 'went past'.
2007 /// \returns true and sets Info.InDebugMap if it is the case.
2008 bool DwarfLinker::RelocationManager::
2009 hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
2010 CompileUnit::DIEInfo &Info) {
2011 assert(NextValidReloc == 0 ||
2012 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
2013 if (NextValidReloc >= ValidRelocs.size())
2016 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
2018 // We might need to skip some relocs that we didn't consider. For
2019 // example the high_pc of a discarded DIE might contain a reloc that
2020 // is in the list because it actually corresponds to the start of a
2021 // function that is in the debug map.
2022 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
2023 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
2025 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
2028 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2029 const auto &Mapping = ValidReloc.Mapping->getValue();
2030 uint64_t ObjectAddress =
2031 Mapping.ObjectAddress ? uint64_t(*Mapping.ObjectAddress) : UINT64_MAX;
2032 if (Linker.Options.Verbose)
2033 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
2034 << " " << format("\t%016" PRIx64 " => %016" PRIx64, ObjectAddress,
2035 uint64_t(Mapping.BinaryAddress));
2037 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend;
2038 if (Mapping.ObjectAddress)
2039 Info.AddrAdjust -= ObjectAddress;
2040 Info.InDebugMap = true;
2044 /// \brief Get the starting and ending (exclusive) offset for the
2045 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
2046 /// supposed to point to the position of the first attribute described
2048 /// \return [StartOffset, EndOffset) as a pair.
2049 static std::pair<uint32_t, uint32_t>
2050 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
2051 unsigned Offset, const DWARFUnit &Unit) {
2052 DataExtractor Data = Unit.getDebugInfoExtractor();
2054 for (unsigned i = 0; i < Idx; ++i)
2055 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
2057 uint32_t End = Offset;
2058 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
2060 return std::make_pair(Offset, End);
2063 /// \brief Check if a variable describing DIE should be kept.
2064 /// \returns updated TraversalFlags.
2065 unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
2066 const DWARFDie &DIE,
2068 CompileUnit::DIEInfo &MyInfo,
2070 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2072 // Global variables with constant value can always be kept.
2073 if (!(Flags & TF_InFunctionScope) &&
2074 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
2075 MyInfo.InDebugMap = true;
2076 return Flags | TF_Keep;
2079 Optional<uint32_t> LocationIdx =
2080 Abbrev->findAttributeIndex(dwarf::DW_AT_location);
2084 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2085 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2086 uint32_t LocationOffset, LocationEndOffset;
2087 std::tie(LocationOffset, LocationEndOffset) =
2088 getAttributeOffsets(Abbrev, *LocationIdx, Offset, OrigUnit);
2090 // See if there is a relocation to a valid debug map entry inside
2091 // this variable's location. The order is important here. We want to
2092 // always check in the variable has a valid relocation, so that the
2093 // DIEInfo is filled. However, we don't want a static variable in a
2094 // function to force us to keep the enclosing function.
2095 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
2096 (Flags & TF_InFunctionScope))
2099 if (Options.Verbose)
2100 DIE.dump(outs(), 0, 8 /* Indent */);
2102 return Flags | TF_Keep;
2105 /// \brief Check if a function describing DIE should be kept.
2106 /// \returns updated TraversalFlags.
2107 unsigned DwarfLinker::shouldKeepSubprogramDIE(
2108 RelocationManager &RelocMgr,
2109 const DWARFDie &DIE, CompileUnit &Unit,
2110 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2111 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2113 Flags |= TF_InFunctionScope;
2115 Optional<uint32_t> LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2119 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2120 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2121 uint32_t LowPcOffset, LowPcEndOffset;
2122 std::tie(LowPcOffset, LowPcEndOffset) =
2123 getAttributeOffsets(Abbrev, *LowPcIdx, Offset, OrigUnit);
2125 auto LowPc = DIE.getAttributeValueAsAddress(dwarf::DW_AT_low_pc);
2126 assert(LowPc.hasValue() && "low_pc attribute is not an address.");
2128 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
2131 if (Options.Verbose)
2132 DIE.dump(outs(), 0, 8 /* Indent */);
2136 Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
2138 reportWarning("Function without high_pc. Range will be discarded.\n",
2143 // Replace the debug map range with a more accurate one.
2144 Ranges[*LowPc] = std::make_pair(*HighPc, MyInfo.AddrAdjust);
2145 Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
2149 /// \brief Check if a DIE should be kept.
2150 /// \returns updated TraversalFlags.
2151 unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
2152 const DWARFDie &DIE,
2154 CompileUnit::DIEInfo &MyInfo,
2156 switch (DIE.getTag()) {
2157 case dwarf::DW_TAG_constant:
2158 case dwarf::DW_TAG_variable:
2159 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
2160 case dwarf::DW_TAG_subprogram:
2161 return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
2162 case dwarf::DW_TAG_module:
2163 case dwarf::DW_TAG_imported_module:
2164 case dwarf::DW_TAG_imported_declaration:
2165 case dwarf::DW_TAG_imported_unit:
2166 // We always want to keep these.
2167 return Flags | TF_Keep;
2175 /// \brief Mark the passed DIE as well as all the ones it depends on
2178 /// This function is called by lookForDIEsToKeep on DIEs that are
2179 /// newly discovered to be needed in the link. It recursively calls
2180 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2181 /// TraversalFlags to inform it that it's not doing the primary DIE
2183 void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
2184 const DWARFDie &Die,
2185 CompileUnit::DIEInfo &MyInfo,
2186 const DebugMapObject &DMO,
2187 CompileUnit &CU, bool UseODR) {
2188 DWARFUnit &Unit = CU.getOrigUnit();
2191 // First mark all the parent chain as kept.
2192 unsigned AncestorIdx = MyInfo.ParentIdx;
2193 while (!CU.getInfo(AncestorIdx).Keep) {
2194 unsigned ODRFlag = UseODR ? TF_ODR : 0;
2195 lookForDIEsToKeep(RelocMgr, Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
2196 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
2197 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2200 // Then we need to mark all the DIEs referenced by this DIE's
2201 // attributes as kept.
2202 DataExtractor Data = Unit.getDebugInfoExtractor();
2203 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2204 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
2206 // Mark all DIEs referenced through atttributes as kept.
2207 for (const auto &AttrSpec : Abbrev->attributes()) {
2208 DWARFFormValue Val(AttrSpec.Form);
2210 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2211 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2215 Val.extractValue(Data, &Offset, &Unit);
2216 CompileUnit *ReferencedCU;
2218 resolveDIEReference(*this, Units, Val, Unit, Die, ReferencedCU)) {
2219 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2220 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2221 // If the referenced DIE has a DeclContext that has already been
2222 // emitted, then do not keep the one in this CU. We'll link to
2223 // the canonical DIE in cloneDieReferenceAttribute.
2224 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2225 // be necessary and could be advantageously replaced by
2226 // ReferencedCU->hasODR() && CU.hasODR().
2227 // FIXME: compatibility with dsymutil-classic. There is no
2228 // reason not to unique ref_addr references.
2229 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2230 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2231 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2234 // Keep a module forward declaration if there is no definition.
2235 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
2236 Info.Ctxt->getCanonicalDIEOffset()))
2239 unsigned ODRFlag = UseODR ? TF_ODR : 0;
2240 lookForDIEsToKeep(RelocMgr, RefDIE, DMO, *ReferencedCU,
2241 TF_Keep | TF_DependencyWalk | ODRFlag);
2246 /// \brief Recursively walk the \p DIE tree and look for DIEs to
2247 /// keep. Store that information in \p CU's DIEInfo.
2249 /// This function is the entry point of the DIE selection
2250 /// algorithm. It is expected to walk the DIE tree in file order and
2251 /// (though the mediation of its helper) call hasValidRelocation() on
2252 /// each DIE that might be a 'root DIE' (See DwarfLinker class
2254 /// While walking the dependencies of root DIEs, this function is
2255 /// also called, but during these dependency walks the file order is
2256 /// not respected. The TF_DependencyWalk flag tells us which kind of
2257 /// traversal we are currently doing.
2258 void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
2259 const DWARFDie &Die,
2260 const DebugMapObject &DMO, CompileUnit &CU,
2262 unsigned Idx = CU.getOrigUnit().getDIEIndex(Die);
2263 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2264 bool AlreadyKept = MyInfo.Keep;
2268 // If the Keep flag is set, we are marking a required DIE's
2269 // dependencies. If our target is already marked as kept, we're all
2271 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2274 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
2275 // because it would screw up the relocation finding logic.
2276 if (!(Flags & TF_DependencyWalk))
2277 Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
2279 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
2280 if (!AlreadyKept && (Flags & TF_Keep)) {
2281 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2282 keepDIEAndDependencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
2284 // The TF_ParentWalk flag tells us that we are currently walking up
2285 // the parent chain of a required DIE, and we don't want to mark all
2286 // the children of the parents as kept (consider for example a
2287 // DW_TAG_namespace node in the parent chain). There are however a
2288 // set of DIE types for which we want to ignore that directive and still
2289 // walk their children.
2290 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
2291 Flags &= ~TF_ParentWalk;
2293 if (!Die.hasChildren() || (Flags & TF_ParentWalk))
2296 for (auto Child: Die.children())
2297 lookForDIEsToKeep(RelocMgr, Child, DMO, CU, Flags);
2300 /// \brief Assign an abbreviation numer to \p Abbrev.
2302 /// Our DIEs get freed after every DebugMapObject has been processed,
2303 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2304 /// the instances hold by the DIEs. When we encounter an abbreviation
2305 /// that we don't know, we create a permanent copy of it.
2306 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2307 // Check the set for priors.
2308 FoldingSetNodeID ID;
2311 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2313 // If it's newly added.
2315 // Assign existing abbreviation number.
2316 Abbrev.setNumber(InSet->getNumber());
2318 // Add to abbreviation list.
2319 Abbreviations.push_back(
2320 llvm::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
2321 for (const auto &Attr : Abbrev.getData())
2322 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2323 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
2324 // Assign the unique abbreviation number.
2325 Abbrev.setNumber(Abbreviations.size());
2326 Abbreviations.back()->setNumber(Abbreviations.size());
2330 unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2331 AttributeSpec AttrSpec,
2332 const DWARFFormValue &Val,
2333 const DWARFUnit &U) {
2334 // Switch everything to out of line strings.
2335 const char *String = *Val.getAsCString();
2336 unsigned Offset = Linker.StringPool.getStringOffset(String);
2337 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
2338 DIEInteger(Offset));
2342 unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
2343 DIE &Die, const DWARFDie &InputDIE,
2344 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
2345 CompileUnit &Unit) {
2346 const DWARFUnit &U = Unit.getOrigUnit();
2347 uint32_t Ref = *Val.getAsReference();
2348 DIE *NewRefDie = nullptr;
2349 CompileUnit *RefUnit = nullptr;
2350 DeclContext *Ctxt = nullptr;
2352 DWARFDie RefDie = resolveDIEReference(Linker, CompileUnits, Val, U, InputDIE,
2355 // If the referenced DIE is not found, drop the attribute.
2359 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2360 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
2362 // If we already have emitted an equivalent DeclContext, just point
2364 if (isODRAttribute(AttrSpec.Attr)) {
2365 Ctxt = RefInfo.Ctxt;
2366 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2367 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2368 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2369 dwarf::DW_FORM_ref_addr, Attr);
2370 return U.getRefAddrByteSize();
2374 if (!RefInfo.Clone) {
2375 assert(Ref > InputDIE.getOffset());
2376 // We haven't cloned this DIE yet. Just create an empty one and
2377 // store it. It'll get really cloned when we process it.
2378 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
2380 NewRefDie = RefInfo.Clone;
2382 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2383 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
2384 // We cannot currently rely on a DIEEntry to emit ref_addr
2385 // references, because the implementation calls back to DwarfDebug
2386 // to find the unit offset. (We don't have a DwarfDebug)
2387 // FIXME: we should be able to design DIEEntry reliance on
2390 if (Ref < InputDIE.getOffset()) {
2391 // We must have already cloned that DIE.
2392 uint32_t NewRefOffset =
2393 RefUnit->getStartOffset() + NewRefDie->getOffset();
2394 Attr = NewRefOffset;
2395 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2396 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
2398 // A forward reference. Note and fixup later.
2400 Unit.noteForwardReference(
2401 NewRefDie, RefUnit, Ctxt,
2402 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2403 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
2405 return U.getRefAddrByteSize();
2408 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2409 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
2413 unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2414 AttributeSpec AttrSpec,
2415 const DWARFFormValue &Val,
2416 unsigned AttrSize) {
2419 DIELoc *Loc = nullptr;
2420 DIEBlock *Block = nullptr;
2421 // Just copy the block data over.
2422 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
2423 Loc = new (DIEAlloc) DIELoc;
2424 Linker.DIELocs.push_back(Loc);
2426 Block = new (DIEAlloc) DIEBlock;
2427 Linker.DIEBlocks.push_back(Block);
2429 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2430 : static_cast<DIEValueList *>(Block);
2433 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2434 dwarf::Form(AttrSpec.Form), Loc);
2436 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2437 dwarf::Form(AttrSpec.Form), Block);
2438 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2439 for (auto Byte : Bytes)
2440 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2441 dwarf::DW_FORM_data1, DIEInteger(Byte));
2442 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2443 // the DIE class, this if could be replaced by
2444 // Attr->setSize(Bytes.size()).
2445 if (Linker.Streamer) {
2446 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
2448 Loc->ComputeSize(AsmPrinter);
2450 Block->ComputeSize(AsmPrinter);
2452 Die.addValue(DIEAlloc, Value);
2456 unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2457 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2458 const CompileUnit &Unit, AttributesInfo &Info) {
2459 uint64_t Addr = *Val.getAsAddress();
2460 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2461 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2462 Die.getTag() == dwarf::DW_TAG_lexical_block)
2463 // The low_pc of a block or inline subroutine might get
2464 // relocated because it happens to match the low_pc of the
2465 // enclosing subprogram. To prevent issues with that, always use
2466 // the low_pc from the input DIE if relocations have been applied.
2467 Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2469 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2470 Addr = Unit.getLowPc();
2471 if (Addr == UINT64_MAX)
2474 Info.HasLowPc = true;
2475 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
2476 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2477 if (uint64_t HighPc = Unit.getHighPc())
2482 // If we have a high_pc recorded for the input DIE, use
2483 // it. Otherwise (when no relocations where applied) just use the
2484 // one we just decoded.
2485 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
2488 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
2489 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
2490 return Unit.getOrigUnit().getAddressByteSize();
2493 unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
2494 DIE &Die, const DWARFDie &InputDIE, CompileUnit &Unit,
2495 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
2496 AttributesInfo &Info) {
2498 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2499 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2500 if (Unit.getLowPc() == -1ULL)
2502 // Dwarf >= 4 high_pc is an size, not an address.
2503 Value = Unit.getHighPc() - Unit.getLowPc();
2504 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
2505 Value = *Val.getAsSectionOffset();
2506 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2507 Value = *Val.getAsSignedConstant();
2508 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2509 Value = *OptionalValue;
2511 Linker.reportWarning(
2512 "Unsupported scalar attribute form. Dropping attribute.",
2516 PatchLocation Patch =
2517 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2518 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
2519 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
2520 Unit.noteRangeAttribute(Die, Patch);
2522 // A more generic way to check for location attributes would be
2523 // nice, but it's very unlikely that any other attribute needs a
2525 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2526 AttrSpec.Attr == dwarf::DW_AT_frame_base)
2527 Unit.noteLocationAttribute(Patch, Info.PCOffset);
2528 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2529 Info.IsDeclaration = true;
2534 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2535 /// value \p Val, and add it to \p Die.
2536 /// \returns the size of the cloned attribute.
2537 unsigned DwarfLinker::DIECloner::cloneAttribute(
2538 DIE &Die, const DWARFDie &InputDIE, CompileUnit &Unit,
2539 const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2540 AttributesInfo &Info) {
2541 const DWARFUnit &U = Unit.getOrigUnit();
2543 switch (AttrSpec.Form) {
2544 case dwarf::DW_FORM_strp:
2545 case dwarf::DW_FORM_string:
2546 return cloneStringAttribute(Die, AttrSpec, Val, U);
2547 case dwarf::DW_FORM_ref_addr:
2548 case dwarf::DW_FORM_ref1:
2549 case dwarf::DW_FORM_ref2:
2550 case dwarf::DW_FORM_ref4:
2551 case dwarf::DW_FORM_ref8:
2552 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
2554 case dwarf::DW_FORM_block:
2555 case dwarf::DW_FORM_block1:
2556 case dwarf::DW_FORM_block2:
2557 case dwarf::DW_FORM_block4:
2558 case dwarf::DW_FORM_exprloc:
2559 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2560 case dwarf::DW_FORM_addr:
2561 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
2562 case dwarf::DW_FORM_data1:
2563 case dwarf::DW_FORM_data2:
2564 case dwarf::DW_FORM_data4:
2565 case dwarf::DW_FORM_data8:
2566 case dwarf::DW_FORM_udata:
2567 case dwarf::DW_FORM_sdata:
2568 case dwarf::DW_FORM_sec_offset:
2569 case dwarf::DW_FORM_flag:
2570 case dwarf::DW_FORM_flag_present:
2571 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2574 Linker.reportWarning(
2575 "Unsupported attribute form in cloneAttribute. Dropping.", &InputDIE);
2581 /// \brief Apply the valid relocations found by findValidRelocs() to
2582 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
2583 /// in the debug_info section.
2585 /// Like for findValidRelocs(), this function must be called with
2586 /// monotonic \p BaseOffset values.
2588 /// \returns wether any reloc has been applied.
2589 bool DwarfLinker::RelocationManager::
2590 applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2591 bool isLittleEndian) {
2592 assert((NextValidReloc == 0 ||
2593 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2594 "BaseOffset should only be increasing.");
2595 if (NextValidReloc >= ValidRelocs.size())
2598 // Skip relocs that haven't been applied.
2599 while (NextValidReloc < ValidRelocs.size() &&
2600 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2603 bool Applied = false;
2604 uint64_t EndOffset = BaseOffset + Data.size();
2605 while (NextValidReloc < ValidRelocs.size() &&
2606 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2607 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2608 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2609 assert(ValidReloc.Offset - BaseOffset < Data.size());
2610 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2612 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2613 Value += ValidReloc.Addend;
2614 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2615 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2616 Buf[i] = uint8_t(Value >> (Index * 8));
2618 assert(ValidReloc.Size <= sizeof(Buf));
2619 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2626 static bool isTypeTag(uint16_t Tag) {
2628 case dwarf::DW_TAG_array_type:
2629 case dwarf::DW_TAG_class_type:
2630 case dwarf::DW_TAG_enumeration_type:
2631 case dwarf::DW_TAG_pointer_type:
2632 case dwarf::DW_TAG_reference_type:
2633 case dwarf::DW_TAG_string_type:
2634 case dwarf::DW_TAG_structure_type:
2635 case dwarf::DW_TAG_subroutine_type:
2636 case dwarf::DW_TAG_typedef:
2637 case dwarf::DW_TAG_union_type:
2638 case dwarf::DW_TAG_ptr_to_member_type:
2639 case dwarf::DW_TAG_set_type:
2640 case dwarf::DW_TAG_subrange_type:
2641 case dwarf::DW_TAG_base_type:
2642 case dwarf::DW_TAG_const_type:
2643 case dwarf::DW_TAG_constant:
2644 case dwarf::DW_TAG_file_type:
2645 case dwarf::DW_TAG_namelist:
2646 case dwarf::DW_TAG_packed_type:
2647 case dwarf::DW_TAG_volatile_type:
2648 case dwarf::DW_TAG_restrict_type:
2649 case dwarf::DW_TAG_atomic_type:
2650 case dwarf::DW_TAG_interface_type:
2651 case dwarf::DW_TAG_unspecified_type:
2652 case dwarf::DW_TAG_shared_type:
2661 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2662 uint16_t Tag, bool InDebugMap, bool SkipPC,
2663 bool InFunctionScope) {
2664 switch (AttrSpec.Attr) {
2667 case dwarf::DW_AT_low_pc:
2668 case dwarf::DW_AT_high_pc:
2669 case dwarf::DW_AT_ranges:
2671 case dwarf::DW_AT_location:
2672 case dwarf::DW_AT_frame_base:
2673 // FIXME: for some reason dsymutil-classic keeps the location
2674 // attributes when they are of block type (ie. not location
2675 // lists). This is totally wrong for globals where we will keep a
2676 // wrong address. It is mostly harmless for locals, but there is
2677 // no point in keeping these anyway when the function wasn't linked.
2678 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2680 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2684 DIE *DwarfLinker::DIECloner::cloneDIE(
2685 const DWARFDie &InputDIE, CompileUnit &Unit,
2686 int64_t PCOffset, uint32_t OutOffset, unsigned Flags, DIE *Die) {
2687 DWARFUnit &U = Unit.getOrigUnit();
2688 unsigned Idx = U.getDIEIndex(InputDIE);
2689 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2691 // Should the DIE appear in the output?
2692 if (!Unit.getInfo(Idx).Keep)
2695 uint32_t Offset = InputDIE.getOffset();
2696 assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
2698 // The DIE might have been already created by a forward reference
2699 // (see cloneDieReferenceAttribute()).
2701 Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
2705 assert(Die->getTag() == InputDIE.getTag());
2706 Die->setOffset(OutOffset);
2707 if ((Unit.hasODR() || Unit.isClangModule()) &&
2708 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2709 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2710 !Info.Ctxt->getCanonicalDIEOffset()) {
2711 // We are about to emit a DIE that is the root of its own valid
2712 // DeclContext tree. Make the current offset the canonical offset
2713 // for this context.
2714 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2717 // Extract and clone every attribute.
2718 DataExtractor Data = U.getDebugInfoExtractor();
2719 // Point to the next DIE (generally there is always at least a NULL
2720 // entry after the current one). If this is a lone
2721 // DW_TAG_compile_unit without any children, point to the next unit.
2722 uint32_t NextOffset =
2723 (Idx + 1 < U.getNumDIEs())
2724 ? U.getDIEAtIndex(Idx + 1).getOffset()
2725 : U.getNextUnitOffset();
2726 AttributesInfo AttrInfo;
2728 // We could copy the data only if we need to aply a relocation to
2729 // it. After testing, it seems there is no performance downside to
2730 // doing the copy unconditionally, and it makes the code simpler.
2731 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2732 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2733 // Modify the copy with relocated addresses.
2734 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2735 // If we applied relocations, we store the value of high_pc that was
2736 // potentially stored in the input DIE. If high_pc is an address
2737 // (Dwarf version == 2), then it might have been relocated to a
2738 // totally unrelated value (because the end address in the object
2739 // file might be start address of another function which got moved
2740 // independantly by the linker). The computation of the actual
2741 // high_pc value is done in cloneAddressAttribute().
2742 AttrInfo.OrigHighPc =
2743 InputDIE.getAttributeValueAsAddress(dwarf::DW_AT_high_pc, 0);
2744 // Also store the low_pc. It might get relocated in an
2745 // inline_subprogram that happens at the beginning of its
2746 // inlining function.
2747 AttrInfo.OrigLowPc =
2748 InputDIE.getAttributeValueAsAddress(dwarf::DW_AT_low_pc, UINT64_MAX);
2751 // Reset the Offset to 0 as we will be working on the local copy of
2755 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2756 Offset += getULEB128Size(Abbrev->getCode());
2758 // We are entering a subprogram. Get and propagate the PCOffset.
2759 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2760 PCOffset = Info.AddrAdjust;
2761 AttrInfo.PCOffset = PCOffset;
2763 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2764 Flags |= TF_InFunctionScope;
2765 if (!Info.InDebugMap)
2769 bool Copied = false;
2770 for (const auto &AttrSpec : Abbrev->attributes()) {
2771 if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2772 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2773 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2774 // FIXME: dsymutil-classic keeps the old abbreviation around
2775 // even if it's not used. We can remove this (and the copyAbbrev
2776 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2778 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2784 DWARFFormValue Val(AttrSpec.Form);
2785 uint32_t AttrSize = Offset;
2786 Val.extractValue(Data, &Offset, &U);
2787 AttrSize = Offset - AttrSize;
2790 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2793 // Look for accelerator entries.
2794 uint16_t Tag = InputDIE.getTag();
2795 // FIXME: This is slightly wrong. An inline_subroutine without a
2796 // low_pc, but with AT_ranges might be interesting to get into the
2797 // accelerator tables too. For now stick with dsymutil's behavior.
2798 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2799 Tag != dwarf::DW_TAG_compile_unit &&
2800 getDIENames(InputDIE, AttrInfo)) {
2801 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2802 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2803 AttrInfo.MangledNameOffset,
2804 Tag == dwarf::DW_TAG_inlined_subroutine);
2806 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2807 Tag == dwarf::DW_TAG_inlined_subroutine);
2808 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2809 getDIENames(InputDIE, AttrInfo)) {
2810 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2813 // Determine whether there are any children that we want to keep.
2814 bool HasChildren = false;
2815 for (auto Child: InputDIE.children()) {
2816 unsigned Idx = U.getDIEIndex(Child);
2817 if (Unit.getInfo(Idx).Keep) {
2823 DIEAbbrev NewAbbrev = Die->generateAbbrev();
2825 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2826 // Assign a permanent abbrev number
2827 Linker.AssignAbbrev(NewAbbrev);
2828 Die->setAbbrevNumber(NewAbbrev.getNumber());
2830 // Add the size of the abbreviation number to the output offset.
2831 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2835 Die->setSize(OutOffset - Die->getOffset());
2839 // Recursively clone children.
2840 for (auto Child: InputDIE.children()) {
2841 if (DIE *Clone = cloneDIE(Child, Unit, PCOffset, OutOffset, Flags)) {
2842 Die->addChild(Clone);
2843 OutOffset = Clone->getOffset() + Clone->getSize();
2847 // Account for the end of children marker.
2848 OutOffset += sizeof(int8_t);
2850 Die->setSize(OutOffset - Die->getOffset());
2854 /// \brief Patch the input object file relevant debug_ranges entries
2855 /// and emit them in the output file. Update the relevant attributes
2856 /// to point at the new entries.
2857 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2858 DWARFContext &OrigDwarf) const {
2859 DWARFDebugRangeList RangeList;
2860 const auto &FunctionRanges = Unit.getFunctionRanges();
2861 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2862 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2863 OrigDwarf.isLittleEndian(), AddressSize);
2864 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2865 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2866 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
2867 uint64_t OrigLowPc = OrigUnitDie.getAttributeValueAsAddress(
2868 dwarf::DW_AT_low_pc, -1ULL);
2869 // Ranges addresses are based on the unit's low_pc. Compute the
2870 // offset we need to apply to adapt to the new unit's low_pc.
2871 int64_t UnitPcOffset = 0;
2872 if (OrigLowPc != -1ULL)
2873 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2875 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2876 uint32_t Offset = RangeAttribute.get();
2877 RangeAttribute.set(Streamer->getRangesSectionSize());
2878 RangeList.extract(RangeExtractor, &Offset);
2879 const auto &Entries = RangeList.getEntries();
2880 if (!Entries.empty()) {
2881 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2883 if (CurrRange == InvalidRange ||
2884 First.StartAddress + OrigLowPc < CurrRange.start() ||
2885 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2886 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2887 if (CurrRange == InvalidRange ||
2888 CurrRange.start() > First.StartAddress + OrigLowPc) {
2889 reportWarning("no mapping for range.");
2895 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2900 /// \brief Generate the debug_aranges entries for \p Unit and if the
2901 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2902 /// contribution for this attribute.
2903 /// FIXME: this could actually be done right in patchRangesForUnit,
2904 /// but for the sake of initial bit-for-bit compatibility with legacy
2905 /// dsymutil, we have to do it in a delayed pass.
2906 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2907 auto Attr = Unit.getUnitRangesAttribute();
2909 Attr->set(Streamer->getRangesSectionSize());
2910 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
2913 /// \brief Insert the new line info sequence \p Seq into the current
2914 /// set of already linked line info \p Rows.
2915 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2916 std::vector<DWARFDebugLine::Row> &Rows) {
2920 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2921 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2926 auto InsertPoint = std::lower_bound(
2927 Rows.begin(), Rows.end(), Seq.front(),
2928 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2929 return LHS.Address < RHS.Address;
2932 // FIXME: this only removes the unneeded end_sequence if the
2933 // sequences have been inserted in order. using a global sort like
2934 // described in patchLineTableForUnit() and delaying the end_sequene
2935 // elimination to emitLineTableForUnit() we can get rid of all of them.
2936 if (InsertPoint != Rows.end() &&
2937 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2938 *InsertPoint = Seq.front();
2939 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2941 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2947 static void patchStmtList(DIE &Die, DIEInteger Offset) {
2948 for (auto &V : Die.values())
2949 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2950 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2954 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2957 /// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2958 /// recreate a relocated version of these for the address ranges that
2959 /// are present in the binary.
2960 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2961 DWARFContext &OrigDwarf) {
2962 DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
2963 auto StmtList = CUDie.getAttributeValueAsSectionOffset(dwarf::DW_AT_stmt_list);
2967 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2968 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2969 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
2971 // Parse the original line info for the unit.
2972 DWARFDebugLine::LineTable LineTable;
2973 uint32_t StmtOffset = *StmtList;
2974 StringRef LineData = OrigDwarf.getLineSection().Data;
2975 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2976 Unit.getOrigUnit().getAddressByteSize());
2977 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2980 // This vector is the output line table.
2981 std::vector<DWARFDebugLine::Row> NewRows;
2982 NewRows.reserve(LineTable.Rows.size());
2984 // Current sequence of rows being extracted, before being inserted
2986 std::vector<DWARFDebugLine::Row> Seq;
2987 const auto &FunctionRanges = Unit.getFunctionRanges();
2988 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2990 // FIXME: This logic is meant to generate exactly the same output as
2991 // Darwin's classic dsynutil. There is a nicer way to implement this
2992 // by simply putting all the relocated line info in NewRows and simply
2993 // sorting NewRows before passing it to emitLineTableForUnit. This
2994 // should be correct as sequences for a function should stay
2995 // together in the sorted output. There are a few corner cases that
2996 // look suspicious though, and that required to implement the logic
2997 // this way. Revisit that once initial validation is finished.
2999 // Iterate over the object file line info and extract the sequences
3000 // that correspond to linked functions.
3001 for (auto &Row : LineTable.Rows) {
3002 // Check wether we stepped out of the range. The range is
3003 // half-open, but consider accept the end address of the range if
3004 // it is marked as end_sequence in the input (because in that
3005 // case, the relocation offset is accurate and that entry won't
3006 // serve as the start of another function).
3007 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
3008 Row.Address > CurrRange.stop() ||
3009 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
3010 // We just stepped out of a known range. Insert a end_sequence
3011 // corresponding to the end of the range.
3012 uint64_t StopAddress = CurrRange != InvalidRange
3013 ? CurrRange.stop() + CurrRange.value()
3015 CurrRange = FunctionRanges.find(Row.Address);
3016 bool CurrRangeValid =
3017 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
3018 if (!CurrRangeValid) {
3019 CurrRange = InvalidRange;
3020 if (StopAddress != -1ULL) {
3021 // Try harder by looking in the DebugMapObject function
3022 // ranges map. There are corner cases where this finds a
3023 // valid entry. It's unclear if this is right or wrong, but
3024 // for now do as dsymutil.
3025 // FIXME: Understand exactly what cases this addresses and
3026 // potentially remove it along with the Ranges map.
3027 auto Range = Ranges.lower_bound(Row.Address);
3028 if (Range != Ranges.begin() && Range != Ranges.end())
3031 if (Range != Ranges.end() && Range->first <= Row.Address &&
3032 Range->second.first >= Row.Address) {
3033 StopAddress = Row.Address + Range->second.second;
3037 if (StopAddress != -1ULL && !Seq.empty()) {
3038 // Insert end sequence row with the computed end address, but
3039 // the same line as the previous one.
3040 auto NextLine = Seq.back();
3041 NextLine.Address = StopAddress;
3042 NextLine.EndSequence = 1;
3043 NextLine.PrologueEnd = 0;
3044 NextLine.BasicBlock = 0;
3045 NextLine.EpilogueBegin = 0;
3046 Seq.push_back(NextLine);
3047 insertLineSequence(Seq, NewRows);
3050 if (!CurrRangeValid)
3054 // Ignore empty sequences.
3055 if (Row.EndSequence && Seq.empty())
3058 // Relocate row address and add it to the current sequence.
3059 Row.Address += CurrRange.value();
3060 Seq.emplace_back(Row);
3062 if (Row.EndSequence)
3063 insertLineSequence(Seq, NewRows);
3066 // Finished extracting, now emit the line tables.
3067 uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength;
3068 // FIXME: LLVM hardcodes it's prologue values. We just copy the
3069 // prologue over and that works because we act as both producer and
3070 // consumer. It would be nicer to have a real configurable line
3072 if (LineTable.Prologue.Version != 2 ||
3073 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
3074 LineTable.Prologue.OpcodeBase > 13)
3075 reportWarning("line table paramters mismatch. Cannot emit.");
3077 MCDwarfLineTableParams Params;
3078 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
3079 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
3080 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
3081 Streamer->emitLineTableForUnit(Params,
3082 LineData.slice(*StmtList + 4, PrologueEnd),
3083 LineTable.Prologue.MinInstLength, NewRows,
3084 Unit.getOrigUnit().getAddressByteSize());
3088 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
3089 Streamer->emitPubNamesForUnit(Unit);
3090 Streamer->emitPubTypesForUnit(Unit);
3093 /// \brief Read the frame info stored in the object, and emit the
3094 /// patched frame descriptions for the linked binary.
3096 /// This is actually pretty easy as the data of the CIEs and FDEs can
3097 /// be considered as black boxes and moved as is. The only thing to do
3098 /// is to patch the addresses in the headers.
3099 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
3100 DWARFContext &OrigDwarf,
3101 unsigned AddrSize) {
3102 StringRef FrameData = OrigDwarf.getDebugFrameSection();
3103 if (FrameData.empty())
3106 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
3107 uint32_t InputOffset = 0;
3109 // Store the data of the CIEs defined in this object, keyed by their
3111 DenseMap<uint32_t, StringRef> LocalCIES;
3113 while (Data.isValidOffset(InputOffset)) {
3114 uint32_t EntryOffset = InputOffset;
3115 uint32_t InitialLength = Data.getU32(&InputOffset);
3116 if (InitialLength == 0xFFFFFFFF)
3117 return reportWarning("Dwarf64 bits no supported");
3119 uint32_t CIEId = Data.getU32(&InputOffset);
3120 if (CIEId == 0xFFFFFFFF) {
3121 // This is a CIE, store it.
3122 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
3123 LocalCIES[EntryOffset] = CIEData;
3124 // The -4 is to account for the CIEId we just read.
3125 InputOffset += InitialLength - 4;
3129 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
3131 // Some compilers seem to emit frame info that doesn't start at
3132 // the function entry point, thus we can't just lookup the address
3133 // in the debug map. Use the linker's range map to see if the FDE
3134 // describes something that we can relocate.
3135 auto Range = Ranges.upper_bound(Loc);
3136 if (Range != Ranges.begin())
3138 if (Range == Ranges.end() || Range->first > Loc ||
3139 Range->second.first <= Loc) {
3140 // The +4 is to account for the size of the InitialLength field itself.
3141 InputOffset = EntryOffset + InitialLength + 4;
3145 // This is an FDE, and we have a mapping.
3146 // Have we already emitted a corresponding CIE?
3147 StringRef CIEData = LocalCIES[CIEId];
3148 if (CIEData.empty())
3149 return reportWarning("Inconsistent debug_frame content. Dropping.");
3151 // Look if we already emitted a CIE that corresponds to the
3152 // referenced one (the CIE data is the key of that lookup).
3153 auto IteratorInserted = EmittedCIEs.insert(
3154 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3155 // If there is no CIE yet for this ID, emit it.
3156 if (IteratorInserted.second ||
3157 // FIXME: dsymutil-classic only caches the last used CIE for
3158 // reuse. Mimic that behavior for now. Just removing that
3159 // second half of the condition and the LastCIEOffset variable
3160 // makes the code DTRT.
3161 LastCIEOffset != IteratorInserted.first->getValue()) {
3162 LastCIEOffset = Streamer->getFrameSectionSize();
3163 IteratorInserted.first->getValue() = LastCIEOffset;
3164 Streamer->emitCIE(CIEData);
3167 // Emit the FDE with updated address and CIE pointer.
3168 // (4 + AddrSize) is the size of the CIEId + initial_location
3169 // fields that will get reconstructed by emitFDE().
3170 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3171 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3172 Loc + Range->second.second,
3173 FrameData.substr(InputOffset, FDERemainingBytes));
3174 InputOffset += FDERemainingBytes;
3178 void DwarfLinker::DIECloner::copyAbbrev(
3179 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
3180 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3181 dwarf::Form(Abbrev.hasChildren()));
3183 for (const auto &Attr : Abbrev.attributes()) {
3184 uint16_t Form = Attr.Form;
3185 if (hasODR && isODRAttribute(Attr.Attr))
3186 Form = dwarf::DW_FORM_ref_addr;
3187 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3190 Linker.AssignAbbrev(Copy);
3193 static uint64_t getDwoId(const DWARFDie &CUDie,
3194 const DWARFUnit &Unit) {
3195 auto DwoId = CUDie.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_dwo_id);
3198 DwoId = CUDie.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_GNU_dwo_id);
3204 bool DwarfLinker::registerModuleReference(
3205 const DWARFDie &CUDie, const DWARFUnit &Unit,
3206 DebugMap &ModuleMap, unsigned Indent) {
3207 std::string PCMfile =
3208 CUDie.getAttributeValueAsString(dwarf::DW_AT_dwo_name, "");
3209 if (PCMfile.empty())
3211 CUDie.getAttributeValueAsString(dwarf::DW_AT_GNU_dwo_name, "");
3212 if (PCMfile.empty())
3215 // Clang module DWARF skeleton CUs abuse this for the path to the module.
3216 std::string PCMpath =
3217 CUDie.getAttributeValueAsString(dwarf::DW_AT_comp_dir, "");
3218 uint64_t DwoId = getDwoId(CUDie, Unit);
3221 CUDie.getAttributeValueAsString(dwarf::DW_AT_name, "");
3223 reportWarning("Anonymous module skeleton CU for " + PCMfile);
3227 if (Options.Verbose) {
3228 outs().indent(Indent);
3229 outs() << "Found clang module reference " << PCMfile;
3232 auto Cached = ClangModules.find(PCMfile);
3233 if (Cached != ClangModules.end()) {
3234 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
3235 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
3236 // ASTFileSignatures will change randomly when a module is rebuilt.
3237 if (Options.Verbose && (Cached->second != DwoId))
3238 reportWarning(Twine("hash mismatch: this object file was built against a "
3239 "different version of the module ") + PCMfile);
3240 if (Options.Verbose)
3241 outs() << " [cached].\n";
3244 if (Options.Verbose)
3247 // Cyclic dependencies are disallowed by Clang, but we still
3248 // shouldn't run into an infinite loop, so mark it as processed now.
3249 ClangModules.insert({PCMfile, DwoId});
3250 loadClangModule(PCMfile, PCMpath, Name, DwoId, ModuleMap, Indent + 2);
3254 ErrorOr<const object::ObjectFile &>
3255 DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3256 const DebugMap &Map) {
3258 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
3259 if (std::error_code EC = ErrOrObjs.getError()) {
3260 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3263 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3264 if (std::error_code EC = ErrOrObj.getError())
3265 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3269 void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
3270 StringRef ModuleName, uint64_t DwoId,
3271 DebugMap &ModuleMap, unsigned Indent) {
3272 SmallString<80> Path(Options.PrependPath);
3273 if (sys::path::is_relative(Filename))
3274 sys::path::append(Path, ModulePath, Filename);
3276 sys::path::append(Path, Filename);
3277 BinaryHolder ObjHolder(Options.Verbose);
3279 ModuleMap.addDebugMapObject(Path, sys::TimePoint<std::chrono::seconds>());
3280 auto ErrOrObj = loadObject(ObjHolder, Obj, ModuleMap);
3282 // Try and emit more helpful warnings by applying some heuristics.
3283 StringRef ObjFile = CurrentDebugObject->getObjectFilename();
3284 bool isClangModule = sys::path::extension(Filename).equals(".pcm");
3285 bool isArchive = ObjFile.endswith(")");
3286 if (isClangModule) {
3287 StringRef ModuleCacheDir = sys::path::parent_path(Path);
3288 if (sys::fs::exists(ModuleCacheDir)) {
3289 // If the module's parent directory exists, we assume that the module
3290 // cache has expired and was pruned by clang. A more adventurous
3291 // dsymutil would invoke clang to rebuild the module now.
3292 if (!ModuleCacheHintDisplayed) {
3293 errs() << "note: The clang module cache may have expired since this "
3294 "object file was built. Rebuilding the object file will "
3295 "rebuild the module cache.\n";
3296 ModuleCacheHintDisplayed = true;
3298 } else if (isArchive) {
3299 // If the module cache directory doesn't exist at all and the object
3300 // file is inside a static library, we assume that the static library
3301 // was built on a different machine. We don't want to discourage module
3302 // debugging for convenience libraries within a project though.
3303 if (!ArchiveHintDisplayed) {
3304 errs() << "note: Linking a static library that was built with "
3305 "-gmodules, but the module cache was not found. "
3306 "Redistributable static libraries should never be built "
3307 "with module debugging enabled. The debug experience will "
3308 "be degraded due to incomplete debug information.\n";
3309 ArchiveHintDisplayed = true;
3316 std::unique_ptr<CompileUnit> Unit;
3318 // Setup access to the debug info.
3319 DWARFContextInMemory DwarfContext(*ErrOrObj);
3320 RelocationManager RelocMgr(*this);
3321 for (const auto &CU : DwarfContext.compile_units()) {
3322 auto CUDie = CU->getUnitDIE(false);
3323 // Recursively get all modules imported by this one.
3324 if (!registerModuleReference(CUDie, *CU, ModuleMap, Indent)) {
3326 errs() << Filename << ": Clang modules are expected to have exactly"
3327 << " 1 compile unit.\n";
3330 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
3331 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
3332 // ASTFileSignatures will change randomly when a module is rebuilt.
3333 uint64_t PCMDwoId = getDwoId(CUDie, *CU);
3334 if (PCMDwoId != DwoId) {
3335 if (Options.Verbose)
3337 Twine("hash mismatch: this object file was built against a "
3338 "different version of the module ") + Filename);
3339 // Update the cache entry with the DwoId of the module loaded from disk.
3340 ClangModules[Filename] = PCMDwoId;
3344 Unit = llvm::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
3346 Unit->setHasInterestingContent();
3347 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), StringPool,
3350 Unit->markEverythingAsKept();
3353 if (Options.Verbose) {
3354 outs().indent(Indent);
3355 outs() << "cloning .debug_info from " << Filename << "\n";
3358 std::vector<std::unique_ptr<CompileUnit>> CompileUnits;
3359 CompileUnits.push_back(std::move(Unit));
3360 DIECloner(*this, RelocMgr, DIEAlloc, CompileUnits, Options)
3361 .cloneAllCompileUnits(DwarfContext);
3364 void DwarfLinker::DIECloner::cloneAllCompileUnits(
3365 DWARFContextInMemory &DwarfContext) {
3366 if (!Linker.Streamer)
3369 for (auto &CurrentUnit : CompileUnits) {
3370 auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
3371 CurrentUnit->setStartOffset(Linker.OutputDebugInfoSize);
3372 // Clonse the InputDIE into your Unit DIE in our compile unit since it
3373 // already has a DIE inside of it.
3374 if (!cloneDIE(InputDIE, *CurrentUnit, 0 /* PC offset */,
3375 11 /* Unit Header size */, 0,
3376 CurrentUnit->getOutputUnitDIE()))
3378 Linker.OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset();
3379 if (Linker.Options.NoOutput)
3381 // FIXME: for compatibility with the classic dsymutil, we emit
3382 // an empty line table for the unit, even if the unit doesn't
3383 // actually exist in the DIE tree.
3384 Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext);
3385 Linker.patchRangesForUnit(*CurrentUnit, DwarfContext);
3386 Linker.Streamer->emitLocationsForUnit(*CurrentUnit, DwarfContext);
3387 Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
3390 if (Linker.Options.NoOutput)
3393 // Emit all the compile unit's debug information.
3394 for (auto &CurrentUnit : CompileUnits) {
3395 Linker.generateUnitRanges(*CurrentUnit);
3396 CurrentUnit->fixupForwardReferences();
3397 Linker.Streamer->emitCompileUnitHeader(*CurrentUnit);
3398 if (!CurrentUnit->getOutputUnitDIE())
3400 Linker.Streamer->emitDIE(*CurrentUnit->getOutputUnitDIE());
3404 bool DwarfLinker::link(const DebugMap &Map) {
3406 if (!createStreamer(Map.getTriple(), OutputFilename))
3409 // Size of the DIEs (and headers) generated for the linked output.
3410 OutputDebugInfoSize = 0;
3411 // A unique ID that identifies each compile unit.
3413 DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
3415 for (const auto &Obj : Map.objects()) {
3416 CurrentDebugObject = Obj.get();
3418 if (Options.Verbose)
3419 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
3420 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3424 // Look for relocations that correspond to debug map entries.
3425 RelocationManager RelocMgr(*this);
3426 if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
3427 if (Options.Verbose)
3428 outs() << "No valid relocations found. Skipping.\n";
3432 // Setup access to the debug info.
3433 DWARFContextInMemory DwarfContext(*ErrOrObj);
3434 startDebugObject(DwarfContext, *Obj);
3436 // In a first phase, just read in the debug info and load all clang modules.
3437 for (const auto &CU : DwarfContext.compile_units()) {
3438 auto CUDie = CU->getUnitDIE(false);
3439 if (Options.Verbose) {
3440 outs() << "Input compilation unit:";
3441 CUDie.dump(outs(), 0);
3444 if (!registerModuleReference(CUDie, *CU, ModuleMap))
3445 Units.push_back(llvm::make_unique<CompileUnit>(*CU, UnitID++,
3446 !Options.NoODR, ""));
3449 // Now build the DIE parent links that we will use during the next phase.
3450 for (auto &CurrentUnit : Units)
3451 analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0, *CurrentUnit,
3452 &ODRContexts.getRoot(), StringPool, ODRContexts);
3454 // Then mark all the DIEs that need to be present in the linked
3455 // output and collect some information about them. Note that this
3456 // loop can not be merged with the previous one becaue cross-cu
3457 // references require the ParentIdx to be setup for every CU in
3458 // the object file before calling this.
3459 for (auto &CurrentUnit : Units)
3460 lookForDIEsToKeep(RelocMgr, CurrentUnit->getOrigUnit().getUnitDIE(), *Obj,
3463 // The calls to applyValidRelocs inside cloneDIE will walk the
3464 // reloc array again (in the same way findValidRelocsInDebugInfo()
3465 // did). We need to reset the NextValidReloc index to the beginning.
3466 RelocMgr.resetValidRelocs();
3467 if (RelocMgr.hasValidRelocs())
3468 DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3469 .cloneAllCompileUnits(DwarfContext);
3470 if (!Options.NoOutput && !Units.empty())
3471 patchFrameInfoForObject(*Obj, DwarfContext,
3472 Units[0]->getOrigUnit().getAddressByteSize());
3474 // Clean-up before starting working on the next object.
3478 // Emit everything that's global.
3479 if (!Options.NoOutput) {
3480 Streamer->emitAbbrevs(Abbreviations);
3481 Streamer->emitStrings(StringPool);
3484 return Options.NoOutput ? true : Streamer->finish(Map);
3488 /// \brief Get the offset of string \p S in the string table. This
3489 /// can insert a new element or return the offset of a preexisitng
3491 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3492 if (S.empty() && !Strings.empty())
3495 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3499 // A non-empty string can't be at offset 0, so if we have an entry
3500 // with a 0 offset, it must be a previously interned string.
3501 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3502 if (Inserted || It->getValue().first == 0) {
3503 // Set offset and chain at the end of the entries list.
3504 It->getValue().first = CurrentEndOffset;
3505 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3506 Last->getValue().second = &*It;
3509 return It->getValue().first;
3512 /// \brief Put \p S into the StringMap so that it gets permanent
3513 /// storage, but do not actually link it in the chain of elements
3514 /// that go into the output section. A latter call to
3515 /// getStringOffset() with the same string will chain it though.
3516 StringRef NonRelocatableStringpool::internString(StringRef S) {
3517 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3518 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3519 return InsertResult.first->getKey();
3522 void warn(const Twine &Warning, const Twine &Context) {
3523 errs() << Twine("while processing ") + Context + ":\n";
3524 errs() << Twine("warning: ") + Warning + "\n";
3527 bool error(const Twine &Error, const Twine &Context) {
3528 errs() << Twine("while processing ") + Context + ":\n";
3529 errs() << Twine("error: ") + Error + "\n";
3533 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3534 const LinkOptions &Options) {
3535 DwarfLinker Linker(OutputFilename, Options);
3536 return Linker.link(DM);