Bug Summary

File:tools/dsymutil/DwarfLinker.cpp
Warning:line 2467, column 7
Called C++ object pointer is null

Annotated Source Code

1//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "DebugMap.h"
10#include "BinaryHolder.h"
11#include "DebugMap.h"
12#include "dsymutil.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"
41#include <memory>
42#include <string>
43#include <tuple>
44
45// For GNU Hurd
46#if defined(__GNU__) && !defined(PATH_MAX4096)
47# define PATH_MAX4096 4096
48#endif
49
50namespace llvm {
51namespace dsymutil {
52
53namespace {
54
55template <typename KeyT, typename ValT>
56using HalfOpenIntervalMap =
57 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
58 IntervalMapHalfOpenInfo<KeyT>>;
59
60typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
61
62// FIXME: Delete this structure.
63struct PatchLocation {
64 DIE::value_iterator I;
65
66 PatchLocation() = default;
67 PatchLocation(DIE::value_iterator I) : I(I) {}
68
69 void set(uint64_t New) const {
70 assert(I)((I) ? static_cast<void> (0) : __assert_fail ("I", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 70, __PRETTY_FUNCTION__))
;
71 const auto &Old = *I;
72 assert(Old.getType() == DIEValue::isInteger)((Old.getType() == DIEValue::isInteger) ? static_cast<void
> (0) : __assert_fail ("Old.getType() == DIEValue::isInteger"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 72, __PRETTY_FUNCTION__))
;
73 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
74 }
75
76 uint64_t get() const {
77 assert(I)((I) ? static_cast<void> (0) : __assert_fail ("I", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 77, __PRETTY_FUNCTION__))
;
78 return I->getDIEInteger().getValue();
79 }
80};
81
82class CompileUnit;
83struct DeclMapInfo;
84
85/// A DeclContext is a named program scope that is used for ODR
86/// uniquing of types.
87/// The set of DeclContext for the ODR-subject parts of a Dwarf link
88/// is expanded (and uniqued) with each new object file processed. We
89/// need to determine the context of each DIE in an linked object file
90/// to see if the corresponding type has already been emitted.
91///
92/// The contexts are conceptually organised as a tree (eg. a function
93/// scope is contained in a namespace scope that contains other
94/// scopes), but storing/accessing them in an actual tree is too
95/// inefficient: we need to be able to very quickly query a context
96/// for a given child context by name. Storing a StringMap in each
97/// DeclContext would be too space inefficient.
98/// The solution here is to give each DeclContext a link to its parent
99/// (this allows to walk up the tree), but to query the existance of a
100/// specific DeclContext using a separate DenseMap keyed on the hash
101/// of the fully qualified name of the context.
102class DeclContext {
103 unsigned QualifiedNameHash;
104 uint32_t Line;
105 uint32_t ByteSize;
106 uint16_t Tag;
107 StringRef Name;
108 StringRef File;
109 const DeclContext &Parent;
110 DWARFDie LastSeenDIE;
111 uint32_t LastSeenCompileUnitID;
112 uint32_t CanonicalDIEOffset;
113
114 friend DeclMapInfo;
115
116public:
117 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
118
119 DeclContext()
120 : QualifiedNameHash(0), Line(0), ByteSize(0),
121 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
122 LastSeenDIE(), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
123
124 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
125 StringRef Name, StringRef File, const DeclContext &Parent,
126 DWARFDie LastSeenDIE = DWARFDie(), unsigned CUId = 0)
127 : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
128 Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
129 LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
130
131 uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
132
133 bool setLastSeenDIE(CompileUnit &U, const DWARFDie &Die);
134
135 uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
136 void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
137
138 uint16_t getTag() const { return Tag; }
139 StringRef getName() const { return Name; }
140};
141
142/// Info type for the DenseMap storing the DeclContext pointers.
143struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
144 using DenseMapInfo<DeclContext *>::getEmptyKey;
145 using DenseMapInfo<DeclContext *>::getTombstoneKey;
146
147 static unsigned getHashValue(const DeclContext *Ctxt) {
148 return Ctxt->QualifiedNameHash;
149 }
150
151 static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
152 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
153 return RHS == LHS;
154 return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
155 LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
156 LHS->Name.data() == RHS->Name.data() &&
157 LHS->File.data() == RHS->File.data() &&
158 LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
159 }
160};
161
162/// This class gives a tree-like API to the DenseMap that stores the
163/// DeclContext objects. It also holds the BumpPtrAllocator where
164/// these objects will be allocated.
165class DeclContextTree {
166 BumpPtrAllocator Allocator;
167 DeclContext Root;
168 DeclContext::Map Contexts;
169
170public:
171 /// Get the child of \a Context described by \a DIE in \a Unit. The
172 /// required strings will be interned in \a StringPool.
173 /// \returns The child DeclContext along with one bit that is set if
174 /// this context is invalid.
175 /// An invalid context means it shouldn't be considered for uniquing, but its
176 /// not returning null, because some children of that context might be
177 /// uniquing candidates. FIXME: The invalid bit along the return value is to
178 /// emulate some dsymutil-classic functionality.
179 PointerIntPair<DeclContext *, 1>
180 getChildDeclContext(DeclContext &Context,
181 const DWARFDie &DIE, CompileUnit &Unit,
182 NonRelocatableStringpool &StringPool, bool InClangModule);
183
184 DeclContext &getRoot() { return Root; }
185};
186
187/// \brief Stores all information relating to a compile unit, be it in
188/// its original instance in the object file to its brand new cloned
189/// and linked DIE tree.
190class CompileUnit {
191public:
192 /// \brief Information gathered about a DIE in the object file.
193 struct DIEInfo {
194 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
195 DeclContext *Ctxt; ///< ODR Declaration context.
196 DIE *Clone; ///< Cloned version of that DIE.
197 uint32_t ParentIdx; ///< The index of this DIE's parent.
198 bool Keep : 1; ///< Is the DIE part of the linked output?
199 bool InDebugMap : 1;///< Was this DIE's entity found in the map?
200 bool Prune : 1; ///< Is this a pure forward declaration we can strip?
201 };
202
203 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR,
204 StringRef ClangModuleName)
205 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX(18446744073709551615UL)), HighPc(0), RangeAlloc(),
206 Ranges(RangeAlloc), ClangModuleName(ClangModuleName) {
207 Info.resize(OrigUnit.getNumDIEs());
208
209 auto CUDie = OrigUnit.getUnitDIE(false);
210 if (auto Lang = dwarf::toUnsigned(CUDie.find(dwarf::DW_AT_language)))
211 HasODR = CanUseODR && (*Lang == dwarf::DW_LANG_C_plus_plus ||
212 *Lang == dwarf::DW_LANG_C_plus_plus_03 ||
213 *Lang == dwarf::DW_LANG_C_plus_plus_11 ||
214 *Lang == dwarf::DW_LANG_C_plus_plus_14 ||
215 *Lang == dwarf::DW_LANG_ObjC_plus_plus);
216 else
217 HasODR = false;
218 }
219
220 DWARFUnit &getOrigUnit() const { return OrigUnit; }
221
222 unsigned getUniqueID() const { return ID; }
223
224 void createOutputDIE() {
225 NewUnit.emplace(OrigUnit.getVersion(), OrigUnit.getAddressByteSize(),
226 OrigUnit.getUnitDIE().getTag());
227 }
228
229 DIE *getOutputUnitDIE() const {
230 if (NewUnit)
231 return &const_cast<BasicDIEUnit &>(*NewUnit).getUnitDie();
232 return nullptr;
233 }
234
235 bool hasODR() const { return HasODR; }
236 bool isClangModule() const { return !ClangModuleName.empty(); }
237 const std::string &getClangModuleName() const { return ClangModuleName; }
238
239 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
240 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
241
242 uint64_t getStartOffset() const { return StartOffset; }
243 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
244 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
245
246 uint64_t getLowPc() const { return LowPc; }
247 uint64_t getHighPc() const { return HighPc; }
248
249 Optional<PatchLocation> getUnitRangesAttribute() const {
250 return UnitRangeAttribute;
251 }
252 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
253 const std::vector<PatchLocation> &getRangesAttributes() const {
254 return RangeAttributes;
255 }
256
257 const std::vector<std::pair<PatchLocation, int64_t>> &
258 getLocationAttributes() const {
259 return LocationAttributes;
260 }
261
262 void setHasInterestingContent() { HasInterestingContent = true; }
263 bool hasInterestingContent() { return HasInterestingContent; }
264
265 /// Mark every DIE in this unit as kept. This function also
266 /// marks variables as InDebugMap so that they appear in the
267 /// reconstructed accelerator tables.
268 void markEverythingAsKept();
269
270 /// \brief Compute the end offset for this unit. Must be
271 /// called after the CU's DIEs have been cloned.
272 /// \returns the next unit offset (which is also the current
273 /// debug_info section size).
274 uint64_t computeNextUnitOffset();
275
276 /// \brief Keep track of a forward reference to DIE \p Die in \p
277 /// RefUnit by \p Attr. The attribute should be fixed up later to
278 /// point to the absolute offset of \p Die in the debug_info section
279 /// or to the canonical offset of \p Ctxt if it is non-null.
280 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
281 DeclContext *Ctxt, PatchLocation Attr);
282
283 /// \brief Apply all fixups recored by noteForwardReference().
284 void fixupForwardReferences();
285
286 /// \brief Add a function range [\p LowPC, \p HighPC) that is
287 /// relocatad by applying offset \p PCOffset.
288 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
289
290 /// \brief Keep track of a DW_AT_range attribute that we will need to
291 /// patch up later.
292 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
293
294 /// \brief Keep track of a location attribute pointing to a location
295 /// list in the debug_loc section.
296 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
297
298 /// \brief Add a name accelerator entry for \p Die with \p Name
299 /// which is stored in the string table at \p Offset.
300 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
301 bool SkipPubnamesSection = false);
302
303 /// \brief Add a type accelerator entry for \p Die with \p Name
304 /// which is stored in the string table at \p Offset.
305 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
306
307 struct AccelInfo {
308 StringRef Name; ///< Name of the entry.
309 const DIE *Die; ///< DIE this entry describes.
310 uint32_t NameOffset; ///< Offset of Name in the string pool.
311 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
312
313 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
314 bool SkipPubSection = false)
315 : Name(Name), Die(Die), NameOffset(NameOffset),
316 SkipPubSection(SkipPubSection) {}
317 };
318
319 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
320 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
321
322 /// Get the full path for file \a FileNum in the line table
323 StringRef getResolvedPath(unsigned FileNum) {
324 if (FileNum >= ResolvedPaths.size())
325 return StringRef();
326 return ResolvedPaths[FileNum];
327 }
328
329 /// Set the fully resolved path for the line-table's file \a FileNum
330 /// to \a Path.
331 void setResolvedPath(unsigned FileNum, StringRef Path) {
332 if (ResolvedPaths.size() <= FileNum)
333 ResolvedPaths.resize(FileNum + 1);
334 ResolvedPaths[FileNum] = Path;
335 }
336
337private:
338 DWARFUnit &OrigUnit;
339 unsigned ID;
340 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
341 Optional<BasicDIEUnit> NewUnit;
342
343 uint64_t StartOffset;
344 uint64_t NextUnitOffset;
345
346 uint64_t LowPc;
347 uint64_t HighPc;
348
349 /// \brief A list of attributes to fixup with the absolute offset of
350 /// a DIE in the debug_info section.
351 ///
352 /// The offsets for the attributes in this array couldn't be set while
353 /// cloning because for cross-cu forward refences the target DIE's
354 /// offset isn't known you emit the reference attribute.
355 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
356 PatchLocation>> ForwardDIEReferences;
357
358 FunctionIntervals::Allocator RangeAlloc;
359 /// \brief The ranges in that interval map are the PC ranges for
360 /// functions in this unit, associated with the PC offset to apply
361 /// to the addresses to get the linked address.
362 FunctionIntervals Ranges;
363
364 /// \brief DW_AT_ranges attributes to patch after we have gathered
365 /// all the unit's function addresses.
366 /// @{
367 std::vector<PatchLocation> RangeAttributes;
368 Optional<PatchLocation> UnitRangeAttribute;
369 /// @}
370
371 /// \brief Location attributes that need to be transferred from the
372 /// original debug_loc section to the liked one. They are stored
373 /// along with the PC offset that is to be applied to their
374 /// function's address.
375 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
376
377 /// \brief Accelerator entries for the unit, both for the pub*
378 /// sections and the apple* ones.
379 /// @{
380 std::vector<AccelInfo> Pubnames;
381 std::vector<AccelInfo> Pubtypes;
382 /// @}
383
384 /// Cached resolved paths from the line table.
385 /// Note, the StringRefs here point in to the intern (uniquing) string pool.
386 /// This means that a StringRef returned here doesn't need to then be uniqued
387 /// for the purposes of getting a unique address for each string.
388 std::vector<StringRef> ResolvedPaths;
389
390 /// Is this unit subject to the ODR rule?
391 bool HasODR;
392 /// Did a DIE actually contain a valid reloc?
393 bool HasInterestingContent;
394 /// If this is a Clang module, this holds the module's name.
395 std::string ClangModuleName;
396};
397
398void CompileUnit::markEverythingAsKept() {
399 for (auto &I : Info)
400 // Mark everything that wasn't explicity marked for pruning.
401 I.Keep = !I.Prune;
402}
403
404uint64_t CompileUnit::computeNextUnitOffset() {
405 NextUnitOffset = StartOffset + 11 /* Header size */;
406 // The root DIE might be null, meaning that the Unit had nothing to
407 // contribute to the linked output. In that case, we will emit the
408 // unit header without any actual DIE.
409 if (NewUnit)
410 NextUnitOffset += NewUnit->getUnitDie().getSize();
411 return NextUnitOffset;
412}
413
414/// \brief Keep track of a forward cross-cu reference from this unit
415/// to \p Die that lives in \p RefUnit.
416void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
417 DeclContext *Ctxt, PatchLocation Attr) {
418 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
419}
420
421/// \brief Apply all fixups recorded by noteForwardReference().
422void CompileUnit::fixupForwardReferences() {
423 for (const auto &Ref : ForwardDIEReferences) {
424 DIE *RefDie;
425 const CompileUnit *RefUnit;
426 PatchLocation Attr;
427 DeclContext *Ctxt;
428 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
429 if (Ctxt && Ctxt->getCanonicalDIEOffset())
430 Attr.set(Ctxt->getCanonicalDIEOffset());
431 else
432 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
433 }
434}
435
436void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
437 int64_t PcOffset) {
438 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
439 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
440 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
441}
442
443void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
444 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
445 RangeAttributes.push_back(Attr);
446 else
447 UnitRangeAttribute = Attr;
448}
449
450void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
451 LocationAttributes.emplace_back(Attr, PcOffset);
452}
453
454/// \brief Add a name accelerator entry for \p Die with \p Name
455/// which is stored in the string table at \p Offset.
456void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
457 uint32_t Offset, bool SkipPubSection) {
458 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
459}
460
461/// \brief Add a type accelerator entry for \p Die with \p Name
462/// which is stored in the string table at \p Offset.
463void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
464 uint32_t Offset) {
465 Pubtypes.emplace_back(Name, Die, Offset, false);
466}
467
468/// \brief The Dwarf streaming logic
469///
470/// All interactions with the MC layer that is used to build the debug
471/// information binary representation are handled in this class.
472class DwarfStreamer {
473 /// \defgroup MCObjects MC layer objects constructed by the streamer
474 /// @{
475 std::unique_ptr<MCRegisterInfo> MRI;
476 std::unique_ptr<MCAsmInfo> MAI;
477 std::unique_ptr<MCObjectFileInfo> MOFI;
478 std::unique_ptr<MCContext> MC;
479 MCAsmBackend *MAB; // Owned by MCStreamer
480 std::unique_ptr<MCInstrInfo> MII;
481 std::unique_ptr<MCSubtargetInfo> MSTI;
482 MCCodeEmitter *MCE; // Owned by MCStreamer
483 MCStreamer *MS; // Owned by AsmPrinter
484 std::unique_ptr<TargetMachine> TM;
485 std::unique_ptr<AsmPrinter> Asm;
486 /// @}
487
488 /// \brief the file we stream the linked Dwarf to.
489 std::unique_ptr<raw_fd_ostream> OutFile;
490
491 uint32_t RangesSectionSize;
492 uint32_t LocSectionSize;
493 uint32_t LineSectionSize;
494 uint32_t FrameSectionSize;
495
496 /// \brief Emit the pubnames or pubtypes section contribution for \p
497 /// Unit into \p Sec. The data is provided in \p Names.
498 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
499 const CompileUnit &Unit,
500 const std::vector<CompileUnit::AccelInfo> &Names);
501
502public:
503 /// \brief Actually create the streamer and the ouptut file.
504 ///
505 /// This could be done directly in the constructor, but it feels
506 /// more natural to handle errors through return value.
507 bool init(Triple TheTriple, StringRef OutputFilename);
508
509 /// \brief Dump the file to the disk.
510 bool finish(const DebugMap &);
511
512 AsmPrinter &getAsmPrinter() const { return *Asm; }
513
514 /// \brief Set the current output section to debug_info and change
515 /// the MC Dwarf version to \p DwarfVersion.
516 void switchToDebugInfoSection(unsigned DwarfVersion);
517
518 /// \brief Emit the compilation unit header for \p Unit in the
519 /// debug_info section.
520 ///
521 /// As a side effect, this also switches the current Dwarf version
522 /// of the MC layer to the one of U.getOrigUnit().
523 void emitCompileUnitHeader(CompileUnit &Unit);
524
525 /// \brief Recursively emit the DIE tree rooted at \p Die.
526 void emitDIE(DIE &Die);
527
528 /// \brief Emit the abbreviation table \p Abbrevs to the
529 /// debug_abbrev section.
530 void emitAbbrevs(const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs,
531 unsigned DwarfVersion);
532
533 /// \brief Emit the string table described by \p Pool.
534 void emitStrings(const NonRelocatableStringpool &Pool);
535
536 /// \brief Emit debug_ranges for \p FuncRange by translating the
537 /// original \p Entries.
538 void emitRangesEntries(
539 int64_t UnitPcOffset, uint64_t OrigLowPc,
540 const FunctionIntervals::const_iterator &FuncRange,
541 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
542 unsigned AddressSize);
543
544 /// \brief Emit debug_aranges entries for \p Unit and if \p
545 /// DoRangesSection is true, also emit the debug_ranges entries for
546 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
547 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
548
549 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
550
551 /// \brief Emit the debug_loc contribution for \p Unit by copying
552 /// the entries from \p Dwarf and offseting them. Update the
553 /// location attributes to point to the new entries.
554 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
555
556 /// \brief Emit the line table described in \p Rows into the
557 /// debug_line section.
558 void emitLineTableForUnit(MCDwarfLineTableParams Params,
559 StringRef PrologueBytes, unsigned MinInstLength,
560 std::vector<DWARFDebugLine::Row> &Rows,
561 unsigned AdddressSize);
562
563 uint32_t getLineSectionSize() const { return LineSectionSize; }
564
565 /// \brief Emit the .debug_pubnames contribution for \p Unit.
566 void emitPubNamesForUnit(const CompileUnit &Unit);
567
568 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
569 void emitPubTypesForUnit(const CompileUnit &Unit);
570
571 /// \brief Emit a CIE.
572 void emitCIE(StringRef CIEBytes);
573
574 /// \brief Emit an FDE with data \p Bytes.
575 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
576 StringRef Bytes);
577
578 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
579};
580
581bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
582 std::string ErrorStr;
583 std::string TripleName;
584 StringRef Context = "dwarf streamer init";
585
586 // Get the target.
587 const Target *TheTarget =
588 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
589 if (!TheTarget)
590 return error(ErrorStr, Context);
591 TripleName = TheTriple.getTriple();
592
593 // Create all the MC Objects.
594 MRI.reset(TheTarget->createMCRegInfo(TripleName));
595 if (!MRI)
596 return error(Twine("no register info for target ") + TripleName, Context);
597
598 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
599 if (!MAI)
600 return error("no asm info for target " + TripleName, Context);
601
602 MOFI.reset(new MCObjectFileInfo);
603 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
604 MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, CodeModel::Default, *MC);
605
606 MCTargetOptions Options;
607 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "", Options);
608 if (!MAB)
609 return error("no asm backend for target " + TripleName, Context);
610
611 MII.reset(TheTarget->createMCInstrInfo());
612 if (!MII)
613 return error("no instr info info for target " + TripleName, Context);
614
615 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
616 if (!MSTI)
617 return error("no subtarget info for target " + TripleName, Context);
618
619 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
620 if (!MCE)
621 return error("no code emitter for target " + TripleName, Context);
622
623 // Create the output file.
624 std::error_code EC;
625 OutFile =
626 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
627 if (EC)
628 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
629
630 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
631 MS = TheTarget->createMCObjectStreamer(
632 TheTriple, *MC, *MAB, *OutFile, MCE, *MSTI, MCOptions.MCRelaxAll,
633 MCOptions.MCIncrementalLinkerCompatible,
634 /*DWARFMustBeAtTheEnd*/ false);
635 if (!MS)
636 return error("no object streamer for target " + TripleName, Context);
637
638 // Finally create the AsmPrinter we'll use to emit the DIEs.
639 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
640 None));
641 if (!TM)
642 return error("no target machine for target " + TripleName, Context);
643
644 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
645 if (!Asm)
646 return error("no asm printer for target " + TripleName, Context);
647
648 RangesSectionSize = 0;
649 LocSectionSize = 0;
650 LineSectionSize = 0;
651 FrameSectionSize = 0;
652
653 return true;
654}
655
656bool DwarfStreamer::finish(const DebugMap &DM) {
657 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
658 return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
659
660 MS->Finish();
661 return true;
662}
663
664/// \brief Set the current output section to debug_info and change
665/// the MC Dwarf version to \p DwarfVersion.
666void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
667 MS->SwitchSection(MOFI->getDwarfInfoSection());
668 MC->setDwarfVersion(DwarfVersion);
669}
670
671/// \brief Emit the compilation unit header for \p Unit in the
672/// debug_info section.
673///
674/// A Dwarf scetion header is encoded as:
675/// uint32_t Unit length (omiting this field)
676/// uint16_t Version
677/// uint32_t Abbreviation table offset
678/// uint8_t Address size
679///
680/// Leading to a total of 11 bytes.
681void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
682 unsigned Version = Unit.getOrigUnit().getVersion();
683 switchToDebugInfoSection(Version);
684
685 // Emit size of content not including length itself. The size has
686 // already been computed in CompileUnit::computeOffsets(). Substract
687 // 4 to that size to account for the length field.
688 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
689 Asm->EmitInt16(Version);
690 // We share one abbreviations table across all units so it's always at the
691 // start of the section.
692 Asm->EmitInt32(0);
693 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
694}
695
696/// \brief Emit the \p Abbrevs array as the shared abbreviation table
697/// for the linked Dwarf file.
698void DwarfStreamer::emitAbbrevs(
699 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs,
700 unsigned DwarfVersion) {
701 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
702 MC->setDwarfVersion(DwarfVersion);
703 Asm->emitDwarfAbbrevs(Abbrevs);
704}
705
706/// \brief Recursively emit the DIE tree rooted at \p Die.
707void DwarfStreamer::emitDIE(DIE &Die) {
708 MS->SwitchSection(MOFI->getDwarfInfoSection());
709 Asm->emitDwarfDIE(Die);
710}
711
712/// \brief Emit the debug_str section stored in \p Pool.
713void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
714 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
715 for (auto *Entry = Pool.getFirstEntry(); Entry;
716 Entry = Pool.getNextEntry(Entry))
717 Asm->OutStreamer->EmitBytes(
718 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
719}
720
721/// \brief Emit the debug_range section contents for \p FuncRange by
722/// translating the original \p Entries. The debug_range section
723/// format is totally trivial, consisting just of pairs of address
724/// sized addresses describing the ranges.
725void DwarfStreamer::emitRangesEntries(
726 int64_t UnitPcOffset, uint64_t OrigLowPc,
727 const FunctionIntervals::const_iterator &FuncRange,
728 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
729 unsigned AddressSize) {
730 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
731
732 // Offset each range by the right amount.
733 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
734 for (const auto &Range : Entries) {
735 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
736 warn("unsupported base address selection operation",
737 "emitting debug_ranges");
738 break;
739 }
740 // Do not emit empty ranges.
741 if (Range.StartAddress == Range.EndAddress)
742 continue;
743
744 // All range entries should lie in the function range.
745 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
746 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
747 warn("inconsistent range data.", "emitting debug_ranges");
748 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
749 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
750 RangesSectionSize += 2 * AddressSize;
751 }
752
753 // Add the terminator entry.
754 MS->EmitIntValue(0, AddressSize);
755 MS->EmitIntValue(0, AddressSize);
756 RangesSectionSize += 2 * AddressSize;
757}
758
759/// \brief Emit the debug_aranges contribution of a unit and
760/// if \p DoDebugRanges is true the debug_range contents for a
761/// compile_unit level DW_AT_ranges attribute (Which are basically the
762/// same thing with a different base address).
763/// Just aggregate all the ranges gathered inside that unit.
764void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
765 bool DoDebugRanges) {
766 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
767 // Gather the ranges in a vector, so that we can simplify them. The
768 // IntervalMap will have coalesced the non-linked ranges, but here
769 // we want to coalesce the linked addresses.
770 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
771 const auto &FunctionRanges = Unit.getFunctionRanges();
772 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
773 Range != End; ++Range)
774 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
775 Range.stop() + Range.value()));
776
777 // The object addresses where sorted, but again, the linked
778 // addresses might end up in a different order.
779 std::sort(Ranges.begin(), Ranges.end());
780
781 if (!Ranges.empty()) {
782 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
783
784 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
785 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
786
787 unsigned HeaderSize =
788 sizeof(int32_t) + // Size of contents (w/o this field
789 sizeof(int16_t) + // DWARF ARange version number
790 sizeof(int32_t) + // Offset of CU in the .debug_info section
791 sizeof(int8_t) + // Pointer Size (in bytes)
792 sizeof(int8_t); // Segment Size (in bytes)
793
794 unsigned TupleSize = AddressSize * 2;
795 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
796
797 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
798 Asm->OutStreamer->EmitLabel(BeginLabel);
799 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
800 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
801 Asm->EmitInt8(AddressSize); // Address size
802 Asm->EmitInt8(0); // Segment size
803
804 Asm->OutStreamer->emitFill(Padding, 0x0);
805
806 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
807 ++Range) {
808 uint64_t RangeStart = Range->first;
809 MS->EmitIntValue(RangeStart, AddressSize);
810 while ((Range + 1) != End && Range->second == (Range + 1)->first)
811 ++Range;
812 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
813 }
814
815 // Emit terminator
816 Asm->OutStreamer->EmitIntValue(0, AddressSize);
817 Asm->OutStreamer->EmitIntValue(0, AddressSize);
818 Asm->OutStreamer->EmitLabel(EndLabel);
819 }
820
821 if (!DoDebugRanges)
822 return;
823
824 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
825 // Offset each range by the right amount.
826 int64_t PcOffset = -Unit.getLowPc();
827 // Emit coalesced ranges.
828 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
829 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
830 while (Range + 1 != End && Range->second == (Range + 1)->first)
831 ++Range;
832 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
833 RangesSectionSize += 2 * AddressSize;
834 }
835
836 // Add the terminator entry.
837 MS->EmitIntValue(0, AddressSize);
838 MS->EmitIntValue(0, AddressSize);
839 RangesSectionSize += 2 * AddressSize;
840}
841
842/// \brief Emit location lists for \p Unit and update attribtues to
843/// point to the new entries.
844void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
845 DWARFContext &Dwarf) {
846 const auto &Attributes = Unit.getLocationAttributes();
847
848 if (Attributes.empty())
849 return;
850
851 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
852
853 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
854 const DWARFSection &InputSec = Dwarf.getLocSection();
855 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
856 DWARFUnit &OrigUnit = Unit.getOrigUnit();
857 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
858 int64_t UnitPcOffset = 0;
859 if (auto OrigLowPc = dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc)))
860 UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc();
861
862 for (const auto &Attr : Attributes) {
863 uint32_t Offset = Attr.first.get();
864 Attr.first.set(LocSectionSize);
865 // This is the quantity to add to the old location address to get
866 // the correct address for the new one.
867 int64_t LocPcOffset = Attr.second + UnitPcOffset;
868 while (Data.isValidOffset(Offset)) {
869 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
870 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
871 LocSectionSize += 2 * AddressSize;
872 if (Low == 0 && High == 0) {
873 Asm->OutStreamer->EmitIntValue(0, AddressSize);
874 Asm->OutStreamer->EmitIntValue(0, AddressSize);
875 break;
876 }
877 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
878 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
879 uint64_t Length = Data.getU16(&Offset);
880 Asm->OutStreamer->EmitIntValue(Length, 2);
881 // Just copy the bytes over.
882 Asm->OutStreamer->EmitBytes(
883 StringRef(InputSec.Data.substr(Offset, Length)));
884 Offset += Length;
885 LocSectionSize += Length + 2;
886 }
887 }
888}
889
890void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
891 StringRef PrologueBytes,
892 unsigned MinInstLength,
893 std::vector<DWARFDebugLine::Row> &Rows,
894 unsigned PointerSize) {
895 // Switch to the section where the table will be emitted into.
896 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
897 MCSymbol *LineStartSym = MC->createTempSymbol();
898 MCSymbol *LineEndSym = MC->createTempSymbol();
899
900 // The first 4 bytes is the total length of the information for this
901 // compilation unit (not including these 4 bytes for the length).
902 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
903 Asm->OutStreamer->EmitLabel(LineStartSym);
904 // Copy Prologue.
905 MS->EmitBytes(PrologueBytes);
906 LineSectionSize += PrologueBytes.size() + 4;
907
908 SmallString<128> EncodingBuffer;
909 raw_svector_ostream EncodingOS(EncodingBuffer);
910
911 if (Rows.empty()) {
912 // We only have the dummy entry, dsymutil emits an entry with a 0
913 // address in that case.
914 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX(9223372036854775807L), 0, EncodingOS);
915 MS->EmitBytes(EncodingOS.str());
916 LineSectionSize += EncodingBuffer.size();
917 MS->EmitLabel(LineEndSym);
918 return;
919 }
920
921 // Line table state machine fields
922 unsigned FileNum = 1;
923 unsigned LastLine = 1;
924 unsigned Column = 0;
925 unsigned IsStatement = 1;
926 unsigned Isa = 0;
927 uint64_t Address = -1ULL;
928
929 unsigned RowsSinceLastSequence = 0;
930
931 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
932 auto &Row = Rows[Idx];
933
934 int64_t AddressDelta;
935 if (Address == -1ULL) {
936 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
937 MS->EmitULEB128IntValue(PointerSize + 1);
938 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
939 MS->EmitIntValue(Row.Address, PointerSize);
940 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
941 AddressDelta = 0;
942 } else {
943 AddressDelta = (Row.Address - Address) / MinInstLength;
944 }
945
946 // FIXME: code copied and transfromed from
947 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
948 // this code, but the current compatibility requirement with
949 // classic dsymutil makes it hard. Revisit that once this
950 // requirement is dropped.
951
952 if (FileNum != Row.File) {
953 FileNum = Row.File;
954 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
955 MS->EmitULEB128IntValue(FileNum);
956 LineSectionSize += 1 + getULEB128Size(FileNum);
957 }
958 if (Column != Row.Column) {
959 Column = Row.Column;
960 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
961 MS->EmitULEB128IntValue(Column);
962 LineSectionSize += 1 + getULEB128Size(Column);
963 }
964
965 // FIXME: We should handle the discriminator here, but dsymutil
966 // doesn' consider it, thus ignore it for now.
967
968 if (Isa != Row.Isa) {
969 Isa = Row.Isa;
970 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
971 MS->EmitULEB128IntValue(Isa);
972 LineSectionSize += 1 + getULEB128Size(Isa);
973 }
974 if (IsStatement != Row.IsStmt) {
975 IsStatement = Row.IsStmt;
976 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
977 LineSectionSize += 1;
978 }
979 if (Row.BasicBlock) {
980 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
981 LineSectionSize += 1;
982 }
983
984 if (Row.PrologueEnd) {
985 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
986 LineSectionSize += 1;
987 }
988
989 if (Row.EpilogueBegin) {
990 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
991 LineSectionSize += 1;
992 }
993
994 int64_t LineDelta = int64_t(Row.Line) - LastLine;
995 if (!Row.EndSequence) {
996 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
997 MS->EmitBytes(EncodingOS.str());
998 LineSectionSize += EncodingBuffer.size();
999 EncodingBuffer.resize(0);
1000 Address = Row.Address;
1001 LastLine = Row.Line;
1002 RowsSinceLastSequence++;
1003 } else {
1004 if (LineDelta) {
1005 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
1006 MS->EmitSLEB128IntValue(LineDelta);
1007 LineSectionSize += 1 + getSLEB128Size(LineDelta);
1008 }
1009 if (AddressDelta) {
1010 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
1011 MS->EmitULEB128IntValue(AddressDelta);
1012 LineSectionSize += 1 + getULEB128Size(AddressDelta);
1013 }
1014 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX(9223372036854775807L), 0, EncodingOS);
1015 MS->EmitBytes(EncodingOS.str());
1016 LineSectionSize += EncodingBuffer.size();
1017 EncodingBuffer.resize(0);
1018 Address = -1ULL;
1019 LastLine = FileNum = IsStatement = 1;
1020 RowsSinceLastSequence = Column = Isa = 0;
1021 }
1022 }
1023
1024 if (RowsSinceLastSequence) {
1025 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX(9223372036854775807L), 0, EncodingOS);
1026 MS->EmitBytes(EncodingOS.str());
1027 LineSectionSize += EncodingBuffer.size();
1028 EncodingBuffer.resize(0);
1029 }
1030
1031 MS->EmitLabel(LineEndSym);
1032}
1033
1034/// \brief Emit the pubnames or pubtypes section contribution for \p
1035/// Unit into \p Sec. The data is provided in \p Names.
1036void DwarfStreamer::emitPubSectionForUnit(
1037 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
1038 const std::vector<CompileUnit::AccelInfo> &Names) {
1039 if (Names.empty())
1040 return;
1041
1042 // Start the dwarf pubnames section.
1043 Asm->OutStreamer->SwitchSection(Sec);
1044 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1045 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
1046
1047 bool HeaderEmitted = false;
1048 // Emit the pubnames for this compilation unit.
1049 for (const auto &Name : Names) {
1050 if (Name.SkipPubSection)
1051 continue;
1052
1053 if (!HeaderEmitted) {
1054 // Emit the header.
1055 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
1056 Asm->OutStreamer->EmitLabel(BeginLabel);
1057 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
1058 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
1059 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1060 HeaderEmitted = true;
1061 }
1062 Asm->EmitInt32(Name.Die->getOffset());
1063 Asm->OutStreamer->EmitBytes(
1064 StringRef(Name.Name.data(), Name.Name.size() + 1));
1065 }
1066
1067 if (!HeaderEmitted)
1068 return;
1069 Asm->EmitInt32(0); // End marker.
1070 Asm->OutStreamer->EmitLabel(EndLabel);
1071}
1072
1073/// \brief Emit .debug_pubnames for \p Unit.
1074void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1075 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1076 "names", Unit, Unit.getPubnames());
1077}
1078
1079/// \brief Emit .debug_pubtypes for \p Unit.
1080void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1081 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1082 "types", Unit, Unit.getPubtypes());
1083}
1084
1085/// \brief Emit a CIE into the debug_frame section.
1086void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1087 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1088
1089 MS->EmitBytes(CIEBytes);
1090 FrameSectionSize += CIEBytes.size();
1091}
1092
1093/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1094/// contains the FDE data without the length, CIE offset and address
1095/// which will be replaced with the parameter values.
1096void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1097 uint32_t Address, StringRef FDEBytes) {
1098 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1099
1100 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1101 MS->EmitIntValue(CIEOffset, 4);
1102 MS->EmitIntValue(Address, AddrSize);
1103 MS->EmitBytes(FDEBytes);
1104 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1105}
1106
1107/// \brief The core of the Dwarf linking logic.
1108///
1109/// The link of the dwarf information from the object files will be
1110/// driven by the selection of 'root DIEs', which are DIEs that
1111/// describe variables or functions that are present in the linked
1112/// binary (and thus have entries in the debug map). All the debug
1113/// information that will be linked (the DIEs, but also the line
1114/// tables, ranges, ...) is derived from that set of root DIEs.
1115///
1116/// The root DIEs are identified because they contain relocations that
1117/// correspond to a debug map entry at specific places (the low_pc for
1118/// a function, the location for a variable). These relocations are
1119/// called ValidRelocs in the DwarfLinker and are gathered as a very
1120/// first step when we start processing a DebugMapObject.
1121class DwarfLinker {
1122public:
1123 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1124 : OutputFilename(OutputFilename), Options(Options),
1125 BinHolder(Options.Verbose), LastCIEOffset(0) {}
1126
1127 /// \brief Link the contents of the DebugMap.
1128 bool link(const DebugMap &);
1129
1130 void reportWarning(const Twine &Warning,
1131 const DWARFDie *DIE = nullptr) const;
1132
1133private:
1134 /// \brief Called at the start of a debug object link.
1135 void startDebugObject(DWARFContext &, DebugMapObject &);
1136
1137 /// \brief Called at the end of a debug object link.
1138 void endDebugObject();
1139
1140 /// Remembers the newest DWARF version we've seen in a unit.
1141 void maybeUpdateMaxDwarfVersion(unsigned Version) {
1142 if (MaxDwarfVersion < Version)
1143 MaxDwarfVersion = Version;
1144 }
1145
1146 /// Keeps track of relocations.
1147 class RelocationManager {
1148 struct ValidReloc {
1149 uint32_t Offset;
1150 uint32_t Size;
1151 uint64_t Addend;
1152 const DebugMapObject::DebugMapEntry *Mapping;
1153
1154 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1155 const DebugMapObject::DebugMapEntry *Mapping)
1156 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1157
1158 bool operator<(const ValidReloc &RHS) const {
1159 return Offset < RHS.Offset;
1160 }
1161 };
1162
1163 DwarfLinker &Linker;
1164
1165 /// \brief The valid relocations for the current DebugMapObject.
1166 /// This vector is sorted by relocation offset.
1167 std::vector<ValidReloc> ValidRelocs;
1168
1169 /// \brief Index into ValidRelocs of the next relocation to
1170 /// consider. As we walk the DIEs in acsending file offset and as
1171 /// ValidRelocs is sorted by file offset, keeping this index
1172 /// uptodate is all we have to do to have a cheap lookup during the
1173 /// root DIE selection and during DIE cloning.
1174 unsigned NextValidReloc;
1175
1176 public:
1177 RelocationManager(DwarfLinker &Linker)
1178 : Linker(Linker), NextValidReloc(0) {}
1179
1180 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1181 /// \brief Reset the NextValidReloc counter.
1182 void resetValidRelocs() { NextValidReloc = 0; }
1183
1184 /// \defgroup FindValidRelocations Translate debug map into a list
1185 /// of relevant relocations
1186 ///
1187 /// @{
1188 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1189 const DebugMapObject &DMO);
1190
1191 bool findValidRelocs(const object::SectionRef &Section,
1192 const object::ObjectFile &Obj,
1193 const DebugMapObject &DMO);
1194
1195 void findValidRelocsMachO(const object::SectionRef &Section,
1196 const object::MachOObjectFile &Obj,
1197 const DebugMapObject &DMO);
1198 /// @}
1199
1200 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1201 CompileUnit::DIEInfo &Info);
1202
1203 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1204 bool isLittleEndian);
1205 };
1206
1207 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1208 ///
1209 /// @{
1210 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1211 /// keep. Store that information in \p CU's DIEInfo.
1212 void lookForDIEsToKeep(RelocationManager &RelocMgr,
1213 const DWARFDie &DIE,
1214 const DebugMapObject &DMO, CompileUnit &CU,
1215 unsigned Flags);
1216
1217 /// If this compile unit is really a skeleton CU that points to a
1218 /// clang module, register it in ClangModules and return true.
1219 ///
1220 /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
1221 /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
1222 /// hash.
1223 bool registerModuleReference(const DWARFDie &CUDie,
1224 const DWARFUnit &Unit, DebugMap &ModuleMap,
1225 unsigned Indent = 0);
1226
1227 /// Recursively add the debug info in this clang module .pcm
1228 /// file (and all the modules imported by it in a bottom-up fashion)
1229 /// to Units.
1230 void loadClangModule(StringRef Filename, StringRef ModulePath,
1231 StringRef ModuleName, uint64_t DwoId,
1232 DebugMap &ModuleMap, unsigned Indent = 0);
1233
1234 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1235 enum TravesalFlags {
1236 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1237 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1238 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1239 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1240 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
1241 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
1242 };
1243
1244 /// \brief Mark the passed DIE as well as all the ones it depends on
1245 /// as kept.
1246 void keepDIEAndDependencies(RelocationManager &RelocMgr,
1247 const DWARFDie &DIE,
1248 CompileUnit::DIEInfo &MyInfo,
1249 const DebugMapObject &DMO, CompileUnit &CU,
1250 bool UseODR);
1251
1252 unsigned shouldKeepDIE(RelocationManager &RelocMgr,
1253 const DWARFDie &DIE,
1254 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1255 unsigned Flags);
1256
1257 unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
1258 const DWARFDie &DIE,
1259 CompileUnit &Unit,
1260 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1261
1262 unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
1263 const DWARFDie &DIE,
1264 CompileUnit &Unit,
1265 CompileUnit::DIEInfo &MyInfo,
1266 unsigned Flags);
1267
1268 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1269 CompileUnit::DIEInfo &Info);
1270 /// @}
1271
1272 /// \defgroup Linking Methods used to link the debug information
1273 ///
1274 /// @{
1275
1276 class DIECloner {
1277 DwarfLinker &Linker;
1278 RelocationManager &RelocMgr;
1279 /// Allocator used for all the DIEValue objects.
1280 BumpPtrAllocator &DIEAlloc;
1281 std::vector<std::unique_ptr<CompileUnit>> &CompileUnits;
1282 LinkOptions Options;
1283
1284 public:
1285 DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1286 BumpPtrAllocator &DIEAlloc,
1287 std::vector<std::unique_ptr<CompileUnit>> &CompileUnits,
1288 LinkOptions &Options)
1289 : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1290 CompileUnits(CompileUnits), Options(Options) {}
1291
1292 /// Recursively clone \p InputDIE into an tree of DIE objects
1293 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1294 /// stripped out and addresses have been rewritten according to the
1295 /// debug map.
1296 ///
1297 /// \param OutOffset is the offset the cloned DIE in the output
1298 /// compile unit.
1299 /// \param PCOffset (while cloning a function scope) is the offset
1300 /// applied to the entry point of the function to get the linked address.
1301 /// \param Die the output DIE to use, pass NULL to create one.
1302 /// \returns the root of the cloned tree or null if nothing was selected.
1303 DIE *cloneDIE(const DWARFDie &InputDIE, CompileUnit &U,
1304 int64_t PCOffset, uint32_t OutOffset, unsigned Flags,
1305 DIE *Die = nullptr);
1306
1307 /// Construct the output DIE tree by cloning the DIEs we
1308 /// chose to keep above. If there are no valid relocs, then there's
1309 /// nothing to clone/emit.
1310 void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
1311
1312 private:
1313 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1314
1315 /// Information gathered and exchanged between the various
1316 /// clone*Attributes helpers about the attributes of a particular DIE.
1317 struct AttributesInfo {
1318 const char *Name, *MangledName; ///< Names.
1319 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1320
1321 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1322 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1323 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1324
1325 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1326 bool IsDeclaration; ///< Is this DIE only a declaration?
1327
1328 AttributesInfo()
1329 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1330 MangledNameOffset(0), OrigLowPc(UINT64_MAX(18446744073709551615UL)), OrigHighPc(0),
1331 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1332 };
1333
1334 /// Helper for cloneDIE.
1335 unsigned cloneAttribute(DIE &Die,
1336 const DWARFDie &InputDIE,
1337 CompileUnit &U, const DWARFFormValue &Val,
1338 const AttributeSpec AttrSpec, unsigned AttrSize,
1339 AttributesInfo &AttrInfo);
1340
1341 /// Clone a string attribute described by \p AttrSpec and add
1342 /// it to \p Die.
1343 /// \returns the size of the new attribute.
1344 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1345 const DWARFFormValue &Val,
1346 const DWARFUnit &U);
1347
1348 /// Clone an attribute referencing another DIE and add
1349 /// it to \p Die.
1350 /// \returns the size of the new attribute.
1351 unsigned
1352 cloneDieReferenceAttribute(DIE &Die,
1353 const DWARFDie &InputDIE,
1354 AttributeSpec AttrSpec, unsigned AttrSize,
1355 const DWARFFormValue &Val, CompileUnit &Unit);
1356
1357 /// Clone an attribute referencing another DIE and add
1358 /// it to \p Die.
1359 /// \returns the size of the new attribute.
1360 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1361 const DWARFFormValue &Val, unsigned AttrSize);
1362
1363 /// Clone an attribute referencing another DIE and add
1364 /// it to \p Die.
1365 /// \returns the size of the new attribute.
1366 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1367 const DWARFFormValue &Val,
1368 const CompileUnit &Unit,
1369 AttributesInfo &Info);
1370
1371 /// Clone a scalar attribute and add it to \p Die.
1372 /// \returns the size of the new attribute.
1373 unsigned cloneScalarAttribute(DIE &Die,
1374 const DWARFDie &InputDIE,
1375 CompileUnit &U, AttributeSpec AttrSpec,
1376 const DWARFFormValue &Val, unsigned AttrSize,
1377 AttributesInfo &Info);
1378
1379 /// Get the potential name and mangled name for the entity
1380 /// described by \p Die and store them in \Info if they are not
1381 /// already there.
1382 /// \returns is a name was found.
1383 bool getDIENames(const DWARFDie &Die, AttributesInfo &Info);
1384
1385 /// Create a copy of abbreviation Abbrev.
1386 void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
1387 };
1388
1389 /// \brief Assign an abbreviation number to \p Abbrev
1390 void AssignAbbrev(DIEAbbrev &Abbrev);
1391
1392 /// \brief FoldingSet that uniques the abbreviations.
1393 FoldingSet<DIEAbbrev> AbbreviationsSet;
1394 /// \brief Storage for the unique Abbreviations.
1395 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1396 /// be changed to a vecot of unique_ptrs.
1397 std::vector<std::unique_ptr<DIEAbbrev>> Abbreviations;
1398
1399 /// \brief Compute and emit debug_ranges section for \p Unit, and
1400 /// patch the attributes referencing it.
1401 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1402
1403 /// \brief Generate and emit the DW_AT_ranges attribute for a
1404 /// compile_unit if it had one.
1405 void generateUnitRanges(CompileUnit &Unit) const;
1406
1407 /// \brief Extract the line tables fromt he original dwarf, extract
1408 /// the relevant parts according to the linked function ranges and
1409 /// emit the result in the debug_line section.
1410 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1411
1412 /// \brief Emit the accelerator entries for \p Unit.
1413 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1414
1415 /// \brief Patch the frame info for an object file and emit it.
1416 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1417 unsigned AddressSize);
1418
1419 /// \brief DIELoc objects that need to be destructed (but not freed!).
1420 std::vector<DIELoc *> DIELocs;
1421 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1422 std::vector<DIEBlock *> DIEBlocks;
1423 /// \brief Allocator used for all the DIEValue objects.
1424 BumpPtrAllocator DIEAlloc;
1425 /// @}
1426
1427 /// ODR Contexts for that link.
1428 DeclContextTree ODRContexts;
1429
1430 /// \defgroup Helpers Various helper methods.
1431 ///
1432 /// @{
1433 bool createStreamer(const Triple &TheTriple, StringRef OutputFilename);
1434
1435 /// \brief Attempt to load a debug object from disk.
1436 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1437 DebugMapObject &Obj,
1438 const DebugMap &Map);
1439 /// @}
1440
1441 std::string OutputFilename;
1442 LinkOptions Options;
1443 BinaryHolder BinHolder;
1444 std::unique_ptr<DwarfStreamer> Streamer;
1445 uint64_t OutputDebugInfoSize;
1446 unsigned UnitID; ///< A unique ID that identifies each compile unit.
1447 unsigned MaxDwarfVersion = 0;
1448
1449 /// The units of the current debug map object.
1450 std::vector<std::unique_ptr<CompileUnit>> Units;
1451
1452
1453 /// The debug map object currently under consideration.
1454 DebugMapObject *CurrentDebugObject;
1455
1456 /// \brief The Dwarf string pool
1457 NonRelocatableStringpool StringPool;
1458
1459 /// \brief This map is keyed by the entry PC of functions in that
1460 /// debug object and the associated value is a pair storing the
1461 /// corresponding end PC and the offset to apply to get the linked
1462 /// address.
1463 ///
1464 /// See startDebugObject() for a more complete description of its use.
1465 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1466
1467 /// \brief The CIEs that have been emitted in the output
1468 /// section. The actual CIE data serves a the key to this StringMap,
1469 /// this takes care of comparing the semantics of CIEs defined in
1470 /// different object files.
1471 StringMap<uint32_t> EmittedCIEs;
1472
1473 /// Offset of the last CIE that has been emitted in the output
1474 /// debug_frame section.
1475 uint32_t LastCIEOffset;
1476
1477 /// Mapping the PCM filename to the DwoId.
1478 StringMap<uint64_t> ClangModules;
1479
1480 bool ModuleCacheHintDisplayed = false;
1481 bool ArchiveHintDisplayed = false;
1482};
1483
1484/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
1485/// CompileUnit object instead.
1486static CompileUnit *getUnitForOffset(
1487 std::vector<std::unique_ptr<CompileUnit>> &Units, unsigned Offset) {
1488 auto CU =
1489 std::upper_bound(Units.begin(), Units.end(), Offset,
1490 [](uint32_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
1491 return LHS < RHS->getOrigUnit().getNextUnitOffset();
1492 });
1493 return CU != Units.end() ? CU->get() : nullptr;
1494}
1495
1496/// Resolve the DIE attribute reference that has been
1497/// extracted in \p RefValue. The resulting DIE migh be in another
1498/// CompileUnit which is stored into \p ReferencedCU.
1499/// \returns null if resolving fails for any reason.
1500static DWARFDie resolveDIEReference(
1501 const DwarfLinker &Linker, std::vector<std::unique_ptr<CompileUnit>> &Units,
1502 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1503 const DWARFDie &DIE, CompileUnit *&RefCU) {
1504 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference))((RefValue.isFormClass(DWARFFormValue::FC_Reference)) ? static_cast
<void> (0) : __assert_fail ("RefValue.isFormClass(DWARFFormValue::FC_Reference)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 1504, __PRETTY_FUNCTION__))
;
1505 uint64_t RefOffset = *RefValue.getAsReference();
1506
1507 if ((RefCU = getUnitForOffset(Units, RefOffset)))
1508 if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1509 return RefDie;
1510
1511 Linker.reportWarning("could not find referenced DIE", &DIE);
1512 return DWARFDie();
1513}
1514
1515/// \returns whether the passed \a Attr type might contain a DIE
1516/// reference suitable for ODR uniquing.
1517static bool isODRAttribute(uint16_t Attr) {
1518 switch (Attr) {
1519 default:
1520 return false;
1521 case dwarf::DW_AT_type:
1522 case dwarf::DW_AT_containing_type:
1523 case dwarf::DW_AT_specification:
1524 case dwarf::DW_AT_abstract_origin:
1525 case dwarf::DW_AT_import:
1526 return true;
1527 }
1528 llvm_unreachable("Improper attribute.")::llvm::llvm_unreachable_internal("Improper attribute.", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 1528)
;
1529}
1530
1531/// Set the last DIE/CU a context was seen in and, possibly invalidate
1532/// the context if it is ambiguous.
1533///
1534/// In the current implementation, we don't handle overloaded
1535/// functions well, because the argument types are not taken into
1536/// account when computing the DeclContext tree.
1537///
1538/// Some of this is mitigated byt using mangled names that do contain
1539/// the arguments types, but sometimes (eg. with function templates)
1540/// we don't have that. In that case, just do not unique anything that
1541/// refers to the contexts we are not able to distinguish.
1542///
1543/// If a context that is not a namespace appears twice in the same CU,
1544/// we know it is ambiguous. Make it invalid.
1545bool DeclContext::setLastSeenDIE(CompileUnit &U,
1546 const DWARFDie &Die) {
1547 if (LastSeenCompileUnitID == U.getUniqueID()) {
1548 DWARFUnit &OrigUnit = U.getOrigUnit();
1549 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1550 U.getInfo(FirstIdx).Ctxt = nullptr;
1551 return false;
1552 }
1553
1554 LastSeenCompileUnitID = U.getUniqueID();
1555 LastSeenDIE = Die;
1556 return true;
1557}
1558
1559PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1560 DeclContext &Context, const DWARFDie &DIE, CompileUnit &U,
1561 NonRelocatableStringpool &StringPool, bool InClangModule) {
1562 unsigned Tag = DIE.getTag();
1563
1564 // FIXME: dsymutil-classic compat: We should bail out here if we
1565 // have a specification or an abstract_origin. We will get the
1566 // parent context wrong here.
1567
1568 switch (Tag) {
1569 default:
1570 // By default stop gathering child contexts.
1571 return PointerIntPair<DeclContext *, 1>(nullptr);
1572 case dwarf::DW_TAG_module:
1573 break;
1574 case dwarf::DW_TAG_compile_unit:
1575 return PointerIntPair<DeclContext *, 1>(&Context);
1576 case dwarf::DW_TAG_subprogram:
1577 // Do not unique anything inside CU local functions.
1578 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1579 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1580 !dwarf::toUnsigned(DIE.find(dwarf::DW_AT_external), 0))
1581 return PointerIntPair<DeclContext *, 1>(nullptr);
1582 LLVM_FALLTHROUGH[[clang::fallthrough]];
1583 case dwarf::DW_TAG_member:
1584 case dwarf::DW_TAG_namespace:
1585 case dwarf::DW_TAG_structure_type:
1586 case dwarf::DW_TAG_class_type:
1587 case dwarf::DW_TAG_union_type:
1588 case dwarf::DW_TAG_enumeration_type:
1589 case dwarf::DW_TAG_typedef:
1590 // Artificial things might be ambiguous, because they might be
1591 // created on demand. For example implicitely defined constructors
1592 // are ambiguous because of the way we identify contexts, and they
1593 // won't be generated everytime everywhere.
1594 if (dwarf::toUnsigned(DIE.find(dwarf::DW_AT_artificial), 0))
1595 return PointerIntPair<DeclContext *, 1>(nullptr);
1596 break;
1597 }
1598
1599 const char *Name = DIE.getName(DINameKind::LinkageName);
1600 const char *ShortName = DIE.getName(DINameKind::ShortName);
1601 StringRef NameRef;
1602 StringRef ShortNameRef;
1603 StringRef FileRef;
1604
1605 if (Name)
1606 NameRef = StringPool.internString(Name);
1607 else if (Tag == dwarf::DW_TAG_namespace)
1608 // FIXME: For dsymutil-classic compatibility. I think uniquing
1609 // within anonymous namespaces is wrong. There is no ODR guarantee
1610 // there.
1611 NameRef = StringPool.internString("(anonymous namespace)");
1612
1613 if (ShortName && ShortName != Name)
1614 ShortNameRef = StringPool.internString(ShortName);
1615 else
1616 ShortNameRef = NameRef;
1617
1618 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1619 Tag != dwarf::DW_TAG_union_type &&
1620 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1621 return PointerIntPair<DeclContext *, 1>(nullptr);
1622
1623 unsigned Line = 0;
1624 unsigned ByteSize = UINT32_MAX(4294967295U);
1625
1626 if (!InClangModule) {
1627 // Gather some discriminating data about the DeclContext we will be
1628 // creating: File, line number and byte size. This shouldn't be
1629 // necessary, because the ODR is just about names, but given that we
1630 // do some approximations with overloaded functions and anonymous
1631 // namespaces, use these additional data points to make the process
1632 // safer. This is disabled for clang modules, because forward
1633 // declarations of module-defined types do not have a file and line.
1634 ByteSize = dwarf::toUnsigned(DIE.find(dwarf::DW_AT_byte_size), UINT64_MAX(18446744073709551615UL));
1635 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1636 if (unsigned FileNum = dwarf::toUnsigned(DIE.find(dwarf::DW_AT_decl_file), 0)) {
1637 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1638 &U.getOrigUnit())) {
1639 // FIXME: dsymutil-classic compatibility. I'd rather not
1640 // unique anything in anonymous namespaces, but if we do, then
1641 // verify that the file and line correspond.
1642 if (!Name && Tag == dwarf::DW_TAG_namespace)
1643 FileNum = 1;
1644
1645 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1646 // instead of "" would allow more uniquing, but for now, do
1647 // it this way to match dsymutil-classic.
1648 if (LT->hasFileAtIndex(FileNum)) {
1649 Line = dwarf::toUnsigned(DIE.find(dwarf::DW_AT_decl_line), 0);
1650 // Cache the resolved paths, because calling realpath is expansive.
1651 StringRef ResolvedPath = U.getResolvedPath(FileNum);
1652 if (!ResolvedPath.empty()) {
1653 FileRef = ResolvedPath;
1654 } else {
1655 std::string File;
1656 bool gotFileName =
1657 LT->getFileNameByIndex(FileNum, "",
1658 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1659 File);
1660 (void)gotFileName;
1661 assert(gotFileName && "Must get file name from line table")((gotFileName && "Must get file name from line table"
) ? static_cast<void> (0) : __assert_fail ("gotFileName && \"Must get file name from line table\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 1661, __PRETTY_FUNCTION__))
;
1662#ifdef HAVE_REALPATH1
1663 char RealPath[PATH_MAX4096 + 1];
1664 RealPath[PATH_MAX4096] = 0;
1665 if (::realpath(File.c_str(), RealPath))
1666 File = RealPath;
1667#endif
1668 FileRef = StringPool.internString(File);
1669 U.setResolvedPath(FileNum, FileRef);
1670 }
1671 }
1672 }
1673 }
1674 }
1675 }
1676
1677 if (!Line && NameRef.empty())
1678 return PointerIntPair<DeclContext *, 1>(nullptr);
1679
1680 // We hash NameRef, which is the mangled name, in order to get most
1681 // overloaded functions resolve correctly.
1682 //
1683 // Strictly speaking, hashing the Tag is only necessary for a
1684 // DW_TAG_module, to prevent uniquing of a module and a namespace
1685 // with the same name.
1686 //
1687 // FIXME: dsymutil-classic won't unique the same type presented
1688 // once as a struct and once as a class. Using the Tag in the fully
1689 // qualified name hash to get the same effect.
1690 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1691
1692 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1693 // use the filename.
1694 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1695 Hash = hash_combine(Hash, FileRef);
1696
1697 // Now look if this context already exists.
1698 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1699 auto ContextIter = Contexts.find(&Key);
1700
1701 if (ContextIter == Contexts.end()) {
1702 // The context wasn't found.
1703 bool Inserted;
1704 DeclContext *NewContext =
1705 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1706 Context, DIE, U.getUniqueID());
1707 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1708 assert(Inserted && "Failed to insert DeclContext")((Inserted && "Failed to insert DeclContext") ? static_cast
<void> (0) : __assert_fail ("Inserted && \"Failed to insert DeclContext\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 1708, __PRETTY_FUNCTION__))
;
1709 (void)Inserted;
1710 } else if (Tag != dwarf::DW_TAG_namespace &&
1711 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1712 // The context was found, but it is ambiguous with another context
1713 // in the same file. Mark it invalid.
1714 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1715 }
1716
1717 assert(ContextIter != Contexts.end())((ContextIter != Contexts.end()) ? static_cast<void> (0
) : __assert_fail ("ContextIter != Contexts.end()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 1717, __PRETTY_FUNCTION__))
;
1718 // FIXME: dsymutil-classic compatibility. Union types aren't
1719 // uniques, but their children might be.
1720 if ((Tag == dwarf::DW_TAG_subprogram &&
1721 Context.getTag() != dwarf::DW_TAG_structure_type &&
1722 Context.getTag() != dwarf::DW_TAG_class_type) ||
1723 (Tag == dwarf::DW_TAG_union_type))
1724 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1725
1726 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1727}
1728
1729bool DwarfLinker::DIECloner::getDIENames(const DWARFDie &Die,
1730 AttributesInfo &Info) {
1731 // FIXME: a bit wasteful as the first getName might return the
1732 // short name.
1733 if (!Info.MangledName &&
1734 (Info.MangledName = Die.getName(DINameKind::LinkageName)))
1735 Info.MangledNameOffset =
1736 Linker.StringPool.getStringOffset(Info.MangledName);
1737
1738 if (!Info.Name && (Info.Name = Die.getName(DINameKind::ShortName)))
1739 Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
1740
1741 return Info.Name || Info.MangledName;
1742}
1743
1744/// \brief Report a warning to the user, optionaly including
1745/// information about a specific \p DIE related to the warning.
1746void DwarfLinker::reportWarning(const Twine &Warning,
1747 const DWARFDie *DIE) const {
1748 StringRef Context = "<debug map>";
1749 if (CurrentDebugObject)
1750 Context = CurrentDebugObject->getObjectFilename();
1751 warn(Warning, Context);
1752
1753 if (!Options.Verbose || !DIE)
1754 return;
1755
1756 errs() << " in DIE:\n";
1757 DIE->dump(errs(), 0 /* RecurseDepth */, 6 /* Indent */);
1758}
1759
1760bool DwarfLinker::createStreamer(const Triple &TheTriple,
1761 StringRef OutputFilename) {
1762 if (Options.NoOutput)
1763 return true;
1764
1765 Streamer = llvm::make_unique<DwarfStreamer>();
1766 return Streamer->init(TheTriple, OutputFilename);
1767}
1768
1769/// Recursive helper to build the global DeclContext information and
1770/// gather the child->parent relationships in the original compile unit.
1771///
1772/// \return true when this DIE and all of its children are only
1773/// forward declarations to types defined in external clang modules
1774/// (i.e., forward declarations that are children of a DW_TAG_module).
1775static bool analyzeContextInfo(const DWARFDie &DIE,
1776 unsigned ParentIdx, CompileUnit &CU,
1777 DeclContext *CurrentDeclContext,
1778 NonRelocatableStringpool &StringPool,
1779 DeclContextTree &Contexts,
1780 bool InImportedModule = false) {
1781 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1782 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1783
1784 // Clang imposes an ODR on modules(!) regardless of the language:
1785 // "The module-id should consist of only a single identifier,
1786 // which provides the name of the module being defined. Each
1787 // module shall have a single definition."
1788 //
1789 // This does not extend to the types inside the modules:
1790 // "[I]n C, this implies that if two structs are defined in
1791 // different submodules with the same name, those two types are
1792 // distinct types (but may be compatible types if their
1793 // definitions match)."
1794 //
1795 // We treat non-C++ modules like namespaces for this reason.
1796 if (DIE.getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
1797 dwarf::toString(DIE.find(dwarf::DW_AT_name), "") != CU.getClangModuleName()) {
1798 InImportedModule = true;
1799 }
1800
1801 Info.ParentIdx = ParentIdx;
1802 bool InClangModule = CU.isClangModule() || InImportedModule;
1803 if (CU.hasODR() || InClangModule) {
1804 if (CurrentDeclContext) {
1805 auto PtrInvalidPair = Contexts.getChildDeclContext(
1806 *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
1807 CurrentDeclContext = PtrInvalidPair.getPointer();
1808 Info.Ctxt =
1809 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1810 } else
1811 Info.Ctxt = CurrentDeclContext = nullptr;
1812 }
1813
1814 Info.Prune = InImportedModule;
1815 if (DIE.hasChildren())
1816 for (auto Child: DIE.children())
1817 Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
1818 StringPool, Contexts, InImportedModule);
1819
1820 // Prune this DIE if it is either a forward declaration inside a
1821 // DW_TAG_module or a DW_TAG_module that contains nothing but
1822 // forward declarations.
1823 Info.Prune &=
1824 (DIE.getTag() == dwarf::DW_TAG_module) ||
1825 dwarf::toUnsigned(DIE.find(dwarf::DW_AT_declaration), 0);
1826
1827 // Don't prune it if there is no definition for the DIE.
1828 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
1829
1830 return Info.Prune;
1831}
1832
1833static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1834 switch (Tag) {
1835 default:
1836 return false;
1837 case dwarf::DW_TAG_subprogram:
1838 case dwarf::DW_TAG_lexical_block:
1839 case dwarf::DW_TAG_subroutine_type:
1840 case dwarf::DW_TAG_structure_type:
1841 case dwarf::DW_TAG_class_type:
1842 case dwarf::DW_TAG_union_type:
1843 return true;
1844 }
1845 llvm_unreachable("Invalid Tag")::llvm::llvm_unreachable_internal("Invalid Tag", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 1845)
;
1846}
1847
1848void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1849 // Iterate over the debug map entries and put all the ones that are
1850 // functions (because they have a size) into the Ranges map. This
1851 // map is very similar to the FunctionRanges that are stored in each
1852 // unit, with 2 notable differences:
1853 // - obviously this one is global, while the other ones are per-unit.
1854 // - this one contains not only the functions described in the DIE
1855 // tree, but also the ones that are only in the debug map.
1856 // The latter information is required to reproduce dsymutil's logic
1857 // while linking line tables. The cases where this information
1858 // matters look like bugs that need to be investigated, but for now
1859 // we need to reproduce dsymutil's behavior.
1860 // FIXME: Once we understood exactly if that information is needed,
1861 // maybe totally remove this (or try to use it to do a real
1862 // -gline-tables-only on Darwin.
1863 for (const auto &Entry : Obj.symbols()) {
1864 const auto &Mapping = Entry.getValue();
1865 if (Mapping.Size && Mapping.ObjectAddress)
1866 Ranges[*Mapping.ObjectAddress] = std::make_pair(
1867 *Mapping.ObjectAddress + Mapping.Size,
1868 int64_t(Mapping.BinaryAddress) - *Mapping.ObjectAddress);
1869 }
1870}
1871
1872void DwarfLinker::endDebugObject() {
1873 Units.clear();
1874 Ranges.clear();
1875
1876 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1877 (*I)->~DIEBlock();
1878 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1879 (*I)->~DIELoc();
1880
1881 DIEBlocks.clear();
1882 DIELocs.clear();
1883 DIEAlloc.Reset();
1884}
1885
1886static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
1887 switch (Arch) {
1888 case Triple::x86:
1889 return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
1890 RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
1891 case Triple::x86_64:
1892 return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
1893 case Triple::arm:
1894 case Triple::thumb:
1895 return RelocType == MachO::ARM_RELOC_SECTDIFF ||
1896 RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1897 RelocType == MachO::ARM_RELOC_HALF ||
1898 RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
1899 case Triple::aarch64:
1900 return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
1901 default:
1902 return false;
1903 }
1904}
1905
1906/// \brief Iterate over the relocations of the given \p Section and
1907/// store the ones that correspond to debug map entries into the
1908/// ValidRelocs array.
1909void DwarfLinker::RelocationManager::
1910findValidRelocsMachO(const object::SectionRef &Section,
1911 const object::MachOObjectFile &Obj,
1912 const DebugMapObject &DMO) {
1913 StringRef Contents;
1914 Section.getContents(Contents);
1915 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1916 bool SkipNext = false;
1917
1918 for (const object::RelocationRef &Reloc : Section.relocations()) {
1919 if (SkipNext) {
1920 SkipNext = false;
1921 continue;
1922 }
1923
1924 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1925 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1926
1927 if (isMachOPairedReloc(Obj.getAnyRelocationType(MachOReloc),
1928 Obj.getArch())) {
1929 SkipNext = true;
1930 Linker.reportWarning(" unsupported relocation in debug_info section.");
1931 continue;
1932 }
1933
1934 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1935 uint64_t Offset64 = Reloc.getOffset();
1936 if ((RelocSize != 4 && RelocSize != 8)) {
1937 Linker.reportWarning(" unsupported relocation in debug_info section.");
1938 continue;
1939 }
1940 uint32_t Offset = Offset64;
1941 // Mach-o uses REL relocations, the addend is at the relocation offset.
1942 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1943 uint64_t SymAddress;
1944 int64_t SymOffset;
1945
1946 if (Obj.isRelocationScattered(MachOReloc)) {
1947 // The address of the base symbol for scattered relocations is
1948 // stored in the reloc itself. The actual addend will store the
1949 // base address plus the offset.
1950 SymAddress = Obj.getScatteredRelocationValue(MachOReloc);
1951 SymOffset = int64_t(Addend) - SymAddress;
1952 } else {
1953 SymAddress = Addend;
1954 SymOffset = 0;
1955 }
1956
1957 auto Sym = Reloc.getSymbol();
1958 if (Sym != Obj.symbol_end()) {
1959 Expected<StringRef> SymbolName = Sym->getName();
1960 if (!SymbolName) {
1961 consumeError(SymbolName.takeError());
1962 Linker.reportWarning("error getting relocation symbol name.");
1963 continue;
1964 }
1965 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
1966 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1967 } else if (const auto *Mapping = DMO.lookupObjectAddress(SymAddress)) {
1968 // Do not store the addend. The addend was the address of the
1969 // symbol in the object file, the address in the binary that is
1970 // stored in the debug map doesn't need to be offseted.
1971 ValidRelocs.emplace_back(Offset64, RelocSize, SymOffset, Mapping);
1972 }
1973 }
1974}
1975
1976/// \brief Dispatch the valid relocation finding logic to the
1977/// appropriate handler depending on the object file format.
1978bool DwarfLinker::RelocationManager::findValidRelocs(
1979 const object::SectionRef &Section, const object::ObjectFile &Obj,
1980 const DebugMapObject &DMO) {
1981 // Dispatch to the right handler depending on the file type.
1982 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1983 findValidRelocsMachO(Section, *MachOObj, DMO);
1984 else
1985 Linker.reportWarning(Twine("unsupported object file type: ") +
1986 Obj.getFileName());
1987
1988 if (ValidRelocs.empty())
1989 return false;
1990
1991 // Sort the relocations by offset. We will walk the DIEs linearly in
1992 // the file, this allows us to just keep an index in the relocation
1993 // array that we advance during our walk, rather than resorting to
1994 // some associative container. See DwarfLinker::NextValidReloc.
1995 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1996 return true;
1997}
1998
1999/// \brief Look for relocations in the debug_info section that match
2000/// entries in the debug map. These relocations will drive the Dwarf
2001/// link by indicating which DIEs refer to symbols present in the
2002/// linked binary.
2003/// \returns wether there are any valid relocations in the debug info.
2004bool DwarfLinker::RelocationManager::
2005findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
2006 const DebugMapObject &DMO) {
2007 // Find the debug_info section.
2008 for (const object::SectionRef &Section : Obj.sections()) {
2009 StringRef SectionName;
2010 Section.getName(SectionName);
2011 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
2012 if (SectionName != "debug_info")
2013 continue;
2014 return findValidRelocs(Section, Obj, DMO);
2015 }
2016 return false;
2017}
2018
2019/// \brief Checks that there is a relocation against an actual debug
2020/// map entry between \p StartOffset and \p NextOffset.
2021///
2022/// This function must be called with offsets in strictly ascending
2023/// order because it never looks back at relocations it already 'went past'.
2024/// \returns true and sets Info.InDebugMap if it is the case.
2025bool DwarfLinker::RelocationManager::
2026hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
2027 CompileUnit::DIEInfo &Info) {
2028 assert(NextValidReloc == 0 ||((NextValidReloc == 0 || StartOffset > ValidRelocs[NextValidReloc
- 1].Offset) ? static_cast<void> (0) : __assert_fail (
"NextValidReloc == 0 || StartOffset > ValidRelocs[NextValidReloc - 1].Offset"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2029, __PRETTY_FUNCTION__))
2029 StartOffset > ValidRelocs[NextValidReloc - 1].Offset)((NextValidReloc == 0 || StartOffset > ValidRelocs[NextValidReloc
- 1].Offset) ? static_cast<void> (0) : __assert_fail (
"NextValidReloc == 0 || StartOffset > ValidRelocs[NextValidReloc - 1].Offset"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2029, __PRETTY_FUNCTION__))
;
2030 if (NextValidReloc >= ValidRelocs.size())
2031 return false;
2032
2033 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
2034
2035 // We might need to skip some relocs that we didn't consider. For
2036 // example the high_pc of a discarded DIE might contain a reloc that
2037 // is in the list because it actually corresponds to the start of a
2038 // function that is in the debug map.
2039 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
2040 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
2041
2042 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
2043 return false;
2044
2045 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2046 const auto &Mapping = ValidReloc.Mapping->getValue();
2047 uint64_t ObjectAddress =
2048 Mapping.ObjectAddress ? uint64_t(*Mapping.ObjectAddress) : UINT64_MAX(18446744073709551615UL);
2049 if (Linker.Options.Verbose)
2050 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
2051 << " " << format("\t%016" PRIx64"l" "x" " => %016" PRIx64"l" "x", ObjectAddress,
2052 uint64_t(Mapping.BinaryAddress));
2053
2054 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend;
2055 if (Mapping.ObjectAddress)
2056 Info.AddrAdjust -= ObjectAddress;
2057 Info.InDebugMap = true;
2058 return true;
2059}
2060
2061/// \brief Get the starting and ending (exclusive) offset for the
2062/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
2063/// supposed to point to the position of the first attribute described
2064/// by \p Abbrev.
2065/// \return [StartOffset, EndOffset) as a pair.
2066static std::pair<uint32_t, uint32_t>
2067getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
2068 unsigned Offset, const DWARFUnit &Unit) {
2069 DataExtractor Data = Unit.getDebugInfoExtractor();
2070
2071 for (unsigned i = 0; i < Idx; ++i)
2072 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
2073
2074 uint32_t End = Offset;
2075 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
2076
2077 return std::make_pair(Offset, End);
2078}
2079
2080/// \brief Check if a variable describing DIE should be kept.
2081/// \returns updated TraversalFlags.
2082unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
2083 const DWARFDie &DIE,
2084 CompileUnit &Unit,
2085 CompileUnit::DIEInfo &MyInfo,
2086 unsigned Flags) {
2087 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2088
2089 // Global variables with constant value can always be kept.
2090 if (!(Flags & TF_InFunctionScope) &&
2091 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
2092 MyInfo.InDebugMap = true;
2093 return Flags | TF_Keep;
2094 }
2095
2096 Optional<uint32_t> LocationIdx =
2097 Abbrev->findAttributeIndex(dwarf::DW_AT_location);
2098 if (!LocationIdx)
2099 return Flags;
2100
2101 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2102 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2103 uint32_t LocationOffset, LocationEndOffset;
2104 std::tie(LocationOffset, LocationEndOffset) =
2105 getAttributeOffsets(Abbrev, *LocationIdx, Offset, OrigUnit);
2106
2107 // See if there is a relocation to a valid debug map entry inside
2108 // this variable's location. The order is important here. We want to
2109 // always check in the variable has a valid relocation, so that the
2110 // DIEInfo is filled. However, we don't want a static variable in a
2111 // function to force us to keep the enclosing function.
2112 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
2113 (Flags & TF_InFunctionScope))
2114 return Flags;
2115
2116 if (Options.Verbose)
2117 DIE.dump(outs(), 0, 8 /* Indent */);
2118
2119 return Flags | TF_Keep;
2120}
2121
2122/// \brief Check if a function describing DIE should be kept.
2123/// \returns updated TraversalFlags.
2124unsigned DwarfLinker::shouldKeepSubprogramDIE(
2125 RelocationManager &RelocMgr,
2126 const DWARFDie &DIE, CompileUnit &Unit,
2127 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2128 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2129
2130 Flags |= TF_InFunctionScope;
2131
2132 Optional<uint32_t> LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2133 if (!LowPcIdx)
2134 return Flags;
2135
2136 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2137 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2138 uint32_t LowPcOffset, LowPcEndOffset;
2139 std::tie(LowPcOffset, LowPcEndOffset) =
2140 getAttributeOffsets(Abbrev, *LowPcIdx, Offset, OrigUnit);
2141
2142 auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
2143 assert(LowPc.hasValue() && "low_pc attribute is not an address.")((LowPc.hasValue() && "low_pc attribute is not an address."
) ? static_cast<void> (0) : __assert_fail ("LowPc.hasValue() && \"low_pc attribute is not an address.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2143, __PRETTY_FUNCTION__))
;
2144 if (!LowPc ||
2145 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
2146 return Flags;
2147
2148 if (Options.Verbose)
2149 DIE.dump(outs(), 0, 8 /* Indent */);
2150
2151 Flags |= TF_Keep;
2152
2153 Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
2154 if (!HighPc) {
2155 reportWarning("Function without high_pc. Range will be discarded.\n",
2156 &DIE);
2157 return Flags;
2158 }
2159
2160 // Replace the debug map range with a more accurate one.
2161 Ranges[*LowPc] = std::make_pair(*HighPc, MyInfo.AddrAdjust);
2162 Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
2163 return Flags;
2164}
2165
2166/// \brief Check if a DIE should be kept.
2167/// \returns updated TraversalFlags.
2168unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
2169 const DWARFDie &DIE,
2170 CompileUnit &Unit,
2171 CompileUnit::DIEInfo &MyInfo,
2172 unsigned Flags) {
2173 switch (DIE.getTag()) {
2174 case dwarf::DW_TAG_constant:
2175 case dwarf::DW_TAG_variable:
2176 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
2177 case dwarf::DW_TAG_subprogram:
2178 return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
2179 case dwarf::DW_TAG_module:
2180 case dwarf::DW_TAG_imported_module:
2181 case dwarf::DW_TAG_imported_declaration:
2182 case dwarf::DW_TAG_imported_unit:
2183 // We always want to keep these.
2184 return Flags | TF_Keep;
2185 default:
2186 break;
2187 }
2188
2189 return Flags;
2190}
2191
2192/// \brief Mark the passed DIE as well as all the ones it depends on
2193/// as kept.
2194///
2195/// This function is called by lookForDIEsToKeep on DIEs that are
2196/// newly discovered to be needed in the link. It recursively calls
2197/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2198/// TraversalFlags to inform it that it's not doing the primary DIE
2199/// tree walk.
2200void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
2201 const DWARFDie &Die,
2202 CompileUnit::DIEInfo &MyInfo,
2203 const DebugMapObject &DMO,
2204 CompileUnit &CU, bool UseODR) {
2205 DWARFUnit &Unit = CU.getOrigUnit();
2206 MyInfo.Keep = true;
2207
2208 // First mark all the parent chain as kept.
2209 unsigned AncestorIdx = MyInfo.ParentIdx;
2210 while (!CU.getInfo(AncestorIdx).Keep) {
2211 unsigned ODRFlag = UseODR ? TF_ODR : 0;
2212 lookForDIEsToKeep(RelocMgr, Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
2213 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
2214 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2215 }
2216
2217 // Then we need to mark all the DIEs referenced by this DIE's
2218 // attributes as kept.
2219 DataExtractor Data = Unit.getDebugInfoExtractor();
2220 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2221 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
2222
2223 // Mark all DIEs referenced through atttributes as kept.
2224 for (const auto &AttrSpec : Abbrev->attributes()) {
2225 DWARFFormValue Val(AttrSpec.Form);
2226
2227 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2228 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2229 continue;
2230 }
2231
2232 Val.extractValue(Data, &Offset, &Unit);
2233 CompileUnit *ReferencedCU;
2234 if (auto RefDIE =
2235 resolveDIEReference(*this, Units, Val, Unit, Die, ReferencedCU)) {
2236 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2237 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2238 // If the referenced DIE has a DeclContext that has already been
2239 // emitted, then do not keep the one in this CU. We'll link to
2240 // the canonical DIE in cloneDieReferenceAttribute.
2241 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2242 // be necessary and could be advantageously replaced by
2243 // ReferencedCU->hasODR() && CU.hasODR().
2244 // FIXME: compatibility with dsymutil-classic. There is no
2245 // reason not to unique ref_addr references.
2246 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2247 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2248 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2249 continue;
2250
2251 // Keep a module forward declaration if there is no definition.
2252 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
2253 Info.Ctxt->getCanonicalDIEOffset()))
2254 Info.Prune = false;
2255
2256 unsigned ODRFlag = UseODR ? TF_ODR : 0;
2257 lookForDIEsToKeep(RelocMgr, RefDIE, DMO, *ReferencedCU,
2258 TF_Keep | TF_DependencyWalk | ODRFlag);
2259 }
2260 }
2261}
2262
2263/// \brief Recursively walk the \p DIE tree and look for DIEs to
2264/// keep. Store that information in \p CU's DIEInfo.
2265///
2266/// This function is the entry point of the DIE selection
2267/// algorithm. It is expected to walk the DIE tree in file order and
2268/// (though the mediation of its helper) call hasValidRelocation() on
2269/// each DIE that might be a 'root DIE' (See DwarfLinker class
2270/// comment).
2271/// While walking the dependencies of root DIEs, this function is
2272/// also called, but during these dependency walks the file order is
2273/// not respected. The TF_DependencyWalk flag tells us which kind of
2274/// traversal we are currently doing.
2275void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
2276 const DWARFDie &Die,
2277 const DebugMapObject &DMO, CompileUnit &CU,
2278 unsigned Flags) {
2279 unsigned Idx = CU.getOrigUnit().getDIEIndex(Die);
2280 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2281 bool AlreadyKept = MyInfo.Keep;
2282 if (MyInfo.Prune)
2283 return;
2284
2285 // If the Keep flag is set, we are marking a required DIE's
2286 // dependencies. If our target is already marked as kept, we're all
2287 // set.
2288 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2289 return;
2290
2291 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
2292 // because it would screw up the relocation finding logic.
2293 if (!(Flags & TF_DependencyWalk))
2294 Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
2295
2296 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
2297 if (!AlreadyKept && (Flags & TF_Keep)) {
2298 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2299 keepDIEAndDependencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
2300 }
2301 // The TF_ParentWalk flag tells us that we are currently walking up
2302 // the parent chain of a required DIE, and we don't want to mark all
2303 // the children of the parents as kept (consider for example a
2304 // DW_TAG_namespace node in the parent chain). There are however a
2305 // set of DIE types for which we want to ignore that directive and still
2306 // walk their children.
2307 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
2308 Flags &= ~TF_ParentWalk;
2309
2310 if (!Die.hasChildren() || (Flags & TF_ParentWalk))
2311 return;
2312
2313 for (auto Child: Die.children())
2314 lookForDIEsToKeep(RelocMgr, Child, DMO, CU, Flags);
2315}
2316
2317/// \brief Assign an abbreviation numer to \p Abbrev.
2318///
2319/// Our DIEs get freed after every DebugMapObject has been processed,
2320/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2321/// the instances hold by the DIEs. When we encounter an abbreviation
2322/// that we don't know, we create a permanent copy of it.
2323void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2324 // Check the set for priors.
2325 FoldingSetNodeID ID;
2326 Abbrev.Profile(ID);
2327 void *InsertToken;
2328 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2329
2330 // If it's newly added.
2331 if (InSet) {
2332 // Assign existing abbreviation number.
2333 Abbrev.setNumber(InSet->getNumber());
2334 } else {
2335 // Add to abbreviation list.
2336 Abbreviations.push_back(
2337 llvm::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
2338 for (const auto &Attr : Abbrev.getData())
2339 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2340 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
2341 // Assign the unique abbreviation number.
2342 Abbrev.setNumber(Abbreviations.size());
2343 Abbreviations.back()->setNumber(Abbreviations.size());
2344 }
2345}
2346
2347unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2348 AttributeSpec AttrSpec,
2349 const DWARFFormValue &Val,
2350 const DWARFUnit &U) {
2351 // Switch everything to out of line strings.
2352 const char *String = *Val.getAsCString();
2353 unsigned Offset = Linker.StringPool.getStringOffset(String);
2354 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
2355 DIEInteger(Offset));
2356 return 4;
2357}
2358
2359unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
2360 DIE &Die, const DWARFDie &InputDIE,
2361 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
2362 CompileUnit &Unit) {
2363 const DWARFUnit &U = Unit.getOrigUnit();
2364 uint32_t Ref = *Val.getAsReference();
2365 DIE *NewRefDie = nullptr;
2366 CompileUnit *RefUnit = nullptr;
2367 DeclContext *Ctxt = nullptr;
2368
2369 DWARFDie RefDie = resolveDIEReference(Linker, CompileUnits, Val, U, InputDIE,
2370 RefUnit);
2371
2372 // If the referenced DIE is not found, drop the attribute.
2373 if (!RefDie)
2374 return 0;
2375
2376 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2377 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
2378
2379 // If we already have emitted an equivalent DeclContext, just point
2380 // at it.
2381 if (isODRAttribute(AttrSpec.Attr)) {
2382 Ctxt = RefInfo.Ctxt;
2383 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2384 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2385 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2386 dwarf::DW_FORM_ref_addr, Attr);
2387 return U.getRefAddrByteSize();
2388 }
2389 }
2390
2391 if (!RefInfo.Clone) {
2392 assert(Ref > InputDIE.getOffset())((Ref > InputDIE.getOffset()) ? static_cast<void> (0
) : __assert_fail ("Ref > InputDIE.getOffset()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2392, __PRETTY_FUNCTION__))
;
2393 // We haven't cloned this DIE yet. Just create an empty one and
2394 // store it. It'll get really cloned when we process it.
2395 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
2396 }
2397 NewRefDie = RefInfo.Clone;
2398
2399 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2400 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
2401 // We cannot currently rely on a DIEEntry to emit ref_addr
2402 // references, because the implementation calls back to DwarfDebug
2403 // to find the unit offset. (We don't have a DwarfDebug)
2404 // FIXME: we should be able to design DIEEntry reliance on
2405 // DwarfDebug away.
2406 uint64_t Attr;
2407 if (Ref < InputDIE.getOffset()) {
2408 // We must have already cloned that DIE.
2409 uint32_t NewRefOffset =
2410 RefUnit->getStartOffset() + NewRefDie->getOffset();
2411 Attr = NewRefOffset;
2412 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2413 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
2414 } else {
2415 // A forward reference. Note and fixup later.
2416 Attr = 0xBADDEF;
2417 Unit.noteForwardReference(
2418 NewRefDie, RefUnit, Ctxt,
2419 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2420 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
2421 }
2422 return U.getRefAddrByteSize();
2423 }
2424
2425 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2426 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
2427 return AttrSize;
2428}
2429
2430unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2431 AttributeSpec AttrSpec,
2432 const DWARFFormValue &Val,
2433 unsigned AttrSize) {
2434 DIEValueList *Attr;
2435 DIEValue Value;
2436 DIELoc *Loc = nullptr;
2437 DIEBlock *Block = nullptr;
1
'Block' initialized to a null pointer value
2438 // Just copy the block data over.
2439 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
2
Assuming the condition is true
3
Taking true branch
2440 Loc = new (DIEAlloc) DIELoc;
2441 Linker.DIELocs.push_back(Loc);
2442 } else {
2443 Block = new (DIEAlloc) DIEBlock;
2444 Linker.DIEBlocks.push_back(Block);
2445 }
2446 Attr = Loc ? static_cast<DIEValueList *>(Loc)
4
Assuming 'Loc' is null
5
'?' condition is false
2447 : static_cast<DIEValueList *>(Block);
2448
2449 if (Loc)
6
Taking false branch
2450 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2451 dwarf::Form(AttrSpec.Form), Loc);
2452 else
2453 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2454 dwarf::Form(AttrSpec.Form), Block);
2455 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2456 for (auto Byte : Bytes)
7
Assuming '__begin' is equal to '__end'
2457 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2458 dwarf::DW_FORM_data1, DIEInteger(Byte));
2459 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2460 // the DIE class, this if could be replaced by
2461 // Attr->setSize(Bytes.size()).
2462 if (Linker.Streamer) {
8
Taking true branch
2463 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
2464 if (Loc)
9
Taking false branch
2465 Loc->ComputeSize(AsmPrinter);
2466 else
2467 Block->ComputeSize(AsmPrinter);
10
Called C++ object pointer is null
2468 }
2469 Die.addValue(DIEAlloc, Value);
2470 return AttrSize;
2471}
2472
2473unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2474 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2475 const CompileUnit &Unit, AttributesInfo &Info) {
2476 uint64_t Addr = *Val.getAsAddress();
2477 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2478 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2479 Die.getTag() == dwarf::DW_TAG_lexical_block)
2480 // The low_pc of a block or inline subroutine might get
2481 // relocated because it happens to match the low_pc of the
2482 // enclosing subprogram. To prevent issues with that, always use
2483 // the low_pc from the input DIE if relocations have been applied.
2484 Addr = (Info.OrigLowPc != UINT64_MAX(18446744073709551615UL) ? Info.OrigLowPc : Addr) +
2485 Info.PCOffset;
2486 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2487 Addr = Unit.getLowPc();
2488 if (Addr == UINT64_MAX(18446744073709551615UL))
2489 return 0;
2490 }
2491 Info.HasLowPc = true;
2492 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
2493 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2494 if (uint64_t HighPc = Unit.getHighPc())
2495 Addr = HighPc;
2496 else
2497 return 0;
2498 } else
2499 // If we have a high_pc recorded for the input DIE, use
2500 // it. Otherwise (when no relocations where applied) just use the
2501 // one we just decoded.
2502 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
2503 }
2504
2505 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
2506 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
2507 return Unit.getOrigUnit().getAddressByteSize();
2508}
2509
2510unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
2511 DIE &Die, const DWARFDie &InputDIE, CompileUnit &Unit,
2512 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
2513 AttributesInfo &Info) {
2514 uint64_t Value;
2515 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2516 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2517 if (Unit.getLowPc() == -1ULL)
2518 return 0;
2519 // Dwarf >= 4 high_pc is an size, not an address.
2520 Value = Unit.getHighPc() - Unit.getLowPc();
2521 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
2522 Value = *Val.getAsSectionOffset();
2523 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2524 Value = *Val.getAsSignedConstant();
2525 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2526 Value = *OptionalValue;
2527 else {
2528 Linker.reportWarning(
2529 "Unsupported scalar attribute form. Dropping attribute.",
2530 &InputDIE);
2531 return 0;
2532 }
2533 PatchLocation Patch =
2534 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2535 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
2536 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
2537 Unit.noteRangeAttribute(Die, Patch);
2538
2539 // A more generic way to check for location attributes would be
2540 // nice, but it's very unlikely that any other attribute needs a
2541 // location list.
2542 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2543 AttrSpec.Attr == dwarf::DW_AT_frame_base)
2544 Unit.noteLocationAttribute(Patch, Info.PCOffset);
2545 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2546 Info.IsDeclaration = true;
2547
2548 return AttrSize;
2549}
2550
2551/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2552/// value \p Val, and add it to \p Die.
2553/// \returns the size of the cloned attribute.
2554unsigned DwarfLinker::DIECloner::cloneAttribute(
2555 DIE &Die, const DWARFDie &InputDIE, CompileUnit &Unit,
2556 const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2557 AttributesInfo &Info) {
2558 const DWARFUnit &U = Unit.getOrigUnit();
2559
2560 switch (AttrSpec.Form) {
2561 case dwarf::DW_FORM_strp:
2562 case dwarf::DW_FORM_string:
2563 return cloneStringAttribute(Die, AttrSpec, Val, U);
2564 case dwarf::DW_FORM_ref_addr:
2565 case dwarf::DW_FORM_ref1:
2566 case dwarf::DW_FORM_ref2:
2567 case dwarf::DW_FORM_ref4:
2568 case dwarf::DW_FORM_ref8:
2569 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
2570 Unit);
2571 case dwarf::DW_FORM_block:
2572 case dwarf::DW_FORM_block1:
2573 case dwarf::DW_FORM_block2:
2574 case dwarf::DW_FORM_block4:
2575 case dwarf::DW_FORM_exprloc:
2576 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2577 case dwarf::DW_FORM_addr:
2578 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
2579 case dwarf::DW_FORM_data1:
2580 case dwarf::DW_FORM_data2:
2581 case dwarf::DW_FORM_data4:
2582 case dwarf::DW_FORM_data8:
2583 case dwarf::DW_FORM_udata:
2584 case dwarf::DW_FORM_sdata:
2585 case dwarf::DW_FORM_sec_offset:
2586 case dwarf::DW_FORM_flag:
2587 case dwarf::DW_FORM_flag_present:
2588 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2589 Info);
2590 default:
2591 Linker.reportWarning(
2592 "Unsupported attribute form in cloneAttribute. Dropping.", &InputDIE);
2593 }
2594
2595 return 0;
2596}
2597
2598/// \brief Apply the valid relocations found by findValidRelocs() to
2599/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2600/// in the debug_info section.
2601///
2602/// Like for findValidRelocs(), this function must be called with
2603/// monotonic \p BaseOffset values.
2604///
2605/// \returns wether any reloc has been applied.
2606bool DwarfLinker::RelocationManager::
2607applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2608 bool isLittleEndian) {
2609 assert((NextValidReloc == 0 ||(((NextValidReloc == 0 || BaseOffset > ValidRelocs[NextValidReloc
- 1].Offset) && "BaseOffset should only be increasing."
) ? static_cast<void> (0) : __assert_fail ("(NextValidReloc == 0 || BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) && \"BaseOffset should only be increasing.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2611, __PRETTY_FUNCTION__))
2610 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&(((NextValidReloc == 0 || BaseOffset > ValidRelocs[NextValidReloc
- 1].Offset) && "BaseOffset should only be increasing."
) ? static_cast<void> (0) : __assert_fail ("(NextValidReloc == 0 || BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) && \"BaseOffset should only be increasing.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2611, __PRETTY_FUNCTION__))
2611 "BaseOffset should only be increasing.")(((NextValidReloc == 0 || BaseOffset > ValidRelocs[NextValidReloc
- 1].Offset) && "BaseOffset should only be increasing."
) ? static_cast<void> (0) : __assert_fail ("(NextValidReloc == 0 || BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) && \"BaseOffset should only be increasing.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2611, __PRETTY_FUNCTION__))
;
2612 if (NextValidReloc >= ValidRelocs.size())
2613 return false;
2614
2615 // Skip relocs that haven't been applied.
2616 while (NextValidReloc < ValidRelocs.size() &&
2617 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2618 ++NextValidReloc;
2619
2620 bool Applied = false;
2621 uint64_t EndOffset = BaseOffset + Data.size();
2622 while (NextValidReloc < ValidRelocs.size() &&
2623 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2624 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2625 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2626 assert(ValidReloc.Offset - BaseOffset < Data.size())((ValidReloc.Offset - BaseOffset < Data.size()) ? static_cast
<void> (0) : __assert_fail ("ValidReloc.Offset - BaseOffset < Data.size()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2626, __PRETTY_FUNCTION__))
;
2627 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size())((ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data
.size()) ? static_cast<void> (0) : __assert_fail ("ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2627, __PRETTY_FUNCTION__))
;
2628 char Buf[8];
2629 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2630 Value += ValidReloc.Addend;
2631 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2632 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2633 Buf[i] = uint8_t(Value >> (Index * 8));
2634 }
2635 assert(ValidReloc.Size <= sizeof(Buf))((ValidReloc.Size <= sizeof(Buf)) ? static_cast<void>
(0) : __assert_fail ("ValidReloc.Size <= sizeof(Buf)", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2635, __PRETTY_FUNCTION__))
;
2636 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2637 Applied = true;
2638 }
2639
2640 return Applied;
2641}
2642
2643static bool isTypeTag(uint16_t Tag) {
2644 switch (Tag) {
2645 case dwarf::DW_TAG_array_type:
2646 case dwarf::DW_TAG_class_type:
2647 case dwarf::DW_TAG_enumeration_type:
2648 case dwarf::DW_TAG_pointer_type:
2649 case dwarf::DW_TAG_reference_type:
2650 case dwarf::DW_TAG_string_type:
2651 case dwarf::DW_TAG_structure_type:
2652 case dwarf::DW_TAG_subroutine_type:
2653 case dwarf::DW_TAG_typedef:
2654 case dwarf::DW_TAG_union_type:
2655 case dwarf::DW_TAG_ptr_to_member_type:
2656 case dwarf::DW_TAG_set_type:
2657 case dwarf::DW_TAG_subrange_type:
2658 case dwarf::DW_TAG_base_type:
2659 case dwarf::DW_TAG_const_type:
2660 case dwarf::DW_TAG_constant:
2661 case dwarf::DW_TAG_file_type:
2662 case dwarf::DW_TAG_namelist:
2663 case dwarf::DW_TAG_packed_type:
2664 case dwarf::DW_TAG_volatile_type:
2665 case dwarf::DW_TAG_restrict_type:
2666 case dwarf::DW_TAG_atomic_type:
2667 case dwarf::DW_TAG_interface_type:
2668 case dwarf::DW_TAG_unspecified_type:
2669 case dwarf::DW_TAG_shared_type:
2670 return true;
2671 default:
2672 break;
2673 }
2674 return false;
2675}
2676
2677static bool
2678shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2679 uint16_t Tag, bool InDebugMap, bool SkipPC,
2680 bool InFunctionScope) {
2681 switch (AttrSpec.Attr) {
2682 default:
2683 return false;
2684 case dwarf::DW_AT_low_pc:
2685 case dwarf::DW_AT_high_pc:
2686 case dwarf::DW_AT_ranges:
2687 return SkipPC;
2688 case dwarf::DW_AT_location:
2689 case dwarf::DW_AT_frame_base:
2690 // FIXME: for some reason dsymutil-classic keeps the location
2691 // attributes when they are of block type (ie. not location
2692 // lists). This is totally wrong for globals where we will keep a
2693 // wrong address. It is mostly harmless for locals, but there is
2694 // no point in keeping these anyway when the function wasn't linked.
2695 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2696 !InDebugMap)) &&
2697 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2698 }
2699}
2700
2701DIE *DwarfLinker::DIECloner::cloneDIE(
2702 const DWARFDie &InputDIE, CompileUnit &Unit,
2703 int64_t PCOffset, uint32_t OutOffset, unsigned Flags, DIE *Die) {
2704 DWARFUnit &U = Unit.getOrigUnit();
2705 unsigned Idx = U.getDIEIndex(InputDIE);
2706 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2707
2708 // Should the DIE appear in the output?
2709 if (!Unit.getInfo(Idx).Keep)
2710 return nullptr;
2711
2712 uint32_t Offset = InputDIE.getOffset();
2713 assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE")((!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE"
) ? static_cast<void> (0) : __assert_fail ("!(Die && Info.Clone) && \"Can't supply a DIE and a cloned DIE\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2713, __PRETTY_FUNCTION__))
;
2714 if (!Die) {
2715 // The DIE might have been already created by a forward reference
2716 // (see cloneDieReferenceAttribute()).
2717 if (!Info.Clone)
2718 Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
2719 Die = Info.Clone;
2720 }
2721
2722 assert(Die->getTag() == InputDIE.getTag())((Die->getTag() == InputDIE.getTag()) ? static_cast<void
> (0) : __assert_fail ("Die->getTag() == InputDIE.getTag()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2722, __PRETTY_FUNCTION__))
;
2723 Die->setOffset(OutOffset);
2724 if ((Unit.hasODR() || Unit.isClangModule()) &&
2725 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2726 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2727 !Info.Ctxt->getCanonicalDIEOffset()) {
2728 // We are about to emit a DIE that is the root of its own valid
2729 // DeclContext tree. Make the current offset the canonical offset
2730 // for this context.
2731 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2732 }
2733
2734 // Extract and clone every attribute.
2735 DataExtractor Data = U.getDebugInfoExtractor();
2736 // Point to the next DIE (generally there is always at least a NULL
2737 // entry after the current one). If this is a lone
2738 // DW_TAG_compile_unit without any children, point to the next unit.
2739 uint32_t NextOffset =
2740 (Idx + 1 < U.getNumDIEs())
2741 ? U.getDIEAtIndex(Idx + 1).getOffset()
2742 : U.getNextUnitOffset();
2743 AttributesInfo AttrInfo;
2744
2745 // We could copy the data only if we need to aply a relocation to
2746 // it. After testing, it seems there is no performance downside to
2747 // doing the copy unconditionally, and it makes the code simpler.
2748 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2749 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2750 // Modify the copy with relocated addresses.
2751 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2752 // If we applied relocations, we store the value of high_pc that was
2753 // potentially stored in the input DIE. If high_pc is an address
2754 // (Dwarf version == 2), then it might have been relocated to a
2755 // totally unrelated value (because the end address in the object
2756 // file might be start address of another function which got moved
2757 // independantly by the linker). The computation of the actual
2758 // high_pc value is done in cloneAddressAttribute().
2759 AttrInfo.OrigHighPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_high_pc), 0);
2760 // Also store the low_pc. It might get relocated in an
2761 // inline_subprogram that happens at the beginning of its
2762 // inlining function.
2763 AttrInfo.OrigLowPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc), UINT64_MAX(18446744073709551615UL));
2764 }
2765
2766 // Reset the Offset to 0 as we will be working on the local copy of
2767 // the data.
2768 Offset = 0;
2769
2770 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2771 Offset += getULEB128Size(Abbrev->getCode());
2772
2773 // We are entering a subprogram. Get and propagate the PCOffset.
2774 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2775 PCOffset = Info.AddrAdjust;
2776 AttrInfo.PCOffset = PCOffset;
2777
2778 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2779 Flags |= TF_InFunctionScope;
2780 if (!Info.InDebugMap)
2781 Flags |= TF_SkipPC;
2782 }
2783
2784 bool Copied = false;
2785 for (const auto &AttrSpec : Abbrev->attributes()) {
2786 if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2787 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2788 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2789 // FIXME: dsymutil-classic keeps the old abbreviation around
2790 // even if it's not used. We can remove this (and the copyAbbrev
2791 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2792 if (!Copied) {
2793 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2794 Copied = true;
2795 }
2796 continue;
2797 }
2798
2799 DWARFFormValue Val(AttrSpec.Form);
2800 uint32_t AttrSize = Offset;
2801 Val.extractValue(Data, &Offset, &U);
2802 AttrSize = Offset - AttrSize;
2803
2804 OutOffset +=
2805 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2806 }
2807
2808 // Look for accelerator entries.
2809 uint16_t Tag = InputDIE.getTag();
2810 // FIXME: This is slightly wrong. An inline_subroutine without a
2811 // low_pc, but with AT_ranges might be interesting to get into the
2812 // accelerator tables too. For now stick with dsymutil's behavior.
2813 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2814 Tag != dwarf::DW_TAG_compile_unit &&
2815 getDIENames(InputDIE, AttrInfo)) {
2816 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2817 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2818 AttrInfo.MangledNameOffset,
2819 Tag == dwarf::DW_TAG_inlined_subroutine);
2820 if (AttrInfo.Name)
2821 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2822 Tag == dwarf::DW_TAG_inlined_subroutine);
2823 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2824 getDIENames(InputDIE, AttrInfo)) {
2825 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2826 }
2827
2828 // Determine whether there are any children that we want to keep.
2829 bool HasChildren = false;
2830 for (auto Child: InputDIE.children()) {
2831 unsigned Idx = U.getDIEIndex(Child);
2832 if (Unit.getInfo(Idx).Keep) {
2833 HasChildren = true;
2834 break;
2835 }
2836 }
2837
2838 DIEAbbrev NewAbbrev = Die->generateAbbrev();
2839 if (HasChildren)
2840 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2841 // Assign a permanent abbrev number
2842 Linker.AssignAbbrev(NewAbbrev);
2843 Die->setAbbrevNumber(NewAbbrev.getNumber());
2844
2845 // Add the size of the abbreviation number to the output offset.
2846 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2847
2848 if (!HasChildren) {
2849 // Update our size.
2850 Die->setSize(OutOffset - Die->getOffset());
2851 return Die;
2852 }
2853
2854 // Recursively clone children.
2855 for (auto Child: InputDIE.children()) {
2856 if (DIE *Clone = cloneDIE(Child, Unit, PCOffset, OutOffset, Flags)) {
2857 Die->addChild(Clone);
2858 OutOffset = Clone->getOffset() + Clone->getSize();
2859 }
2860 }
2861
2862 // Account for the end of children marker.
2863 OutOffset += sizeof(int8_t);
2864 // Update our size.
2865 Die->setSize(OutOffset - Die->getOffset());
2866 return Die;
2867}
2868
2869/// \brief Patch the input object file relevant debug_ranges entries
2870/// and emit them in the output file. Update the relevant attributes
2871/// to point at the new entries.
2872void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2873 DWARFContext &OrigDwarf) const {
2874 DWARFDebugRangeList RangeList;
2875 const auto &FunctionRanges = Unit.getFunctionRanges();
2876 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2877 DataExtractor RangeExtractor(OrigDwarf.getRangeSection().Data,
2878 OrigDwarf.isLittleEndian(), AddressSize);
2879 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2880 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2881 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
2882 uint64_t OrigLowPc = dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc), -1ULL);
2883 // Ranges addresses are based on the unit's low_pc. Compute the
2884 // offset we need to apply to adapt to the new unit's low_pc.
2885 int64_t UnitPcOffset = 0;
2886 if (OrigLowPc != -1ULL)
2887 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2888
2889 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2890 uint32_t Offset = RangeAttribute.get();
2891 RangeAttribute.set(Streamer->getRangesSectionSize());
2892 RangeList.extract(RangeExtractor, &Offset, OrigDwarf.getRangeSection().Relocs);
2893 const auto &Entries = RangeList.getEntries();
2894 if (!Entries.empty()) {
2895 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2896
2897 if (CurrRange == InvalidRange ||
2898 First.StartAddress + OrigLowPc < CurrRange.start() ||
2899 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2900 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2901 if (CurrRange == InvalidRange ||
2902 CurrRange.start() > First.StartAddress + OrigLowPc) {
2903 reportWarning("no mapping for range.");
2904 continue;
2905 }
2906 }
2907 }
2908
2909 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2910 AddressSize);
2911 }
2912}
2913
2914/// \brief Generate the debug_aranges entries for \p Unit and if the
2915/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2916/// contribution for this attribute.
2917/// FIXME: this could actually be done right in patchRangesForUnit,
2918/// but for the sake of initial bit-for-bit compatibility with legacy
2919/// dsymutil, we have to do it in a delayed pass.
2920void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2921 auto Attr = Unit.getUnitRangesAttribute();
2922 if (Attr)
2923 Attr->set(Streamer->getRangesSectionSize());
2924 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
2925}
2926
2927/// \brief Insert the new line info sequence \p Seq into the current
2928/// set of already linked line info \p Rows.
2929static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2930 std::vector<DWARFDebugLine::Row> &Rows) {
2931 if (Seq.empty())
2932 return;
2933
2934 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2935 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2936 Seq.clear();
2937 return;
2938 }
2939
2940 auto InsertPoint = std::lower_bound(
2941 Rows.begin(), Rows.end(), Seq.front(),
2942 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2943 return LHS.Address < RHS.Address;
2944 });
2945
2946 // FIXME: this only removes the unneeded end_sequence if the
2947 // sequences have been inserted in order. using a global sort like
2948 // described in patchLineTableForUnit() and delaying the end_sequene
2949 // elimination to emitLineTableForUnit() we can get rid of all of them.
2950 if (InsertPoint != Rows.end() &&
2951 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2952 *InsertPoint = Seq.front();
2953 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2954 } else {
2955 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2956 }
2957
2958 Seq.clear();
2959}
2960
2961static void patchStmtList(DIE &Die, DIEInteger Offset) {
2962 for (auto &V : Die.values())
2963 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2964 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2965 return;
2966 }
2967
2968 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!")::llvm::llvm_unreachable_internal("Didn't find DW_AT_stmt_list in cloned DIE!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/dsymutil/DwarfLinker.cpp"
, 2968)
;
2969}
2970
2971/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2972/// recreate a relocated version of these for the address ranges that
2973/// are present in the binary.
2974void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2975 DWARFContext &OrigDwarf) {
2976 DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
2977 auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
2978 if (!StmtList)
2979 return;
2980
2981 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2982 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2983 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
2984
2985 // Parse the original line info for the unit.
2986 DWARFDebugLine::LineTable LineTable;
2987 uint32_t StmtOffset = *StmtList;
2988 StringRef LineData = OrigDwarf.getLineSection().Data;
2989 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2990 Unit.getOrigUnit().getAddressByteSize());
2991 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2992 &StmtOffset);
2993
2994 // This vector is the output line table.
2995 std::vector<DWARFDebugLine::Row> NewRows;
2996 NewRows.reserve(LineTable.Rows.size());
2997
2998 // Current sequence of rows being extracted, before being inserted
2999 // in NewRows.
3000 std::vector<DWARFDebugLine::Row> Seq;
3001 const auto &FunctionRanges = Unit.getFunctionRanges();
3002 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
3003
3004 // FIXME: This logic is meant to generate exactly the same output as
3005 // Darwin's classic dsynutil. There is a nicer way to implement this
3006 // by simply putting all the relocated line info in NewRows and simply
3007 // sorting NewRows before passing it to emitLineTableForUnit. This
3008 // should be correct as sequences for a function should stay
3009 // together in the sorted output. There are a few corner cases that
3010 // look suspicious though, and that required to implement the logic
3011 // this way. Revisit that once initial validation is finished.
3012
3013 // Iterate over the object file line info and extract the sequences
3014 // that correspond to linked functions.
3015 for (auto &Row : LineTable.Rows) {
3016 // Check wether we stepped out of the range. The range is
3017 // half-open, but consider accept the end address of the range if
3018 // it is marked as end_sequence in the input (because in that
3019 // case, the relocation offset is accurate and that entry won't
3020 // serve as the start of another function).
3021 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
3022 Row.Address > CurrRange.stop() ||
3023 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
3024 // We just stepped out of a known range. Insert a end_sequence
3025 // corresponding to the end of the range.
3026 uint64_t StopAddress = CurrRange != InvalidRange
3027 ? CurrRange.stop() + CurrRange.value()
3028 : -1ULL;
3029 CurrRange = FunctionRanges.find(Row.Address);
3030 bool CurrRangeValid =
3031 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
3032 if (!CurrRangeValid) {
3033 CurrRange = InvalidRange;
3034 if (StopAddress != -1ULL) {
3035 // Try harder by looking in the DebugMapObject function
3036 // ranges map. There are corner cases where this finds a
3037 // valid entry. It's unclear if this is right or wrong, but
3038 // for now do as dsymutil.
3039 // FIXME: Understand exactly what cases this addresses and
3040 // potentially remove it along with the Ranges map.
3041 auto Range = Ranges.lower_bound(Row.Address);
3042 if (Range != Ranges.begin() && Range != Ranges.end())
3043 --Range;
3044
3045 if (Range != Ranges.end() && Range->first <= Row.Address &&
3046 Range->second.first >= Row.Address) {
3047 StopAddress = Row.Address + Range->second.second;
3048 }
3049 }
3050 }
3051 if (StopAddress != -1ULL && !Seq.empty()) {
3052 // Insert end sequence row with the computed end address, but
3053 // the same line as the previous one.
3054 auto NextLine = Seq.back();
3055 NextLine.Address = StopAddress;
3056 NextLine.EndSequence = 1;
3057 NextLine.PrologueEnd = 0;
3058 NextLine.BasicBlock = 0;
3059 NextLine.EpilogueBegin = 0;
3060 Seq.push_back(NextLine);
3061 insertLineSequence(Seq, NewRows);
3062 }
3063
3064 if (!CurrRangeValid)
3065 continue;
3066 }
3067
3068 // Ignore empty sequences.
3069 if (Row.EndSequence && Seq.empty())
3070 continue;
3071
3072 // Relocate row address and add it to the current sequence.
3073 Row.Address += CurrRange.value();
3074 Seq.emplace_back(Row);
3075
3076 if (Row.EndSequence)
3077 insertLineSequence(Seq, NewRows);
3078 }
3079
3080 // Finished extracting, now emit the line tables.
3081 uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength;
3082 // FIXME: LLVM hardcodes it's prologue values. We just copy the
3083 // prologue over and that works because we act as both producer and
3084 // consumer. It would be nicer to have a real configurable line
3085 // table emitter.
3086 if (LineTable.Prologue.Version != 2 ||
3087 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT1 ||
3088 LineTable.Prologue.OpcodeBase > 13)
3089 reportWarning("line table parameters mismatch. Cannot emit.");
3090 else {
3091 MCDwarfLineTableParams Params;
3092 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
3093 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
3094 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
3095 Streamer->emitLineTableForUnit(Params,
3096 LineData.slice(*StmtList + 4, PrologueEnd),
3097 LineTable.Prologue.MinInstLength, NewRows,
3098 Unit.getOrigUnit().getAddressByteSize());
3099 }
3100}
3101
3102void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
3103 Streamer->emitPubNamesForUnit(Unit);
3104 Streamer->emitPubTypesForUnit(Unit);
3105}
3106
3107/// \brief Read the frame info stored in the object, and emit the
3108/// patched frame descriptions for the linked binary.
3109///
3110/// This is actually pretty easy as the data of the CIEs and FDEs can
3111/// be considered as black boxes and moved as is. The only thing to do
3112/// is to patch the addresses in the headers.
3113void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
3114 DWARFContext &OrigDwarf,
3115 unsigned AddrSize) {
3116 StringRef FrameData = OrigDwarf.getDebugFrameSection();
3117 if (FrameData.empty())
3118 return;
3119
3120 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
3121 uint32_t InputOffset = 0;
3122
3123 // Store the data of the CIEs defined in this object, keyed by their
3124 // offsets.
3125 DenseMap<uint32_t, StringRef> LocalCIES;
3126
3127 while (Data.isValidOffset(InputOffset)) {
3128 uint32_t EntryOffset = InputOffset;
3129 uint32_t InitialLength = Data.getU32(&InputOffset);
3130 if (InitialLength == 0xFFFFFFFF)
3131 return reportWarning("Dwarf64 bits no supported");
3132
3133 uint32_t CIEId = Data.getU32(&InputOffset);
3134 if (CIEId == 0xFFFFFFFF) {
3135 // This is a CIE, store it.
3136 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
3137 LocalCIES[EntryOffset] = CIEData;
3138 // The -4 is to account for the CIEId we just read.
3139 InputOffset += InitialLength - 4;
3140 continue;
3141 }
3142
3143 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
3144
3145 // Some compilers seem to emit frame info that doesn't start at
3146 // the function entry point, thus we can't just lookup the address
3147 // in the debug map. Use the linker's range map to see if the FDE
3148 // describes something that we can relocate.
3149 auto Range = Ranges.upper_bound(Loc);
3150 if (Range != Ranges.begin())
3151 --Range;
3152 if (Range == Ranges.end() || Range->first > Loc ||
3153 Range->second.first <= Loc) {
3154 // The +4 is to account for the size of the InitialLength field itself.
3155 InputOffset = EntryOffset + InitialLength + 4;
3156 continue;
3157 }
3158
3159 // This is an FDE, and we have a mapping.
3160 // Have we already emitted a corresponding CIE?
3161 StringRef CIEData = LocalCIES[CIEId];
3162 if (CIEData.empty())
3163 return reportWarning("Inconsistent debug_frame content. Dropping.");
3164
3165 // Look if we already emitted a CIE that corresponds to the
3166 // referenced one (the CIE data is the key of that lookup).
3167 auto IteratorInserted = EmittedCIEs.insert(
3168 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3169 // If there is no CIE yet for this ID, emit it.
3170 if (IteratorInserted.second ||
3171 // FIXME: dsymutil-classic only caches the last used CIE for
3172 // reuse. Mimic that behavior for now. Just removing that
3173 // second half of the condition and the LastCIEOffset variable
3174 // makes the code DTRT.
3175 LastCIEOffset != IteratorInserted.first->getValue()) {
3176 LastCIEOffset = Streamer->getFrameSectionSize();
3177 IteratorInserted.first->getValue() = LastCIEOffset;
3178 Streamer->emitCIE(CIEData);
3179 }
3180
3181 // Emit the FDE with updated address and CIE pointer.
3182 // (4 + AddrSize) is the size of the CIEId + initial_location
3183 // fields that will get reconstructed by emitFDE().
3184 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3185 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3186 Loc + Range->second.second,
3187 FrameData.substr(InputOffset, FDERemainingBytes));
3188 InputOffset += FDERemainingBytes;
3189 }
3190}
3191
3192void DwarfLinker::DIECloner::copyAbbrev(
3193 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
3194 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3195 dwarf::Form(Abbrev.hasChildren()));
3196
3197 for (const auto &Attr : Abbrev.attributes()) {
3198 uint16_t Form = Attr.Form;
3199 if (hasODR && isODRAttribute(Attr.Attr))
3200 Form = dwarf::DW_FORM_ref_addr;
3201 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3202 }
3203
3204 Linker.AssignAbbrev(Copy);
3205}
3206
3207static uint64_t getDwoId(const DWARFDie &CUDie,
3208 const DWARFUnit &Unit) {
3209 auto DwoId = dwarf::toUnsigned(CUDie.find({dwarf::DW_AT_dwo_id,
3210 dwarf::DW_AT_GNU_dwo_id}));
3211 if (DwoId)
3212 return *DwoId;
3213 return 0;
3214}
3215
3216bool DwarfLinker::registerModuleReference(
3217 const DWARFDie &CUDie, const DWARFUnit &Unit,
3218 DebugMap &ModuleMap, unsigned Indent) {
3219 std::string PCMfile =
3220 dwarf::toString(CUDie.find({dwarf::DW_AT_dwo_name,
3221 dwarf::DW_AT_GNU_dwo_name}), "");
3222 if (PCMfile.empty())
3223 return false;
3224
3225 // Clang module DWARF skeleton CUs abuse this for the path to the module.
3226 std::string PCMpath = dwarf::toString(CUDie.find(dwarf::DW_AT_comp_dir), "");
3227 uint64_t DwoId = getDwoId(CUDie, Unit);
3228
3229 std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
3230 if (Name.empty()) {
3231 reportWarning("Anonymous module skeleton CU for " + PCMfile);
3232 return true;
3233 }
3234
3235 if (Options.Verbose) {
3236 outs().indent(Indent);
3237 outs() << "Found clang module reference " << PCMfile;
3238 }
3239
3240 auto Cached = ClangModules.find(PCMfile);
3241 if (Cached != ClangModules.end()) {
3242 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
3243 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
3244 // ASTFileSignatures will change randomly when a module is rebuilt.
3245 if (Options.Verbose && (Cached->second != DwoId))
3246 reportWarning(Twine("hash mismatch: this object file was built against a "
3247 "different version of the module ") + PCMfile);
3248 if (Options.Verbose)
3249 outs() << " [cached].\n";
3250 return true;
3251 }
3252 if (Options.Verbose)
3253 outs() << " ...\n";
3254
3255 // Cyclic dependencies are disallowed by Clang, but we still
3256 // shouldn't run into an infinite loop, so mark it as processed now.
3257 ClangModules.insert({PCMfile, DwoId});
3258 loadClangModule(PCMfile, PCMpath, Name, DwoId, ModuleMap, Indent + 2);
3259 return true;
3260}
3261
3262ErrorOr<const object::ObjectFile &>
3263DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3264 const DebugMap &Map) {
3265 auto ErrOrObjs =
3266 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
3267 if (std::error_code EC = ErrOrObjs.getError()) {
3268 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3269 return EC;
3270 }
3271 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3272 if (std::error_code EC = ErrOrObj.getError())
3273 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3274 return ErrOrObj;
3275}
3276
3277void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
3278 StringRef ModuleName, uint64_t DwoId,
3279 DebugMap &ModuleMap, unsigned Indent) {
3280 SmallString<80> Path(Options.PrependPath);
3281 if (sys::path::is_relative(Filename))
3282 sys::path::append(Path, ModulePath, Filename);
3283 else
3284 sys::path::append(Path, Filename);
3285 BinaryHolder ObjHolder(Options.Verbose);
3286 auto &Obj =
3287 ModuleMap.addDebugMapObject(Path, sys::TimePoint<std::chrono::seconds>());
3288 auto ErrOrObj = loadObject(ObjHolder, Obj, ModuleMap);
3289 if (!ErrOrObj) {
3290 // Try and emit more helpful warnings by applying some heuristics.
3291 StringRef ObjFile = CurrentDebugObject->getObjectFilename();
3292 bool isClangModule = sys::path::extension(Filename).equals(".pcm");
3293 bool isArchive = ObjFile.endswith(")");
3294 if (isClangModule) {
3295 StringRef ModuleCacheDir = sys::path::parent_path(Path);
3296 if (sys::fs::exists(ModuleCacheDir)) {
3297 // If the module's parent directory exists, we assume that the module
3298 // cache has expired and was pruned by clang. A more adventurous
3299 // dsymutil would invoke clang to rebuild the module now.
3300 if (!ModuleCacheHintDisplayed) {
3301 errs() << "note: The clang module cache may have expired since this "
3302 "object file was built. Rebuilding the object file will "
3303 "rebuild the module cache.\n";
3304 ModuleCacheHintDisplayed = true;
3305 }
3306 } else if (isArchive) {
3307 // If the module cache directory doesn't exist at all and the object
3308 // file is inside a static library, we assume that the static library
3309 // was built on a different machine. We don't want to discourage module
3310 // debugging for convenience libraries within a project though.
3311 if (!ArchiveHintDisplayed) {
3312 errs() << "note: Linking a static library that was built with "
3313 "-gmodules, but the module cache was not found. "
3314 "Redistributable static libraries should never be built "
3315 "with module debugging enabled. The debug experience will "
3316 "be degraded due to incomplete debug information.\n";
3317 ArchiveHintDisplayed = true;
3318 }
3319 }
3320 }
3321 return;
3322 }
3323
3324 std::unique_ptr<CompileUnit> Unit;
3325
3326 // Setup access to the debug info.
3327 DWARFContextInMemory DwarfContext(*ErrOrObj);
3328 RelocationManager RelocMgr(*this);
3329 for (const auto &CU : DwarfContext.compile_units()) {
3330 auto CUDie = CU->getUnitDIE(false);
3331 // Recursively get all modules imported by this one.
3332 if (!registerModuleReference(CUDie, *CU, ModuleMap, Indent)) {
3333 if (Unit) {
3334 errs() << Filename << ": Clang modules are expected to have exactly"
3335 << " 1 compile unit.\n";
3336 exitDsymutil(1);
3337 }
3338 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
3339 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
3340 // ASTFileSignatures will change randomly when a module is rebuilt.
3341 uint64_t PCMDwoId = getDwoId(CUDie, *CU);
3342 if (PCMDwoId != DwoId) {
3343 if (Options.Verbose)
3344 reportWarning(
3345 Twine("hash mismatch: this object file was built against a "
3346 "different version of the module ") + Filename);
3347 // Update the cache entry with the DwoId of the module loaded from disk.
3348 ClangModules[Filename] = PCMDwoId;
3349 }
3350
3351 // Add this module.
3352 Unit = llvm::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
3353 ModuleName);
3354 Unit->setHasInterestingContent();
3355 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), StringPool,
3356 ODRContexts);
3357 // Keep everything.
3358 Unit->markEverythingAsKept();
3359 }
3360 }
3361 if (Options.Verbose) {
3362 outs().indent(Indent);
3363 outs() << "cloning .debug_info from " << Filename << "\n";
3364 }
3365
3366 std::vector<std::unique_ptr<CompileUnit>> CompileUnits;
3367 CompileUnits.push_back(std::move(Unit));
3368 DIECloner(*this, RelocMgr, DIEAlloc, CompileUnits, Options)
3369 .cloneAllCompileUnits(DwarfContext);
3370}
3371
3372void DwarfLinker::DIECloner::cloneAllCompileUnits(
3373 DWARFContextInMemory &DwarfContext) {
3374 if (!Linker.Streamer)
3375 return;
3376
3377 for (auto &CurrentUnit : CompileUnits) {
3378 auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
3379 CurrentUnit->setStartOffset(Linker.OutputDebugInfoSize);
3380 if (CurrentUnit->getInfo(0).Keep) {
3381 // Clone the InputDIE into your Unit DIE in our compile unit since it
3382 // already has a DIE inside of it.
3383 CurrentUnit->createOutputDIE();
3384 cloneDIE(InputDIE, *CurrentUnit, 0 /* PC offset */,
3385 11 /* Unit Header size */, 0, CurrentUnit->getOutputUnitDIE());
3386 }
3387 Linker.OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset();
3388 if (Linker.Options.NoOutput)
3389 continue;
3390 // FIXME: for compatibility with the classic dsymutil, we emit
3391 // an empty line table for the unit, even if the unit doesn't
3392 // actually exist in the DIE tree.
3393 Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext);
3394 Linker.patchRangesForUnit(*CurrentUnit, DwarfContext);
3395 Linker.Streamer->emitLocationsForUnit(*CurrentUnit, DwarfContext);
3396 Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
3397 }
3398
3399 if (Linker.Options.NoOutput)
3400 return;
3401
3402 // Emit all the compile unit's debug information.
3403 for (auto &CurrentUnit : CompileUnits) {
3404 Linker.generateUnitRanges(*CurrentUnit);
3405 CurrentUnit->fixupForwardReferences();
3406 Linker.Streamer->emitCompileUnitHeader(*CurrentUnit);
3407 if (!CurrentUnit->getOutputUnitDIE())
3408 continue;
3409 Linker.Streamer->emitDIE(*CurrentUnit->getOutputUnitDIE());
3410 }
3411}
3412
3413bool DwarfLinker::link(const DebugMap &Map) {
3414
3415 if (!createStreamer(Map.getTriple(), OutputFilename))
3416 return false;
3417
3418 // Size of the DIEs (and headers) generated for the linked output.
3419 OutputDebugInfoSize = 0;
3420 // A unique ID that identifies each compile unit.
3421 UnitID = 0;
3422 DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
3423
3424 for (const auto &Obj : Map.objects()) {
3425 CurrentDebugObject = Obj.get();
3426
3427 if (Options.Verbose)
3428 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
3429 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3430 if (!ErrOrObj)
3431 continue;
3432
3433 // Look for relocations that correspond to debug map entries.
3434 RelocationManager RelocMgr(*this);
3435 if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
3436 if (Options.Verbose)
3437 outs() << "No valid relocations found. Skipping.\n";
3438 continue;
3439 }
3440
3441 // Setup access to the debug info.
3442 DWARFContextInMemory DwarfContext(*ErrOrObj);
3443 startDebugObject(DwarfContext, *Obj);
3444
3445 // In a first phase, just read in the debug info and load all clang modules.
3446 for (const auto &CU : DwarfContext.compile_units()) {
3447 auto CUDie = CU->getUnitDIE(false);
3448 if (Options.Verbose) {
3449 outs() << "Input compilation unit:";
3450 CUDie.dump(outs(), 0);
3451 }
3452
3453 if (!registerModuleReference(CUDie, *CU, ModuleMap)) {
3454 Units.push_back(llvm::make_unique<CompileUnit>(*CU, UnitID++,
3455 !Options.NoODR, ""));
3456 maybeUpdateMaxDwarfVersion(CU->getVersion());
3457 }
3458 }
3459
3460 // Now build the DIE parent links that we will use during the next phase.
3461 for (auto &CurrentUnit : Units)
3462 analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0, *CurrentUnit,
3463 &ODRContexts.getRoot(), StringPool, ODRContexts);
3464
3465 // Then mark all the DIEs that need to be present in the linked
3466 // output and collect some information about them. Note that this
3467 // loop can not be merged with the previous one becaue cross-cu
3468 // references require the ParentIdx to be setup for every CU in
3469 // the object file before calling this.
3470 for (auto &CurrentUnit : Units)
3471 lookForDIEsToKeep(RelocMgr, CurrentUnit->getOrigUnit().getUnitDIE(), *Obj,
3472 *CurrentUnit, 0);
3473
3474 // The calls to applyValidRelocs inside cloneDIE will walk the
3475 // reloc array again (in the same way findValidRelocsInDebugInfo()
3476 // did). We need to reset the NextValidReloc index to the beginning.
3477 RelocMgr.resetValidRelocs();
3478 if (RelocMgr.hasValidRelocs())
3479 DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3480 .cloneAllCompileUnits(DwarfContext);
3481 if (!Options.NoOutput && !Units.empty())
3482 patchFrameInfoForObject(*Obj, DwarfContext,
3483 Units[0]->getOrigUnit().getAddressByteSize());
3484
3485 // Clean-up before starting working on the next object.
3486 endDebugObject();
3487 }
3488
3489 // Emit everything that's global.
3490 if (!Options.NoOutput) {
3491 Streamer->emitAbbrevs(Abbreviations, MaxDwarfVersion);
3492 Streamer->emitStrings(StringPool);
3493 }
3494
3495 return Options.NoOutput ? true : Streamer->finish(Map);
3496}
3497}
3498
3499/// \brief Get the offset of string \p S in the string table. This
3500/// can insert a new element or return the offset of a preexisitng
3501/// one.
3502uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3503 if (S.empty() && !Strings.empty())
3504 return 0;
3505
3506 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3507 MapTy::iterator It;
3508 bool Inserted;
3509
3510 // A non-empty string can't be at offset 0, so if we have an entry
3511 // with a 0 offset, it must be a previously interned string.
3512 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3513 if (Inserted || It->getValue().first == 0) {
3514 // Set offset and chain at the end of the entries list.
3515 It->getValue().first = CurrentEndOffset;
3516 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3517 Last->getValue().second = &*It;
3518 Last = &*It;
3519 }
3520 return It->getValue().first;
3521}
3522
3523/// \brief Put \p S into the StringMap so that it gets permanent
3524/// storage, but do not actually link it in the chain of elements
3525/// that go into the output section. A latter call to
3526/// getStringOffset() with the same string will chain it though.
3527StringRef NonRelocatableStringpool::internString(StringRef S) {
3528 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3529 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3530 return InsertResult.first->getKey();
3531}
3532
3533void warn(const Twine &Warning, const Twine &Context) {
3534 errs() << Twine("while processing ") + Context + ":\n";
3535 errs() << Twine("warning: ") + Warning + "\n";
3536}
3537
3538bool error(const Twine &Error, const Twine &Context) {
3539 errs() << Twine("while processing ") + Context + ":\n";
3540 errs() << Twine("error: ") + Error + "\n";
3541 return false;
3542}
3543
3544bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3545 const LinkOptions &Options) {
3546 DwarfLinker Linker(OutputFilename, Options);
3547 return Linker.link(DM);
3548}
3549}
3550}