Bug Summary

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