blob: aa769058c72cba4aff2d6c4db5469da0c006a34a [file] [log] [blame]
Frederic Riss231f7142014-12-12 17:31:24 +00001//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "DebugMap.h"
Frederic Rissd3455182015-01-28 18:27:01 +000010#include "BinaryHolder.h"
11#include "DebugMap.h"
Frederic Riss231f7142014-12-12 17:31:24 +000012#include "dsymutil.h"
Frederic Riss24faade2015-09-02 16:49:13 +000013#include "MachOUtils.h"
Frederic Riss30711fb2015-08-26 05:09:52 +000014#include "NonRelocatableStringpool.h"
Frederic Riss1af75f72015-03-12 18:45:10 +000015#include "llvm/ADT/IntervalMap.h"
Adrian Prantl20937022015-09-23 17:11:10 +000016#include "llvm/ADT/StringMap.h"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000017#include "llvm/ADT/STLExtras.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000018#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000019#include "llvm/CodeGen/DIE.h"
Frederic Riss1c650942015-07-21 22:41:43 +000020#include "llvm/Config/config.h"
Zachary Turner82af9432015-01-30 18:07:45 +000021#include "llvm/DebugInfo/DWARF/DWARFContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000023#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000024#include "llvm/MC/MCAsmBackend.h"
25#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCContext.h"
27#include "llvm/MC/MCCodeEmitter.h"
Frederic Riss63786b02015-03-15 20:45:43 +000028#include "llvm/MC/MCDwarf.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000029#include "llvm/MC/MCInstrInfo.h"
30#include "llvm/MC/MCObjectFileInfo.h"
31#include "llvm/MC/MCRegisterInfo.h"
32#include "llvm/MC/MCStreamer.h"
Pete Cooper81902a32015-05-15 22:19:42 +000033#include "llvm/MC/MCSubtargetInfo.h"
David Majnemer03e2cc32015-12-21 22:09:27 +000034#include "llvm/MC/MCTargetOptionsCommandFlags.h"
Frederic Riss1036e642015-02-13 23:18:22 +000035#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000036#include "llvm/Support/Dwarf.h"
37#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000038#include "llvm/Support/TargetRegistry.h"
39#include "llvm/Target/TargetMachine.h"
40#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000041#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000042#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000043
44namespace llvm {
45namespace dsymutil {
46
Frederic Rissd3455182015-01-28 18:27:01 +000047namespace {
48
Frederic Riss1af75f72015-03-12 18:45:10 +000049template <typename KeyT, typename ValT>
50using HalfOpenIntervalMap =
51 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
52 IntervalMapHalfOpenInfo<KeyT>>;
53
Frederic Riss25440872015-03-13 23:30:31 +000054typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
55
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000056// FIXME: Delete this structure.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000057struct PatchLocation {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000058 DIE::value_iterator I;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000059
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000060 PatchLocation() = default;
61 PatchLocation(DIE::value_iterator I) : I(I) {}
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000062
63 void set(uint64_t New) const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000064 assert(I);
65 const auto &Old = *I;
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000066 assert(Old.getType() == DIEValue::isInteger);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000067 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000068 }
69
70 uint64_t get() const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000071 assert(I);
72 return I->getDIEInteger().getValue();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000073 }
74};
75
Frederic Riss1c650942015-07-21 22:41:43 +000076class CompileUnit;
77struct DeclMapInfo;
Frederic Riss1c650942015-07-21 22:41:43 +000078
79/// A DeclContext is a named program scope that is used for ODR
80/// uniquing of types.
81/// The set of DeclContext for the ODR-subject parts of a Dwarf link
82/// is expanded (and uniqued) with each new object file processed. We
83/// need to determine the context of each DIE in an linked object file
84/// to see if the corresponding type has already been emitted.
85///
86/// The contexts are conceptually organised as a tree (eg. a function
87/// scope is contained in a namespace scope that contains other
88/// scopes), but storing/accessing them in an actual tree is too
89/// inefficient: we need to be able to very quickly query a context
90/// for a given child context by name. Storing a StringMap in each
91/// DeclContext would be too space inefficient.
92/// The solution here is to give each DeclContext a link to its parent
93/// (this allows to walk up the tree), but to query the existance of a
94/// specific DeclContext using a separate DenseMap keyed on the hash
95/// of the fully qualified name of the context.
96class DeclContext {
97 unsigned QualifiedNameHash;
98 uint32_t Line;
99 uint32_t ByteSize;
100 uint16_t Tag;
101 StringRef Name;
102 StringRef File;
103 const DeclContext &Parent;
104 const DWARFDebugInfoEntryMinimal *LastSeenDIE;
105 uint32_t LastSeenCompileUnitID;
106 uint32_t CanonicalDIEOffset;
107
108 friend DeclMapInfo;
109
110public:
111 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
112
113 DeclContext()
114 : QualifiedNameHash(0), Line(0), ByteSize(0),
115 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
116 LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
117
118 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
119 StringRef Name, StringRef File, const DeclContext &Parent,
120 const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
121 unsigned CUId = 0)
122 : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
123 Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
124 LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
125
126 uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
127
128 bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
129
130 uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
131 void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
132
133 uint16_t getTag() const { return Tag; }
134 StringRef getName() const { return Name; }
135};
136
137/// Info type for the DenseMap storing the DeclContext pointers.
138struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
139 using DenseMapInfo<DeclContext *>::getEmptyKey;
140 using DenseMapInfo<DeclContext *>::getTombstoneKey;
141
142 static unsigned getHashValue(const DeclContext *Ctxt) {
143 return Ctxt->QualifiedNameHash;
144 }
145
146 static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
147 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
148 return RHS == LHS;
149 return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
150 LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
151 LHS->Name.data() == RHS->Name.data() &&
152 LHS->File.data() == RHS->File.data() &&
153 LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
154 }
155};
156
157/// This class gives a tree-like API to the DenseMap that stores the
158/// DeclContext objects. It also holds the BumpPtrAllocator where
159/// these objects will be allocated.
160class DeclContextTree {
161 BumpPtrAllocator Allocator;
162 DeclContext Root;
163 DeclContext::Map Contexts;
164
165public:
166 /// Get the child of \a Context described by \a DIE in \a Unit. The
167 /// required strings will be interned in \a StringPool.
168 /// \returns The child DeclContext along with one bit that is set if
169 /// this context is invalid.
Adrian Prantl42562c32015-10-02 00:27:08 +0000170 /// An invalid context means it shouldn't be considered for uniquing, but its
171 /// not returning null, because some children of that context might be
172 /// uniquing candidates. FIXME: The invalid bit along the return value is to
173 /// emulate some dsymutil-classic functionality.
Frederic Riss1c650942015-07-21 22:41:43 +0000174 PointerIntPair<DeclContext *, 1>
175 getChildDeclContext(DeclContext &Context,
176 const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
Adrian Prantl42562c32015-10-02 00:27:08 +0000177 NonRelocatableStringpool &StringPool, bool InClangModule);
Frederic Riss1c650942015-07-21 22:41:43 +0000178
179 DeclContext &getRoot() { return Root; }
180};
181
Frederic Riss563cba62015-01-28 22:15:14 +0000182/// \brief Stores all information relating to a compile unit, be it in
183/// its original instance in the object file to its brand new cloned
184/// and linked DIE tree.
185class CompileUnit {
186public:
187 /// \brief Information gathered about a DIE in the object file.
188 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +0000189 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss1c650942015-07-21 22:41:43 +0000190 DeclContext *Ctxt; ///< ODR Declaration context.
Frederic Riss9833de62015-03-06 23:22:53 +0000191 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +0000192 uint32_t ParentIdx; ///< The index of this DIE's parent.
Adrian Prantla112ef92015-09-23 17:35:52 +0000193 bool Keep : 1; ///< Is the DIE part of the linked output?
194 bool InDebugMap : 1;///< Was this DIE's entity found in the map?
195 bool Prune : 1; ///< Is this a pure forward declaration we can strip?
Frederic Riss563cba62015-01-28 22:15:14 +0000196 };
197
Adrian Prantla112ef92015-09-23 17:35:52 +0000198 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR,
199 StringRef ClangModuleName)
Frederic Riss3cced052015-03-14 03:46:40 +0000200 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Adrian Prantla112ef92015-09-23 17:35:52 +0000201 Ranges(RangeAlloc), ClangModuleName(ClangModuleName) {
Frederic Riss563cba62015-01-28 22:15:14 +0000202 Info.resize(OrigUnit.getNumDIEs());
Frederic Riss1c650942015-07-21 22:41:43 +0000203
204 const auto *CUDie = OrigUnit.getUnitDIE(false);
205 unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
206 &OrigUnit, dwarf::DW_AT_language, 0);
207 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
208 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
209 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
210 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
211 Lang == dwarf::DW_LANG_ObjC_plus_plus);
Frederic Riss563cba62015-01-28 22:15:14 +0000212 }
213
Frederic Riss2838f9e2015-03-05 05:29:05 +0000214 CompileUnit(CompileUnit &&RHS)
215 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
216 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +0000217 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
218 // The CompileUnit container has been 'reserve()'d with the right
219 // size. We cannot move the IntervalMap anyway.
220 llvm_unreachable("CompileUnits should not be moved.");
221 }
David Blaikiea8adc132015-03-04 22:20:52 +0000222
Frederic Rissc3349d42015-02-13 23:18:27 +0000223 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000224
Frederic Riss3cced052015-03-14 03:46:40 +0000225 unsigned getUniqueID() const { return ID; }
226
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +0000227 DIE *getOutputUnitDIE() const { return CUDie; }
228 void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000229
Frederic Riss1c650942015-07-21 22:41:43 +0000230 bool hasODR() const { return HasODR; }
Adrian Prantla112ef92015-09-23 17:35:52 +0000231 bool isClangModule() const { return !ClangModuleName.empty(); }
232 const std::string &getClangModuleName() const { return ClangModuleName; }
Frederic Riss1c650942015-07-21 22:41:43 +0000233
Frederic Riss563cba62015-01-28 22:15:14 +0000234 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
235 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
236
Frederic Rissb8b43d52015-03-04 22:07:44 +0000237 uint64_t getStartOffset() const { return StartOffset; }
238 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000239 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000240
Frederic Riss5a62dc32015-03-13 18:35:54 +0000241 uint64_t getLowPc() const { return LowPc; }
242 uint64_t getHighPc() const { return HighPc; }
243
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000244 Optional<PatchLocation> getUnitRangesAttribute() const {
245 return UnitRangeAttribute;
246 }
Frederic Riss25440872015-03-13 23:30:31 +0000247 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000248 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000249 return RangeAttributes;
250 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000251
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000252 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000253 getLocationAttributes() const {
254 return LocationAttributes;
255 }
256
Adrian Prantle5162db2015-09-22 22:20:50 +0000257 void setHasInterestingContent() { HasInterestingContent = true; }
258 bool hasInterestingContent() { return HasInterestingContent; }
259
260 /// Mark every DIE in this unit as kept. This function also
261 /// marks variables as InDebugMap so that they appear in the
262 /// reconstructed accelerator tables.
263 void markEverythingAsKept();
264
Frederic Riss9d441b62015-03-06 23:22:50 +0000265 /// \brief Compute the end offset for this unit. Must be
266 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000267 /// \returns the next unit offset (which is also the current
268 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000269 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000270
Frederic Riss6afcfce2015-03-13 18:35:57 +0000271 /// \brief Keep track of a forward reference to DIE \p Die in \p
272 /// RefUnit by \p Attr. The attribute should be fixed up later to
Frederic Riss1c650942015-07-21 22:41:43 +0000273 /// point to the absolute offset of \p Die in the debug_info section
274 /// or to the canonical offset of \p Ctxt if it is non-null.
Frederic Riss6afcfce2015-03-13 18:35:57 +0000275 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000276 DeclContext *Ctxt, PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000277
278 /// \brief Apply all fixups recored by noteForwardReference().
279 void fixupForwardReferences();
280
Frederic Riss1af75f72015-03-12 18:45:10 +0000281 /// \brief Add a function range [\p LowPC, \p HighPC) that is
282 /// relocatad by applying offset \p PCOffset.
283 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
284
Frederic Riss5c9c7062015-03-13 23:55:29 +0000285 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000286 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000287 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000288
Frederic Rissdfb97902015-03-14 15:49:07 +0000289 /// \brief Keep track of a location attribute pointing to a location
290 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000291 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000292
Frederic Rissbce93ff2015-03-16 02:05:10 +0000293 /// \brief Add a name accelerator entry for \p Die with \p Name
294 /// which is stored in the string table at \p Offset.
295 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
296 bool SkipPubnamesSection = false);
297
298 /// \brief Add a type accelerator entry for \p Die with \p Name
299 /// which is stored in the string table at \p Offset.
300 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
301
302 struct AccelInfo {
Frederic Rissf37964c2015-06-05 20:27:07 +0000303 StringRef Name; ///< Name of the entry.
304 const DIE *Die; ///< DIE this entry describes.
Frederic Rissbce93ff2015-03-16 02:05:10 +0000305 uint32_t NameOffset; ///< Offset of Name in the string pool.
306 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
307
308 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
309 bool SkipPubSection = false)
310 : Name(Name), Die(Die), NameOffset(NameOffset),
311 SkipPubSection(SkipPubSection) {}
312 };
313
314 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
315 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
316
Frederic Riss1c650942015-07-21 22:41:43 +0000317 /// Get the full path for file \a FileNum in the line table
Pete Cooperef4e36a2016-03-18 03:48:09 +0000318 StringRef getResolvedPath(unsigned FileNum) {
Frederic Riss1c650942015-07-21 22:41:43 +0000319 if (FileNum >= ResolvedPaths.size())
Pete Cooperef4e36a2016-03-18 03:48:09 +0000320 return StringRef();
321 return ResolvedPaths[FileNum];
Frederic Riss1c650942015-07-21 22:41:43 +0000322 }
323
324 /// Set the fully resolved path for the line-table's file \a FileNum
325 /// to \a Path.
Pete Cooperef4e36a2016-03-18 03:48:09 +0000326 void setResolvedPath(unsigned FileNum, StringRef Path) {
Frederic Riss1c650942015-07-21 22:41:43 +0000327 if (ResolvedPaths.size() <= FileNum)
328 ResolvedPaths.resize(FileNum + 1);
329 ResolvedPaths[FileNum] = Path;
330 }
331
Frederic Riss563cba62015-01-28 22:15:14 +0000332private:
333 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000334 unsigned ID;
Frederic Riss1c650942015-07-21 22:41:43 +0000335 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
336 DIE *CUDie; ///< Root of the linked DIE tree.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000337
338 uint64_t StartOffset;
339 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000340
Frederic Riss5a62dc32015-03-13 18:35:54 +0000341 uint64_t LowPc;
342 uint64_t HighPc;
343
Frederic Riss9833de62015-03-06 23:22:53 +0000344 /// \brief A list of attributes to fixup with the absolute offset of
345 /// a DIE in the debug_info section.
346 ///
347 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000348 /// cloning because for cross-cu forward refences the target DIE's
349 /// offset isn't known you emit the reference attribute.
Frederic Riss1c650942015-07-21 22:41:43 +0000350 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
351 PatchLocation>> ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000352
Frederic Riss25440872015-03-13 23:30:31 +0000353 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000354 /// \brief The ranges in that interval map are the PC ranges for
355 /// functions in this unit, associated with the PC offset to apply
356 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000357 FunctionIntervals Ranges;
358
359 /// \brief DW_AT_ranges attributes to patch after we have gathered
360 /// all the unit's function addresses.
361 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000362 std::vector<PatchLocation> RangeAttributes;
363 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000364 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000365
366 /// \brief Location attributes that need to be transfered from th
367 /// original debug_loc section to the liked one. They are stored
368 /// along with the PC offset that is to be applied to their
369 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000370 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000371
372 /// \brief Accelerator entries for the unit, both for the pub*
373 /// sections and the apple* ones.
374 /// @{
375 std::vector<AccelInfo> Pubnames;
376 std::vector<AccelInfo> Pubtypes;
377 /// @}
Frederic Riss1c650942015-07-21 22:41:43 +0000378
379 /// Cached resolved paths from the line table.
Pete Cooperef4e36a2016-03-18 03:48:09 +0000380 /// Note, the StringRefs here point in to the intern (uniquing) string pool.
381 /// This means that a StringRef returned here doesn't need to then be uniqued
382 /// for the purposes of getting a unique address for each string.
383 std::vector<StringRef> ResolvedPaths;
Frederic Riss1c650942015-07-21 22:41:43 +0000384
385 /// Is this unit subject to the ODR rule?
386 bool HasODR;
Adrian Prantle5162db2015-09-22 22:20:50 +0000387 /// Did a DIE actually contain a valid reloc?
388 bool HasInterestingContent;
Adrian Prantla112ef92015-09-23 17:35:52 +0000389 /// If this is a Clang module, this holds the module's name.
390 std::string ClangModuleName;
Frederic Riss563cba62015-01-28 22:15:14 +0000391};
392
Adrian Prantle5162db2015-09-22 22:20:50 +0000393void CompileUnit::markEverythingAsKept() {
394 for (auto &I : Info)
Adrian Prantla112ef92015-09-23 17:35:52 +0000395 // Mark everything that wasn't explicity marked for pruning.
396 I.Keep = !I.Prune;
Adrian Prantle5162db2015-09-22 22:20:50 +0000397}
398
Frederic Riss9d441b62015-03-06 23:22:50 +0000399uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000400 NextUnitOffset = StartOffset + 11 /* Header size */;
401 // The root DIE might be null, meaning that the Unit had nothing to
402 // contribute to the linked output. In that case, we will emit the
403 // unit header without any actual DIE.
404 if (CUDie)
405 NextUnitOffset += CUDie->getSize();
406 return NextUnitOffset;
407}
408
Frederic Riss6afcfce2015-03-13 18:35:57 +0000409/// \brief Keep track of a forward cross-cu reference from this unit
410/// to \p Die that lives in \p RefUnit.
411void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000412 DeclContext *Ctxt, PatchLocation Attr) {
413 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000414}
415
416/// \brief Apply all fixups recorded by noteForwardReference().
417void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000418 for (const auto &Ref : ForwardDIEReferences) {
419 DIE *RefDie;
420 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000421 PatchLocation Attr;
Frederic Riss1c650942015-07-21 22:41:43 +0000422 DeclContext *Ctxt;
423 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
424 if (Ctxt && Ctxt->getCanonicalDIEOffset())
425 Attr.set(Ctxt->getCanonicalDIEOffset());
426 else
427 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000428 }
Frederic Riss9833de62015-03-06 23:22:53 +0000429}
430
Frederic Riss5a62dc32015-03-13 18:35:54 +0000431void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
432 int64_t PcOffset) {
433 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
434 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
435 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000436}
437
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000438void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000439 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
440 RangeAttributes.push_back(Attr);
441 else
442 UnitRangeAttribute = Attr;
443}
444
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000445void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000446 LocationAttributes.emplace_back(Attr, PcOffset);
447}
448
Frederic Rissbce93ff2015-03-16 02:05:10 +0000449/// \brief Add a name accelerator entry for \p Die with \p Name
450/// which is stored in the string table at \p Offset.
451void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
452 uint32_t Offset, bool SkipPubSection) {
453 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
454}
455
456/// \brief Add a type accelerator entry for \p Die with \p Name
457/// which is stored in the string table at \p Offset.
458void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
459 uint32_t Offset) {
460 Pubtypes.emplace_back(Name, Die, Offset, false);
461}
462
Frederic Rissc99ea202015-02-28 00:29:11 +0000463/// \brief The Dwarf streaming logic
464///
465/// All interactions with the MC layer that is used to build the debug
466/// information binary representation are handled in this class.
467class DwarfStreamer {
468 /// \defgroup MCObjects MC layer objects constructed by the streamer
469 /// @{
470 std::unique_ptr<MCRegisterInfo> MRI;
471 std::unique_ptr<MCAsmInfo> MAI;
472 std::unique_ptr<MCObjectFileInfo> MOFI;
473 std::unique_ptr<MCContext> MC;
474 MCAsmBackend *MAB; // Owned by MCStreamer
475 std::unique_ptr<MCInstrInfo> MII;
476 std::unique_ptr<MCSubtargetInfo> MSTI;
477 MCCodeEmitter *MCE; // Owned by MCStreamer
478 MCStreamer *MS; // Owned by AsmPrinter
479 std::unique_ptr<TargetMachine> TM;
480 std::unique_ptr<AsmPrinter> Asm;
481 /// @}
482
483 /// \brief the file we stream the linked Dwarf to.
484 std::unique_ptr<raw_fd_ostream> OutFile;
485
Frederic Riss25440872015-03-13 23:30:31 +0000486 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000487 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000488 uint32_t LineSectionSize;
Frederic Riss5a642072015-06-05 23:06:11 +0000489 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000490
Frederic Rissbce93ff2015-03-16 02:05:10 +0000491 /// \brief Emit the pubnames or pubtypes section contribution for \p
492 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000493 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000494 const CompileUnit &Unit,
495 const std::vector<CompileUnit::AccelInfo> &Names);
496
Frederic Rissc99ea202015-02-28 00:29:11 +0000497public:
498 /// \brief Actually create the streamer and the ouptut file.
499 ///
500 /// This could be done directly in the constructor, but it feels
501 /// more natural to handle errors through return value.
502 bool init(Triple TheTriple, StringRef OutputFilename);
503
Frederic Rissb8b43d52015-03-04 22:07:44 +0000504 /// \brief Dump the file to the disk.
Frederic Riss24faade2015-09-02 16:49:13 +0000505 bool finish(const DebugMap &);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000506
507 AsmPrinter &getAsmPrinter() const { return *Asm; }
508
509 /// \brief Set the current output section to debug_info and change
510 /// the MC Dwarf version to \p DwarfVersion.
511 void switchToDebugInfoSection(unsigned DwarfVersion);
512
513 /// \brief Emit the compilation unit header for \p Unit in the
514 /// debug_info section.
515 ///
516 /// As a side effect, this also switches the current Dwarf version
517 /// of the MC layer to the one of U.getOrigUnit().
518 void emitCompileUnitHeader(CompileUnit &Unit);
519
520 /// \brief Recursively emit the DIE tree rooted at \p Die.
521 void emitDIE(DIE &Die);
522
523 /// \brief Emit the abbreviation table \p Abbrevs to the
524 /// debug_abbrev section.
David Blaikie6196aa02015-11-18 00:34:10 +0000525 void emitAbbrevs(const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000526
527 /// \brief Emit the string table described by \p Pool.
528 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000529
530 /// \brief Emit debug_ranges for \p FuncRange by translating the
531 /// original \p Entries.
532 void emitRangesEntries(
533 int64_t UnitPcOffset, uint64_t OrigLowPc,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000534 const FunctionIntervals::const_iterator &FuncRange,
Frederic Riss25440872015-03-13 23:30:31 +0000535 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
536 unsigned AddressSize);
537
Frederic Riss563b1b02015-03-14 03:46:51 +0000538 /// \brief Emit debug_aranges entries for \p Unit and if \p
539 /// DoRangesSection is true, also emit the debug_ranges entries for
540 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
541 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000542
543 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000544
545 /// \brief Emit the debug_loc contribution for \p Unit by copying
546 /// the entries from \p Dwarf and offseting them. Update the
547 /// location attributes to point to the new entries.
548 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000549
550 /// \brief Emit the line table described in \p Rows into the
551 /// debug_line section.
Frederic Rissa5e14532015-08-07 15:14:13 +0000552 void emitLineTableForUnit(MCDwarfLineTableParams Params,
553 StringRef PrologueBytes, unsigned MinInstLength,
Frederic Riss63786b02015-03-15 20:45:43 +0000554 std::vector<DWARFDebugLine::Row> &Rows,
555 unsigned AdddressSize);
556
557 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000558
559 /// \brief Emit the .debug_pubnames contribution for \p Unit.
560 void emitPubNamesForUnit(const CompileUnit &Unit);
561
562 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
563 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000564
565 /// \brief Emit a CIE.
566 void emitCIE(StringRef CIEBytes);
567
568 /// \brief Emit an FDE with data \p Bytes.
569 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
570 StringRef Bytes);
571
572 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000573};
574
575bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
576 std::string ErrorStr;
577 std::string TripleName;
578 StringRef Context = "dwarf streamer init";
579
580 // Get the target.
581 const Target *TheTarget =
582 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
583 if (!TheTarget)
584 return error(ErrorStr, Context);
585 TripleName = TheTriple.getTriple();
586
587 // Create all the MC Objects.
588 MRI.reset(TheTarget->createMCRegInfo(TripleName));
589 if (!MRI)
590 return error(Twine("no register info for target ") + TripleName, Context);
591
592 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
593 if (!MAI)
594 return error("no asm info for target " + TripleName, Context);
595
596 MOFI.reset(new MCObjectFileInfo);
597 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Rafael Espindola699281c2016-05-18 11:58:50 +0000598 MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, CodeModel::Default, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000599
Joel Jones373d7d32016-07-25 17:18:28 +0000600 MCTargetOptions Options;
601 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "", Options);
Frederic Rissc99ea202015-02-28 00:29:11 +0000602 if (!MAB)
603 return error("no asm backend for target " + TripleName, Context);
604
605 MII.reset(TheTarget->createMCInstrInfo());
606 if (!MII)
607 return error("no instr info info for target " + TripleName, Context);
608
609 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
610 if (!MSTI)
611 return error("no subtarget info for target " + TripleName, Context);
612
Eric Christopher0169e422015-03-10 22:03:14 +0000613 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000614 if (!MCE)
615 return error("no code emitter for target " + TripleName, Context);
616
617 // Create the output file.
618 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000619 OutFile =
620 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000621 if (EC)
622 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
623
David Majnemer03e2cc32015-12-21 22:09:27 +0000624 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
625 MS = TheTarget->createMCObjectStreamer(
626 TheTriple, *MC, *MAB, *OutFile, MCE, *MSTI, MCOptions.MCRelaxAll,
627 MCOptions.MCIncrementalLinkerCompatible,
628 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000629 if (!MS)
630 return error("no object streamer for target " + TripleName, Context);
631
632 // Finally create the AsmPrinter we'll use to emit the DIEs.
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000633 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
634 None));
Frederic Rissc99ea202015-02-28 00:29:11 +0000635 if (!TM)
636 return error("no target machine for target " + TripleName, Context);
637
638 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
639 if (!Asm)
640 return error("no asm printer for target " + TripleName, Context);
641
Frederic Riss25440872015-03-13 23:30:31 +0000642 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000643 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000644 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000645 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000646
Frederic Rissc99ea202015-02-28 00:29:11 +0000647 return true;
648}
649
Frederic Riss24faade2015-09-02 16:49:13 +0000650bool DwarfStreamer::finish(const DebugMap &DM) {
651 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
652 return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
653
Frederic Rissc99ea202015-02-28 00:29:11 +0000654 MS->Finish();
655 return true;
656}
657
Frederic Rissb8b43d52015-03-04 22:07:44 +0000658/// \brief Set the current output section to debug_info and change
659/// the MC Dwarf version to \p DwarfVersion.
660void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
661 MS->SwitchSection(MOFI->getDwarfInfoSection());
662 MC->setDwarfVersion(DwarfVersion);
663}
664
665/// \brief Emit the compilation unit header for \p Unit in the
666/// debug_info section.
667///
668/// A Dwarf scetion header is encoded as:
669/// uint32_t Unit length (omiting this field)
670/// uint16_t Version
671/// uint32_t Abbreviation table offset
672/// uint8_t Address size
673///
674/// Leading to a total of 11 bytes.
675void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
676 unsigned Version = Unit.getOrigUnit().getVersion();
677 switchToDebugInfoSection(Version);
678
679 // Emit size of content not including length itself. The size has
680 // already been computed in CompileUnit::computeOffsets(). Substract
681 // 4 to that size to account for the length field.
682 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
683 Asm->EmitInt16(Version);
684 // We share one abbreviations table across all units so it's always at the
685 // start of the section.
686 Asm->EmitInt32(0);
687 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
688}
689
690/// \brief Emit the \p Abbrevs array as the shared abbreviation table
691/// for the linked Dwarf file.
David Blaikie6196aa02015-11-18 00:34:10 +0000692void DwarfStreamer::emitAbbrevs(
693 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs) {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000694 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
695 Asm->emitDwarfAbbrevs(Abbrevs);
696}
697
698/// \brief Recursively emit the DIE tree rooted at \p Die.
699void DwarfStreamer::emitDIE(DIE &Die) {
700 MS->SwitchSection(MOFI->getDwarfInfoSection());
701 Asm->emitDwarfDIE(Die);
702}
703
Frederic Rissef648462015-03-06 17:56:30 +0000704/// \brief Emit the debug_str section stored in \p Pool.
705void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000706 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000707 for (auto *Entry = Pool.getFirstEntry(); Entry;
708 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000709 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000710 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
711}
712
Frederic Riss25440872015-03-13 23:30:31 +0000713/// \brief Emit the debug_range section contents for \p FuncRange by
714/// translating the original \p Entries. The debug_range section
715/// format is totally trivial, consisting just of pairs of address
716/// sized addresses describing the ranges.
717void DwarfStreamer::emitRangesEntries(
718 int64_t UnitPcOffset, uint64_t OrigLowPc,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000719 const FunctionIntervals::const_iterator &FuncRange,
Frederic Riss25440872015-03-13 23:30:31 +0000720 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
721 unsigned AddressSize) {
722 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
723
724 // Offset each range by the right amount.
Frederic Riss94546202015-08-31 05:09:32 +0000725 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
Frederic Riss25440872015-03-13 23:30:31 +0000726 for (const auto &Range : Entries) {
727 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
728 warn("unsupported base address selection operation",
729 "emitting debug_ranges");
730 break;
731 }
732 // Do not emit empty ranges.
733 if (Range.StartAddress == Range.EndAddress)
734 continue;
735
736 // All range entries should lie in the function range.
737 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
738 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
739 warn("inconsistent range data.", "emitting debug_ranges");
740 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
741 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
742 RangesSectionSize += 2 * AddressSize;
743 }
744
745 // Add the terminator entry.
746 MS->EmitIntValue(0, AddressSize);
747 MS->EmitIntValue(0, AddressSize);
748 RangesSectionSize += 2 * AddressSize;
749}
750
Frederic Riss563b1b02015-03-14 03:46:51 +0000751/// \brief Emit the debug_aranges contribution of a unit and
752/// if \p DoDebugRanges is true the debug_range contents for a
753/// compile_unit level DW_AT_ranges attribute (Which are basically the
754/// same thing with a different base address).
755/// Just aggregate all the ranges gathered inside that unit.
756void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
757 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000758 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
759 // Gather the ranges in a vector, so that we can simplify them. The
760 // IntervalMap will have coalesced the non-linked ranges, but here
761 // we want to coalesce the linked addresses.
762 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
763 const auto &FunctionRanges = Unit.getFunctionRanges();
764 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
765 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000766 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
767 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000768
769 // The object addresses where sorted, but again, the linked
770 // addresses might end up in a different order.
771 std::sort(Ranges.begin(), Ranges.end());
772
Frederic Riss563b1b02015-03-14 03:46:51 +0000773 if (!Ranges.empty()) {
774 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
775
Rafael Espindola9ab09232015-03-17 20:07:06 +0000776 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
777 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000778
779 unsigned HeaderSize =
780 sizeof(int32_t) + // Size of contents (w/o this field
781 sizeof(int16_t) + // DWARF ARange version number
782 sizeof(int32_t) + // Offset of CU in the .debug_info section
783 sizeof(int8_t) + // Pointer Size (in bytes)
784 sizeof(int8_t); // Segment Size (in bytes)
785
786 unsigned TupleSize = AddressSize * 2;
787 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
788
789 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000790 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000791 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
792 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
793 Asm->EmitInt8(AddressSize); // Address size
794 Asm->EmitInt8(0); // Segment size
795
Petr Hosekfaef3202016-06-01 01:59:58 +0000796 Asm->OutStreamer->emitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000797
798 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
799 ++Range) {
800 uint64_t RangeStart = Range->first;
801 MS->EmitIntValue(RangeStart, AddressSize);
802 while ((Range + 1) != End && Range->second == (Range + 1)->first)
803 ++Range;
804 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
805 }
806
807 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000808 Asm->OutStreamer->EmitIntValue(0, AddressSize);
809 Asm->OutStreamer->EmitIntValue(0, AddressSize);
810 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000811 }
812
813 if (!DoDebugRanges)
814 return;
815
816 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
817 // Offset each range by the right amount.
818 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000819 // Emit coalesced ranges.
820 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000821 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000822 while (Range + 1 != End && Range->second == (Range + 1)->first)
823 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000824 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000825 RangesSectionSize += 2 * AddressSize;
826 }
827
828 // Add the terminator entry.
829 MS->EmitIntValue(0, AddressSize);
830 MS->EmitIntValue(0, AddressSize);
831 RangesSectionSize += 2 * AddressSize;
832}
833
Frederic Rissdfb97902015-03-14 15:49:07 +0000834/// \brief Emit location lists for \p Unit and update attribtues to
835/// point to the new entries.
836void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
837 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000838 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000839
840 if (Attributes.empty())
841 return;
842
843 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
844
845 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
846 const DWARFSection &InputSec = Dwarf.getLocSection();
847 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
848 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000849 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000850 int64_t UnitPcOffset = 0;
851 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
852 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
853 if (OrigLowPc != -1ULL)
854 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
855
856 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000857 uint32_t Offset = Attr.first.get();
858 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000859 // This is the quantity to add to the old location address to get
860 // the correct address for the new one.
861 int64_t LocPcOffset = Attr.second + UnitPcOffset;
862 while (Data.isValidOffset(Offset)) {
863 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
864 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
865 LocSectionSize += 2 * AddressSize;
866 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000867 Asm->OutStreamer->EmitIntValue(0, AddressSize);
868 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000869 break;
870 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000871 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
872 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000873 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000874 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000875 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000876 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000877 StringRef(InputSec.Data.substr(Offset, Length)));
878 Offset += Length;
879 LocSectionSize += Length + 2;
880 }
881 }
882}
883
Frederic Rissa5e14532015-08-07 15:14:13 +0000884void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
885 StringRef PrologueBytes,
Frederic Riss63786b02015-03-15 20:45:43 +0000886 unsigned MinInstLength,
887 std::vector<DWARFDebugLine::Row> &Rows,
888 unsigned PointerSize) {
889 // Switch to the section where the table will be emitted into.
890 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000891 MCSymbol *LineStartSym = MC->createTempSymbol();
892 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000893
894 // The first 4 bytes is the total length of the information for this
895 // compilation unit (not including these 4 bytes for the length).
896 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000897 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000898 // Copy Prologue.
899 MS->EmitBytes(PrologueBytes);
900 LineSectionSize += PrologueBytes.size() + 4;
901
Frederic Rissc3820d02015-03-15 22:20:28 +0000902 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000903 raw_svector_ostream EncodingOS(EncodingBuffer);
904
905 if (Rows.empty()) {
906 // We only have the dummy entry, dsymutil emits an entry with a 0
907 // address in that case.
Frederic Rissa5e14532015-08-07 15:14:13 +0000908 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000909 MS->EmitBytes(EncodingOS.str());
910 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000911 MS->EmitLabel(LineEndSym);
912 return;
913 }
914
915 // Line table state machine fields
916 unsigned FileNum = 1;
917 unsigned LastLine = 1;
918 unsigned Column = 0;
919 unsigned IsStatement = 1;
920 unsigned Isa = 0;
921 uint64_t Address = -1ULL;
922
923 unsigned RowsSinceLastSequence = 0;
924
925 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
926 auto &Row = Rows[Idx];
927
928 int64_t AddressDelta;
929 if (Address == -1ULL) {
930 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
931 MS->EmitULEB128IntValue(PointerSize + 1);
932 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
933 MS->EmitIntValue(Row.Address, PointerSize);
934 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
935 AddressDelta = 0;
936 } else {
937 AddressDelta = (Row.Address - Address) / MinInstLength;
938 }
939
940 // FIXME: code copied and transfromed from
941 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
942 // this code, but the current compatibility requirement with
943 // classic dsymutil makes it hard. Revisit that once this
944 // requirement is dropped.
945
946 if (FileNum != Row.File) {
947 FileNum = Row.File;
948 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
949 MS->EmitULEB128IntValue(FileNum);
950 LineSectionSize += 1 + getULEB128Size(FileNum);
951 }
952 if (Column != Row.Column) {
953 Column = Row.Column;
954 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
955 MS->EmitULEB128IntValue(Column);
956 LineSectionSize += 1 + getULEB128Size(Column);
957 }
958
959 // FIXME: We should handle the discriminator here, but dsymutil
960 // doesn' consider it, thus ignore it for now.
961
962 if (Isa != Row.Isa) {
963 Isa = Row.Isa;
964 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
965 MS->EmitULEB128IntValue(Isa);
966 LineSectionSize += 1 + getULEB128Size(Isa);
967 }
968 if (IsStatement != Row.IsStmt) {
969 IsStatement = Row.IsStmt;
970 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
971 LineSectionSize += 1;
972 }
973 if (Row.BasicBlock) {
974 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
975 LineSectionSize += 1;
976 }
977
978 if (Row.PrologueEnd) {
979 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
980 LineSectionSize += 1;
981 }
982
983 if (Row.EpilogueBegin) {
984 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
985 LineSectionSize += 1;
986 }
987
988 int64_t LineDelta = int64_t(Row.Line) - LastLine;
989 if (!Row.EndSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000990 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000991 MS->EmitBytes(EncodingOS.str());
992 LineSectionSize += EncodingBuffer.size();
993 EncodingBuffer.resize(0);
994 Address = Row.Address;
995 LastLine = Row.Line;
996 RowsSinceLastSequence++;
997 } else {
998 if (LineDelta) {
999 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
1000 MS->EmitSLEB128IntValue(LineDelta);
1001 LineSectionSize += 1 + getSLEB128Size(LineDelta);
1002 }
1003 if (AddressDelta) {
1004 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
1005 MS->EmitULEB128IntValue(AddressDelta);
1006 LineSectionSize += 1 + getULEB128Size(AddressDelta);
1007 }
Frederic Rissa5e14532015-08-07 15:14:13 +00001008 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001009 MS->EmitBytes(EncodingOS.str());
1010 LineSectionSize += EncodingBuffer.size();
1011 EncodingBuffer.resize(0);
Frederic Riss63786b02015-03-15 20:45:43 +00001012 Address = -1ULL;
1013 LastLine = FileNum = IsStatement = 1;
1014 RowsSinceLastSequence = Column = Isa = 0;
1015 }
1016 }
1017
1018 if (RowsSinceLastSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +00001019 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001020 MS->EmitBytes(EncodingOS.str());
1021 LineSectionSize += EncodingBuffer.size();
1022 EncodingBuffer.resize(0);
1023 }
1024
1025 MS->EmitLabel(LineEndSym);
1026}
1027
Frederic Rissbce93ff2015-03-16 02:05:10 +00001028/// \brief Emit the pubnames or pubtypes section contribution for \p
1029/// Unit into \p Sec. The data is provided in \p Names.
1030void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001031 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001032 const std::vector<CompileUnit::AccelInfo> &Names) {
1033 if (Names.empty())
1034 return;
1035
1036 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001037 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001038 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1039 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001040
1041 bool HeaderEmitted = false;
1042 // Emit the pubnames for this compilation unit.
1043 for (const auto &Name : Names) {
1044 if (Name.SkipPubSection)
1045 continue;
1046
1047 if (!HeaderEmitted) {
1048 // Emit the header.
1049 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001050 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001051 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001052 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001053 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1054 HeaderEmitted = true;
1055 }
1056 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001057 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001058 StringRef(Name.Name.data(), Name.Name.size() + 1));
1059 }
1060
1061 if (!HeaderEmitted)
1062 return;
1063 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001064 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001065}
1066
1067/// \brief Emit .debug_pubnames for \p Unit.
1068void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1069 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1070 "names", Unit, Unit.getPubnames());
1071}
1072
1073/// \brief Emit .debug_pubtypes for \p Unit.
1074void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1075 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1076 "types", Unit, Unit.getPubtypes());
1077}
1078
Frederic Riss5a642072015-06-05 23:06:11 +00001079/// \brief Emit a CIE into the debug_frame section.
1080void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1081 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1082
1083 MS->EmitBytes(CIEBytes);
1084 FrameSectionSize += CIEBytes.size();
1085}
1086
1087/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1088/// contains the FDE data without the length, CIE offset and address
1089/// which will be replaced with the paramter values.
1090void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1091 uint32_t Address, StringRef FDEBytes) {
1092 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1093
1094 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1095 MS->EmitIntValue(CIEOffset, 4);
1096 MS->EmitIntValue(Address, AddrSize);
1097 MS->EmitBytes(FDEBytes);
1098 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1099}
1100
Frederic Rissd3455182015-01-28 18:27:01 +00001101/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001102///
1103/// The link of the dwarf information from the object files will be
1104/// driven by the selection of 'root DIEs', which are DIEs that
1105/// describe variables or functions that are present in the linked
1106/// binary (and thus have entries in the debug map). All the debug
1107/// information that will be linked (the DIEs, but also the line
1108/// tables, ranges, ...) is derived from that set of root DIEs.
1109///
1110/// The root DIEs are identified because they contain relocations that
1111/// correspond to a debug map entry at specific places (the low_pc for
1112/// a function, the location for a variable). These relocations are
1113/// called ValidRelocs in the DwarfLinker and are gathered as a very
1114/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001115class DwarfLinker {
1116public:
Frederic Rissb9818322015-02-28 00:29:07 +00001117 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1118 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001119 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001120
1121 /// \brief Link the contents of the DebugMap.
1122 bool link(const DebugMap &);
1123
Adrian Prantlc3021ee2015-09-22 18:50:51 +00001124 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1125 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1126
Frederic Rissd3455182015-01-28 18:27:01 +00001127private:
Frederic Riss563cba62015-01-28 22:15:14 +00001128 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001129 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001130
1131 /// \brief Called at the end of a debug object link.
1132 void endDebugObject();
1133
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001134 /// Keeps track of relocations.
1135 class RelocationManager {
1136 struct ValidReloc {
1137 uint32_t Offset;
1138 uint32_t Size;
1139 uint64_t Addend;
1140 const DebugMapObject::DebugMapEntry *Mapping;
Frederic Riss1036e642015-02-13 23:18:22 +00001141
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001142 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1143 const DebugMapObject::DebugMapEntry *Mapping)
1144 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
Frederic Riss1036e642015-02-13 23:18:22 +00001145
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001146 bool operator<(const ValidReloc &RHS) const {
1147 return Offset < RHS.Offset;
1148 }
1149 };
1150
1151 DwarfLinker &Linker;
1152
1153 /// \brief The valid relocations for the current DebugMapObject.
1154 /// This vector is sorted by relocation offset.
1155 std::vector<ValidReloc> ValidRelocs;
1156
1157 /// \brief Index into ValidRelocs of the next relocation to
1158 /// consider. As we walk the DIEs in acsending file offset and as
1159 /// ValidRelocs is sorted by file offset, keeping this index
1160 /// uptodate is all we have to do to have a cheap lookup during the
1161 /// root DIE selection and during DIE cloning.
1162 unsigned NextValidReloc;
1163
1164 public:
1165 RelocationManager(DwarfLinker &Linker)
1166 : Linker(Linker), NextValidReloc(0) {}
1167
1168 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1169 /// \brief Reset the NextValidReloc counter.
1170 void resetValidRelocs() { NextValidReloc = 0; }
1171
1172 /// \defgroup FindValidRelocations Translate debug map into a list
1173 /// of relevant relocations
1174 ///
1175 /// @{
1176 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1177 const DebugMapObject &DMO);
1178
1179 bool findValidRelocs(const object::SectionRef &Section,
1180 const object::ObjectFile &Obj,
1181 const DebugMapObject &DMO);
1182
1183 void findValidRelocsMachO(const object::SectionRef &Section,
1184 const object::MachOObjectFile &Obj,
1185 const DebugMapObject &DMO);
1186 /// @}
1187
1188 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1189 CompileUnit::DIEInfo &Info);
1190
1191 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1192 bool isLittleEndian);
Frederic Riss1036e642015-02-13 23:18:22 +00001193 };
1194
Frederic Riss84c09a52015-02-13 23:18:34 +00001195 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1196 ///
1197 /// @{
1198 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1199 /// keep. Store that information in \p CU's DIEInfo.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001200 void lookForDIEsToKeep(RelocationManager &RelocMgr,
1201 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001202 const DebugMapObject &DMO, CompileUnit &CU,
1203 unsigned Flags);
1204
Adrian Prantle5162db2015-09-22 22:20:50 +00001205 /// If this compile unit is really a skeleton CU that points to a
1206 /// clang module, register it in ClangModules and return true.
1207 ///
1208 /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
1209 /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
1210 /// hash.
1211 bool registerModuleReference(const DWARFDebugInfoEntryMinimal &CUDie,
1212 const DWARFUnit &Unit, DebugMap &ModuleMap,
1213 unsigned Indent = 0);
1214
1215 /// Recursively add the debug info in this clang module .pcm
1216 /// file (and all the modules imported by it in a bottom-up fashion)
1217 /// to Units.
Adrian Prantla112ef92015-09-23 17:35:52 +00001218 void loadClangModule(StringRef Filename, StringRef ModulePath,
1219 StringRef ModuleName, uint64_t DwoId,
Adrian Prantle5162db2015-09-22 22:20:50 +00001220 DebugMap &ModuleMap, unsigned Indent = 0);
1221
Frederic Riss84c09a52015-02-13 23:18:34 +00001222 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1223 enum TravesalFlags {
1224 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1225 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1226 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1227 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001228 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss29eedc72015-09-11 04:17:30 +00001229 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
Frederic Riss84c09a52015-02-13 23:18:34 +00001230 };
1231
1232 /// \brief Mark the passed DIE as well as all the ones it depends on
1233 /// as kept.
Adrian Prantl6ec47122015-09-22 15:31:14 +00001234 void keepDIEAndDependencies(RelocationManager &RelocMgr,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001235 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001236 CompileUnit::DIEInfo &MyInfo,
1237 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001238 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001239
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001240 unsigned shouldKeepDIE(RelocationManager &RelocMgr,
1241 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001242 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1243 unsigned Flags);
1244
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001245 unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
1246 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001247 CompileUnit &Unit,
1248 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1249
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001250 unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
1251 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001252 CompileUnit &Unit,
1253 CompileUnit::DIEInfo &MyInfo,
1254 unsigned Flags);
1255
1256 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1257 CompileUnit::DIEInfo &Info);
1258 /// @}
1259
Frederic Rissb8b43d52015-03-04 22:07:44 +00001260 /// \defgroup Linking Methods used to link the debug information
1261 ///
1262 /// @{
Frederic Rissb8b43d52015-03-04 22:07:44 +00001263
Adrian Prantl3565af42015-09-14 16:46:10 +00001264 class DIECloner {
1265 DwarfLinker &Linker;
1266 RelocationManager &RelocMgr;
1267 /// Allocator used for all the DIEValue objects.
1268 BumpPtrAllocator &DIEAlloc;
1269 MutableArrayRef<CompileUnit> CompileUnits;
1270 LinkOptions Options;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001271
Adrian Prantl3565af42015-09-14 16:46:10 +00001272 public:
1273 DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1274 BumpPtrAllocator &DIEAlloc,
1275 MutableArrayRef<CompileUnit> CompileUnits, LinkOptions &Options)
1276 : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1277 CompileUnits(CompileUnits), Options(Options) {}
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001278
Adrian Prantl3565af42015-09-14 16:46:10 +00001279 /// Recursively clone \p InputDIE into an tree of DIE objects
1280 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1281 /// stripped out and addresses have been rewritten according to the
1282 /// debug map.
1283 ///
1284 /// \param OutOffset is the offset the cloned DIE in the output
1285 /// compile unit.
1286 /// \param PCOffset (while cloning a function scope) is the offset
1287 /// applied to the entry point of the function to get the linked address.
1288 ///
1289 /// \returns the root of the cloned tree or null if nothing was selected.
Adrian Prantl3abe18d2015-09-14 23:27:26 +00001290 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Adrian Prantl3565af42015-09-14 16:46:10 +00001291 int64_t PCOffset, uint32_t OutOffset, unsigned Flags);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001292
Adrian Prantl3565af42015-09-14 16:46:10 +00001293 /// Construct the output DIE tree by cloning the DIEs we
1294 /// chose to keep above. If there are no valid relocs, then there's
1295 /// nothing to clone/emit.
1296 void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001297
Adrian Prantl3565af42015-09-14 16:46:10 +00001298 private:
1299 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
Frederic Rissbce93ff2015-03-16 02:05:10 +00001300
Adrian Prantl3565af42015-09-14 16:46:10 +00001301 /// Information gathered and exchanged between the various
1302 /// clone*Attributes helpers about the attributes of a particular DIE.
1303 struct AttributesInfo {
1304 const char *Name, *MangledName; ///< Names.
1305 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
Frederic Riss31da3242015-03-11 18:45:52 +00001306
Adrian Prantl3565af42015-09-14 16:46:10 +00001307 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1308 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1309 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
Frederic Rissbce93ff2015-03-16 02:05:10 +00001310
Adrian Prantl3565af42015-09-14 16:46:10 +00001311 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1312 bool IsDeclaration; ///< Is this DIE only a declaration?
1313
1314 AttributesInfo()
1315 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1316 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1317 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1318 };
1319
1320 /// Helper for cloneDIE.
1321 unsigned cloneAttribute(DIE &Die,
1322 const DWARFDebugInfoEntryMinimal &InputDIE,
1323 CompileUnit &U, const DWARFFormValue &Val,
1324 const AttributeSpec AttrSpec, unsigned AttrSize,
1325 AttributesInfo &AttrInfo);
1326
1327 /// Clone a string attribute described by \p AttrSpec and add
1328 /// it to \p Die.
1329 /// \returns the size of the new attribute.
1330 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1331 const DWARFFormValue &Val,
1332 const DWARFUnit &U);
1333
1334 /// Clone an attribute referencing another DIE and add
1335 /// it to \p Die.
1336 /// \returns the size of the new attribute.
1337 unsigned
1338 cloneDieReferenceAttribute(DIE &Die,
1339 const DWARFDebugInfoEntryMinimal &InputDIE,
1340 AttributeSpec AttrSpec, unsigned AttrSize,
1341 const DWARFFormValue &Val, CompileUnit &Unit);
1342
1343 /// Clone an attribute referencing another DIE and add
1344 /// it to \p Die.
1345 /// \returns the size of the new attribute.
1346 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1347 const DWARFFormValue &Val, unsigned AttrSize);
1348
1349 /// Clone an attribute referencing another DIE and add
1350 /// it to \p Die.
1351 /// \returns the size of the new attribute.
1352 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1353 const DWARFFormValue &Val,
1354 const CompileUnit &Unit,
1355 AttributesInfo &Info);
1356
1357 /// Clone a scalar attribute and add it to \p Die.
1358 /// \returns the size of the new attribute.
1359 unsigned cloneScalarAttribute(DIE &Die,
1360 const DWARFDebugInfoEntryMinimal &InputDIE,
1361 CompileUnit &U, AttributeSpec AttrSpec,
1362 const DWARFFormValue &Val, unsigned AttrSize,
1363 AttributesInfo &Info);
1364
1365 /// Get the potential name and mangled name for the entity
1366 /// described by \p Die and store them in \Info if they are not
1367 /// already there.
1368 /// \returns is a name was found.
1369 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1370 AttributesInfo &Info);
1371
1372 /// Create a copy of abbreviation Abbrev.
1373 void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
Frederic Riss31da3242015-03-11 18:45:52 +00001374 };
1375
Frederic Rissb8b43d52015-03-04 22:07:44 +00001376 /// \brief Assign an abbreviation number to \p Abbrev
1377 void AssignAbbrev(DIEAbbrev &Abbrev);
1378
1379 /// \brief FoldingSet that uniques the abbreviations.
1380 FoldingSet<DIEAbbrev> AbbreviationsSet;
1381 /// \brief Storage for the unique Abbreviations.
1382 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1383 /// be changed to a vecot of unique_ptrs.
David Blaikie6196aa02015-11-18 00:34:10 +00001384 std::vector<std::unique_ptr<DIEAbbrev>> Abbreviations;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001385
Frederic Riss25440872015-03-13 23:30:31 +00001386 /// \brief Compute and emit debug_ranges section for \p Unit, and
1387 /// patch the attributes referencing it.
1388 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1389
1390 /// \brief Generate and emit the DW_AT_ranges attribute for a
1391 /// compile_unit if it had one.
1392 void generateUnitRanges(CompileUnit &Unit) const;
1393
Frederic Riss63786b02015-03-15 20:45:43 +00001394 /// \brief Extract the line tables fromt he original dwarf, extract
1395 /// the relevant parts according to the linked function ranges and
1396 /// emit the result in the debug_line section.
1397 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1398
Frederic Rissbce93ff2015-03-16 02:05:10 +00001399 /// \brief Emit the accelerator entries for \p Unit.
1400 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1401
Frederic Riss5a642072015-06-05 23:06:11 +00001402 /// \brief Patch the frame info for an object file and emit it.
1403 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1404 unsigned AddressSize);
1405
Frederic Rissb8b43d52015-03-04 22:07:44 +00001406 /// \brief DIELoc objects that need to be destructed (but not freed!).
1407 std::vector<DIELoc *> DIELocs;
1408 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1409 std::vector<DIEBlock *> DIEBlocks;
1410 /// \brief Allocator used for all the DIEValue objects.
1411 BumpPtrAllocator DIEAlloc;
1412 /// @}
1413
Frederic Riss1c650942015-07-21 22:41:43 +00001414 /// ODR Contexts for that link.
1415 DeclContextTree ODRContexts;
1416
Frederic Riss1b9da422015-02-13 23:18:29 +00001417 /// \defgroup Helpers Various helper methods.
1418 ///
1419 /// @{
Benjamin Kramerc321e532016-06-08 19:09:22 +00001420 bool createStreamer(const Triple &TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001421
1422 /// \brief Attempt to load a debug object from disk.
1423 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1424 DebugMapObject &Obj,
1425 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001426 /// @}
1427
Frederic Rissd3455182015-01-28 18:27:01 +00001428 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001429 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001430 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001431 std::unique_ptr<DwarfStreamer> Streamer;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001432 uint64_t OutputDebugInfoSize;
Adrian Prantle5162db2015-09-22 22:20:50 +00001433 unsigned UnitID; ///< A unique ID that identifies each compile unit.
Frederic Riss563cba62015-01-28 22:15:14 +00001434
1435 /// The units of the current debug map object.
1436 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001437
Oleg Ranevskyy5f78c5c2015-10-23 17:10:44 +00001438 /// The debug map object currently under consideration.
Frederic Riss1b9da422015-02-13 23:18:29 +00001439 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001440
1441 /// \brief The Dwarf string pool
1442 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001443
1444 /// \brief This map is keyed by the entry PC of functions in that
1445 /// debug object and the associated value is a pair storing the
1446 /// corresponding end PC and the offset to apply to get the linked
1447 /// address.
1448 ///
1449 /// See startDebugObject() for a more complete description of its use.
1450 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001451
1452 /// \brief The CIEs that have been emitted in the output
1453 /// section. The actual CIE data serves a the key to this StringMap,
1454 /// this takes care of comparing the semantics of CIEs defined in
1455 /// different object files.
1456 StringMap<uint32_t> EmittedCIEs;
1457
1458 /// Offset of the last CIE that has been emitted in the output
1459 /// debug_frame section.
1460 uint32_t LastCIEOffset;
Adrian Prantle5162db2015-09-22 22:20:50 +00001461
Adrian Prantl20937022015-09-23 17:11:10 +00001462 /// Mapping the PCM filename to the DwoId.
1463 StringMap<uint64_t> ClangModules;
Adrian Prantla9e23832016-01-14 18:31:07 +00001464
1465 bool ModuleCacheHintDisplayed = false;
1466 bool ArchiveHintDisplayed = false;
Frederic Rissd3455182015-01-28 18:27:01 +00001467};
1468
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001469/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
1470/// CompileUnit object instead.
1471static CompileUnit *getUnitForOffset(MutableArrayRef<CompileUnit> Units,
1472 unsigned Offset) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001473 auto CU =
1474 std::upper_bound(Units.begin(), Units.end(), Offset,
1475 [](uint32_t LHS, const CompileUnit &RHS) {
1476 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1477 });
1478 return CU != Units.end() ? &*CU : nullptr;
1479}
1480
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001481/// Resolve the DIE attribute reference that has been
Frederic Riss1b9da422015-02-13 23:18:29 +00001482/// extracted in \p RefValue. The resulting DIE migh be in another
1483/// CompileUnit which is stored into \p ReferencedCU.
1484/// \returns null if resolving fails for any reason.
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001485static const DWARFDebugInfoEntryMinimal *resolveDIEReference(
1486 const DwarfLinker &Linker, MutableArrayRef<CompileUnit> Units,
Frederic Riss1c650942015-07-21 22:41:43 +00001487 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001488 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1489 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
Greg Claytoncddab272016-10-31 16:46:02 +00001490 uint64_t RefOffset = *RefValue.getAsReference();
Frederic Riss1b9da422015-02-13 23:18:29 +00001491
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001492 if ((RefCU = getUnitForOffset(Units, RefOffset)))
Frederic Riss1b9da422015-02-13 23:18:29 +00001493 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1494 return RefDie;
1495
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001496 Linker.reportWarning("could not find referenced DIE", &Unit, &DIE);
Frederic Riss1b9da422015-02-13 23:18:29 +00001497 return nullptr;
1498}
1499
Frederic Riss1c650942015-07-21 22:41:43 +00001500/// \returns whether the passed \a Attr type might contain a DIE
1501/// reference suitable for ODR uniquing.
1502static bool isODRAttribute(uint16_t Attr) {
1503 switch (Attr) {
1504 default:
1505 return false;
1506 case dwarf::DW_AT_type:
1507 case dwarf::DW_AT_containing_type:
1508 case dwarf::DW_AT_specification:
1509 case dwarf::DW_AT_abstract_origin:
1510 case dwarf::DW_AT_import:
1511 return true;
1512 }
1513 llvm_unreachable("Improper attribute.");
1514}
1515
1516/// Set the last DIE/CU a context was seen in and, possibly invalidate
1517/// the context if it is ambiguous.
1518///
1519/// In the current implementation, we don't handle overloaded
1520/// functions well, because the argument types are not taken into
1521/// account when computing the DeclContext tree.
1522///
1523/// Some of this is mitigated byt using mangled names that do contain
1524/// the arguments types, but sometimes (eg. with function templates)
1525/// we don't have that. In that case, just do not unique anything that
1526/// refers to the contexts we are not able to distinguish.
1527///
1528/// If a context that is not a namespace appears twice in the same CU,
1529/// we know it is ambiguous. Make it invalid.
1530bool DeclContext::setLastSeenDIE(CompileUnit &U,
1531 const DWARFDebugInfoEntryMinimal *Die) {
1532 if (LastSeenCompileUnitID == U.getUniqueID()) {
1533 DWARFUnit &OrigUnit = U.getOrigUnit();
1534 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1535 U.getInfo(FirstIdx).Ctxt = nullptr;
1536 return false;
1537 }
1538
1539 LastSeenCompileUnitID = U.getUniqueID();
1540 LastSeenDIE = Die;
1541 return true;
1542}
1543
Frederic Riss1c650942015-07-21 22:41:43 +00001544PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1545 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
Adrian Prantl42562c32015-10-02 00:27:08 +00001546 NonRelocatableStringpool &StringPool, bool InClangModule) {
Frederic Riss1c650942015-07-21 22:41:43 +00001547 unsigned Tag = DIE->getTag();
1548
1549 // FIXME: dsymutil-classic compat: We should bail out here if we
1550 // have a specification or an abstract_origin. We will get the
1551 // parent context wrong here.
1552
1553 switch (Tag) {
1554 default:
1555 // By default stop gathering child contexts.
1556 return PointerIntPair<DeclContext *, 1>(nullptr);
Adrian Prantla112ef92015-09-23 17:35:52 +00001557 case dwarf::DW_TAG_module:
1558 break;
Frederic Riss1c650942015-07-21 22:41:43 +00001559 case dwarf::DW_TAG_compile_unit:
Frederic Riss1c650942015-07-21 22:41:43 +00001560 return PointerIntPair<DeclContext *, 1>(&Context);
1561 case dwarf::DW_TAG_subprogram:
1562 // Do not unique anything inside CU local functions.
1563 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1564 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1565 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1566 dwarf::DW_AT_external, 0))
1567 return PointerIntPair<DeclContext *, 1>(nullptr);
Justin Bognerb03fd122016-08-17 05:10:15 +00001568 LLVM_FALLTHROUGH;
Frederic Riss1c650942015-07-21 22:41:43 +00001569 case dwarf::DW_TAG_member:
1570 case dwarf::DW_TAG_namespace:
1571 case dwarf::DW_TAG_structure_type:
1572 case dwarf::DW_TAG_class_type:
1573 case dwarf::DW_TAG_union_type:
1574 case dwarf::DW_TAG_enumeration_type:
1575 case dwarf::DW_TAG_typedef:
1576 // Artificial things might be ambiguous, because they might be
1577 // created on demand. For example implicitely defined constructors
1578 // are ambiguous because of the way we identify contexts, and they
1579 // won't be generated everytime everywhere.
1580 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1581 dwarf::DW_AT_artificial, 0))
1582 return PointerIntPair<DeclContext *, 1>(nullptr);
1583 break;
1584 }
1585
1586 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1587 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1588 StringRef NameRef;
1589 StringRef ShortNameRef;
1590 StringRef FileRef;
1591
1592 if (Name)
1593 NameRef = StringPool.internString(Name);
1594 else if (Tag == dwarf::DW_TAG_namespace)
1595 // FIXME: For dsymutil-classic compatibility. I think uniquing
1596 // within anonymous namespaces is wrong. There is no ODR guarantee
1597 // there.
1598 NameRef = StringPool.internString("(anonymous namespace)");
1599
1600 if (ShortName && ShortName != Name)
1601 ShortNameRef = StringPool.internString(ShortName);
1602 else
1603 ShortNameRef = NameRef;
1604
1605 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1606 Tag != dwarf::DW_TAG_union_type &&
1607 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1608 return PointerIntPair<DeclContext *, 1>(nullptr);
1609
Frederic Riss1c650942015-07-21 22:41:43 +00001610 unsigned Line = 0;
Adrian Prantl42562c32015-10-02 00:27:08 +00001611 unsigned ByteSize = UINT32_MAX;
Frederic Riss1c650942015-07-21 22:41:43 +00001612
Adrian Prantl42562c32015-10-02 00:27:08 +00001613 if (!InClangModule) {
1614 // Gather some discriminating data about the DeclContext we will be
1615 // creating: File, line number and byte size. This shouldn't be
1616 // necessary, because the ODR is just about names, but given that we
1617 // do some approximations with overloaded functions and anonymous
1618 // namespaces, use these additional data points to make the process
1619 // safer. This is disabled for clang modules, because forward
1620 // declarations of module-defined types do not have a file and line.
1621 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1622 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1623 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1624 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1625 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1626 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1627 &U.getOrigUnit())) {
1628 // FIXME: dsymutil-classic compatibility. I'd rather not
1629 // unique anything in anonymous namespaces, but if we do, then
1630 // verify that the file and line correspond.
1631 if (!Name && Tag == dwarf::DW_TAG_namespace)
1632 FileNum = 1;
Frederic Riss1c650942015-07-21 22:41:43 +00001633
Adrian Prantl42562c32015-10-02 00:27:08 +00001634 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1635 // instead of "" would allow more uniquing, but for now, do
1636 // it this way to match dsymutil-classic.
Pete Cooperb2ba7762016-07-22 01:41:32 +00001637 if (LT->hasFileAtIndex(FileNum)) {
Adrian Prantl42562c32015-10-02 00:27:08 +00001638 Line = DIE->getAttributeValueAsUnsignedConstant(
1639 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
Adrian Prantl42562c32015-10-02 00:27:08 +00001640 // Cache the resolved paths, because calling realpath is expansive.
Pete Cooperef4e36a2016-03-18 03:48:09 +00001641 StringRef ResolvedPath = U.getResolvedPath(FileNum);
1642 if (!ResolvedPath.empty()) {
1643 FileRef = ResolvedPath;
Adrian Prantl42562c32015-10-02 00:27:08 +00001644 } else {
Pete Cooperb2ba7762016-07-22 01:41:32 +00001645 std::string File;
1646 bool gotFileName =
1647 LT->getFileNameByIndex(FileNum, "",
1648 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1649 File);
1650 (void)gotFileName;
1651 assert(gotFileName && "Must get file name from line table");
Pete Coopercadadaa2016-07-22 01:52:58 +00001652#ifdef HAVE_REALPATH
Adrian Prantl42562c32015-10-02 00:27:08 +00001653 char RealPath[PATH_MAX + 1];
1654 RealPath[PATH_MAX] = 0;
1655 if (::realpath(File.c_str(), RealPath))
1656 File = RealPath;
Pete Cooper64d075e2016-03-18 05:04:04 +00001657#endif
Pete Cooperef4e36a2016-03-18 03:48:09 +00001658 FileRef = StringPool.internString(File);
1659 U.setResolvedPath(FileNum, FileRef);
Adrian Prantl42562c32015-10-02 00:27:08 +00001660 }
Adrian Prantl42562c32015-10-02 00:27:08 +00001661 }
Frederic Riss1c650942015-07-21 22:41:43 +00001662 }
1663 }
1664 }
1665 }
1666
1667 if (!Line && NameRef.empty())
1668 return PointerIntPair<DeclContext *, 1>(nullptr);
1669
Frederic Riss1c650942015-07-21 22:41:43 +00001670 // We hash NameRef, which is the mangled name, in order to get most
Adrian Prantla112ef92015-09-23 17:35:52 +00001671 // overloaded functions resolve correctly.
1672 //
1673 // Strictly speaking, hashing the Tag is only necessary for a
1674 // DW_TAG_module, to prevent uniquing of a module and a namespace
1675 // with the same name.
1676 //
1677 // FIXME: dsymutil-classic won't unique the same type presented
1678 // once as a struct and once as a class. Using the Tag in the fully
1679 // qualified name hash to get the same effect.
Frederic Riss1c650942015-07-21 22:41:43 +00001680 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1681
1682 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1683 // use the filename.
1684 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1685 Hash = hash_combine(Hash, FileRef);
1686
1687 // Now look if this context already exists.
1688 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1689 auto ContextIter = Contexts.find(&Key);
1690
1691 if (ContextIter == Contexts.end()) {
1692 // The context wasn't found.
1693 bool Inserted;
1694 DeclContext *NewContext =
1695 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1696 Context, DIE, U.getUniqueID());
1697 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1698 assert(Inserted && "Failed to insert DeclContext");
1699 (void)Inserted;
1700 } else if (Tag != dwarf::DW_TAG_namespace &&
1701 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1702 // The context was found, but it is ambiguous with another context
1703 // in the same file. Mark it invalid.
1704 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1705 }
1706
1707 assert(ContextIter != Contexts.end());
1708 // FIXME: dsymutil-classic compatibility. Union types aren't
1709 // uniques, but their children might be.
1710 if ((Tag == dwarf::DW_TAG_subprogram &&
1711 Context.getTag() != dwarf::DW_TAG_structure_type &&
1712 Context.getTag() != dwarf::DW_TAG_class_type) ||
1713 (Tag == dwarf::DW_TAG_union_type))
1714 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1715
1716 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1717}
1718
Adrian Prantl3565af42015-09-14 16:46:10 +00001719bool DwarfLinker::DIECloner::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1720 DWARFUnit &U, AttributesInfo &Info) {
1721 // FIXME: a bit wasteful as the first getName might return the
Frederic Rissbce93ff2015-03-16 02:05:10 +00001722 // short name.
1723 if (!Info.MangledName &&
1724 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001725 Info.MangledNameOffset =
1726 Linker.StringPool.getStringOffset(Info.MangledName);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001727
1728 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001729 Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001730
1731 return Info.Name || Info.MangledName;
1732}
1733
Frederic Riss1b9da422015-02-13 23:18:29 +00001734/// \brief Report a warning to the user, optionaly including
1735/// information about a specific \p DIE related to the warning.
1736void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001737 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001738 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001739 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001740 Context = CurrentDebugObject->getObjectFilename();
1741 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001742
Frederic Rissb9818322015-02-28 00:29:07 +00001743 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001744 return;
1745
1746 errs() << " in DIE:\n";
1747 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1748 6 /* Indent */);
1749}
1750
Benjamin Kramerc321e532016-06-08 19:09:22 +00001751bool DwarfLinker::createStreamer(const Triple &TheTriple,
1752 StringRef OutputFilename) {
Frederic Rissc99ea202015-02-28 00:29:11 +00001753 if (Options.NoOutput)
1754 return true;
1755
Frederic Rissb52cf522015-02-28 00:42:37 +00001756 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001757 return Streamer->init(TheTriple, OutputFilename);
1758}
1759
Adrian Prantla112ef92015-09-23 17:35:52 +00001760/// Recursive helper to build the global DeclContext information and
1761/// gather the child->parent relationships in the original compile unit.
1762///
1763/// \return true when this DIE and all of its children are only
1764/// forward declarations to types defined in external clang modules
1765/// (i.e., forward declarations that are children of a DW_TAG_module).
1766static bool analyzeContextInfo(const DWARFDebugInfoEntryMinimal *DIE,
1767 unsigned ParentIdx, CompileUnit &CU,
1768 DeclContext *CurrentDeclContext,
1769 NonRelocatableStringpool &StringPool,
1770 DeclContextTree &Contexts,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001771 bool InImportedModule = false) {
Frederic Riss563cba62015-01-28 22:15:14 +00001772 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001773 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1774
Adrian Prantla112ef92015-09-23 17:35:52 +00001775 // Clang imposes an ODR on modules(!) regardless of the language:
1776 // "The module-id should consist of only a single identifier,
1777 // which provides the name of the module being defined. Each
1778 // module shall have a single definition."
1779 //
1780 // This does not extend to the types inside the modules:
1781 // "[I]n C, this implies that if two structs are defined in
1782 // different submodules with the same name, those two types are
1783 // distinct types (but may be compatible types if their
1784 // definitions match)."
1785 //
1786 // We treat non-C++ modules like namespaces for this reason.
Adrian Prantlf3e634b2015-09-24 16:10:14 +00001787 if (DIE->getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
Adrian Prantlea8a7242015-09-23 20:44:37 +00001788 DIE->getAttributeValueAsString(&CU.getOrigUnit(), dwarf::DW_AT_name,
1789 "") != CU.getClangModuleName()) {
1790 InImportedModule = true;
1791 }
Adrian Prantla112ef92015-09-23 17:35:52 +00001792
Frederic Riss1c650942015-07-21 22:41:43 +00001793 Info.ParentIdx = ParentIdx;
Adrian Prantl42562c32015-10-02 00:27:08 +00001794 bool InClangModule = CU.isClangModule() || InImportedModule;
1795 if (CU.hasODR() || InClangModule) {
Frederic Riss1c650942015-07-21 22:41:43 +00001796 if (CurrentDeclContext) {
Adrian Prantl42562c32015-10-02 00:27:08 +00001797 auto PtrInvalidPair = Contexts.getChildDeclContext(
1798 *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
Frederic Riss1c650942015-07-21 22:41:43 +00001799 CurrentDeclContext = PtrInvalidPair.getPointer();
1800 Info.Ctxt =
1801 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1802 } else
1803 Info.Ctxt = CurrentDeclContext = nullptr;
1804 }
Frederic Riss563cba62015-01-28 22:15:14 +00001805
Adrian Prantlea8a7242015-09-23 20:44:37 +00001806 Info.Prune = InImportedModule;
Frederic Riss563cba62015-01-28 22:15:14 +00001807 if (DIE->hasChildren())
1808 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1809 Child = Child->getSibling())
Adrian Prantla112ef92015-09-23 17:35:52 +00001810 Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001811 StringPool, Contexts, InImportedModule);
Adrian Prantla112ef92015-09-23 17:35:52 +00001812
1813 // Prune this DIE if it is either a forward declaration inside a
1814 // DW_TAG_module or a DW_TAG_module that contains nothing but
1815 // forward declarations.
1816 Info.Prune &= (DIE->getTag() == dwarf::DW_TAG_module) ||
1817 DIE->getAttributeValueAsUnsignedConstant(
1818 &CU.getOrigUnit(), dwarf::DW_AT_declaration, 0);
1819
Adrian Prantld2793a02015-10-05 23:11:20 +00001820 // Don't prune it if there is no definition for the DIE.
1821 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
1822
Adrian Prantla112ef92015-09-23 17:35:52 +00001823 return Info.Prune;
Frederic Riss563cba62015-01-28 22:15:14 +00001824}
1825
Frederic Riss84c09a52015-02-13 23:18:34 +00001826static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1827 switch (Tag) {
1828 default:
1829 return false;
1830 case dwarf::DW_TAG_subprogram:
1831 case dwarf::DW_TAG_lexical_block:
1832 case dwarf::DW_TAG_subroutine_type:
1833 case dwarf::DW_TAG_structure_type:
1834 case dwarf::DW_TAG_class_type:
1835 case dwarf::DW_TAG_union_type:
1836 return true;
1837 }
1838 llvm_unreachable("Invalid Tag");
1839}
1840
Frederic Riss63786b02015-03-15 20:45:43 +00001841void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001842 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss63786b02015-03-15 20:45:43 +00001843 // Iterate over the debug map entries and put all the ones that are
1844 // functions (because they have a size) into the Ranges map. This
1845 // map is very similar to the FunctionRanges that are stored in each
1846 // unit, with 2 notable differences:
1847 // - obviously this one is global, while the other ones are per-unit.
1848 // - this one contains not only the functions described in the DIE
1849 // tree, but also the ones that are only in the debug map.
1850 // The latter information is required to reproduce dsymutil's logic
1851 // while linking line tables. The cases where this information
1852 // matters look like bugs that need to be investigated, but for now
1853 // we need to reproduce dsymutil's behavior.
1854 // FIXME: Once we understood exactly if that information is needed,
1855 // maybe totally remove this (or try to use it to do a real
1856 // -gline-tables-only on Darwin.
1857 for (const auto &Entry : Obj.symbols()) {
1858 const auto &Mapping = Entry.getValue();
Frederic Rissd8c33dc2016-01-31 04:29:22 +00001859 if (Mapping.Size && Mapping.ObjectAddress)
1860 Ranges[*Mapping.ObjectAddress] = std::make_pair(
1861 *Mapping.ObjectAddress + Mapping.Size,
1862 int64_t(Mapping.BinaryAddress) - *Mapping.ObjectAddress);
Frederic Riss63786b02015-03-15 20:45:43 +00001863 }
Frederic Riss563cba62015-01-28 22:15:14 +00001864}
1865
Frederic Riss1036e642015-02-13 23:18:22 +00001866void DwarfLinker::endDebugObject() {
1867 Units.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001868 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001869
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001870 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1871 (*I)->~DIEBlock();
1872 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1873 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001874
1875 DIEBlocks.clear();
1876 DIELocs.clear();
1877 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001878}
1879
Frederic Riss1d536582016-02-01 04:43:14 +00001880static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
1881 switch (Arch) {
1882 case Triple::x86:
1883 return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
1884 RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
1885 case Triple::x86_64:
1886 return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
1887 case Triple::arm:
1888 case Triple::thumb:
1889 return RelocType == MachO::ARM_RELOC_SECTDIFF ||
1890 RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1891 RelocType == MachO::ARM_RELOC_HALF ||
1892 RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
1893 case Triple::aarch64:
1894 return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
1895 default:
1896 return false;
1897 }
1898}
1899
Frederic Riss1036e642015-02-13 23:18:22 +00001900/// \brief Iterate over the relocations of the given \p Section and
1901/// store the ones that correspond to debug map entries into the
1902/// ValidRelocs array.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001903void DwarfLinker::RelocationManager::
1904findValidRelocsMachO(const object::SectionRef &Section,
1905 const object::MachOObjectFile &Obj,
1906 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001907 StringRef Contents;
1908 Section.getContents(Contents);
1909 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
Frederic Riss1d536582016-02-01 04:43:14 +00001910 bool SkipNext = false;
Frederic Riss1036e642015-02-13 23:18:22 +00001911
1912 for (const object::RelocationRef &Reloc : Section.relocations()) {
Frederic Riss1d536582016-02-01 04:43:14 +00001913 if (SkipNext) {
1914 SkipNext = false;
1915 continue;
1916 }
1917
Frederic Riss1036e642015-02-13 23:18:22 +00001918 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1919 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
Frederic Riss1d536582016-02-01 04:43:14 +00001920
1921 if (isMachOPairedReloc(Obj.getAnyRelocationType(MachOReloc),
1922 Obj.getArch())) {
1923 SkipNext = true;
1924 Linker.reportWarning(" unsupported relocation in debug_info section.");
1925 continue;
1926 }
1927
Frederic Riss1036e642015-02-13 23:18:22 +00001928 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001929 uint64_t Offset64 = Reloc.getOffset();
1930 if ((RelocSize != 4 && RelocSize != 8)) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001931 Linker.reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001932 continue;
1933 }
1934 uint32_t Offset = Offset64;
1935 // Mach-o uses REL relocations, the addend is at the relocation offset.
1936 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
Frederic Riss0314e1e2016-02-01 03:44:22 +00001937 uint64_t SymAddress;
1938 int64_t SymOffset;
1939
1940 if (Obj.isRelocationScattered(MachOReloc)) {
1941 // The address of the base symbol for scattered relocations is
1942 // stored in the reloc itself. The actual addend will store the
1943 // base address plus the offset.
1944 SymAddress = Obj.getScatteredRelocationValue(MachOReloc);
1945 SymOffset = int64_t(Addend) - SymAddress;
1946 } else {
1947 SymAddress = Addend;
1948 SymOffset = 0;
1949 }
Frederic Riss1036e642015-02-13 23:18:22 +00001950
1951 auto Sym = Reloc.getSymbol();
1952 if (Sym != Obj.symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001953 Expected<StringRef> SymbolName = Sym->getName();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001954 if (!SymbolName) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001955 consumeError(SymbolName.takeError());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001956 Linker.reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001957 continue;
1958 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001959 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001960 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
Frederic Riss0314e1e2016-02-01 03:44:22 +00001961 } else if (const auto *Mapping = DMO.lookupObjectAddress(SymAddress)) {
Frederic Riss1036e642015-02-13 23:18:22 +00001962 // Do not store the addend. The addend was the address of the
1963 // symbol in the object file, the address in the binary that is
1964 // stored in the debug map doesn't need to be offseted.
Frederic Riss0314e1e2016-02-01 03:44:22 +00001965 ValidRelocs.emplace_back(Offset64, RelocSize, SymOffset, Mapping);
Frederic Riss1036e642015-02-13 23:18:22 +00001966 }
1967 }
1968}
1969
1970/// \brief Dispatch the valid relocation finding logic to the
1971/// appropriate handler depending on the object file format.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001972bool DwarfLinker::RelocationManager::findValidRelocs(
1973 const object::SectionRef &Section, const object::ObjectFile &Obj,
1974 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001975 // Dispatch to the right handler depending on the file type.
1976 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1977 findValidRelocsMachO(Section, *MachOObj, DMO);
1978 else
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001979 Linker.reportWarning(Twine("unsupported object file type: ") +
1980 Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001981
1982 if (ValidRelocs.empty())
1983 return false;
1984
1985 // Sort the relocations by offset. We will walk the DIEs linearly in
1986 // the file, this allows us to just keep an index in the relocation
1987 // array that we advance during our walk, rather than resorting to
1988 // some associative container. See DwarfLinker::NextValidReloc.
1989 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1990 return true;
1991}
1992
1993/// \brief Look for relocations in the debug_info section that match
1994/// entries in the debug map. These relocations will drive the Dwarf
1995/// link by indicating which DIEs refer to symbols present in the
1996/// linked binary.
1997/// \returns wether there are any valid relocations in the debug info.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001998bool DwarfLinker::RelocationManager::
1999findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
2000 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00002001 // Find the debug_info section.
2002 for (const object::SectionRef &Section : Obj.sections()) {
2003 StringRef SectionName;
2004 Section.getName(SectionName);
2005 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
2006 if (SectionName != "debug_info")
2007 continue;
2008 return findValidRelocs(Section, Obj, DMO);
2009 }
2010 return false;
2011}
Frederic Riss563cba62015-01-28 22:15:14 +00002012
Frederic Riss84c09a52015-02-13 23:18:34 +00002013/// \brief Checks that there is a relocation against an actual debug
2014/// map entry between \p StartOffset and \p NextOffset.
2015///
2016/// This function must be called with offsets in strictly ascending
2017/// order because it never looks back at relocations it already 'went past'.
2018/// \returns true and sets Info.InDebugMap if it is the case.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002019bool DwarfLinker::RelocationManager::
2020hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
2021 CompileUnit::DIEInfo &Info) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002022 assert(NextValidReloc == 0 ||
2023 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
2024 if (NextValidReloc >= ValidRelocs.size())
2025 return false;
2026
2027 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
2028
2029 // We might need to skip some relocs that we didn't consider. For
2030 // example the high_pc of a discarded DIE might contain a reloc that
2031 // is in the list because it actually corresponds to the start of a
2032 // function that is in the debug map.
2033 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
2034 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
2035
2036 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
2037 return false;
2038
2039 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00002040 const auto &Mapping = ValidReloc.Mapping->getValue();
Frederic Rissd8c33dc2016-01-31 04:29:22 +00002041 uint64_t ObjectAddress =
2042 Mapping.ObjectAddress ? uint64_t(*Mapping.ObjectAddress) : UINT64_MAX;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002043 if (Linker.Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002044 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
Frederic Rissd8c33dc2016-01-31 04:29:22 +00002045 << " " << format("\t%016" PRIx64 " => %016" PRIx64, ObjectAddress,
Frederic Riss08462f72015-06-01 21:12:45 +00002046 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00002047
Frederic Rissd8c33dc2016-01-31 04:29:22 +00002048 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend;
2049 if (Mapping.ObjectAddress)
2050 Info.AddrAdjust -= ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00002051 Info.InDebugMap = true;
2052 return true;
2053}
2054
2055/// \brief Get the starting and ending (exclusive) offset for the
2056/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
2057/// supposed to point to the position of the first attribute described
2058/// by \p Abbrev.
2059/// \return [StartOffset, EndOffset) as a pair.
2060static std::pair<uint32_t, uint32_t>
2061getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
2062 unsigned Offset, const DWARFUnit &Unit) {
2063 DataExtractor Data = Unit.getDebugInfoExtractor();
2064
2065 for (unsigned i = 0; i < Idx; ++i)
2066 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
2067
2068 uint32_t End = Offset;
2069 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
2070
2071 return std::make_pair(Offset, End);
2072}
2073
2074/// \brief Check if a variable describing DIE should be kept.
2075/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002076unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
2077 const DWARFDebugInfoEntryMinimal &DIE,
2078 CompileUnit &Unit,
2079 CompileUnit::DIEInfo &MyInfo,
2080 unsigned Flags) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002081 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2082
2083 // Global variables with constant value can always be kept.
2084 if (!(Flags & TF_InFunctionScope) &&
2085 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
2086 MyInfo.InDebugMap = true;
2087 return Flags | TF_Keep;
2088 }
2089
2090 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
2091 if (LocationIdx == -1U)
2092 return Flags;
2093
2094 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2095 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2096 uint32_t LocationOffset, LocationEndOffset;
2097 std::tie(LocationOffset, LocationEndOffset) =
2098 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
2099
2100 // See if there is a relocation to a valid debug map entry inside
2101 // this variable's location. The order is important here. We want to
2102 // always check in the variable has a valid relocation, so that the
2103 // DIEInfo is filled. However, we don't want a static variable in a
2104 // function to force us to keep the enclosing function.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002105 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
Frederic Riss84c09a52015-02-13 23:18:34 +00002106 (Flags & TF_InFunctionScope))
2107 return Flags;
2108
Frederic Rissb9818322015-02-28 00:29:07 +00002109 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002110 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2111
2112 return Flags | TF_Keep;
2113}
2114
2115/// \brief Check if a function describing DIE should be kept.
2116/// \returns updated TraversalFlags.
2117unsigned DwarfLinker::shouldKeepSubprogramDIE(
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002118 RelocationManager &RelocMgr,
Frederic Riss84c09a52015-02-13 23:18:34 +00002119 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2120 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2121 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2122
2123 Flags |= TF_InFunctionScope;
2124
2125 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2126 if (LowPcIdx == -1U)
2127 return Flags;
2128
2129 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2130 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2131 uint32_t LowPcOffset, LowPcEndOffset;
2132 std::tie(LowPcOffset, LowPcEndOffset) =
2133 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2134
2135 uint64_t LowPc =
2136 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2137 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2138 if (LowPc == -1ULL ||
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002139 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
Frederic Riss84c09a52015-02-13 23:18:34 +00002140 return Flags;
2141
Frederic Rissb9818322015-02-28 00:29:07 +00002142 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002143 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2144
Frederic Riss1af75f72015-03-12 18:45:10 +00002145 Flags |= TF_Keep;
2146
2147 DWARFFormValue HighPcValue;
2148 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2149 reportWarning("Function without high_pc. Range will be discarded.\n",
2150 &OrigUnit, &DIE);
2151 return Flags;
2152 }
2153
2154 uint64_t HighPc;
2155 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
Greg Claytoncddab272016-10-31 16:46:02 +00002156 HighPc = *HighPcValue.getAsAddress();
Frederic Riss1af75f72015-03-12 18:45:10 +00002157 } else {
2158 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2159 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2160 }
2161
Frederic Riss63786b02015-03-15 20:45:43 +00002162 // Replace the debug map range with a more accurate one.
2163 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00002164 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2165 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00002166}
2167
2168/// \brief Check if a DIE should be kept.
2169/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002170unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
2171 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00002172 CompileUnit &Unit,
2173 CompileUnit::DIEInfo &MyInfo,
2174 unsigned Flags) {
2175 switch (DIE.getTag()) {
2176 case dwarf::DW_TAG_constant:
2177 case dwarf::DW_TAG_variable:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002178 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002179 case dwarf::DW_TAG_subprogram:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002180 return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002181 case dwarf::DW_TAG_module:
2182 case dwarf::DW_TAG_imported_module:
2183 case dwarf::DW_TAG_imported_declaration:
2184 case dwarf::DW_TAG_imported_unit:
2185 // We always want to keep these.
2186 return Flags | TF_Keep;
2187 }
2188
2189 return Flags;
2190}
2191
Frederic Riss84c09a52015-02-13 23:18:34 +00002192/// \brief Mark the passed DIE as well as all the ones it depends on
2193/// as kept.
2194///
2195/// This function is called by lookForDIEsToKeep on DIEs that are
2196/// newly discovered to be needed in the link. It recursively calls
2197/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2198/// TraversalFlags to inform it that it's not doing the primary DIE
2199/// tree walk.
Adrian Prantl6ec47122015-09-22 15:31:14 +00002200void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002201 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002202 CompileUnit::DIEInfo &MyInfo,
2203 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002204 CompileUnit &CU, bool UseODR) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002205 const DWARFUnit &Unit = CU.getOrigUnit();
2206 MyInfo.Keep = true;
2207
2208 // First mark all the parent chain as kept.
2209 unsigned AncestorIdx = MyInfo.ParentIdx;
2210 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002211 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002212 lookForDIEsToKeep(RelocMgr, *Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002213 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002214 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2215 }
2216
2217 // Then we need to mark all the DIEs referenced by this DIE's
2218 // attributes as kept.
2219 DataExtractor Data = Unit.getDebugInfoExtractor();
Frederic Riss36c3cb82015-09-11 04:17:25 +00002220 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2221 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
Frederic Riss84c09a52015-02-13 23:18:34 +00002222
2223 // Mark all DIEs referenced through atttributes as kept.
2224 for (const auto &AttrSpec : Abbrev->attributes()) {
2225 DWARFFormValue Val(AttrSpec.Form);
2226
2227 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2228 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2229 continue;
2230 }
2231
2232 Val.extractValue(Data, &Offset, &Unit);
2233 CompileUnit *ReferencedCU;
Frederic Riss1c650942015-07-21 22:41:43 +00002234 if (const auto *RefDIE =
Adrian Prantlfdd9a822015-09-22 18:50:58 +00002235 resolveDIEReference(*this, MutableArrayRef<CompileUnit>(Units), Val,
2236 Unit, Die, ReferencedCU)) {
Frederic Riss1c650942015-07-21 22:41:43 +00002237 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2238 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2239 // If the referenced DIE has a DeclContext that has already been
2240 // emitted, then do not keep the one in this CU. We'll link to
2241 // the canonical DIE in cloneDieReferenceAttribute.
2242 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2243 // be necessary and could be advantageously replaced by
2244 // ReferencedCU->hasODR() && CU.hasODR().
2245 // FIXME: compatibility with dsymutil-classic. There is no
2246 // reason not to unique ref_addr references.
2247 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2248 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2249 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2250 continue;
2251
Adrian Prantle39475d2015-11-10 21:31:05 +00002252 // Keep a module forward declaration if there is no definition.
2253 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
2254 Info.Ctxt->getCanonicalDIEOffset()))
2255 Info.Prune = false;
2256
Frederic Riss1c650942015-07-21 22:41:43 +00002257 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002258 lookForDIEsToKeep(RelocMgr, *RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002259 TF_Keep | TF_DependencyWalk | ODRFlag);
2260 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002261 }
2262}
2263
2264/// \brief Recursively walk the \p DIE tree and look for DIEs to
2265/// keep. Store that information in \p CU's DIEInfo.
2266///
2267/// This function is the entry point of the DIE selection
2268/// algorithm. It is expected to walk the DIE tree in file order and
2269/// (though the mediation of its helper) call hasValidRelocation() on
2270/// each DIE that might be a 'root DIE' (See DwarfLinker class
2271/// comment).
2272/// While walking the dependencies of root DIEs, this function is
2273/// also called, but during these dependency walks the file order is
2274/// not respected. The TF_DependencyWalk flag tells us which kind of
2275/// traversal we are currently doing.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002276void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
2277 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002278 const DebugMapObject &DMO, CompileUnit &CU,
2279 unsigned Flags) {
Frederic Riss36c3cb82015-09-11 04:17:25 +00002280 unsigned Idx = CU.getOrigUnit().getDIEIndex(&Die);
Frederic Riss84c09a52015-02-13 23:18:34 +00002281 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2282 bool AlreadyKept = MyInfo.Keep;
Adrian Prantla112ef92015-09-23 17:35:52 +00002283 if (MyInfo.Prune)
2284 return;
Frederic Riss84c09a52015-02-13 23:18:34 +00002285
2286 // If the Keep flag is set, we are marking a required DIE's
2287 // dependencies. If our target is already marked as kept, we're all
2288 // set.
2289 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2290 return;
2291
Adrian Prantl6ec47122015-09-22 15:31:14 +00002292 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
Frederic Riss84c09a52015-02-13 23:18:34 +00002293 // because it would screw up the relocation finding logic.
2294 if (!(Flags & TF_DependencyWalk))
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002295 Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002296
2297 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002298 if (!AlreadyKept && (Flags & TF_Keep)) {
2299 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
Adrian Prantl6ec47122015-09-22 15:31:14 +00002300 keepDIEAndDependencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
Frederic Riss1c650942015-07-21 22:41:43 +00002301 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002302 // The TF_ParentWalk flag tells us that we are currently walking up
2303 // the parent chain of a required DIE, and we don't want to mark all
2304 // the children of the parents as kept (consider for example a
2305 // DW_TAG_namespace node in the parent chain). There are however a
2306 // set of DIE types for which we want to ignore that directive and still
2307 // walk their children.
Frederic Riss36c3cb82015-09-11 04:17:25 +00002308 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
Frederic Riss84c09a52015-02-13 23:18:34 +00002309 Flags &= ~TF_ParentWalk;
2310
Frederic Riss36c3cb82015-09-11 04:17:25 +00002311 if (!Die.hasChildren() || (Flags & TF_ParentWalk))
Frederic Riss84c09a52015-02-13 23:18:34 +00002312 return;
2313
Frederic Riss36c3cb82015-09-11 04:17:25 +00002314 for (auto *Child = Die.getFirstChild(); Child && !Child->isNULL();
Frederic Riss84c09a52015-02-13 23:18:34 +00002315 Child = Child->getSibling())
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002316 lookForDIEsToKeep(RelocMgr, *Child, DMO, CU, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002317}
2318
Frederic Rissb8b43d52015-03-04 22:07:44 +00002319/// \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(
David Blaikie6196aa02015-11-18 00:34:10 +00002339 llvm::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002340 for (const auto &Attr : Abbrev.getData())
2341 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
David Blaikie6196aa02015-11-18 00:34:10 +00002342 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002343 // Assign the unique abbreviation number.
2344 Abbrev.setNumber(Abbreviations.size());
2345 Abbreviations.back()->setNumber(Abbreviations.size());
2346 }
2347}
2348
Adrian Prantl3565af42015-09-14 16:46:10 +00002349unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2350 AttributeSpec AttrSpec,
2351 const DWARFFormValue &Val,
2352 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002353 // Switch everything to out of line strings.
Greg Claytoncddab272016-10-31 16:46:02 +00002354 const char *String = *Val.getAsCString();
Adrian Prantl3565af42015-09-14 16:46:10 +00002355 unsigned Offset = Linker.StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002356 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002357 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002358 return 4;
2359}
2360
Adrian Prantl3565af42015-09-14 16:46:10 +00002361unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
Frederic Riss9833de62015-03-06 23:22:53 +00002362 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2363 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002364 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002365 const DWARFUnit &U = Unit.getOrigUnit();
Greg Claytoncddab272016-10-31 16:46:02 +00002366 uint32_t Ref = *Val.getAsReference();
Frederic Riss9833de62015-03-06 23:22:53 +00002367 DIE *NewRefDie = nullptr;
2368 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002369 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002370
Frederic Riss1c650942015-07-21 22:41:43 +00002371 const DWARFDebugInfoEntryMinimal *RefDie =
Adrian Prantlfdd9a822015-09-22 18:50:58 +00002372 resolveDIEReference(Linker, CompileUnits, Val, U, InputDIE, RefUnit);
Frederic Riss1c650942015-07-21 22:41:43 +00002373
2374 // If the referenced DIE is not found, drop the attribute.
2375 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002376 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002377
2378 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2379 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002380
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);
Greg Claytoncddab272016-10-31 16:46:02 +00002389 return U.getRefAddrByteSize();
Frederic Riss1c650942015-07-21 22:41:43 +00002390 }
2391 }
2392
Frederic Riss9833de62015-03-06 23:22:53 +00002393 if (!RefInfo.Clone) {
2394 assert(Ref > InputDIE.getOffset());
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.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002397 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002398 }
2399 NewRefDie = RefInfo.Clone;
2400
Frederic Riss1c650942015-07-21 22:41:43 +00002401 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2402 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002403 // 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.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002408 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002409 if (Ref < InputDIE.getOffset()) {
2410 // We must have already cloned that DIE.
2411 uint32_t NewRefOffset =
2412 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002413 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002414 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2415 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002416 } else {
2417 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002418 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002419 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002420 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002421 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2422 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002423 }
Greg Claytoncddab272016-10-31 16:46:02 +00002424 return U.getRefAddrByteSize();
Frederic Riss9833de62015-03-06 23:22:53 +00002425 }
2426
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002427 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2428 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002429 return AttrSize;
2430}
2431
Adrian Prantl3565af42015-09-14 16:46:10 +00002432unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2433 AttributeSpec AttrSpec,
2434 const DWARFFormValue &Val,
2435 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002436 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002437 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002438 DIELoc *Loc = nullptr;
2439 DIEBlock *Block = nullptr;
2440 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002441 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002442 Loc = new (DIEAlloc) DIELoc;
Adrian Prantl3565af42015-09-14 16:46:10 +00002443 Linker.DIELocs.push_back(Loc);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002444 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002445 Block = new (DIEAlloc) DIEBlock;
Adrian Prantl3565af42015-09-14 16:46:10 +00002446 Linker.DIEBlocks.push_back(Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002447 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002448 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2449 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002450
2451 if (Loc)
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);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002457 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2458 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002459 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2460 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002461 // 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()).
Adrian Prantl3565af42015-09-14 16:46:10 +00002464 if (Linker.Streamer) {
2465 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002466 if (Loc)
Adrian Prantl3565af42015-09-14 16:46:10 +00002467 Loc->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002468 else
Adrian Prantl3565af42015-09-14 16:46:10 +00002469 Block->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002470 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002471 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002472 return AttrSize;
2473}
2474
Adrian Prantl3565af42015-09-14 16:46:10 +00002475unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2476 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2477 const CompileUnit &Unit, AttributesInfo &Info) {
Greg Claytoncddab272016-10-31 16:46:02 +00002478 uint64_t Addr = *Val.getAsAddress();
Frederic Riss31da3242015-03-11 18:45:52 +00002479 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)
Frederic Riss7b5563a2015-08-31 01:43:14 +00002482 // 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 ? Info.OrigLowPc : Addr) +
2487 Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002488 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2489 Addr = Unit.getLowPc();
2490 if (Addr == UINT64_MAX)
2491 return 0;
2492 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002493 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002494 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002495 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;
Frederic Riss31da3242015-03-11 18:45:52 +00002505 }
2506
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002507 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002508 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002509 return Unit.getOrigUnit().getAddressByteSize();
2510}
2511
Adrian Prantl3565af42015-09-14 16:46:10 +00002512unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00002513 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002514 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002515 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002516 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002517 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)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002524 Value = *Val.getAsSectionOffset();
2525 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2526 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002527 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2528 Value = *OptionalValue;
2529 else {
Adrian Prantl3565af42015-09-14 16:46:10 +00002530 Linker.reportWarning(
2531 "Unsupported scalar attribute form. Dropping attribute.",
2532 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002533 return 0;
2534 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002535 PatchLocation Patch =
2536 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2537 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002538 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002539 Unit.noteRangeAttribute(Die, Patch);
Frederic Riss29eedc72015-09-11 04:17:30 +00002540
Frederic Rissdfb97902015-03-14 15:49:07 +00002541 // 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)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002546 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002547 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2548 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002549
Frederic Rissb8b43d52015-03-04 22:07:44 +00002550 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.
Adrian Prantl3565af42015-09-14 16:46:10 +00002556unsigned DwarfLinker::DIECloner::cloneAttribute(
2557 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2558 const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2559 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002560 const DWARFUnit &U = Unit.getOrigUnit();
2561
2562 switch (AttrSpec.Form) {
2563 case dwarf::DW_FORM_strp:
2564 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002565 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002566 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:
Frederic Riss9833de62015-03-06 23:22:53 +00002571 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002572 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002573 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);
2579 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002580 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002581 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:
Frederic Rissdfb97902015-03-14 15:49:07 +00002590 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2591 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002592 default:
Adrian Prantl3565af42015-09-14 16:46:10 +00002593 Linker.reportWarning(
2594 "Unsupported attribute form in cloneAttribute. Dropping.", &U,
2595 &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002596 }
2597
2598 return 0;
2599}
2600
Frederic Riss23e20e92015-03-07 01:25:09 +00002601/// \brief Apply the valid relocations found by findValidRelocs() to
2602/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2603/// in the debug_info section.
2604///
2605/// Like for findValidRelocs(), this function must be called with
2606/// monotonic \p BaseOffset values.
2607///
2608/// \returns wether any reloc has been applied.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002609bool DwarfLinker::RelocationManager::
2610applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2611 bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002612 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002613 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2614 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002615 if (NextValidReloc >= ValidRelocs.size())
2616 return false;
2617
2618 // Skip relocs that haven't been applied.
2619 while (NextValidReloc < ValidRelocs.size() &&
2620 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2621 ++NextValidReloc;
2622
2623 bool Applied = false;
2624 uint64_t EndOffset = BaseOffset + Data.size();
2625 while (NextValidReloc < ValidRelocs.size() &&
2626 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2627 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2628 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2629 assert(ValidReloc.Offset - BaseOffset < Data.size());
2630 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2631 char Buf[8];
2632 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2633 Value += ValidReloc.Addend;
2634 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2635 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2636 Buf[i] = uint8_t(Value >> (Index * 8));
2637 }
2638 assert(ValidReloc.Size <= sizeof(Buf));
2639 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2640 Applied = true;
2641 }
2642
2643 return Applied;
2644}
2645
Frederic Rissbce93ff2015-03-16 02:05:10 +00002646static bool isTypeTag(uint16_t Tag) {
2647 switch (Tag) {
2648 case dwarf::DW_TAG_array_type:
2649 case dwarf::DW_TAG_class_type:
2650 case dwarf::DW_TAG_enumeration_type:
2651 case dwarf::DW_TAG_pointer_type:
2652 case dwarf::DW_TAG_reference_type:
2653 case dwarf::DW_TAG_string_type:
2654 case dwarf::DW_TAG_structure_type:
2655 case dwarf::DW_TAG_subroutine_type:
2656 case dwarf::DW_TAG_typedef:
2657 case dwarf::DW_TAG_union_type:
2658 case dwarf::DW_TAG_ptr_to_member_type:
2659 case dwarf::DW_TAG_set_type:
2660 case dwarf::DW_TAG_subrange_type:
2661 case dwarf::DW_TAG_base_type:
2662 case dwarf::DW_TAG_const_type:
2663 case dwarf::DW_TAG_constant:
2664 case dwarf::DW_TAG_file_type:
2665 case dwarf::DW_TAG_namelist:
2666 case dwarf::DW_TAG_packed_type:
2667 case dwarf::DW_TAG_volatile_type:
2668 case dwarf::DW_TAG_restrict_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00002669 case dwarf::DW_TAG_atomic_type:
Frederic Rissbce93ff2015-03-16 02:05:10 +00002670 case dwarf::DW_TAG_interface_type:
2671 case dwarf::DW_TAG_unspecified_type:
2672 case dwarf::DW_TAG_shared_type:
2673 return true;
2674 default:
2675 break;
2676 }
2677 return false;
2678}
2679
Frederic Riss29eedc72015-09-11 04:17:30 +00002680static bool
2681shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2682 uint16_t Tag, bool InDebugMap, bool SkipPC,
2683 bool InFunctionScope) {
2684 switch (AttrSpec.Attr) {
2685 default:
2686 return false;
2687 case dwarf::DW_AT_low_pc:
2688 case dwarf::DW_AT_high_pc:
2689 case dwarf::DW_AT_ranges:
2690 return SkipPC;
2691 case dwarf::DW_AT_location:
2692 case dwarf::DW_AT_frame_base:
2693 // FIXME: for some reason dsymutil-classic keeps the location
2694 // attributes when they are of block type (ie. not location
2695 // lists). This is totally wrong for globals where we will keep a
2696 // wrong address. It is mostly harmless for locals, but there is
2697 // no point in keeping these anyway when the function wasn't linked.
2698 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2699 !InDebugMap)) &&
2700 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2701 }
2702}
2703
Adrian Prantl3565af42015-09-14 16:46:10 +00002704DIE *DwarfLinker::DIECloner::cloneDIE(
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002705 const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2706 int64_t PCOffset, uint32_t OutOffset, unsigned Flags) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002707 DWARFUnit &U = Unit.getOrigUnit();
2708 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002709 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002710
2711 // Should the DIE appear in the output?
2712 if (!Unit.getInfo(Idx).Keep)
2713 return nullptr;
2714
2715 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002716 // The DIE might have been already created by a forward reference
2717 // (see cloneDieReferenceAttribute()).
2718 DIE *Die = Info.Clone;
2719 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002720 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002721 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002722 Die->setOffset(OutOffset);
Adrian Prantla112ef92015-09-23 17:35:52 +00002723 if ((Unit.hasODR() || Unit.isClangModule()) &&
2724 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
Frederic Riss1c650942015-07-21 22:41:43 +00002725 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2726 !Info.Ctxt->getCanonicalDIEOffset()) {
2727 // We are about to emit a DIE that is the root of its own valid
2728 // DeclContext tree. Make the current offset the canonical offset
2729 // for this context.
2730 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2731 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002732
2733 // Extract and clone every attribute.
2734 DataExtractor Data = U.getDebugInfoExtractor();
Adrian Prantle5162db2015-09-22 22:20:50 +00002735 // Point to the next DIE (generally there is always at least a NULL
2736 // entry after the current one). If this is a lone
2737 // DW_TAG_compile_unit without any children, point to the next unit.
2738 uint32_t NextOffset =
2739 (Idx + 1 < U.getNumDIEs())
2740 ? U.getDIEAtIndex(Idx + 1)->getOffset()
2741 : U.getNextUnitOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002742 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002743
2744 // We could copy the data only if we need to aply a relocation to
2745 // it. After testing, it seems there is no performance downside to
2746 // doing the copy unconditionally, and it makes the code simpler.
2747 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2748 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2749 // Modify the copy with relocated addresses.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002750 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
Frederic Riss31da3242015-03-11 18:45:52 +00002751 // If we applied relocations, we store the value of high_pc that was
2752 // potentially stored in the input DIE. If high_pc is an address
2753 // (Dwarf version == 2), then it might have been relocated to a
2754 // totally unrelated value (because the end address in the object
2755 // file might be start address of another function which got moved
2756 // independantly by the linker). The computation of the actual
2757 // high_pc value is done in cloneAddressAttribute().
2758 AttrInfo.OrigHighPc =
2759 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
Frederic Riss7b5563a2015-08-31 01:43:14 +00002760 // Also store the low_pc. It might get relocated in an
2761 // inline_subprogram that happens at the beginning of its
2762 // inlining function.
2763 AttrInfo.OrigLowPc =
2764 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_low_pc, UINT64_MAX);
Frederic Riss31da3242015-03-11 18:45:52 +00002765 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002766
2767 // Reset the Offset to 0 as we will be working on the local copy of
2768 // the data.
2769 Offset = 0;
2770
Frederic Rissb8b43d52015-03-04 22:07:44 +00002771 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2772 Offset += getULEB128Size(Abbrev->getCode());
2773
Frederic Riss31da3242015-03-11 18:45:52 +00002774 // We are entering a subprogram. Get and propagate the PCOffset.
2775 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2776 PCOffset = Info.AddrAdjust;
2777 AttrInfo.PCOffset = PCOffset;
2778
Frederic Riss29eedc72015-09-11 04:17:30 +00002779 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2780 Flags |= TF_InFunctionScope;
2781 if (!Info.InDebugMap)
2782 Flags |= TF_SkipPC;
2783 }
2784
2785 bool Copied = false;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002786 for (const auto &AttrSpec : Abbrev->attributes()) {
Frederic Riss29eedc72015-09-11 04:17:30 +00002787 if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2788 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2789 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2790 // FIXME: dsymutil-classic keeps the old abbreviation around
2791 // even if it's not used. We can remove this (and the copyAbbrev
2792 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2793 if (!Copied) {
2794 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2795 Copied = true;
2796 }
2797 continue;
2798 }
2799
Frederic Rissb8b43d52015-03-04 22:07:44 +00002800 DWARFFormValue Val(AttrSpec.Form);
2801 uint32_t AttrSize = Offset;
2802 Val.extractValue(Data, &Offset, &U);
2803 AttrSize = Offset - AttrSize;
2804
Frederic Riss31da3242015-03-11 18:45:52 +00002805 OutOffset +=
2806 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002807 }
2808
Frederic Rissbce93ff2015-03-16 02:05:10 +00002809 // Look for accelerator entries.
2810 uint16_t Tag = InputDIE.getTag();
2811 // FIXME: This is slightly wrong. An inline_subroutine without a
2812 // low_pc, but with AT_ranges might be interesting to get into the
2813 // accelerator tables too. For now stick with dsymutil's behavior.
2814 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2815 Tag != dwarf::DW_TAG_compile_unit &&
2816 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2817 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2818 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2819 AttrInfo.MangledNameOffset,
2820 Tag == dwarf::DW_TAG_inlined_subroutine);
2821 if (AttrInfo.Name)
2822 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2823 Tag == dwarf::DW_TAG_inlined_subroutine);
2824 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2825 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2826 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2827 }
2828
Adrian Prantle39475d2015-11-10 21:31:05 +00002829 // Determine whether there are any children that we want to keep.
2830 bool HasChildren = false;
2831 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2832 Child = Child->getSibling()) {
2833 unsigned Idx = U.getDIEIndex(Child);
2834 if (Unit.getInfo(Idx).Keep) {
2835 HasChildren = true;
2836 break;
2837 }
2838 }
2839
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002840 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Adrian Prantle39475d2015-11-10 21:31:05 +00002841 if (HasChildren)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002842 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2843 // Assign a permanent abbrev number
Adrian Prantl3565af42015-09-14 16:46:10 +00002844 Linker.AssignAbbrev(NewAbbrev);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002845 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002846
2847 // Add the size of the abbreviation number to the output offset.
2848 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2849
Adrian Prantle39475d2015-11-10 21:31:05 +00002850 if (!HasChildren) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002851 // Update our size.
2852 Die->setSize(OutOffset - Die->getOffset());
2853 return Die;
2854 }
2855
2856 // Recursively clone children.
2857 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2858 Child = Child->getSibling()) {
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002859 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset, Flags)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002860 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002861 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
Frederic Riss25440872015-03-13 23:30:31 +00002872/// \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(),
2881 OrigDwarf.isLittleEndian(), AddressSize);
2882 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2883 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002884 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002885 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2886 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2887 // Ranges addresses are based on the unit's low_pc. Compute the
Sanjay Patele4b9f502015-12-07 19:21:39 +00002888 // offset we need to apply to adapt to the new unit's low_pc.
Frederic Riss25440872015-03-13 23:30:31 +00002889 int64_t UnitPcOffset = 0;
2890 if (OrigLowPc != -1ULL)
2891 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2892
2893 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002894 uint32_t Offset = RangeAttribute.get();
2895 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002896 RangeList.extract(RangeExtractor, &Offset);
2897 const auto &Entries = RangeList.getEntries();
Frederic Riss94546202015-08-31 05:09:32 +00002898 if (!Entries.empty()) {
2899 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
Frederic Riss25440872015-03-13 23:30:31 +00002900
Frederic Riss25440872015-03-13 23:30:31 +00002901 if (CurrRange == InvalidRange ||
Frederic Riss94546202015-08-31 05:09:32 +00002902 First.StartAddress + OrigLowPc < CurrRange.start() ||
2903 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2904 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2905 if (CurrRange == InvalidRange ||
2906 CurrRange.start() > First.StartAddress + OrigLowPc) {
2907 reportWarning("no mapping for range.");
2908 continue;
2909 }
Frederic Riss25440872015-03-13 23:30:31 +00002910 }
2911 }
2912
2913 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2914 AddressSize);
2915 }
2916}
2917
Frederic Riss563b1b02015-03-14 03:46:51 +00002918/// \brief Generate the debug_aranges entries for \p Unit and if the
2919/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2920/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002921/// FIXME: this could actually be done right in patchRangesForUnit,
2922/// but for the sake of initial bit-for-bit compatibility with legacy
2923/// dsymutil, we have to do it in a delayed pass.
2924void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002925 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002926 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002927 Attr->set(Streamer->getRangesSectionSize());
2928 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002929}
2930
Frederic Riss63786b02015-03-15 20:45:43 +00002931/// \brief Insert the new line info sequence \p Seq into the current
2932/// set of already linked line info \p Rows.
2933static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2934 std::vector<DWARFDebugLine::Row> &Rows) {
2935 if (Seq.empty())
2936 return;
2937
2938 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2939 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2940 Seq.clear();
2941 return;
2942 }
2943
2944 auto InsertPoint = std::lower_bound(
2945 Rows.begin(), Rows.end(), Seq.front(),
2946 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2947 return LHS.Address < RHS.Address;
2948 });
2949
2950 // FIXME: this only removes the unneeded end_sequence if the
2951 // sequences have been inserted in order. using a global sort like
2952 // described in patchLineTableForUnit() and delaying the end_sequene
2953 // elimination to emitLineTableForUnit() we can get rid of all of them.
2954 if (InsertPoint != Rows.end() &&
2955 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2956 *InsertPoint = Seq.front();
2957 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2958 } else {
2959 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2960 }
2961
2962 Seq.clear();
2963}
2964
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002965static void patchStmtList(DIE &Die, DIEInteger Offset) {
2966 for (auto &V : Die.values())
2967 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002968 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002969 return;
2970 }
2971
2972 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2973}
2974
Frederic Riss63786b02015-03-15 20:45:43 +00002975/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2976/// recreate a relocated version of these for the address ranges that
2977/// are present in the binary.
2978void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2979 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002980 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002981 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2982 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2983 if (StmtList == -1ULL)
2984 return;
2985
2986 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002987 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2988 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002989
2990 // Parse the original line info for the unit.
2991 DWARFDebugLine::LineTable LineTable;
2992 uint32_t StmtOffset = StmtList;
2993 StringRef LineData = OrigDwarf.getLineSection().Data;
2994 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2995 Unit.getOrigUnit().getAddressByteSize());
2996 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2997 &StmtOffset);
2998
2999 // This vector is the output line table.
3000 std::vector<DWARFDebugLine::Row> NewRows;
3001 NewRows.reserve(LineTable.Rows.size());
3002
3003 // Current sequence of rows being extracted, before being inserted
3004 // in NewRows.
3005 std::vector<DWARFDebugLine::Row> Seq;
3006 const auto &FunctionRanges = Unit.getFunctionRanges();
3007 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
3008
3009 // FIXME: This logic is meant to generate exactly the same output as
3010 // Darwin's classic dsynutil. There is a nicer way to implement this
3011 // by simply putting all the relocated line info in NewRows and simply
3012 // sorting NewRows before passing it to emitLineTableForUnit. This
3013 // should be correct as sequences for a function should stay
3014 // together in the sorted output. There are a few corner cases that
3015 // look suspicious though, and that required to implement the logic
3016 // this way. Revisit that once initial validation is finished.
3017
3018 // Iterate over the object file line info and extract the sequences
3019 // that correspond to linked functions.
3020 for (auto &Row : LineTable.Rows) {
3021 // Check wether we stepped out of the range. The range is
3022 // half-open, but consider accept the end address of the range if
3023 // it is marked as end_sequence in the input (because in that
3024 // case, the relocation offset is accurate and that entry won't
3025 // serve as the start of another function).
3026 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
3027 Row.Address > CurrRange.stop() ||
3028 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
3029 // We just stepped out of a known range. Insert a end_sequence
3030 // corresponding to the end of the range.
3031 uint64_t StopAddress = CurrRange != InvalidRange
3032 ? CurrRange.stop() + CurrRange.value()
3033 : -1ULL;
3034 CurrRange = FunctionRanges.find(Row.Address);
3035 bool CurrRangeValid =
3036 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
3037 if (!CurrRangeValid) {
3038 CurrRange = InvalidRange;
3039 if (StopAddress != -1ULL) {
3040 // Try harder by looking in the DebugMapObject function
3041 // ranges map. There are corner cases where this finds a
3042 // valid entry. It's unclear if this is right or wrong, but
3043 // for now do as dsymutil.
3044 // FIXME: Understand exactly what cases this addresses and
3045 // potentially remove it along with the Ranges map.
3046 auto Range = Ranges.lower_bound(Row.Address);
3047 if (Range != Ranges.begin() && Range != Ranges.end())
3048 --Range;
3049
3050 if (Range != Ranges.end() && Range->first <= Row.Address &&
3051 Range->second.first >= Row.Address) {
3052 StopAddress = Row.Address + Range->second.second;
3053 }
3054 }
3055 }
3056 if (StopAddress != -1ULL && !Seq.empty()) {
3057 // Insert end sequence row with the computed end address, but
3058 // the same line as the previous one.
Yaron Kerene3c07062015-08-10 16:15:51 +00003059 auto NextLine = Seq.back();
Yaron Keren2ad3b332015-08-10 18:27:51 +00003060 NextLine.Address = StopAddress;
3061 NextLine.EndSequence = 1;
3062 NextLine.PrologueEnd = 0;
3063 NextLine.BasicBlock = 0;
3064 NextLine.EpilogueBegin = 0;
Yaron Kerenf850d982015-08-10 18:03:35 +00003065 Seq.push_back(NextLine);
Frederic Riss63786b02015-03-15 20:45:43 +00003066 insertLineSequence(Seq, NewRows);
3067 }
3068
3069 if (!CurrRangeValid)
3070 continue;
3071 }
3072
3073 // Ignore empty sequences.
3074 if (Row.EndSequence && Seq.empty())
3075 continue;
3076
3077 // Relocate row address and add it to the current sequence.
3078 Row.Address += CurrRange.value();
3079 Seq.emplace_back(Row);
3080
3081 if (Row.EndSequence)
3082 insertLineSequence(Seq, NewRows);
3083 }
3084
3085 // Finished extracting, now emit the line tables.
3086 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
3087 // FIXME: LLVM hardcodes it's prologue values. We just copy the
3088 // prologue over and that works because we act as both producer and
3089 // consumer. It would be nicer to have a real configurable line
3090 // table emitter.
3091 if (LineTable.Prologue.Version != 2 ||
3092 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00003093 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00003094 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00003095 else {
3096 MCDwarfLineTableParams Params;
3097 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
3098 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
3099 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
3100 Streamer->emitLineTableForUnit(Params,
3101 LineData.slice(StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00003102 LineTable.Prologue.MinInstLength, NewRows,
3103 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00003104 }
Frederic Riss63786b02015-03-15 20:45:43 +00003105}
3106
Frederic Rissbce93ff2015-03-16 02:05:10 +00003107void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
3108 Streamer->emitPubNamesForUnit(Unit);
3109 Streamer->emitPubTypesForUnit(Unit);
3110}
3111
Frederic Riss5a642072015-06-05 23:06:11 +00003112/// \brief Read the frame info stored in the object, and emit the
3113/// patched frame descriptions for the linked binary.
3114///
3115/// This is actually pretty easy as the data of the CIEs and FDEs can
3116/// be considered as black boxes and moved as is. The only thing to do
3117/// is to patch the addresses in the headers.
3118void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
3119 DWARFContext &OrigDwarf,
3120 unsigned AddrSize) {
3121 StringRef FrameData = OrigDwarf.getDebugFrameSection();
3122 if (FrameData.empty())
3123 return;
3124
3125 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
3126 uint32_t InputOffset = 0;
3127
3128 // Store the data of the CIEs defined in this object, keyed by their
3129 // offsets.
3130 DenseMap<uint32_t, StringRef> LocalCIES;
3131
3132 while (Data.isValidOffset(InputOffset)) {
3133 uint32_t EntryOffset = InputOffset;
3134 uint32_t InitialLength = Data.getU32(&InputOffset);
3135 if (InitialLength == 0xFFFFFFFF)
3136 return reportWarning("Dwarf64 bits no supported");
3137
3138 uint32_t CIEId = Data.getU32(&InputOffset);
3139 if (CIEId == 0xFFFFFFFF) {
3140 // This is a CIE, store it.
3141 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
3142 LocalCIES[EntryOffset] = CIEData;
3143 // The -4 is to account for the CIEId we just read.
3144 InputOffset += InitialLength - 4;
3145 continue;
3146 }
3147
3148 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
3149
3150 // Some compilers seem to emit frame info that doesn't start at
3151 // the function entry point, thus we can't just lookup the address
3152 // in the debug map. Use the linker's range map to see if the FDE
3153 // describes something that we can relocate.
3154 auto Range = Ranges.upper_bound(Loc);
3155 if (Range != Ranges.begin())
3156 --Range;
3157 if (Range == Ranges.end() || Range->first > Loc ||
3158 Range->second.first <= Loc) {
3159 // The +4 is to account for the size of the InitialLength field itself.
3160 InputOffset = EntryOffset + InitialLength + 4;
3161 continue;
3162 }
3163
3164 // This is an FDE, and we have a mapping.
3165 // Have we already emitted a corresponding CIE?
3166 StringRef CIEData = LocalCIES[CIEId];
3167 if (CIEData.empty())
3168 return reportWarning("Inconsistent debug_frame content. Dropping.");
3169
3170 // Look if we already emitted a CIE that corresponds to the
3171 // referenced one (the CIE data is the key of that lookup).
3172 auto IteratorInserted = EmittedCIEs.insert(
3173 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3174 // If there is no CIE yet for this ID, emit it.
3175 if (IteratorInserted.second ||
3176 // FIXME: dsymutil-classic only caches the last used CIE for
3177 // reuse. Mimic that behavior for now. Just removing that
3178 // second half of the condition and the LastCIEOffset variable
3179 // makes the code DTRT.
3180 LastCIEOffset != IteratorInserted.first->getValue()) {
3181 LastCIEOffset = Streamer->getFrameSectionSize();
3182 IteratorInserted.first->getValue() = LastCIEOffset;
3183 Streamer->emitCIE(CIEData);
3184 }
3185
3186 // Emit the FDE with updated address and CIE pointer.
3187 // (4 + AddrSize) is the size of the CIEId + initial_location
3188 // fields that will get reconstructed by emitFDE().
3189 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3190 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3191 Loc + Range->second.second,
3192 FrameData.substr(InputOffset, FDERemainingBytes));
3193 InputOffset += FDERemainingBytes;
3194 }
3195}
3196
Adrian Prantl3565af42015-09-14 16:46:10 +00003197void DwarfLinker::DIECloner::copyAbbrev(
3198 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
Frederic Riss29eedc72015-09-11 04:17:30 +00003199 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3200 dwarf::Form(Abbrev.hasChildren()));
3201
3202 for (const auto &Attr : Abbrev.attributes()) {
3203 uint16_t Form = Attr.Form;
3204 if (hasODR && isODRAttribute(Attr.Attr))
3205 Form = dwarf::DW_FORM_ref_addr;
3206 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3207 }
3208
Adrian Prantl3565af42015-09-14 16:46:10 +00003209 Linker.AssignAbbrev(Copy);
Frederic Riss29eedc72015-09-11 04:17:30 +00003210}
3211
Adrian Prantl20937022015-09-23 17:11:10 +00003212static uint64_t getDwoId(const DWARFDebugInfoEntryMinimal &CUDie,
3213 const DWARFUnit &Unit) {
3214 uint64_t DwoId =
3215 CUDie.getAttributeValueAsUnsignedConstant(&Unit, dwarf::DW_AT_dwo_id, 0);
3216 if (!DwoId)
3217 DwoId = CUDie.getAttributeValueAsUnsignedConstant(&Unit,
3218 dwarf::DW_AT_GNU_dwo_id, 0);
3219 return DwoId;
3220}
3221
Adrian Prantle5162db2015-09-22 22:20:50 +00003222bool DwarfLinker::registerModuleReference(
3223 const DWARFDebugInfoEntryMinimal &CUDie, const DWARFUnit &Unit,
3224 DebugMap &ModuleMap, unsigned Indent) {
3225 std::string PCMfile =
Adrian Prantl20937022015-09-23 17:11:10 +00003226 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_dwo_name, "");
3227 if (PCMfile.empty())
3228 PCMfile =
3229 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_GNU_dwo_name, "");
Adrian Prantle5162db2015-09-22 22:20:50 +00003230 if (PCMfile.empty())
3231 return false;
3232
3233 // Clang module DWARF skeleton CUs abuse this for the path to the module.
3234 std::string PCMpath =
3235 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_comp_dir, "");
Adrian Prantl20937022015-09-23 17:11:10 +00003236 uint64_t DwoId = getDwoId(CUDie, Unit);
Adrian Prantle5162db2015-09-22 22:20:50 +00003237
Adrian Prantla112ef92015-09-23 17:35:52 +00003238 std::string Name =
3239 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_name, "");
3240 if (Name.empty()) {
3241 reportWarning("Anonymous module skeleton CU for " + PCMfile);
3242 return true;
3243 }
3244
Adrian Prantle5162db2015-09-22 22:20:50 +00003245 if (Options.Verbose) {
3246 outs().indent(Indent);
3247 outs() << "Found clang module reference " << PCMfile;
3248 }
3249
Adrian Prantl20937022015-09-23 17:11:10 +00003250 auto Cached = ClangModules.find(PCMfile);
3251 if (Cached != ClangModules.end()) {
Adrian Prantle1bc3e22016-05-13 00:17:58 +00003252 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
3253 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
3254 // ASTFileSignatures will change randomly when a module is rebuilt.
3255 if (Options.Verbose && (Cached->second != DwoId))
Adrian Prantl20937022015-09-23 17:11:10 +00003256 reportWarning(Twine("hash mismatch: this object file was built against a "
3257 "different version of the module ") + PCMfile);
Adrian Prantle5162db2015-09-22 22:20:50 +00003258 if (Options.Verbose)
3259 outs() << " [cached].\n";
3260 return true;
3261 }
3262 if (Options.Verbose)
3263 outs() << " ...\n";
3264
3265 // Cyclic dependencies are disallowed by Clang, but we still
3266 // shouldn't run into an infinite loop, so mark it as processed now.
Adrian Prantl20937022015-09-23 17:11:10 +00003267 ClangModules.insert({PCMfile, DwoId});
Adrian Prantla112ef92015-09-23 17:35:52 +00003268 loadClangModule(PCMfile, PCMpath, Name, DwoId, ModuleMap, Indent + 2);
Adrian Prantle5162db2015-09-22 22:20:50 +00003269 return true;
3270}
3271
Frederic Risseb85c8f2015-07-24 06:41:11 +00003272ErrorOr<const object::ObjectFile &>
3273DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3274 const DebugMap &Map) {
3275 auto ErrOrObjs =
3276 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
Frederic Rissafeac302015-08-31 05:16:35 +00003277 if (std::error_code EC = ErrOrObjs.getError()) {
Frederic Risseb85c8f2015-07-24 06:41:11 +00003278 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
Frederic Rissafeac302015-08-31 05:16:35 +00003279 return EC;
3280 }
Frederic Risseb85c8f2015-07-24 06:41:11 +00003281 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3282 if (std::error_code EC = ErrOrObj.getError())
3283 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3284 return ErrOrObj;
3285}
3286
Adrian Prantle5162db2015-09-22 22:20:50 +00003287void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
Adrian Prantla112ef92015-09-23 17:35:52 +00003288 StringRef ModuleName, uint64_t DwoId,
3289 DebugMap &ModuleMap, unsigned Indent) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003290 SmallString<80> Path(Options.PrependPath);
3291 if (sys::path::is_relative(Filename))
3292 sys::path::append(Path, ModulePath, Filename);
3293 else
3294 sys::path::append(Path, Filename);
3295 BinaryHolder ObjHolder(Options.Verbose);
3296 auto &Obj =
Pavel Labath62d72042016-11-09 11:43:52 +00003297 ModuleMap.addDebugMapObject(Path, sys::TimePoint<std::chrono::seconds>());
Adrian Prantle5162db2015-09-22 22:20:50 +00003298 auto ErrOrObj = loadObject(ObjHolder, Obj, ModuleMap);
Adrian Prantla9e23832016-01-14 18:31:07 +00003299 if (!ErrOrObj) {
3300 // Try and emit more helpful warnings by applying some heuristics.
3301 StringRef ObjFile = CurrentDebugObject->getObjectFilename();
3302 bool isClangModule = sys::path::extension(Filename).equals(".pcm");
3303 bool isArchive = ObjFile.endswith(")");
3304 if (isClangModule) {
Adrian Prantla9e23832016-01-14 18:31:07 +00003305 StringRef ModuleCacheDir = sys::path::parent_path(Path);
3306 if (sys::fs::exists(ModuleCacheDir)) {
3307 // If the module's parent directory exists, we assume that the module
3308 // cache has expired and was pruned by clang. A more adventurous
3309 // dsymutil would invoke clang to rebuild the module now.
3310 if (!ModuleCacheHintDisplayed) {
3311 errs() << "note: The clang module cache may have expired since this "
3312 "object file was built. Rebuilding the object file will "
3313 "rebuild the module cache.\n";
3314 ModuleCacheHintDisplayed = true;
3315 }
3316 } else if (isArchive) {
3317 // If the module cache directory doesn't exist at all and the object
3318 // file is inside a static library, we assume that the static library
3319 // was built on a different machine. We don't want to discourage module
3320 // debugging for convenience libraries within a project though.
3321 if (!ArchiveHintDisplayed) {
Adrian Prantl9e7e8832016-05-20 20:36:06 +00003322 errs() << "note: Linking a static library that was built with "
3323 "-gmodules, but the module cache was not found. "
3324 "Redistributable static libraries should never be built "
3325 "with module debugging enabled. The debug experience will "
3326 "be degraded due to incomplete debug information.\n";
Adrian Prantla9e23832016-01-14 18:31:07 +00003327 ArchiveHintDisplayed = true;
3328 }
3329 }
3330 }
Adrian Prantle5162db2015-09-22 22:20:50 +00003331 return;
Adrian Prantla9e23832016-01-14 18:31:07 +00003332 }
Adrian Prantle5162db2015-09-22 22:20:50 +00003333
Benjamin Kramer008f4be2015-09-23 10:38:59 +00003334 std::unique_ptr<CompileUnit> Unit;
Adrian Prantle5162db2015-09-22 22:20:50 +00003335
3336 // Setup access to the debug info.
3337 DWARFContextInMemory DwarfContext(*ErrOrObj);
3338 RelocationManager RelocMgr(*this);
3339 for (const auto &CU : DwarfContext.compile_units()) {
3340 auto *CUDie = CU->getUnitDIE(false);
3341 // Recursively get all modules imported by this one.
3342 if (!registerModuleReference(*CUDie, *CU, ModuleMap, Indent)) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003343 if (Unit) {
3344 errs() << Filename << ": Clang modules are expected to have exactly"
3345 << " 1 compile unit.\n";
3346 exitDsymutil(1);
3347 }
Adrian Prantl2c0b0ab2016-04-25 17:04:32 +00003348 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
3349 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
3350 // ASTFileSignatures will change randomly when a module is rebuilt.
Adrian Prantle1bc3e22016-05-13 00:17:58 +00003351 uint64_t PCMDwoId = getDwoId(*CUDie, *CU);
3352 if (PCMDwoId != DwoId) {
3353 if (Options.Verbose)
3354 reportWarning(
3355 Twine("hash mismatch: this object file was built against a "
3356 "different version of the module ") + Filename);
3357 // Update the cache entry with the DwoId of the module loaded from disk.
3358 ClangModules[Filename] = PCMDwoId;
3359 }
Adrian Prantl20937022015-09-23 17:11:10 +00003360
3361 // Add this module.
Adrian Prantla112ef92015-09-23 17:35:52 +00003362 Unit = llvm::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
3363 ModuleName);
Adrian Prantle5162db2015-09-22 22:20:50 +00003364 Unit->setHasInterestingContent();
Adrian Prantla112ef92015-09-23 17:35:52 +00003365 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), StringPool,
3366 ODRContexts);
Adrian Prantle5162db2015-09-22 22:20:50 +00003367 // Keep everything.
3368 Unit->markEverythingAsKept();
3369 }
3370 }
3371 if (Options.Verbose) {
3372 outs().indent(Indent);
3373 outs() << "cloning .debug_info from " << Filename << "\n";
3374 }
3375
3376 DIECloner(*this, RelocMgr, DIEAlloc, MutableArrayRef<CompileUnit>(*Unit),
3377 Options)
3378 .cloneAllCompileUnits(DwarfContext);
3379}
3380
Adrian Prantl3565af42015-09-14 16:46:10 +00003381void DwarfLinker::DIECloner::cloneAllCompileUnits(
3382 DWARFContextInMemory &DwarfContext) {
3383 if (!Linker.Streamer)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003384 return;
3385
3386 for (auto &CurrentUnit : CompileUnits) {
3387 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Adrian Prantl3565af42015-09-14 16:46:10 +00003388 CurrentUnit.setStartOffset(Linker.OutputDebugInfoSize);
Adrian Prantl3abe18d2015-09-14 23:27:26 +00003389 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PC offset */,
3390 11 /* Unit Header size */, 0);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003391 CurrentUnit.setOutputUnitDIE(OutputDIE);
Adrian Prantl3565af42015-09-14 16:46:10 +00003392 Linker.OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3393 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003394 continue;
3395 // FIXME: for compatibility with the classic dsymutil, we emit
3396 // an empty line table for the unit, even if the unit doesn't
3397 // actually exist in the DIE tree.
Adrian Prantl3565af42015-09-14 16:46:10 +00003398 Linker.patchLineTableForUnit(CurrentUnit, DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003399 if (!OutputDIE)
3400 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003401 Linker.patchRangesForUnit(CurrentUnit, DwarfContext);
3402 Linker.Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3403 Linker.emitAcceleratorEntriesForUnit(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003404 }
3405
Adrian Prantl3565af42015-09-14 16:46:10 +00003406 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003407 return;
3408
3409 // Emit all the compile unit's debug information.
3410 for (auto &CurrentUnit : CompileUnits) {
Adrian Prantl3565af42015-09-14 16:46:10 +00003411 Linker.generateUnitRanges(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003412 CurrentUnit.fixupForwardReferences();
Adrian Prantl3565af42015-09-14 16:46:10 +00003413 Linker.Streamer->emitCompileUnitHeader(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003414 if (!CurrentUnit.getOutputUnitDIE())
3415 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003416 Linker.Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003417 }
3418}
3419
Frederic Rissd3455182015-01-28 18:27:01 +00003420bool DwarfLinker::link(const DebugMap &Map) {
3421
Frederic Rissc99ea202015-02-28 00:29:11 +00003422 if (!createStreamer(Map.getTriple(), OutputFilename))
3423 return false;
3424
Frederic Rissb8b43d52015-03-04 22:07:44 +00003425 // Size of the DIEs (and headers) generated for the linked output.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003426 OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00003427 // A unique ID that identifies each compile unit.
Adrian Prantle5162db2015-09-22 22:20:50 +00003428 UnitID = 0;
3429 DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
3430
Frederic Rissd3455182015-01-28 18:27:01 +00003431 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00003432 CurrentDebugObject = Obj.get();
3433
Frederic Rissb9818322015-02-28 00:29:07 +00003434 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00003435 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00003436 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3437 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00003438 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00003439
Frederic Riss1036e642015-02-13 23:18:22 +00003440 // Look for relocations that correspond to debug map entries.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003441 RelocationManager RelocMgr(*this);
3442 if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00003443 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00003444 outs() << "No valid relocations found. Skipping.\n";
3445 continue;
3446 }
3447
Frederic Riss563cba62015-01-28 22:15:14 +00003448 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00003449 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00003450 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00003451
Adrian Prantld2793a02015-10-05 23:11:20 +00003452 // In a first phase, just read in the debug info and load all clang modules.
Frederic Rissd3455182015-01-28 18:27:01 +00003453 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003454 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00003455 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00003456 outs() << "Input compilation unit:";
3457 CUDie->dump(outs(), CU.get(), 0);
3458 }
Adrian Prantld2793a02015-10-05 23:11:20 +00003459
3460 if (!registerModuleReference(*CUDie, *CU, ModuleMap))
Adrian Prantla112ef92015-09-23 17:35:52 +00003461 Units.emplace_back(*CU, UnitID++, !Options.NoODR, "");
Frederic Rissd3455182015-01-28 18:27:01 +00003462 }
Frederic Riss563cba62015-01-28 22:15:14 +00003463
Adrian Prantld2793a02015-10-05 23:11:20 +00003464 // Now build the DIE parent links that we will use during the next phase.
3465 for (auto &CurrentUnit : Units)
3466 analyzeContextInfo(CurrentUnit.getOrigUnit().getUnitDIE(), 0, CurrentUnit,
3467 &ODRContexts.getRoot(), StringPool, ODRContexts);
3468
Frederic Riss84c09a52015-02-13 23:18:34 +00003469 // Then mark all the DIEs that need to be present in the linked
3470 // output and collect some information about them. Note that this
3471 // loop can not be merged with the previous one becaue cross-cu
3472 // references require the ParentIdx to be setup for every CU in
3473 // the object file before calling this.
3474 for (auto &CurrentUnit : Units)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003475 lookForDIEsToKeep(RelocMgr, *CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00003476 CurrentUnit, 0);
3477
Frederic Riss23e20e92015-03-07 01:25:09 +00003478 // The calls to applyValidRelocs inside cloneDIE will walk the
3479 // reloc array again (in the same way findValidRelocsInDebugInfo()
3480 // did). We need to reset the NextValidReloc index to the beginning.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003481 RelocMgr.resetValidRelocs();
3482 if (RelocMgr.hasValidRelocs())
Adrian Prantl3565af42015-09-14 16:46:10 +00003483 DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3484 .cloneAllCompileUnits(DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003485 if (!Options.NoOutput && !Units.empty())
Frederic Riss5a642072015-06-05 23:06:11 +00003486 patchFrameInfoForObject(*Obj, DwarfContext,
3487 Units[0].getOrigUnit().getAddressByteSize());
3488
Frederic Riss563cba62015-01-28 22:15:14 +00003489 // Clean-up before starting working on the next object.
3490 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003491 }
3492
Frederic Rissb8b43d52015-03-04 22:07:44 +00003493 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003494 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003495 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003496 Streamer->emitStrings(StringPool);
3497 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003498
Frederic Riss24faade2015-09-02 16:49:13 +00003499 return Options.NoOutput ? true : Streamer->finish(Map);
Frederic Riss231f7142014-12-12 17:31:24 +00003500}
3501}
Frederic Rissd3455182015-01-28 18:27:01 +00003502
Frederic Riss30711fb2015-08-26 05:09:52 +00003503/// \brief Get the offset of string \p S in the string table. This
3504/// can insert a new element or return the offset of a preexisitng
3505/// one.
3506uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3507 if (S.empty() && !Strings.empty())
3508 return 0;
3509
3510 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3511 MapTy::iterator It;
3512 bool Inserted;
3513
3514 // A non-empty string can't be at offset 0, so if we have an entry
3515 // with a 0 offset, it must be a previously interned string.
3516 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3517 if (Inserted || It->getValue().first == 0) {
3518 // Set offset and chain at the end of the entries list.
3519 It->getValue().first = CurrentEndOffset;
3520 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3521 Last->getValue().second = &*It;
3522 Last = &*It;
3523 }
3524 return It->getValue().first;
3525}
3526
3527/// \brief Put \p S into the StringMap so that it gets permanent
3528/// storage, but do not actually link it in the chain of elements
3529/// that go into the output section. A latter call to
3530/// getStringOffset() with the same string will chain it though.
3531StringRef NonRelocatableStringpool::internString(StringRef S) {
3532 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3533 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3534 return InsertResult.first->getKey();
3535}
3536
Frederic Riss65e145c2015-08-26 05:09:55 +00003537void warn(const Twine &Warning, const Twine &Context) {
3538 errs() << Twine("while processing ") + Context + ":\n";
3539 errs() << Twine("warning: ") + Warning + "\n";
3540}
3541
3542bool error(const Twine &Error, const Twine &Context) {
3543 errs() << Twine("while processing ") + Context + ":\n";
3544 errs() << Twine("error: ") + Error + "\n";
3545 return false;
3546}
3547
Frederic Rissb9818322015-02-28 00:29:07 +00003548bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3549 const LinkOptions &Options) {
3550 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003551 return Linker.link(DM);
3552}
3553}
Frederic Riss231f7142014-12-12 17:31:24 +00003554}