Bug Summary

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