Bug Summary

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