blob: 803f7f98cc5cfeeed38471528d80574112fa4b5c [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"
Greg Clayton35630c32016-12-01 18:56:29 +000041#include <memory>
Frederic Rissd3455182015-01-28 18:27:01 +000042#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000043#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000044
45namespace llvm {
46namespace dsymutil {
47
Frederic Rissd3455182015-01-28 18:27:01 +000048namespace {
49
Frederic Riss1af75f72015-03-12 18:45:10 +000050template <typename KeyT, typename ValT>
51using HalfOpenIntervalMap =
52 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
53 IntervalMapHalfOpenInfo<KeyT>>;
54
Frederic Riss25440872015-03-13 23:30:31 +000055typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
56
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000057// FIXME: Delete this structure.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000058struct PatchLocation {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000059 DIE::value_iterator I;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000060
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000061 PatchLocation() = default;
62 PatchLocation(DIE::value_iterator I) : I(I) {}
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000063
64 void set(uint64_t New) const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000065 assert(I);
66 const auto &Old = *I;
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000067 assert(Old.getType() == DIEValue::isInteger);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000068 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000069 }
70
71 uint64_t get() const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000072 assert(I);
73 return I->getDIEInteger().getValue();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000074 }
75};
76
Frederic Riss1c650942015-07-21 22:41:43 +000077class CompileUnit;
78struct DeclMapInfo;
Frederic Riss1c650942015-07-21 22:41:43 +000079
80/// A DeclContext is a named program scope that is used for ODR
81/// uniquing of types.
82/// The set of DeclContext for the ODR-subject parts of a Dwarf link
83/// is expanded (and uniqued) with each new object file processed. We
84/// need to determine the context of each DIE in an linked object file
85/// to see if the corresponding type has already been emitted.
86///
87/// The contexts are conceptually organised as a tree (eg. a function
88/// scope is contained in a namespace scope that contains other
89/// scopes), but storing/accessing them in an actual tree is too
90/// inefficient: we need to be able to very quickly query a context
91/// for a given child context by name. Storing a StringMap in each
92/// DeclContext would be too space inefficient.
93/// The solution here is to give each DeclContext a link to its parent
94/// (this allows to walk up the tree), but to query the existance of a
95/// specific DeclContext using a separate DenseMap keyed on the hash
96/// of the fully qualified name of the context.
97class DeclContext {
98 unsigned QualifiedNameHash;
99 uint32_t Line;
100 uint32_t ByteSize;
101 uint16_t Tag;
102 StringRef Name;
103 StringRef File;
104 const DeclContext &Parent;
Greg Claytonc8c10322016-12-13 18:25:19 +0000105 DWARFDie LastSeenDIE;
Frederic Riss1c650942015-07-21 22:41:43 +0000106 uint32_t LastSeenCompileUnitID;
107 uint32_t CanonicalDIEOffset;
108
109 friend DeclMapInfo;
110
111public:
112 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
113
114 DeclContext()
115 : QualifiedNameHash(0), Line(0), ByteSize(0),
116 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
Greg Claytonc8c10322016-12-13 18:25:19 +0000117 LastSeenDIE(), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
Frederic Riss1c650942015-07-21 22:41:43 +0000118
119 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
120 StringRef Name, StringRef File, const DeclContext &Parent,
Greg Claytonc8c10322016-12-13 18:25:19 +0000121 DWARFDie LastSeenDIE = DWARFDie(), unsigned CUId = 0)
Frederic Riss1c650942015-07-21 22:41:43 +0000122 : 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
Greg Claytonc8c10322016-12-13 18:25:19 +0000128 bool setLastSeenDIE(CompileUnit &U, const DWARFDie &Die);
Frederic Riss1c650942015-07-21 22:41:43 +0000129
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,
Greg Claytonc8c10322016-12-13 18:25:19 +0000176 const DWARFDie &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)
Greg Clayton35630c32016-12-01 18:56:29 +0000200 : OrigUnit(OrigUnit), ID(ID), NewUnit(OrigUnit.getVersion(),
201 OrigUnit.getAddressByteSize(),
Greg Claytonc8c10322016-12-13 18:25:19 +0000202 OrigUnit.getUnitDIE().getTag()),
Greg Clayton35630c32016-12-01 18:56:29 +0000203 LowPc(UINT64_MAX), HighPc(0), RangeAlloc(), Ranges(RangeAlloc),
204 ClangModuleName(ClangModuleName) {
Frederic Riss563cba62015-01-28 22:15:14 +0000205 Info.resize(OrigUnit.getNumDIEs());
Frederic Riss1c650942015-07-21 22:41:43 +0000206
Greg Claytonc8c10322016-12-13 18:25:19 +0000207 auto CUDie = OrigUnit.getUnitDIE(false);
208 unsigned Lang = CUDie.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_language, 0);
Frederic Riss1c650942015-07-21 22:41:43 +0000209 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
210 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
211 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
212 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
213 Lang == dwarf::DW_LANG_ObjC_plus_plus);
Frederic Riss563cba62015-01-28 22:15:14 +0000214 }
215
Frederic Rissc3349d42015-02-13 23:18:27 +0000216 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000217
Frederic Riss3cced052015-03-14 03:46:40 +0000218 unsigned getUniqueID() const { return ID; }
219
Greg Clayton35630c32016-12-01 18:56:29 +0000220 DIE *getOutputUnitDIE() const {
221 return &const_cast<DIEUnit &>(NewUnit).getUnitDie();
222 }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000223
Frederic Riss1c650942015-07-21 22:41:43 +0000224 bool hasODR() const { return HasODR; }
Adrian Prantla112ef92015-09-23 17:35:52 +0000225 bool isClangModule() const { return !ClangModuleName.empty(); }
226 const std::string &getClangModuleName() const { return ClangModuleName; }
Frederic Riss1c650942015-07-21 22:41:43 +0000227
Frederic Riss563cba62015-01-28 22:15:14 +0000228 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
229 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
230
Frederic Rissb8b43d52015-03-04 22:07:44 +0000231 uint64_t getStartOffset() const { return StartOffset; }
232 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000233 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000234
Frederic Riss5a62dc32015-03-13 18:35:54 +0000235 uint64_t getLowPc() const { return LowPc; }
236 uint64_t getHighPc() const { return HighPc; }
237
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000238 Optional<PatchLocation> getUnitRangesAttribute() const {
239 return UnitRangeAttribute;
240 }
Frederic Riss25440872015-03-13 23:30:31 +0000241 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000242 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000243 return RangeAttributes;
244 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000245
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000246 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000247 getLocationAttributes() const {
248 return LocationAttributes;
249 }
250
Adrian Prantle5162db2015-09-22 22:20:50 +0000251 void setHasInterestingContent() { HasInterestingContent = true; }
252 bool hasInterestingContent() { return HasInterestingContent; }
253
254 /// Mark every DIE in this unit as kept. This function also
255 /// marks variables as InDebugMap so that they appear in the
256 /// reconstructed accelerator tables.
257 void markEverythingAsKept();
258
Frederic Riss9d441b62015-03-06 23:22:50 +0000259 /// \brief Compute the end offset for this unit. Must be
260 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000261 /// \returns the next unit offset (which is also the current
262 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000263 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000264
Frederic Riss6afcfce2015-03-13 18:35:57 +0000265 /// \brief Keep track of a forward reference to DIE \p Die in \p
266 /// RefUnit by \p Attr. The attribute should be fixed up later to
Frederic Riss1c650942015-07-21 22:41:43 +0000267 /// point to the absolute offset of \p Die in the debug_info section
268 /// or to the canonical offset of \p Ctxt if it is non-null.
Frederic Riss6afcfce2015-03-13 18:35:57 +0000269 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000270 DeclContext *Ctxt, PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000271
272 /// \brief Apply all fixups recored by noteForwardReference().
273 void fixupForwardReferences();
274
Frederic Riss1af75f72015-03-12 18:45:10 +0000275 /// \brief Add a function range [\p LowPC, \p HighPC) that is
276 /// relocatad by applying offset \p PCOffset.
277 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
278
Frederic Riss5c9c7062015-03-13 23:55:29 +0000279 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000280 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000281 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000282
Frederic Rissdfb97902015-03-14 15:49:07 +0000283 /// \brief Keep track of a location attribute pointing to a location
284 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000285 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000286
Frederic Rissbce93ff2015-03-16 02:05:10 +0000287 /// \brief Add a name accelerator entry for \p Die with \p Name
288 /// which is stored in the string table at \p Offset.
289 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
290 bool SkipPubnamesSection = false);
291
292 /// \brief Add a type accelerator entry for \p Die with \p Name
293 /// which is stored in the string table at \p Offset.
294 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
295
296 struct AccelInfo {
Frederic Rissf37964c2015-06-05 20:27:07 +0000297 StringRef Name; ///< Name of the entry.
298 const DIE *Die; ///< DIE this entry describes.
Frederic Rissbce93ff2015-03-16 02:05:10 +0000299 uint32_t NameOffset; ///< Offset of Name in the string pool.
300 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
301
302 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
303 bool SkipPubSection = false)
304 : Name(Name), Die(Die), NameOffset(NameOffset),
305 SkipPubSection(SkipPubSection) {}
306 };
307
308 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
309 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
310
Frederic Riss1c650942015-07-21 22:41:43 +0000311 /// Get the full path for file \a FileNum in the line table
Pete Cooperef4e36a2016-03-18 03:48:09 +0000312 StringRef getResolvedPath(unsigned FileNum) {
Frederic Riss1c650942015-07-21 22:41:43 +0000313 if (FileNum >= ResolvedPaths.size())
Pete Cooperef4e36a2016-03-18 03:48:09 +0000314 return StringRef();
315 return ResolvedPaths[FileNum];
Frederic Riss1c650942015-07-21 22:41:43 +0000316 }
317
318 /// Set the fully resolved path for the line-table's file \a FileNum
319 /// to \a Path.
Pete Cooperef4e36a2016-03-18 03:48:09 +0000320 void setResolvedPath(unsigned FileNum, StringRef Path) {
Frederic Riss1c650942015-07-21 22:41:43 +0000321 if (ResolvedPaths.size() <= FileNum)
322 ResolvedPaths.resize(FileNum + 1);
323 ResolvedPaths[FileNum] = Path;
324 }
325
Frederic Riss563cba62015-01-28 22:15:14 +0000326private:
327 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000328 unsigned ID;
Frederic Riss1c650942015-07-21 22:41:43 +0000329 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
Greg Clayton35630c32016-12-01 18:56:29 +0000330 DIEUnit NewUnit;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000331
332 uint64_t StartOffset;
333 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000334
Frederic Riss5a62dc32015-03-13 18:35:54 +0000335 uint64_t LowPc;
336 uint64_t HighPc;
337
Frederic Riss9833de62015-03-06 23:22:53 +0000338 /// \brief A list of attributes to fixup with the absolute offset of
339 /// a DIE in the debug_info section.
340 ///
341 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000342 /// cloning because for cross-cu forward refences the target DIE's
343 /// offset isn't known you emit the reference attribute.
Frederic Riss1c650942015-07-21 22:41:43 +0000344 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
345 PatchLocation>> ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000346
Frederic Riss25440872015-03-13 23:30:31 +0000347 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000348 /// \brief The ranges in that interval map are the PC ranges for
349 /// functions in this unit, associated with the PC offset to apply
350 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000351 FunctionIntervals Ranges;
352
353 /// \brief DW_AT_ranges attributes to patch after we have gathered
354 /// all the unit's function addresses.
355 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000356 std::vector<PatchLocation> RangeAttributes;
357 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000358 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000359
360 /// \brief Location attributes that need to be transfered from th
361 /// original debug_loc section to the liked one. They are stored
362 /// along with the PC offset that is to be applied to their
363 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000364 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000365
366 /// \brief Accelerator entries for the unit, both for the pub*
367 /// sections and the apple* ones.
368 /// @{
369 std::vector<AccelInfo> Pubnames;
370 std::vector<AccelInfo> Pubtypes;
371 /// @}
Frederic Riss1c650942015-07-21 22:41:43 +0000372
373 /// Cached resolved paths from the line table.
Pete Cooperef4e36a2016-03-18 03:48:09 +0000374 /// Note, the StringRefs here point in to the intern (uniquing) string pool.
375 /// This means that a StringRef returned here doesn't need to then be uniqued
376 /// for the purposes of getting a unique address for each string.
377 std::vector<StringRef> ResolvedPaths;
Frederic Riss1c650942015-07-21 22:41:43 +0000378
379 /// Is this unit subject to the ODR rule?
380 bool HasODR;
Adrian Prantle5162db2015-09-22 22:20:50 +0000381 /// Did a DIE actually contain a valid reloc?
382 bool HasInterestingContent;
Adrian Prantla112ef92015-09-23 17:35:52 +0000383 /// If this is a Clang module, this holds the module's name.
384 std::string ClangModuleName;
Frederic Riss563cba62015-01-28 22:15:14 +0000385};
386
Adrian Prantle5162db2015-09-22 22:20:50 +0000387void CompileUnit::markEverythingAsKept() {
388 for (auto &I : Info)
Adrian Prantla112ef92015-09-23 17:35:52 +0000389 // Mark everything that wasn't explicity marked for pruning.
390 I.Keep = !I.Prune;
Adrian Prantle5162db2015-09-22 22:20:50 +0000391}
392
Frederic Riss9d441b62015-03-06 23:22:50 +0000393uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000394 NextUnitOffset = StartOffset + 11 /* Header size */;
395 // The root DIE might be null, meaning that the Unit had nothing to
396 // contribute to the linked output. In that case, we will emit the
397 // unit header without any actual DIE.
Greg Clayton35630c32016-12-01 18:56:29 +0000398 NextUnitOffset += NewUnit.getUnitDie().getSize();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000399 return NextUnitOffset;
400}
401
Frederic Riss6afcfce2015-03-13 18:35:57 +0000402/// \brief Keep track of a forward cross-cu reference from this unit
403/// to \p Die that lives in \p RefUnit.
404void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000405 DeclContext *Ctxt, PatchLocation Attr) {
406 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000407}
408
409/// \brief Apply all fixups recorded by noteForwardReference().
410void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000411 for (const auto &Ref : ForwardDIEReferences) {
412 DIE *RefDie;
413 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000414 PatchLocation Attr;
Frederic Riss1c650942015-07-21 22:41:43 +0000415 DeclContext *Ctxt;
416 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
417 if (Ctxt && Ctxt->getCanonicalDIEOffset())
418 Attr.set(Ctxt->getCanonicalDIEOffset());
419 else
420 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000421 }
Frederic Riss9833de62015-03-06 23:22:53 +0000422}
423
Frederic Riss5a62dc32015-03-13 18:35:54 +0000424void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
425 int64_t PcOffset) {
426 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
427 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
428 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000429}
430
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000431void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000432 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
433 RangeAttributes.push_back(Attr);
434 else
435 UnitRangeAttribute = Attr;
436}
437
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000438void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000439 LocationAttributes.emplace_back(Attr, PcOffset);
440}
441
Frederic Rissbce93ff2015-03-16 02:05:10 +0000442/// \brief Add a name accelerator entry for \p Die with \p Name
443/// which is stored in the string table at \p Offset.
444void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
445 uint32_t Offset, bool SkipPubSection) {
446 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
447}
448
449/// \brief Add a type accelerator entry for \p Die with \p Name
450/// which is stored in the string table at \p Offset.
451void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
452 uint32_t Offset) {
453 Pubtypes.emplace_back(Name, Die, Offset, false);
454}
455
Frederic Rissc99ea202015-02-28 00:29:11 +0000456/// \brief The Dwarf streaming logic
457///
458/// All interactions with the MC layer that is used to build the debug
459/// information binary representation are handled in this class.
460class DwarfStreamer {
461 /// \defgroup MCObjects MC layer objects constructed by the streamer
462 /// @{
463 std::unique_ptr<MCRegisterInfo> MRI;
464 std::unique_ptr<MCAsmInfo> MAI;
465 std::unique_ptr<MCObjectFileInfo> MOFI;
466 std::unique_ptr<MCContext> MC;
467 MCAsmBackend *MAB; // Owned by MCStreamer
468 std::unique_ptr<MCInstrInfo> MII;
469 std::unique_ptr<MCSubtargetInfo> MSTI;
470 MCCodeEmitter *MCE; // Owned by MCStreamer
471 MCStreamer *MS; // Owned by AsmPrinter
472 std::unique_ptr<TargetMachine> TM;
473 std::unique_ptr<AsmPrinter> Asm;
474 /// @}
475
476 /// \brief the file we stream the linked Dwarf to.
477 std::unique_ptr<raw_fd_ostream> OutFile;
478
Frederic Riss25440872015-03-13 23:30:31 +0000479 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000480 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000481 uint32_t LineSectionSize;
Frederic Riss5a642072015-06-05 23:06:11 +0000482 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000483
Frederic Rissbce93ff2015-03-16 02:05:10 +0000484 /// \brief Emit the pubnames or pubtypes section contribution for \p
485 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000486 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000487 const CompileUnit &Unit,
488 const std::vector<CompileUnit::AccelInfo> &Names);
489
Frederic Rissc99ea202015-02-28 00:29:11 +0000490public:
491 /// \brief Actually create the streamer and the ouptut file.
492 ///
493 /// This could be done directly in the constructor, but it feels
494 /// more natural to handle errors through return value.
495 bool init(Triple TheTriple, StringRef OutputFilename);
496
Frederic Rissb8b43d52015-03-04 22:07:44 +0000497 /// \brief Dump the file to the disk.
Frederic Riss24faade2015-09-02 16:49:13 +0000498 bool finish(const DebugMap &);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000499
500 AsmPrinter &getAsmPrinter() const { return *Asm; }
501
502 /// \brief Set the current output section to debug_info and change
503 /// the MC Dwarf version to \p DwarfVersion.
504 void switchToDebugInfoSection(unsigned DwarfVersion);
505
506 /// \brief Emit the compilation unit header for \p Unit in the
507 /// debug_info section.
508 ///
509 /// As a side effect, this also switches the current Dwarf version
510 /// of the MC layer to the one of U.getOrigUnit().
511 void emitCompileUnitHeader(CompileUnit &Unit);
512
513 /// \brief Recursively emit the DIE tree rooted at \p Die.
514 void emitDIE(DIE &Die);
515
516 /// \brief Emit the abbreviation table \p Abbrevs to the
517 /// debug_abbrev section.
David Blaikie6196aa02015-11-18 00:34:10 +0000518 void emitAbbrevs(const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000519
520 /// \brief Emit the string table described by \p Pool.
521 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000522
523 /// \brief Emit debug_ranges for \p FuncRange by translating the
524 /// original \p Entries.
525 void emitRangesEntries(
526 int64_t UnitPcOffset, uint64_t OrigLowPc,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000527 const FunctionIntervals::const_iterator &FuncRange,
Frederic Riss25440872015-03-13 23:30:31 +0000528 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
529 unsigned AddressSize);
530
Frederic Riss563b1b02015-03-14 03:46:51 +0000531 /// \brief Emit debug_aranges entries for \p Unit and if \p
532 /// DoRangesSection is true, also emit the debug_ranges entries for
533 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
534 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000535
536 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000537
538 /// \brief Emit the debug_loc contribution for \p Unit by copying
539 /// the entries from \p Dwarf and offseting them. Update the
540 /// location attributes to point to the new entries.
541 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000542
543 /// \brief Emit the line table described in \p Rows into the
544 /// debug_line section.
Frederic Rissa5e14532015-08-07 15:14:13 +0000545 void emitLineTableForUnit(MCDwarfLineTableParams Params,
546 StringRef PrologueBytes, unsigned MinInstLength,
Frederic Riss63786b02015-03-15 20:45:43 +0000547 std::vector<DWARFDebugLine::Row> &Rows,
548 unsigned AdddressSize);
549
550 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000551
552 /// \brief Emit the .debug_pubnames contribution for \p Unit.
553 void emitPubNamesForUnit(const CompileUnit &Unit);
554
555 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
556 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000557
558 /// \brief Emit a CIE.
559 void emitCIE(StringRef CIEBytes);
560
561 /// \brief Emit an FDE with data \p Bytes.
562 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
563 StringRef Bytes);
564
565 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000566};
567
568bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
569 std::string ErrorStr;
570 std::string TripleName;
571 StringRef Context = "dwarf streamer init";
572
573 // Get the target.
574 const Target *TheTarget =
575 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
576 if (!TheTarget)
577 return error(ErrorStr, Context);
578 TripleName = TheTriple.getTriple();
579
580 // Create all the MC Objects.
581 MRI.reset(TheTarget->createMCRegInfo(TripleName));
582 if (!MRI)
583 return error(Twine("no register info for target ") + TripleName, Context);
584
585 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
586 if (!MAI)
587 return error("no asm info for target " + TripleName, Context);
588
589 MOFI.reset(new MCObjectFileInfo);
590 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Rafael Espindola699281c2016-05-18 11:58:50 +0000591 MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, CodeModel::Default, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000592
Joel Jones373d7d32016-07-25 17:18:28 +0000593 MCTargetOptions Options;
594 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "", Options);
Frederic Rissc99ea202015-02-28 00:29:11 +0000595 if (!MAB)
596 return error("no asm backend for target " + TripleName, Context);
597
598 MII.reset(TheTarget->createMCInstrInfo());
599 if (!MII)
600 return error("no instr info info for target " + TripleName, Context);
601
602 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
603 if (!MSTI)
604 return error("no subtarget info for target " + TripleName, Context);
605
Eric Christopher0169e422015-03-10 22:03:14 +0000606 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000607 if (!MCE)
608 return error("no code emitter for target " + TripleName, Context);
609
610 // Create the output file.
611 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000612 OutFile =
613 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000614 if (EC)
615 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
616
David Majnemer03e2cc32015-12-21 22:09:27 +0000617 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
618 MS = TheTarget->createMCObjectStreamer(
619 TheTriple, *MC, *MAB, *OutFile, MCE, *MSTI, MCOptions.MCRelaxAll,
620 MCOptions.MCIncrementalLinkerCompatible,
621 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000622 if (!MS)
623 return error("no object streamer for target " + TripleName, Context);
624
625 // Finally create the AsmPrinter we'll use to emit the DIEs.
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000626 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
627 None));
Frederic Rissc99ea202015-02-28 00:29:11 +0000628 if (!TM)
629 return error("no target machine for target " + TripleName, Context);
630
631 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
632 if (!Asm)
633 return error("no asm printer for target " + TripleName, Context);
634
Frederic Riss25440872015-03-13 23:30:31 +0000635 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000636 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000637 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000638 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000639
Frederic Rissc99ea202015-02-28 00:29:11 +0000640 return true;
641}
642
Frederic Riss24faade2015-09-02 16:49:13 +0000643bool DwarfStreamer::finish(const DebugMap &DM) {
644 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
645 return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
646
Frederic Rissc99ea202015-02-28 00:29:11 +0000647 MS->Finish();
648 return true;
649}
650
Frederic Rissb8b43d52015-03-04 22:07:44 +0000651/// \brief Set the current output section to debug_info and change
652/// the MC Dwarf version to \p DwarfVersion.
653void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
654 MS->SwitchSection(MOFI->getDwarfInfoSection());
655 MC->setDwarfVersion(DwarfVersion);
656}
657
658/// \brief Emit the compilation unit header for \p Unit in the
659/// debug_info section.
660///
661/// A Dwarf scetion header is encoded as:
662/// uint32_t Unit length (omiting this field)
663/// uint16_t Version
664/// uint32_t Abbreviation table offset
665/// uint8_t Address size
666///
667/// Leading to a total of 11 bytes.
668void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
669 unsigned Version = Unit.getOrigUnit().getVersion();
670 switchToDebugInfoSection(Version);
671
672 // Emit size of content not including length itself. The size has
673 // already been computed in CompileUnit::computeOffsets(). Substract
674 // 4 to that size to account for the length field.
675 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
676 Asm->EmitInt16(Version);
677 // We share one abbreviations table across all units so it's always at the
678 // start of the section.
679 Asm->EmitInt32(0);
680 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
681}
682
683/// \brief Emit the \p Abbrevs array as the shared abbreviation table
684/// for the linked Dwarf file.
David Blaikie6196aa02015-11-18 00:34:10 +0000685void DwarfStreamer::emitAbbrevs(
686 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs) {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000687 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
688 Asm->emitDwarfAbbrevs(Abbrevs);
689}
690
691/// \brief Recursively emit the DIE tree rooted at \p Die.
692void DwarfStreamer::emitDIE(DIE &Die) {
693 MS->SwitchSection(MOFI->getDwarfInfoSection());
694 Asm->emitDwarfDIE(Die);
695}
696
Frederic Rissef648462015-03-06 17:56:30 +0000697/// \brief Emit the debug_str section stored in \p Pool.
698void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000699 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000700 for (auto *Entry = Pool.getFirstEntry(); Entry;
701 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000702 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000703 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
704}
705
Frederic Riss25440872015-03-13 23:30:31 +0000706/// \brief Emit the debug_range section contents for \p FuncRange by
707/// translating the original \p Entries. The debug_range section
708/// format is totally trivial, consisting just of pairs of address
709/// sized addresses describing the ranges.
710void DwarfStreamer::emitRangesEntries(
711 int64_t UnitPcOffset, uint64_t OrigLowPc,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000712 const FunctionIntervals::const_iterator &FuncRange,
Frederic Riss25440872015-03-13 23:30:31 +0000713 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
714 unsigned AddressSize) {
715 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
716
717 // Offset each range by the right amount.
Frederic Riss94546202015-08-31 05:09:32 +0000718 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
Frederic Riss25440872015-03-13 23:30:31 +0000719 for (const auto &Range : Entries) {
720 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
721 warn("unsupported base address selection operation",
722 "emitting debug_ranges");
723 break;
724 }
725 // Do not emit empty ranges.
726 if (Range.StartAddress == Range.EndAddress)
727 continue;
728
729 // All range entries should lie in the function range.
730 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
731 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
732 warn("inconsistent range data.", "emitting debug_ranges");
733 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
734 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
735 RangesSectionSize += 2 * AddressSize;
736 }
737
738 // Add the terminator entry.
739 MS->EmitIntValue(0, AddressSize);
740 MS->EmitIntValue(0, AddressSize);
741 RangesSectionSize += 2 * AddressSize;
742}
743
Frederic Riss563b1b02015-03-14 03:46:51 +0000744/// \brief Emit the debug_aranges contribution of a unit and
745/// if \p DoDebugRanges is true the debug_range contents for a
746/// compile_unit level DW_AT_ranges attribute (Which are basically the
747/// same thing with a different base address).
748/// Just aggregate all the ranges gathered inside that unit.
749void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
750 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000751 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
752 // Gather the ranges in a vector, so that we can simplify them. The
753 // IntervalMap will have coalesced the non-linked ranges, but here
754 // we want to coalesce the linked addresses.
755 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
756 const auto &FunctionRanges = Unit.getFunctionRanges();
757 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
758 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000759 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
760 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000761
762 // The object addresses where sorted, but again, the linked
763 // addresses might end up in a different order.
764 std::sort(Ranges.begin(), Ranges.end());
765
Frederic Riss563b1b02015-03-14 03:46:51 +0000766 if (!Ranges.empty()) {
767 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
768
Rafael Espindola9ab09232015-03-17 20:07:06 +0000769 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
770 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000771
772 unsigned HeaderSize =
773 sizeof(int32_t) + // Size of contents (w/o this field
774 sizeof(int16_t) + // DWARF ARange version number
775 sizeof(int32_t) + // Offset of CU in the .debug_info section
776 sizeof(int8_t) + // Pointer Size (in bytes)
777 sizeof(int8_t); // Segment Size (in bytes)
778
779 unsigned TupleSize = AddressSize * 2;
780 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
781
782 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000783 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000784 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
785 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
786 Asm->EmitInt8(AddressSize); // Address size
787 Asm->EmitInt8(0); // Segment size
788
Petr Hosekfaef3202016-06-01 01:59:58 +0000789 Asm->OutStreamer->emitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000790
791 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
792 ++Range) {
793 uint64_t RangeStart = Range->first;
794 MS->EmitIntValue(RangeStart, AddressSize);
795 while ((Range + 1) != End && Range->second == (Range + 1)->first)
796 ++Range;
797 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
798 }
799
800 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000801 Asm->OutStreamer->EmitIntValue(0, AddressSize);
802 Asm->OutStreamer->EmitIntValue(0, AddressSize);
803 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000804 }
805
806 if (!DoDebugRanges)
807 return;
808
809 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
810 // Offset each range by the right amount.
811 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000812 // Emit coalesced ranges.
813 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000814 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000815 while (Range + 1 != End && Range->second == (Range + 1)->first)
816 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000817 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000818 RangesSectionSize += 2 * AddressSize;
819 }
820
821 // Add the terminator entry.
822 MS->EmitIntValue(0, AddressSize);
823 MS->EmitIntValue(0, AddressSize);
824 RangesSectionSize += 2 * AddressSize;
825}
826
Frederic Rissdfb97902015-03-14 15:49:07 +0000827/// \brief Emit location lists for \p Unit and update attribtues to
828/// point to the new entries.
829void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
830 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000831 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000832
833 if (Attributes.empty())
834 return;
835
836 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
837
838 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
839 const DWARFSection &InputSec = Dwarf.getLocSection();
840 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
841 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Greg Claytonc8c10322016-12-13 18:25:19 +0000842 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000843 int64_t UnitPcOffset = 0;
Greg Clayton52fe1f62016-12-14 22:38:08 +0000844 auto OrigLowPc = OrigUnitDie.getAttributeValueAsAddress(dwarf::DW_AT_low_pc);
845 if (OrigLowPc)
846 UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc();
Frederic Rissdfb97902015-03-14 15:49:07 +0000847
848 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000849 uint32_t Offset = Attr.first.get();
850 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000851 // This is the quantity to add to the old location address to get
852 // the correct address for the new one.
853 int64_t LocPcOffset = Attr.second + UnitPcOffset;
854 while (Data.isValidOffset(Offset)) {
855 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
856 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
857 LocSectionSize += 2 * AddressSize;
858 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000859 Asm->OutStreamer->EmitIntValue(0, AddressSize);
860 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000861 break;
862 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000863 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
864 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000865 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000866 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000867 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000868 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000869 StringRef(InputSec.Data.substr(Offset, Length)));
870 Offset += Length;
871 LocSectionSize += Length + 2;
872 }
873 }
874}
875
Frederic Rissa5e14532015-08-07 15:14:13 +0000876void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
877 StringRef PrologueBytes,
Frederic Riss63786b02015-03-15 20:45:43 +0000878 unsigned MinInstLength,
879 std::vector<DWARFDebugLine::Row> &Rows,
880 unsigned PointerSize) {
881 // Switch to the section where the table will be emitted into.
882 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000883 MCSymbol *LineStartSym = MC->createTempSymbol();
884 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000885
886 // The first 4 bytes is the total length of the information for this
887 // compilation unit (not including these 4 bytes for the length).
888 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000889 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000890 // Copy Prologue.
891 MS->EmitBytes(PrologueBytes);
892 LineSectionSize += PrologueBytes.size() + 4;
893
Frederic Rissc3820d02015-03-15 22:20:28 +0000894 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000895 raw_svector_ostream EncodingOS(EncodingBuffer);
896
897 if (Rows.empty()) {
898 // We only have the dummy entry, dsymutil emits an entry with a 0
899 // address in that case.
Frederic Rissa5e14532015-08-07 15:14:13 +0000900 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000901 MS->EmitBytes(EncodingOS.str());
902 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000903 MS->EmitLabel(LineEndSym);
904 return;
905 }
906
907 // Line table state machine fields
908 unsigned FileNum = 1;
909 unsigned LastLine = 1;
910 unsigned Column = 0;
911 unsigned IsStatement = 1;
912 unsigned Isa = 0;
913 uint64_t Address = -1ULL;
914
915 unsigned RowsSinceLastSequence = 0;
916
917 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
918 auto &Row = Rows[Idx];
919
920 int64_t AddressDelta;
921 if (Address == -1ULL) {
922 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
923 MS->EmitULEB128IntValue(PointerSize + 1);
924 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
925 MS->EmitIntValue(Row.Address, PointerSize);
926 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
927 AddressDelta = 0;
928 } else {
929 AddressDelta = (Row.Address - Address) / MinInstLength;
930 }
931
932 // FIXME: code copied and transfromed from
933 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
934 // this code, but the current compatibility requirement with
935 // classic dsymutil makes it hard. Revisit that once this
936 // requirement is dropped.
937
938 if (FileNum != Row.File) {
939 FileNum = Row.File;
940 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
941 MS->EmitULEB128IntValue(FileNum);
942 LineSectionSize += 1 + getULEB128Size(FileNum);
943 }
944 if (Column != Row.Column) {
945 Column = Row.Column;
946 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
947 MS->EmitULEB128IntValue(Column);
948 LineSectionSize += 1 + getULEB128Size(Column);
949 }
950
951 // FIXME: We should handle the discriminator here, but dsymutil
952 // doesn' consider it, thus ignore it for now.
953
954 if (Isa != Row.Isa) {
955 Isa = Row.Isa;
956 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
957 MS->EmitULEB128IntValue(Isa);
958 LineSectionSize += 1 + getULEB128Size(Isa);
959 }
960 if (IsStatement != Row.IsStmt) {
961 IsStatement = Row.IsStmt;
962 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
963 LineSectionSize += 1;
964 }
965 if (Row.BasicBlock) {
966 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
967 LineSectionSize += 1;
968 }
969
970 if (Row.PrologueEnd) {
971 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
972 LineSectionSize += 1;
973 }
974
975 if (Row.EpilogueBegin) {
976 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
977 LineSectionSize += 1;
978 }
979
980 int64_t LineDelta = int64_t(Row.Line) - LastLine;
981 if (!Row.EndSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000982 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000983 MS->EmitBytes(EncodingOS.str());
984 LineSectionSize += EncodingBuffer.size();
985 EncodingBuffer.resize(0);
986 Address = Row.Address;
987 LastLine = Row.Line;
988 RowsSinceLastSequence++;
989 } else {
990 if (LineDelta) {
991 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
992 MS->EmitSLEB128IntValue(LineDelta);
993 LineSectionSize += 1 + getSLEB128Size(LineDelta);
994 }
995 if (AddressDelta) {
996 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
997 MS->EmitULEB128IntValue(AddressDelta);
998 LineSectionSize += 1 + getULEB128Size(AddressDelta);
999 }
Frederic Rissa5e14532015-08-07 15:14:13 +00001000 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001001 MS->EmitBytes(EncodingOS.str());
1002 LineSectionSize += EncodingBuffer.size();
1003 EncodingBuffer.resize(0);
Frederic Riss63786b02015-03-15 20:45:43 +00001004 Address = -1ULL;
1005 LastLine = FileNum = IsStatement = 1;
1006 RowsSinceLastSequence = Column = Isa = 0;
1007 }
1008 }
1009
1010 if (RowsSinceLastSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +00001011 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001012 MS->EmitBytes(EncodingOS.str());
1013 LineSectionSize += EncodingBuffer.size();
1014 EncodingBuffer.resize(0);
1015 }
1016
1017 MS->EmitLabel(LineEndSym);
1018}
1019
Frederic Rissbce93ff2015-03-16 02:05:10 +00001020/// \brief Emit the pubnames or pubtypes section contribution for \p
1021/// Unit into \p Sec. The data is provided in \p Names.
1022void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001023 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001024 const std::vector<CompileUnit::AccelInfo> &Names) {
1025 if (Names.empty())
1026 return;
1027
1028 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001029 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001030 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1031 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001032
1033 bool HeaderEmitted = false;
1034 // Emit the pubnames for this compilation unit.
1035 for (const auto &Name : Names) {
1036 if (Name.SkipPubSection)
1037 continue;
1038
1039 if (!HeaderEmitted) {
1040 // Emit the header.
1041 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001042 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001043 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001044 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001045 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1046 HeaderEmitted = true;
1047 }
1048 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001049 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001050 StringRef(Name.Name.data(), Name.Name.size() + 1));
1051 }
1052
1053 if (!HeaderEmitted)
1054 return;
1055 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001056 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001057}
1058
1059/// \brief Emit .debug_pubnames for \p Unit.
1060void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1061 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1062 "names", Unit, Unit.getPubnames());
1063}
1064
1065/// \brief Emit .debug_pubtypes for \p Unit.
1066void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1067 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1068 "types", Unit, Unit.getPubtypes());
1069}
1070
Frederic Riss5a642072015-06-05 23:06:11 +00001071/// \brief Emit a CIE into the debug_frame section.
1072void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1073 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1074
1075 MS->EmitBytes(CIEBytes);
1076 FrameSectionSize += CIEBytes.size();
1077}
1078
1079/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1080/// contains the FDE data without the length, CIE offset and address
1081/// which will be replaced with the paramter values.
1082void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1083 uint32_t Address, StringRef FDEBytes) {
1084 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1085
1086 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1087 MS->EmitIntValue(CIEOffset, 4);
1088 MS->EmitIntValue(Address, AddrSize);
1089 MS->EmitBytes(FDEBytes);
1090 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1091}
1092
Frederic Rissd3455182015-01-28 18:27:01 +00001093/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001094///
1095/// The link of the dwarf information from the object files will be
1096/// driven by the selection of 'root DIEs', which are DIEs that
1097/// describe variables or functions that are present in the linked
1098/// binary (and thus have entries in the debug map). All the debug
1099/// information that will be linked (the DIEs, but also the line
1100/// tables, ranges, ...) is derived from that set of root DIEs.
1101///
1102/// The root DIEs are identified because they contain relocations that
1103/// correspond to a debug map entry at specific places (the low_pc for
1104/// a function, the location for a variable). These relocations are
1105/// called ValidRelocs in the DwarfLinker and are gathered as a very
1106/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001107class DwarfLinker {
1108public:
Frederic Rissb9818322015-02-28 00:29:07 +00001109 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1110 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001111 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001112
1113 /// \brief Link the contents of the DebugMap.
1114 bool link(const DebugMap &);
1115
Greg Claytonc8c10322016-12-13 18:25:19 +00001116 void reportWarning(const Twine &Warning,
1117 const DWARFDie *DIE = nullptr) const;
Adrian Prantlc3021ee2015-09-22 18:50:51 +00001118
Frederic Rissd3455182015-01-28 18:27:01 +00001119private:
Frederic Riss563cba62015-01-28 22:15:14 +00001120 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001121 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001122
1123 /// \brief Called at the end of a debug object link.
1124 void endDebugObject();
1125
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001126 /// Keeps track of relocations.
1127 class RelocationManager {
1128 struct ValidReloc {
1129 uint32_t Offset;
1130 uint32_t Size;
1131 uint64_t Addend;
1132 const DebugMapObject::DebugMapEntry *Mapping;
Frederic Riss1036e642015-02-13 23:18:22 +00001133
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001134 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1135 const DebugMapObject::DebugMapEntry *Mapping)
1136 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
Frederic Riss1036e642015-02-13 23:18:22 +00001137
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001138 bool operator<(const ValidReloc &RHS) const {
1139 return Offset < RHS.Offset;
1140 }
1141 };
1142
1143 DwarfLinker &Linker;
1144
1145 /// \brief The valid relocations for the current DebugMapObject.
1146 /// This vector is sorted by relocation offset.
1147 std::vector<ValidReloc> ValidRelocs;
1148
1149 /// \brief Index into ValidRelocs of the next relocation to
1150 /// consider. As we walk the DIEs in acsending file offset and as
1151 /// ValidRelocs is sorted by file offset, keeping this index
1152 /// uptodate is all we have to do to have a cheap lookup during the
1153 /// root DIE selection and during DIE cloning.
1154 unsigned NextValidReloc;
1155
1156 public:
1157 RelocationManager(DwarfLinker &Linker)
1158 : Linker(Linker), NextValidReloc(0) {}
1159
1160 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1161 /// \brief Reset the NextValidReloc counter.
1162 void resetValidRelocs() { NextValidReloc = 0; }
1163
1164 /// \defgroup FindValidRelocations Translate debug map into a list
1165 /// of relevant relocations
1166 ///
1167 /// @{
1168 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1169 const DebugMapObject &DMO);
1170
1171 bool findValidRelocs(const object::SectionRef &Section,
1172 const object::ObjectFile &Obj,
1173 const DebugMapObject &DMO);
1174
1175 void findValidRelocsMachO(const object::SectionRef &Section,
1176 const object::MachOObjectFile &Obj,
1177 const DebugMapObject &DMO);
1178 /// @}
1179
1180 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1181 CompileUnit::DIEInfo &Info);
1182
1183 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1184 bool isLittleEndian);
Frederic Riss1036e642015-02-13 23:18:22 +00001185 };
1186
Frederic Riss84c09a52015-02-13 23:18:34 +00001187 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1188 ///
1189 /// @{
1190 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1191 /// keep. Store that information in \p CU's DIEInfo.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001192 void lookForDIEsToKeep(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00001193 const DWARFDie &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001194 const DebugMapObject &DMO, CompileUnit &CU,
1195 unsigned Flags);
1196
Adrian Prantle5162db2015-09-22 22:20:50 +00001197 /// If this compile unit is really a skeleton CU that points to a
1198 /// clang module, register it in ClangModules and return true.
1199 ///
1200 /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
1201 /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
1202 /// hash.
Greg Claytonc8c10322016-12-13 18:25:19 +00001203 bool registerModuleReference(const DWARFDie &CUDie,
Adrian Prantle5162db2015-09-22 22:20:50 +00001204 const DWARFUnit &Unit, DebugMap &ModuleMap,
1205 unsigned Indent = 0);
1206
1207 /// Recursively add the debug info in this clang module .pcm
1208 /// file (and all the modules imported by it in a bottom-up fashion)
1209 /// to Units.
Adrian Prantla112ef92015-09-23 17:35:52 +00001210 void loadClangModule(StringRef Filename, StringRef ModulePath,
1211 StringRef ModuleName, uint64_t DwoId,
Adrian Prantle5162db2015-09-22 22:20:50 +00001212 DebugMap &ModuleMap, unsigned Indent = 0);
1213
Frederic Riss84c09a52015-02-13 23:18:34 +00001214 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1215 enum TravesalFlags {
1216 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1217 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1218 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1219 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001220 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss29eedc72015-09-11 04:17:30 +00001221 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
Frederic Riss84c09a52015-02-13 23:18:34 +00001222 };
1223
1224 /// \brief Mark the passed DIE as well as all the ones it depends on
1225 /// as kept.
Adrian Prantl6ec47122015-09-22 15:31:14 +00001226 void keepDIEAndDependencies(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00001227 const DWARFDie &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001228 CompileUnit::DIEInfo &MyInfo,
1229 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001230 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001231
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001232 unsigned shouldKeepDIE(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00001233 const DWARFDie &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001234 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1235 unsigned Flags);
1236
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001237 unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00001238 const DWARFDie &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001239 CompileUnit &Unit,
1240 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1241
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001242 unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00001243 const DWARFDie &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001244 CompileUnit &Unit,
1245 CompileUnit::DIEInfo &MyInfo,
1246 unsigned Flags);
1247
1248 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1249 CompileUnit::DIEInfo &Info);
1250 /// @}
1251
Frederic Rissb8b43d52015-03-04 22:07:44 +00001252 /// \defgroup Linking Methods used to link the debug information
1253 ///
1254 /// @{
Frederic Rissb8b43d52015-03-04 22:07:44 +00001255
Adrian Prantl3565af42015-09-14 16:46:10 +00001256 class DIECloner {
1257 DwarfLinker &Linker;
1258 RelocationManager &RelocMgr;
1259 /// Allocator used for all the DIEValue objects.
1260 BumpPtrAllocator &DIEAlloc;
Greg Clayton35630c32016-12-01 18:56:29 +00001261 std::vector<std::unique_ptr<CompileUnit>> &CompileUnits;
Adrian Prantl3565af42015-09-14 16:46:10 +00001262 LinkOptions Options;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001263
Adrian Prantl3565af42015-09-14 16:46:10 +00001264 public:
1265 DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1266 BumpPtrAllocator &DIEAlloc,
Greg Clayton35630c32016-12-01 18:56:29 +00001267 std::vector<std::unique_ptr<CompileUnit>> &CompileUnits,
1268 LinkOptions &Options)
Adrian Prantl3565af42015-09-14 16:46:10 +00001269 : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1270 CompileUnits(CompileUnits), Options(Options) {}
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001271
Adrian Prantl3565af42015-09-14 16:46:10 +00001272 /// Recursively clone \p InputDIE into an tree of DIE objects
1273 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1274 /// stripped out and addresses have been rewritten according to the
1275 /// debug map.
1276 ///
1277 /// \param OutOffset is the offset the cloned DIE in the output
1278 /// compile unit.
1279 /// \param PCOffset (while cloning a function scope) is the offset
1280 /// applied to the entry point of the function to get the linked address.
Greg Clayton35630c32016-12-01 18:56:29 +00001281 /// \param Die the output DIE to use, pass NULL to create one.
Adrian Prantl3565af42015-09-14 16:46:10 +00001282 /// \returns the root of the cloned tree or null if nothing was selected.
Greg Claytonc8c10322016-12-13 18:25:19 +00001283 DIE *cloneDIE(const DWARFDie &InputDIE, CompileUnit &U,
Greg Clayton35630c32016-12-01 18:56:29 +00001284 int64_t PCOffset, uint32_t OutOffset, unsigned Flags,
1285 DIE *Die = nullptr);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001286
Adrian Prantl3565af42015-09-14 16:46:10 +00001287 /// Construct the output DIE tree by cloning the DIEs we
1288 /// chose to keep above. If there are no valid relocs, then there's
1289 /// nothing to clone/emit.
1290 void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001291
Adrian Prantl3565af42015-09-14 16:46:10 +00001292 private:
1293 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
Frederic Rissbce93ff2015-03-16 02:05:10 +00001294
Adrian Prantl3565af42015-09-14 16:46:10 +00001295 /// Information gathered and exchanged between the various
1296 /// clone*Attributes helpers about the attributes of a particular DIE.
1297 struct AttributesInfo {
1298 const char *Name, *MangledName; ///< Names.
1299 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
Frederic Riss31da3242015-03-11 18:45:52 +00001300
Adrian Prantl3565af42015-09-14 16:46:10 +00001301 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1302 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1303 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
Frederic Rissbce93ff2015-03-16 02:05:10 +00001304
Adrian Prantl3565af42015-09-14 16:46:10 +00001305 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1306 bool IsDeclaration; ///< Is this DIE only a declaration?
1307
1308 AttributesInfo()
1309 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1310 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1311 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1312 };
1313
1314 /// Helper for cloneDIE.
1315 unsigned cloneAttribute(DIE &Die,
Greg Claytonc8c10322016-12-13 18:25:19 +00001316 const DWARFDie &InputDIE,
Adrian Prantl3565af42015-09-14 16:46:10 +00001317 CompileUnit &U, const DWARFFormValue &Val,
1318 const AttributeSpec AttrSpec, unsigned AttrSize,
1319 AttributesInfo &AttrInfo);
1320
1321 /// Clone a string attribute described by \p AttrSpec and add
1322 /// it to \p Die.
1323 /// \returns the size of the new attribute.
1324 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1325 const DWARFFormValue &Val,
1326 const DWARFUnit &U);
1327
1328 /// Clone an attribute referencing another DIE and add
1329 /// it to \p Die.
1330 /// \returns the size of the new attribute.
1331 unsigned
1332 cloneDieReferenceAttribute(DIE &Die,
Greg Claytonc8c10322016-12-13 18:25:19 +00001333 const DWARFDie &InputDIE,
Adrian Prantl3565af42015-09-14 16:46:10 +00001334 AttributeSpec AttrSpec, unsigned AttrSize,
1335 const DWARFFormValue &Val, CompileUnit &Unit);
1336
1337 /// Clone an attribute referencing another DIE and add
1338 /// it to \p Die.
1339 /// \returns the size of the new attribute.
1340 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1341 const DWARFFormValue &Val, unsigned AttrSize);
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 cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1347 const DWARFFormValue &Val,
1348 const CompileUnit &Unit,
1349 AttributesInfo &Info);
1350
1351 /// Clone a scalar attribute and add it to \p Die.
1352 /// \returns the size of the new attribute.
1353 unsigned cloneScalarAttribute(DIE &Die,
Greg Claytonc8c10322016-12-13 18:25:19 +00001354 const DWARFDie &InputDIE,
Adrian Prantl3565af42015-09-14 16:46:10 +00001355 CompileUnit &U, AttributeSpec AttrSpec,
1356 const DWARFFormValue &Val, unsigned AttrSize,
1357 AttributesInfo &Info);
1358
1359 /// Get the potential name and mangled name for the entity
1360 /// described by \p Die and store them in \Info if they are not
1361 /// already there.
1362 /// \returns is a name was found.
Greg Claytonc8c10322016-12-13 18:25:19 +00001363 bool getDIENames(const DWARFDie &Die, AttributesInfo &Info);
Adrian Prantl3565af42015-09-14 16:46:10 +00001364
1365 /// Create a copy of abbreviation Abbrev.
1366 void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
Frederic Riss31da3242015-03-11 18:45:52 +00001367 };
1368
Frederic Rissb8b43d52015-03-04 22:07:44 +00001369 /// \brief Assign an abbreviation number to \p Abbrev
1370 void AssignAbbrev(DIEAbbrev &Abbrev);
1371
1372 /// \brief FoldingSet that uniques the abbreviations.
1373 FoldingSet<DIEAbbrev> AbbreviationsSet;
1374 /// \brief Storage for the unique Abbreviations.
1375 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1376 /// be changed to a vecot of unique_ptrs.
David Blaikie6196aa02015-11-18 00:34:10 +00001377 std::vector<std::unique_ptr<DIEAbbrev>> Abbreviations;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001378
Frederic Riss25440872015-03-13 23:30:31 +00001379 /// \brief Compute and emit debug_ranges section for \p Unit, and
1380 /// patch the attributes referencing it.
1381 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1382
1383 /// \brief Generate and emit the DW_AT_ranges attribute for a
1384 /// compile_unit if it had one.
1385 void generateUnitRanges(CompileUnit &Unit) const;
1386
Frederic Riss63786b02015-03-15 20:45:43 +00001387 /// \brief Extract the line tables fromt he original dwarf, extract
1388 /// the relevant parts according to the linked function ranges and
1389 /// emit the result in the debug_line section.
1390 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1391
Frederic Rissbce93ff2015-03-16 02:05:10 +00001392 /// \brief Emit the accelerator entries for \p Unit.
1393 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1394
Frederic Riss5a642072015-06-05 23:06:11 +00001395 /// \brief Patch the frame info for an object file and emit it.
1396 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1397 unsigned AddressSize);
1398
Frederic Rissb8b43d52015-03-04 22:07:44 +00001399 /// \brief DIELoc objects that need to be destructed (but not freed!).
1400 std::vector<DIELoc *> DIELocs;
1401 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1402 std::vector<DIEBlock *> DIEBlocks;
1403 /// \brief Allocator used for all the DIEValue objects.
1404 BumpPtrAllocator DIEAlloc;
1405 /// @}
1406
Frederic Riss1c650942015-07-21 22:41:43 +00001407 /// ODR Contexts for that link.
1408 DeclContextTree ODRContexts;
1409
Frederic Riss1b9da422015-02-13 23:18:29 +00001410 /// \defgroup Helpers Various helper methods.
1411 ///
1412 /// @{
Benjamin Kramerc321e532016-06-08 19:09:22 +00001413 bool createStreamer(const Triple &TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001414
1415 /// \brief Attempt to load a debug object from disk.
1416 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1417 DebugMapObject &Obj,
1418 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001419 /// @}
1420
Frederic Rissd3455182015-01-28 18:27:01 +00001421 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001422 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001423 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001424 std::unique_ptr<DwarfStreamer> Streamer;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001425 uint64_t OutputDebugInfoSize;
Adrian Prantle5162db2015-09-22 22:20:50 +00001426 unsigned UnitID; ///< A unique ID that identifies each compile unit.
Frederic Riss563cba62015-01-28 22:15:14 +00001427
1428 /// The units of the current debug map object.
Greg Clayton35630c32016-12-01 18:56:29 +00001429 std::vector<std::unique_ptr<CompileUnit>> Units;
1430
Frederic Riss1b9da422015-02-13 23:18:29 +00001431
Oleg Ranevskyy5f78c5c2015-10-23 17:10:44 +00001432 /// The debug map object currently under consideration.
Frederic Riss1b9da422015-02-13 23:18:29 +00001433 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001434
1435 /// \brief The Dwarf string pool
1436 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001437
1438 /// \brief This map is keyed by the entry PC of functions in that
1439 /// debug object and the associated value is a pair storing the
1440 /// corresponding end PC and the offset to apply to get the linked
1441 /// address.
1442 ///
1443 /// See startDebugObject() for a more complete description of its use.
1444 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001445
1446 /// \brief The CIEs that have been emitted in the output
1447 /// section. The actual CIE data serves a the key to this StringMap,
1448 /// this takes care of comparing the semantics of CIEs defined in
1449 /// different object files.
1450 StringMap<uint32_t> EmittedCIEs;
1451
1452 /// Offset of the last CIE that has been emitted in the output
1453 /// debug_frame section.
1454 uint32_t LastCIEOffset;
Adrian Prantle5162db2015-09-22 22:20:50 +00001455
Adrian Prantl20937022015-09-23 17:11:10 +00001456 /// Mapping the PCM filename to the DwoId.
1457 StringMap<uint64_t> ClangModules;
Adrian Prantla9e23832016-01-14 18:31:07 +00001458
1459 bool ModuleCacheHintDisplayed = false;
1460 bool ArchiveHintDisplayed = false;
Frederic Rissd3455182015-01-28 18:27:01 +00001461};
1462
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001463/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
1464/// CompileUnit object instead.
Greg Clayton35630c32016-12-01 18:56:29 +00001465static CompileUnit *getUnitForOffset(
1466 std::vector<std::unique_ptr<CompileUnit>> &Units, unsigned Offset) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001467 auto CU =
1468 std::upper_bound(Units.begin(), Units.end(), Offset,
Greg Clayton35630c32016-12-01 18:56:29 +00001469 [](uint32_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
1470 return LHS < RHS->getOrigUnit().getNextUnitOffset();
Frederic Riss1b9da422015-02-13 23:18:29 +00001471 });
Greg Clayton35630c32016-12-01 18:56:29 +00001472 return CU != Units.end() ? CU->get() : nullptr;
Frederic Riss1b9da422015-02-13 23:18:29 +00001473}
1474
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001475/// Resolve the DIE attribute reference that has been
Frederic Riss1b9da422015-02-13 23:18:29 +00001476/// extracted in \p RefValue. The resulting DIE migh be in another
1477/// CompileUnit which is stored into \p ReferencedCU.
1478/// \returns null if resolving fails for any reason.
Greg Claytonc8c10322016-12-13 18:25:19 +00001479static DWARFDie resolveDIEReference(
Greg Clayton35630c32016-12-01 18:56:29 +00001480 const DwarfLinker &Linker, std::vector<std::unique_ptr<CompileUnit>> &Units,
Frederic Riss1c650942015-07-21 22:41:43 +00001481 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Greg Claytonc8c10322016-12-13 18:25:19 +00001482 const DWARFDie &DIE, CompileUnit *&RefCU) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001483 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
Greg Claytoncddab272016-10-31 16:46:02 +00001484 uint64_t RefOffset = *RefValue.getAsReference();
Frederic Riss1b9da422015-02-13 23:18:29 +00001485
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001486 if ((RefCU = getUnitForOffset(Units, RefOffset)))
Greg Claytonc8c10322016-12-13 18:25:19 +00001487 if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
Frederic Riss1b9da422015-02-13 23:18:29 +00001488 return RefDie;
1489
Greg Claytonc8c10322016-12-13 18:25:19 +00001490 Linker.reportWarning("could not find referenced DIE", &DIE);
1491 return DWARFDie();
Frederic Riss1b9da422015-02-13 23:18:29 +00001492}
1493
Frederic Riss1c650942015-07-21 22:41:43 +00001494/// \returns whether the passed \a Attr type might contain a DIE
1495/// reference suitable for ODR uniquing.
1496static bool isODRAttribute(uint16_t Attr) {
1497 switch (Attr) {
1498 default:
1499 return false;
1500 case dwarf::DW_AT_type:
1501 case dwarf::DW_AT_containing_type:
1502 case dwarf::DW_AT_specification:
1503 case dwarf::DW_AT_abstract_origin:
1504 case dwarf::DW_AT_import:
1505 return true;
1506 }
1507 llvm_unreachable("Improper attribute.");
1508}
1509
1510/// Set the last DIE/CU a context was seen in and, possibly invalidate
1511/// the context if it is ambiguous.
1512///
1513/// In the current implementation, we don't handle overloaded
1514/// functions well, because the argument types are not taken into
1515/// account when computing the DeclContext tree.
1516///
1517/// Some of this is mitigated byt using mangled names that do contain
1518/// the arguments types, but sometimes (eg. with function templates)
1519/// we don't have that. In that case, just do not unique anything that
1520/// refers to the contexts we are not able to distinguish.
1521///
1522/// If a context that is not a namespace appears twice in the same CU,
1523/// we know it is ambiguous. Make it invalid.
1524bool DeclContext::setLastSeenDIE(CompileUnit &U,
Greg Claytonc8c10322016-12-13 18:25:19 +00001525 const DWARFDie &Die) {
Frederic Riss1c650942015-07-21 22:41:43 +00001526 if (LastSeenCompileUnitID == U.getUniqueID()) {
1527 DWARFUnit &OrigUnit = U.getOrigUnit();
1528 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1529 U.getInfo(FirstIdx).Ctxt = nullptr;
1530 return false;
1531 }
1532
1533 LastSeenCompileUnitID = U.getUniqueID();
1534 LastSeenDIE = Die;
1535 return true;
1536}
1537
Frederic Riss1c650942015-07-21 22:41:43 +00001538PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
Greg Claytonc8c10322016-12-13 18:25:19 +00001539 DeclContext &Context, const DWARFDie &DIE, CompileUnit &U,
Adrian Prantl42562c32015-10-02 00:27:08 +00001540 NonRelocatableStringpool &StringPool, bool InClangModule) {
Greg Claytonc8c10322016-12-13 18:25:19 +00001541 unsigned Tag = DIE.getTag();
Frederic Riss1c650942015-07-21 22:41:43 +00001542
1543 // FIXME: dsymutil-classic compat: We should bail out here if we
1544 // have a specification or an abstract_origin. We will get the
1545 // parent context wrong here.
1546
1547 switch (Tag) {
1548 default:
1549 // By default stop gathering child contexts.
1550 return PointerIntPair<DeclContext *, 1>(nullptr);
Adrian Prantla112ef92015-09-23 17:35:52 +00001551 case dwarf::DW_TAG_module:
1552 break;
Frederic Riss1c650942015-07-21 22:41:43 +00001553 case dwarf::DW_TAG_compile_unit:
Frederic Riss1c650942015-07-21 22:41:43 +00001554 return PointerIntPair<DeclContext *, 1>(&Context);
1555 case dwarf::DW_TAG_subprogram:
1556 // Do not unique anything inside CU local functions.
1557 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1558 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
Greg Claytonc8c10322016-12-13 18:25:19 +00001559 !DIE.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_external, 0))
Frederic Riss1c650942015-07-21 22:41:43 +00001560 return PointerIntPair<DeclContext *, 1>(nullptr);
Justin Bognerb03fd122016-08-17 05:10:15 +00001561 LLVM_FALLTHROUGH;
Frederic Riss1c650942015-07-21 22:41:43 +00001562 case dwarf::DW_TAG_member:
1563 case dwarf::DW_TAG_namespace:
1564 case dwarf::DW_TAG_structure_type:
1565 case dwarf::DW_TAG_class_type:
1566 case dwarf::DW_TAG_union_type:
1567 case dwarf::DW_TAG_enumeration_type:
1568 case dwarf::DW_TAG_typedef:
1569 // Artificial things might be ambiguous, because they might be
1570 // created on demand. For example implicitely defined constructors
1571 // are ambiguous because of the way we identify contexts, and they
1572 // won't be generated everytime everywhere.
Greg Claytonc8c10322016-12-13 18:25:19 +00001573 if (DIE.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_artificial, 0))
Frederic Riss1c650942015-07-21 22:41:43 +00001574 return PointerIntPair<DeclContext *, 1>(nullptr);
1575 break;
1576 }
1577
Greg Claytonc8c10322016-12-13 18:25:19 +00001578 const char *Name = DIE.getName(DINameKind::LinkageName);
1579 const char *ShortName = DIE.getName(DINameKind::ShortName);
Frederic Riss1c650942015-07-21 22:41:43 +00001580 StringRef NameRef;
1581 StringRef ShortNameRef;
1582 StringRef FileRef;
1583
1584 if (Name)
1585 NameRef = StringPool.internString(Name);
1586 else if (Tag == dwarf::DW_TAG_namespace)
1587 // FIXME: For dsymutil-classic compatibility. I think uniquing
1588 // within anonymous namespaces is wrong. There is no ODR guarantee
1589 // there.
1590 NameRef = StringPool.internString("(anonymous namespace)");
1591
1592 if (ShortName && ShortName != Name)
1593 ShortNameRef = StringPool.internString(ShortName);
1594 else
1595 ShortNameRef = NameRef;
1596
1597 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1598 Tag != dwarf::DW_TAG_union_type &&
1599 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1600 return PointerIntPair<DeclContext *, 1>(nullptr);
1601
Frederic Riss1c650942015-07-21 22:41:43 +00001602 unsigned Line = 0;
Adrian Prantl42562c32015-10-02 00:27:08 +00001603 unsigned ByteSize = UINT32_MAX;
Frederic Riss1c650942015-07-21 22:41:43 +00001604
Adrian Prantl42562c32015-10-02 00:27:08 +00001605 if (!InClangModule) {
1606 // Gather some discriminating data about the DeclContext we will be
1607 // creating: File, line number and byte size. This shouldn't be
1608 // necessary, because the ODR is just about names, but given that we
1609 // do some approximations with overloaded functions and anonymous
1610 // namespaces, use these additional data points to make the process
1611 // safer. This is disabled for clang modules, because forward
1612 // declarations of module-defined types do not have a file and line.
Greg Claytonc8c10322016-12-13 18:25:19 +00001613 ByteSize = DIE.getAttributeValueAsUnsignedConstant(
1614 dwarf::DW_AT_byte_size, UINT64_MAX);
Adrian Prantl42562c32015-10-02 00:27:08 +00001615 if (Tag != dwarf::DW_TAG_namespace || !Name) {
Greg Claytonc8c10322016-12-13 18:25:19 +00001616 if (unsigned FileNum = DIE.getAttributeValueAsUnsignedConstant(
1617 dwarf::DW_AT_decl_file, 0)) {
Adrian Prantl42562c32015-10-02 00:27:08 +00001618 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1619 &U.getOrigUnit())) {
1620 // FIXME: dsymutil-classic compatibility. I'd rather not
1621 // unique anything in anonymous namespaces, but if we do, then
1622 // verify that the file and line correspond.
1623 if (!Name && Tag == dwarf::DW_TAG_namespace)
1624 FileNum = 1;
Frederic Riss1c650942015-07-21 22:41:43 +00001625
Adrian Prantl42562c32015-10-02 00:27:08 +00001626 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1627 // instead of "" would allow more uniquing, but for now, do
1628 // it this way to match dsymutil-classic.
Pete Cooperb2ba7762016-07-22 01:41:32 +00001629 if (LT->hasFileAtIndex(FileNum)) {
Greg Claytonc8c10322016-12-13 18:25:19 +00001630 Line = DIE.getAttributeValueAsUnsignedConstant(
1631 dwarf::DW_AT_decl_line, 0);
Adrian Prantl42562c32015-10-02 00:27:08 +00001632 // Cache the resolved paths, because calling realpath is expansive.
Pete Cooperef4e36a2016-03-18 03:48:09 +00001633 StringRef ResolvedPath = U.getResolvedPath(FileNum);
1634 if (!ResolvedPath.empty()) {
1635 FileRef = ResolvedPath;
Adrian Prantl42562c32015-10-02 00:27:08 +00001636 } else {
Pete Cooperb2ba7762016-07-22 01:41:32 +00001637 std::string File;
1638 bool gotFileName =
1639 LT->getFileNameByIndex(FileNum, "",
1640 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1641 File);
1642 (void)gotFileName;
1643 assert(gotFileName && "Must get file name from line table");
Pete Coopercadadaa2016-07-22 01:52:58 +00001644#ifdef HAVE_REALPATH
Adrian Prantl42562c32015-10-02 00:27:08 +00001645 char RealPath[PATH_MAX + 1];
1646 RealPath[PATH_MAX] = 0;
1647 if (::realpath(File.c_str(), RealPath))
1648 File = RealPath;
Pete Cooper64d075e2016-03-18 05:04:04 +00001649#endif
Pete Cooperef4e36a2016-03-18 03:48:09 +00001650 FileRef = StringPool.internString(File);
1651 U.setResolvedPath(FileNum, FileRef);
Adrian Prantl42562c32015-10-02 00:27:08 +00001652 }
Adrian Prantl42562c32015-10-02 00:27:08 +00001653 }
Frederic Riss1c650942015-07-21 22:41:43 +00001654 }
1655 }
1656 }
1657 }
1658
1659 if (!Line && NameRef.empty())
1660 return PointerIntPair<DeclContext *, 1>(nullptr);
1661
Frederic Riss1c650942015-07-21 22:41:43 +00001662 // We hash NameRef, which is the mangled name, in order to get most
Adrian Prantla112ef92015-09-23 17:35:52 +00001663 // overloaded functions resolve correctly.
1664 //
1665 // Strictly speaking, hashing the Tag is only necessary for a
1666 // DW_TAG_module, to prevent uniquing of a module and a namespace
1667 // with the same name.
1668 //
1669 // FIXME: dsymutil-classic won't unique the same type presented
1670 // once as a struct and once as a class. Using the Tag in the fully
1671 // qualified name hash to get the same effect.
Frederic Riss1c650942015-07-21 22:41:43 +00001672 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1673
1674 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1675 // use the filename.
1676 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1677 Hash = hash_combine(Hash, FileRef);
1678
1679 // Now look if this context already exists.
1680 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1681 auto ContextIter = Contexts.find(&Key);
1682
1683 if (ContextIter == Contexts.end()) {
1684 // The context wasn't found.
1685 bool Inserted;
1686 DeclContext *NewContext =
1687 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1688 Context, DIE, U.getUniqueID());
1689 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1690 assert(Inserted && "Failed to insert DeclContext");
1691 (void)Inserted;
1692 } else if (Tag != dwarf::DW_TAG_namespace &&
1693 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1694 // The context was found, but it is ambiguous with another context
1695 // in the same file. Mark it invalid.
1696 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1697 }
1698
1699 assert(ContextIter != Contexts.end());
1700 // FIXME: dsymutil-classic compatibility. Union types aren't
1701 // uniques, but their children might be.
1702 if ((Tag == dwarf::DW_TAG_subprogram &&
1703 Context.getTag() != dwarf::DW_TAG_structure_type &&
1704 Context.getTag() != dwarf::DW_TAG_class_type) ||
1705 (Tag == dwarf::DW_TAG_union_type))
1706 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1707
1708 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1709}
1710
Greg Claytonc8c10322016-12-13 18:25:19 +00001711bool DwarfLinker::DIECloner::getDIENames(const DWARFDie &Die,
1712 AttributesInfo &Info) {
Adrian Prantl3565af42015-09-14 16:46:10 +00001713 // FIXME: a bit wasteful as the first getName might return the
Frederic Rissbce93ff2015-03-16 02:05:10 +00001714 // short name.
1715 if (!Info.MangledName &&
Greg Claytonc8c10322016-12-13 18:25:19 +00001716 (Info.MangledName = Die.getName(DINameKind::LinkageName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001717 Info.MangledNameOffset =
1718 Linker.StringPool.getStringOffset(Info.MangledName);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001719
Greg Claytonc8c10322016-12-13 18:25:19 +00001720 if (!Info.Name && (Info.Name = Die.getName(DINameKind::ShortName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001721 Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001722
1723 return Info.Name || Info.MangledName;
1724}
1725
Frederic Riss1b9da422015-02-13 23:18:29 +00001726/// \brief Report a warning to the user, optionaly including
1727/// information about a specific \p DIE related to the warning.
Greg Claytonc8c10322016-12-13 18:25:19 +00001728void DwarfLinker::reportWarning(const Twine &Warning,
1729 const DWARFDie *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001730 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001731 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001732 Context = CurrentDebugObject->getObjectFilename();
1733 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001734
Frederic Rissb9818322015-02-28 00:29:07 +00001735 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001736 return;
1737
1738 errs() << " in DIE:\n";
Greg Claytonc8c10322016-12-13 18:25:19 +00001739 DIE->dump(errs(), 0 /* RecurseDepth */, 6 /* Indent */);
Frederic Riss1b9da422015-02-13 23:18:29 +00001740}
1741
Benjamin Kramerc321e532016-06-08 19:09:22 +00001742bool DwarfLinker::createStreamer(const Triple &TheTriple,
1743 StringRef OutputFilename) {
Frederic Rissc99ea202015-02-28 00:29:11 +00001744 if (Options.NoOutput)
1745 return true;
1746
Frederic Rissb52cf522015-02-28 00:42:37 +00001747 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001748 return Streamer->init(TheTriple, OutputFilename);
1749}
1750
Adrian Prantla112ef92015-09-23 17:35:52 +00001751/// Recursive helper to build the global DeclContext information and
1752/// gather the child->parent relationships in the original compile unit.
1753///
1754/// \return true when this DIE and all of its children are only
1755/// forward declarations to types defined in external clang modules
1756/// (i.e., forward declarations that are children of a DW_TAG_module).
Greg Claytonc8c10322016-12-13 18:25:19 +00001757static bool analyzeContextInfo(const DWARFDie &DIE,
Adrian Prantla112ef92015-09-23 17:35:52 +00001758 unsigned ParentIdx, CompileUnit &CU,
1759 DeclContext *CurrentDeclContext,
1760 NonRelocatableStringpool &StringPool,
1761 DeclContextTree &Contexts,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001762 bool InImportedModule = false) {
Frederic Riss563cba62015-01-28 22:15:14 +00001763 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001764 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1765
Adrian Prantla112ef92015-09-23 17:35:52 +00001766 // Clang imposes an ODR on modules(!) regardless of the language:
1767 // "The module-id should consist of only a single identifier,
1768 // which provides the name of the module being defined. Each
1769 // module shall have a single definition."
1770 //
1771 // This does not extend to the types inside the modules:
1772 // "[I]n C, this implies that if two structs are defined in
1773 // different submodules with the same name, those two types are
1774 // distinct types (but may be compatible types if their
1775 // definitions match)."
1776 //
1777 // We treat non-C++ modules like namespaces for this reason.
Greg Claytonc8c10322016-12-13 18:25:19 +00001778 if (DIE.getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
1779 DIE.getAttributeValueAsString(dwarf::DW_AT_name,
1780 "") != CU.getClangModuleName()) {
Adrian Prantlea8a7242015-09-23 20:44:37 +00001781 InImportedModule = true;
1782 }
Adrian Prantla112ef92015-09-23 17:35:52 +00001783
Frederic Riss1c650942015-07-21 22:41:43 +00001784 Info.ParentIdx = ParentIdx;
Adrian Prantl42562c32015-10-02 00:27:08 +00001785 bool InClangModule = CU.isClangModule() || InImportedModule;
1786 if (CU.hasODR() || InClangModule) {
Frederic Riss1c650942015-07-21 22:41:43 +00001787 if (CurrentDeclContext) {
Adrian Prantl42562c32015-10-02 00:27:08 +00001788 auto PtrInvalidPair = Contexts.getChildDeclContext(
1789 *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
Frederic Riss1c650942015-07-21 22:41:43 +00001790 CurrentDeclContext = PtrInvalidPair.getPointer();
1791 Info.Ctxt =
1792 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1793 } else
1794 Info.Ctxt = CurrentDeclContext = nullptr;
1795 }
Frederic Riss563cba62015-01-28 22:15:14 +00001796
Adrian Prantlea8a7242015-09-23 20:44:37 +00001797 Info.Prune = InImportedModule;
Greg Claytonc8c10322016-12-13 18:25:19 +00001798 if (DIE.hasChildren())
1799 for (auto Child = DIE.getFirstChild(); Child && !Child.isNULL();
1800 Child = Child.getSibling())
Adrian Prantla112ef92015-09-23 17:35:52 +00001801 Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001802 StringPool, Contexts, InImportedModule);
Adrian Prantla112ef92015-09-23 17:35:52 +00001803
1804 // Prune this DIE if it is either a forward declaration inside a
1805 // DW_TAG_module or a DW_TAG_module that contains nothing but
1806 // forward declarations.
Greg Claytonc8c10322016-12-13 18:25:19 +00001807 Info.Prune &= (DIE.getTag() == dwarf::DW_TAG_module) ||
1808 DIE.getAttributeValueAsUnsignedConstant(
1809 dwarf::DW_AT_declaration, 0);
Adrian Prantla112ef92015-09-23 17:35:52 +00001810
Adrian Prantld2793a02015-10-05 23:11:20 +00001811 // Don't prune it if there is no definition for the DIE.
1812 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
1813
Adrian Prantla112ef92015-09-23 17:35:52 +00001814 return Info.Prune;
Frederic Riss563cba62015-01-28 22:15:14 +00001815}
1816
Frederic Riss84c09a52015-02-13 23:18:34 +00001817static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1818 switch (Tag) {
1819 default:
1820 return false;
1821 case dwarf::DW_TAG_subprogram:
1822 case dwarf::DW_TAG_lexical_block:
1823 case dwarf::DW_TAG_subroutine_type:
1824 case dwarf::DW_TAG_structure_type:
1825 case dwarf::DW_TAG_class_type:
1826 case dwarf::DW_TAG_union_type:
1827 return true;
1828 }
1829 llvm_unreachable("Invalid Tag");
1830}
1831
Frederic Riss63786b02015-03-15 20:45:43 +00001832void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss63786b02015-03-15 20:45:43 +00001833 // Iterate over the debug map entries and put all the ones that are
1834 // functions (because they have a size) into the Ranges map. This
1835 // map is very similar to the FunctionRanges that are stored in each
1836 // unit, with 2 notable differences:
1837 // - obviously this one is global, while the other ones are per-unit.
1838 // - this one contains not only the functions described in the DIE
1839 // tree, but also the ones that are only in the debug map.
1840 // The latter information is required to reproduce dsymutil's logic
1841 // while linking line tables. The cases where this information
1842 // matters look like bugs that need to be investigated, but for now
1843 // we need to reproduce dsymutil's behavior.
1844 // FIXME: Once we understood exactly if that information is needed,
1845 // maybe totally remove this (or try to use it to do a real
1846 // -gline-tables-only on Darwin.
1847 for (const auto &Entry : Obj.symbols()) {
1848 const auto &Mapping = Entry.getValue();
Frederic Rissd8c33dc2016-01-31 04:29:22 +00001849 if (Mapping.Size && Mapping.ObjectAddress)
1850 Ranges[*Mapping.ObjectAddress] = std::make_pair(
1851 *Mapping.ObjectAddress + Mapping.Size,
1852 int64_t(Mapping.BinaryAddress) - *Mapping.ObjectAddress);
Frederic Riss63786b02015-03-15 20:45:43 +00001853 }
Frederic Riss563cba62015-01-28 22:15:14 +00001854}
1855
Frederic Riss1036e642015-02-13 23:18:22 +00001856void DwarfLinker::endDebugObject() {
1857 Units.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001858 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001859
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001860 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1861 (*I)->~DIEBlock();
1862 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1863 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001864
1865 DIEBlocks.clear();
1866 DIELocs.clear();
1867 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001868}
1869
Frederic Riss1d536582016-02-01 04:43:14 +00001870static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
1871 switch (Arch) {
1872 case Triple::x86:
1873 return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
1874 RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
1875 case Triple::x86_64:
1876 return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
1877 case Triple::arm:
1878 case Triple::thumb:
1879 return RelocType == MachO::ARM_RELOC_SECTDIFF ||
1880 RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1881 RelocType == MachO::ARM_RELOC_HALF ||
1882 RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
1883 case Triple::aarch64:
1884 return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
1885 default:
1886 return false;
1887 }
1888}
1889
Frederic Riss1036e642015-02-13 23:18:22 +00001890/// \brief Iterate over the relocations of the given \p Section and
1891/// store the ones that correspond to debug map entries into the
1892/// ValidRelocs array.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001893void DwarfLinker::RelocationManager::
1894findValidRelocsMachO(const object::SectionRef &Section,
1895 const object::MachOObjectFile &Obj,
1896 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001897 StringRef Contents;
1898 Section.getContents(Contents);
1899 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
Frederic Riss1d536582016-02-01 04:43:14 +00001900 bool SkipNext = false;
Frederic Riss1036e642015-02-13 23:18:22 +00001901
1902 for (const object::RelocationRef &Reloc : Section.relocations()) {
Frederic Riss1d536582016-02-01 04:43:14 +00001903 if (SkipNext) {
1904 SkipNext = false;
1905 continue;
1906 }
1907
Frederic Riss1036e642015-02-13 23:18:22 +00001908 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1909 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
Frederic Riss1d536582016-02-01 04:43:14 +00001910
1911 if (isMachOPairedReloc(Obj.getAnyRelocationType(MachOReloc),
1912 Obj.getArch())) {
1913 SkipNext = true;
1914 Linker.reportWarning(" unsupported relocation in debug_info section.");
1915 continue;
1916 }
1917
Frederic Riss1036e642015-02-13 23:18:22 +00001918 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001919 uint64_t Offset64 = Reloc.getOffset();
1920 if ((RelocSize != 4 && RelocSize != 8)) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001921 Linker.reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001922 continue;
1923 }
1924 uint32_t Offset = Offset64;
1925 // Mach-o uses REL relocations, the addend is at the relocation offset.
1926 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
Frederic Riss0314e1e2016-02-01 03:44:22 +00001927 uint64_t SymAddress;
1928 int64_t SymOffset;
1929
1930 if (Obj.isRelocationScattered(MachOReloc)) {
1931 // The address of the base symbol for scattered relocations is
1932 // stored in the reloc itself. The actual addend will store the
1933 // base address plus the offset.
1934 SymAddress = Obj.getScatteredRelocationValue(MachOReloc);
1935 SymOffset = int64_t(Addend) - SymAddress;
1936 } else {
1937 SymAddress = Addend;
1938 SymOffset = 0;
1939 }
Frederic Riss1036e642015-02-13 23:18:22 +00001940
1941 auto Sym = Reloc.getSymbol();
1942 if (Sym != Obj.symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001943 Expected<StringRef> SymbolName = Sym->getName();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001944 if (!SymbolName) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001945 consumeError(SymbolName.takeError());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001946 Linker.reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001947 continue;
1948 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001949 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001950 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
Frederic Riss0314e1e2016-02-01 03:44:22 +00001951 } else if (const auto *Mapping = DMO.lookupObjectAddress(SymAddress)) {
Frederic Riss1036e642015-02-13 23:18:22 +00001952 // Do not store the addend. The addend was the address of the
1953 // symbol in the object file, the address in the binary that is
1954 // stored in the debug map doesn't need to be offseted.
Frederic Riss0314e1e2016-02-01 03:44:22 +00001955 ValidRelocs.emplace_back(Offset64, RelocSize, SymOffset, Mapping);
Frederic Riss1036e642015-02-13 23:18:22 +00001956 }
1957 }
1958}
1959
1960/// \brief Dispatch the valid relocation finding logic to the
1961/// appropriate handler depending on the object file format.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001962bool DwarfLinker::RelocationManager::findValidRelocs(
1963 const object::SectionRef &Section, const object::ObjectFile &Obj,
1964 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001965 // Dispatch to the right handler depending on the file type.
1966 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1967 findValidRelocsMachO(Section, *MachOObj, DMO);
1968 else
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001969 Linker.reportWarning(Twine("unsupported object file type: ") +
1970 Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001971
1972 if (ValidRelocs.empty())
1973 return false;
1974
1975 // Sort the relocations by offset. We will walk the DIEs linearly in
1976 // the file, this allows us to just keep an index in the relocation
1977 // array that we advance during our walk, rather than resorting to
1978 // some associative container. See DwarfLinker::NextValidReloc.
1979 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1980 return true;
1981}
1982
1983/// \brief Look for relocations in the debug_info section that match
1984/// entries in the debug map. These relocations will drive the Dwarf
1985/// link by indicating which DIEs refer to symbols present in the
1986/// linked binary.
1987/// \returns wether there are any valid relocations in the debug info.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001988bool DwarfLinker::RelocationManager::
1989findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1990 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001991 // Find the debug_info section.
1992 for (const object::SectionRef &Section : Obj.sections()) {
1993 StringRef SectionName;
1994 Section.getName(SectionName);
1995 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1996 if (SectionName != "debug_info")
1997 continue;
1998 return findValidRelocs(Section, Obj, DMO);
1999 }
2000 return false;
2001}
Frederic Riss563cba62015-01-28 22:15:14 +00002002
Frederic Riss84c09a52015-02-13 23:18:34 +00002003/// \brief Checks that there is a relocation against an actual debug
2004/// map entry between \p StartOffset and \p NextOffset.
2005///
2006/// This function must be called with offsets in strictly ascending
2007/// order because it never looks back at relocations it already 'went past'.
2008/// \returns true and sets Info.InDebugMap if it is the case.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002009bool DwarfLinker::RelocationManager::
2010hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
2011 CompileUnit::DIEInfo &Info) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002012 assert(NextValidReloc == 0 ||
2013 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
2014 if (NextValidReloc >= ValidRelocs.size())
2015 return false;
2016
2017 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
2018
2019 // We might need to skip some relocs that we didn't consider. For
2020 // example the high_pc of a discarded DIE might contain a reloc that
2021 // is in the list because it actually corresponds to the start of a
2022 // function that is in the debug map.
2023 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
2024 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
2025
2026 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
2027 return false;
2028
2029 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00002030 const auto &Mapping = ValidReloc.Mapping->getValue();
Frederic Rissd8c33dc2016-01-31 04:29:22 +00002031 uint64_t ObjectAddress =
2032 Mapping.ObjectAddress ? uint64_t(*Mapping.ObjectAddress) : UINT64_MAX;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002033 if (Linker.Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002034 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
Frederic Rissd8c33dc2016-01-31 04:29:22 +00002035 << " " << format("\t%016" PRIx64 " => %016" PRIx64, ObjectAddress,
Frederic Riss08462f72015-06-01 21:12:45 +00002036 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00002037
Frederic Rissd8c33dc2016-01-31 04:29:22 +00002038 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend;
2039 if (Mapping.ObjectAddress)
2040 Info.AddrAdjust -= ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00002041 Info.InDebugMap = true;
2042 return true;
2043}
2044
2045/// \brief Get the starting and ending (exclusive) offset for the
2046/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
2047/// supposed to point to the position of the first attribute described
2048/// by \p Abbrev.
2049/// \return [StartOffset, EndOffset) as a pair.
2050static std::pair<uint32_t, uint32_t>
2051getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
2052 unsigned Offset, const DWARFUnit &Unit) {
2053 DataExtractor Data = Unit.getDebugInfoExtractor();
2054
2055 for (unsigned i = 0; i < Idx; ++i)
2056 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
2057
2058 uint32_t End = Offset;
2059 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
2060
2061 return std::make_pair(Offset, End);
2062}
2063
2064/// \brief Check if a variable describing DIE should be kept.
2065/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002066unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00002067 const DWARFDie &DIE,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002068 CompileUnit &Unit,
2069 CompileUnit::DIEInfo &MyInfo,
2070 unsigned Flags) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002071 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2072
2073 // Global variables with constant value can always be kept.
2074 if (!(Flags & TF_InFunctionScope) &&
Greg Clayton6f6e4db2016-11-15 01:23:06 +00002075 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002076 MyInfo.InDebugMap = true;
2077 return Flags | TF_Keep;
2078 }
2079
Greg Clayton6f6e4db2016-11-15 01:23:06 +00002080 Optional<uint32_t> LocationIdx =
2081 Abbrev->findAttributeIndex(dwarf::DW_AT_location);
2082 if (!LocationIdx)
Frederic Riss84c09a52015-02-13 23:18:34 +00002083 return Flags;
2084
2085 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2086 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2087 uint32_t LocationOffset, LocationEndOffset;
2088 std::tie(LocationOffset, LocationEndOffset) =
Greg Clayton6f6e4db2016-11-15 01:23:06 +00002089 getAttributeOffsets(Abbrev, *LocationIdx, Offset, OrigUnit);
Frederic Riss84c09a52015-02-13 23:18:34 +00002090
2091 // See if there is a relocation to a valid debug map entry inside
2092 // this variable's location. The order is important here. We want to
2093 // always check in the variable has a valid relocation, so that the
2094 // DIEInfo is filled. However, we don't want a static variable in a
2095 // function to force us to keep the enclosing function.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002096 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
Frederic Riss84c09a52015-02-13 23:18:34 +00002097 (Flags & TF_InFunctionScope))
2098 return Flags;
2099
Frederic Rissb9818322015-02-28 00:29:07 +00002100 if (Options.Verbose)
Greg Claytonc8c10322016-12-13 18:25:19 +00002101 DIE.dump(outs(), 0, 8 /* Indent */);
Frederic Riss84c09a52015-02-13 23:18:34 +00002102
2103 return Flags | TF_Keep;
2104}
2105
2106/// \brief Check if a function describing DIE should be kept.
2107/// \returns updated TraversalFlags.
2108unsigned DwarfLinker::shouldKeepSubprogramDIE(
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002109 RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00002110 const DWARFDie &DIE, CompileUnit &Unit,
Frederic Riss84c09a52015-02-13 23:18:34 +00002111 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2112 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2113
2114 Flags |= TF_InFunctionScope;
2115
Greg Clayton6f6e4db2016-11-15 01:23:06 +00002116 Optional<uint32_t> LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2117 if (!LowPcIdx)
Frederic Riss84c09a52015-02-13 23:18:34 +00002118 return Flags;
2119
2120 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2121 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2122 uint32_t LowPcOffset, LowPcEndOffset;
2123 std::tie(LowPcOffset, LowPcEndOffset) =
Greg Clayton6f6e4db2016-11-15 01:23:06 +00002124 getAttributeOffsets(Abbrev, *LowPcIdx, Offset, OrigUnit);
Frederic Riss84c09a52015-02-13 23:18:34 +00002125
Greg Clayton52fe1f62016-12-14 22:38:08 +00002126 auto LowPc = DIE.getAttributeValueAsAddress(dwarf::DW_AT_low_pc);
2127 assert(LowPc.hasValue() && "low_pc attribute is not an address.");
2128 if (!LowPc ||
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002129 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
Frederic Riss84c09a52015-02-13 23:18:34 +00002130 return Flags;
2131
Frederic Rissb9818322015-02-28 00:29:07 +00002132 if (Options.Verbose)
Greg Claytonc8c10322016-12-13 18:25:19 +00002133 DIE.dump(outs(), 0, 8 /* Indent */);
Frederic Riss84c09a52015-02-13 23:18:34 +00002134
Frederic Riss1af75f72015-03-12 18:45:10 +00002135 Flags |= TF_Keep;
2136
Greg Clayton1cbf3fa2016-12-13 23:20:56 +00002137 Optional<DWARFFormValue> HighPcValue;
2138 if (!(HighPcValue = DIE.getAttributeValue(dwarf::DW_AT_high_pc))) {
Frederic Riss1af75f72015-03-12 18:45:10 +00002139 reportWarning("Function without high_pc. Range will be discarded.\n",
Greg Claytonc8c10322016-12-13 18:25:19 +00002140 &DIE);
Frederic Riss1af75f72015-03-12 18:45:10 +00002141 return Flags;
2142 }
2143
2144 uint64_t HighPc;
Greg Clayton1cbf3fa2016-12-13 23:20:56 +00002145 if (HighPcValue->isFormClass(DWARFFormValue::FC_Address)) {
2146 HighPc = *HighPcValue->getAsAddress();
Frederic Riss1af75f72015-03-12 18:45:10 +00002147 } else {
Greg Clayton1cbf3fa2016-12-13 23:20:56 +00002148 assert(HighPcValue->isFormClass(DWARFFormValue::FC_Constant));
Greg Clayton52fe1f62016-12-14 22:38:08 +00002149 HighPc = *LowPc + *HighPcValue->getAsUnsignedConstant();
Frederic Riss1af75f72015-03-12 18:45:10 +00002150 }
2151
Frederic Riss63786b02015-03-15 20:45:43 +00002152 // Replace the debug map range with a more accurate one.
Greg Clayton52fe1f62016-12-14 22:38:08 +00002153 Ranges[*LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
2154 Unit.addFunctionRange(*LowPc, HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00002155 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00002156}
2157
2158/// \brief Check if a DIE should be kept.
2159/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002160unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00002161 const DWARFDie &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00002162 CompileUnit &Unit,
2163 CompileUnit::DIEInfo &MyInfo,
2164 unsigned Flags) {
2165 switch (DIE.getTag()) {
2166 case dwarf::DW_TAG_constant:
2167 case dwarf::DW_TAG_variable:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002168 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002169 case dwarf::DW_TAG_subprogram:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002170 return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002171 case dwarf::DW_TAG_module:
2172 case dwarf::DW_TAG_imported_module:
2173 case dwarf::DW_TAG_imported_declaration:
2174 case dwarf::DW_TAG_imported_unit:
2175 // We always want to keep these.
2176 return Flags | TF_Keep;
Greg Clayton35630c32016-12-01 18:56:29 +00002177 default:
2178 break;
Frederic Riss84c09a52015-02-13 23:18:34 +00002179 }
2180
2181 return Flags;
2182}
2183
Frederic Riss84c09a52015-02-13 23:18:34 +00002184/// \brief Mark the passed DIE as well as all the ones it depends on
2185/// as kept.
2186///
2187/// This function is called by lookForDIEsToKeep on DIEs that are
2188/// newly discovered to be needed in the link. It recursively calls
2189/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2190/// TraversalFlags to inform it that it's not doing the primary DIE
2191/// tree walk.
Adrian Prantl6ec47122015-09-22 15:31:14 +00002192void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00002193 const DWARFDie &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002194 CompileUnit::DIEInfo &MyInfo,
2195 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002196 CompileUnit &CU, bool UseODR) {
Greg Claytonc8c10322016-12-13 18:25:19 +00002197 DWARFUnit &Unit = CU.getOrigUnit();
Frederic Riss84c09a52015-02-13 23:18:34 +00002198 MyInfo.Keep = true;
2199
2200 // First mark all the parent chain as kept.
2201 unsigned AncestorIdx = MyInfo.ParentIdx;
2202 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002203 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Greg Claytonc8c10322016-12-13 18:25:19 +00002204 lookForDIEsToKeep(RelocMgr, Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002205 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002206 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2207 }
2208
2209 // Then we need to mark all the DIEs referenced by this DIE's
2210 // attributes as kept.
2211 DataExtractor Data = Unit.getDebugInfoExtractor();
Frederic Riss36c3cb82015-09-11 04:17:25 +00002212 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2213 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
Frederic Riss84c09a52015-02-13 23:18:34 +00002214
2215 // Mark all DIEs referenced through atttributes as kept.
2216 for (const auto &AttrSpec : Abbrev->attributes()) {
2217 DWARFFormValue Val(AttrSpec.Form);
2218
2219 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2220 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2221 continue;
2222 }
2223
2224 Val.extractValue(Data, &Offset, &Unit);
2225 CompileUnit *ReferencedCU;
Greg Claytonc8c10322016-12-13 18:25:19 +00002226 if (auto RefDIE =
Greg Clayton35630c32016-12-01 18:56:29 +00002227 resolveDIEReference(*this, Units, Val, Unit, Die, ReferencedCU)) {
Frederic Riss1c650942015-07-21 22:41:43 +00002228 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2229 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2230 // If the referenced DIE has a DeclContext that has already been
2231 // emitted, then do not keep the one in this CU. We'll link to
2232 // the canonical DIE in cloneDieReferenceAttribute.
2233 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2234 // be necessary and could be advantageously replaced by
2235 // ReferencedCU->hasODR() && CU.hasODR().
2236 // FIXME: compatibility with dsymutil-classic. There is no
2237 // reason not to unique ref_addr references.
2238 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2239 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2240 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2241 continue;
2242
Adrian Prantle39475d2015-11-10 21:31:05 +00002243 // Keep a module forward declaration if there is no definition.
2244 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
2245 Info.Ctxt->getCanonicalDIEOffset()))
2246 Info.Prune = false;
2247
Frederic Riss1c650942015-07-21 22:41:43 +00002248 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Greg Claytonc8c10322016-12-13 18:25:19 +00002249 lookForDIEsToKeep(RelocMgr, RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002250 TF_Keep | TF_DependencyWalk | ODRFlag);
2251 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002252 }
2253}
2254
2255/// \brief Recursively walk the \p DIE tree and look for DIEs to
2256/// keep. Store that information in \p CU's DIEInfo.
2257///
2258/// This function is the entry point of the DIE selection
2259/// algorithm. It is expected to walk the DIE tree in file order and
2260/// (though the mediation of its helper) call hasValidRelocation() on
2261/// each DIE that might be a 'root DIE' (See DwarfLinker class
2262/// comment).
2263/// While walking the dependencies of root DIEs, this function is
2264/// also called, but during these dependency walks the file order is
2265/// not respected. The TF_DependencyWalk flag tells us which kind of
2266/// traversal we are currently doing.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002267void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00002268 const DWARFDie &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002269 const DebugMapObject &DMO, CompileUnit &CU,
2270 unsigned Flags) {
Greg Claytonc8c10322016-12-13 18:25:19 +00002271 unsigned Idx = CU.getOrigUnit().getDIEIndex(Die);
Frederic Riss84c09a52015-02-13 23:18:34 +00002272 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2273 bool AlreadyKept = MyInfo.Keep;
Adrian Prantla112ef92015-09-23 17:35:52 +00002274 if (MyInfo.Prune)
2275 return;
Frederic Riss84c09a52015-02-13 23:18:34 +00002276
2277 // If the Keep flag is set, we are marking a required DIE's
2278 // dependencies. If our target is already marked as kept, we're all
2279 // set.
2280 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2281 return;
2282
Adrian Prantl6ec47122015-09-22 15:31:14 +00002283 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
Frederic Riss84c09a52015-02-13 23:18:34 +00002284 // because it would screw up the relocation finding logic.
2285 if (!(Flags & TF_DependencyWalk))
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002286 Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002287
2288 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002289 if (!AlreadyKept && (Flags & TF_Keep)) {
2290 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
Adrian Prantl6ec47122015-09-22 15:31:14 +00002291 keepDIEAndDependencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
Frederic Riss1c650942015-07-21 22:41:43 +00002292 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002293 // The TF_ParentWalk flag tells us that we are currently walking up
2294 // the parent chain of a required DIE, and we don't want to mark all
2295 // the children of the parents as kept (consider for example a
2296 // DW_TAG_namespace node in the parent chain). There are however a
2297 // set of DIE types for which we want to ignore that directive and still
2298 // walk their children.
Frederic Riss36c3cb82015-09-11 04:17:25 +00002299 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
Frederic Riss84c09a52015-02-13 23:18:34 +00002300 Flags &= ~TF_ParentWalk;
2301
Frederic Riss36c3cb82015-09-11 04:17:25 +00002302 if (!Die.hasChildren() || (Flags & TF_ParentWalk))
Frederic Riss84c09a52015-02-13 23:18:34 +00002303 return;
2304
Greg Claytonc8c10322016-12-13 18:25:19 +00002305 for (auto Child = Die.getFirstChild(); Child && !Child.isNULL();
2306 Child = Child.getSibling())
2307 lookForDIEsToKeep(RelocMgr, Child, DMO, CU, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002308}
2309
Frederic Rissb8b43d52015-03-04 22:07:44 +00002310/// \brief Assign an abbreviation numer to \p Abbrev.
2311///
2312/// Our DIEs get freed after every DebugMapObject has been processed,
2313/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2314/// the instances hold by the DIEs. When we encounter an abbreviation
2315/// that we don't know, we create a permanent copy of it.
2316void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2317 // Check the set for priors.
2318 FoldingSetNodeID ID;
2319 Abbrev.Profile(ID);
2320 void *InsertToken;
2321 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2322
2323 // If it's newly added.
2324 if (InSet) {
2325 // Assign existing abbreviation number.
2326 Abbrev.setNumber(InSet->getNumber());
2327 } else {
2328 // Add to abbreviation list.
2329 Abbreviations.push_back(
David Blaikie6196aa02015-11-18 00:34:10 +00002330 llvm::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002331 for (const auto &Attr : Abbrev.getData())
2332 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
David Blaikie6196aa02015-11-18 00:34:10 +00002333 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002334 // Assign the unique abbreviation number.
2335 Abbrev.setNumber(Abbreviations.size());
2336 Abbreviations.back()->setNumber(Abbreviations.size());
2337 }
2338}
2339
Adrian Prantl3565af42015-09-14 16:46:10 +00002340unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2341 AttributeSpec AttrSpec,
2342 const DWARFFormValue &Val,
2343 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002344 // Switch everything to out of line strings.
Greg Claytoncddab272016-10-31 16:46:02 +00002345 const char *String = *Val.getAsCString();
Adrian Prantl3565af42015-09-14 16:46:10 +00002346 unsigned Offset = Linker.StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002347 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002348 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002349 return 4;
2350}
2351
Adrian Prantl3565af42015-09-14 16:46:10 +00002352unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
Greg Claytonc8c10322016-12-13 18:25:19 +00002353 DIE &Die, const DWARFDie &InputDIE,
Frederic Riss9833de62015-03-06 23:22:53 +00002354 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002355 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002356 const DWARFUnit &U = Unit.getOrigUnit();
Greg Claytoncddab272016-10-31 16:46:02 +00002357 uint32_t Ref = *Val.getAsReference();
Frederic Riss9833de62015-03-06 23:22:53 +00002358 DIE *NewRefDie = nullptr;
2359 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002360 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002361
Greg Claytonc8c10322016-12-13 18:25:19 +00002362 DWARFDie RefDie = resolveDIEReference(Linker, CompileUnits, Val, U, InputDIE,
2363 RefUnit);
Frederic Riss1c650942015-07-21 22:41:43 +00002364
2365 // If the referenced DIE is not found, drop the attribute.
2366 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002367 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002368
2369 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2370 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002371
2372 // If we already have emitted an equivalent DeclContext, just point
2373 // at it.
2374 if (isODRAttribute(AttrSpec.Attr)) {
2375 Ctxt = RefInfo.Ctxt;
2376 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2377 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2378 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2379 dwarf::DW_FORM_ref_addr, Attr);
Greg Claytoncddab272016-10-31 16:46:02 +00002380 return U.getRefAddrByteSize();
Frederic Riss1c650942015-07-21 22:41:43 +00002381 }
2382 }
2383
Frederic Riss9833de62015-03-06 23:22:53 +00002384 if (!RefInfo.Clone) {
2385 assert(Ref > InputDIE.getOffset());
2386 // We haven't cloned this DIE yet. Just create an empty one and
2387 // store it. It'll get really cloned when we process it.
Greg Claytonc8c10322016-12-13 18:25:19 +00002388 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002389 }
2390 NewRefDie = RefInfo.Clone;
2391
Frederic Riss1c650942015-07-21 22:41:43 +00002392 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2393 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002394 // We cannot currently rely on a DIEEntry to emit ref_addr
2395 // references, because the implementation calls back to DwarfDebug
2396 // to find the unit offset. (We don't have a DwarfDebug)
2397 // FIXME: we should be able to design DIEEntry reliance on
2398 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002399 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002400 if (Ref < InputDIE.getOffset()) {
2401 // We must have already cloned that DIE.
2402 uint32_t NewRefOffset =
2403 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002404 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002405 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2406 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002407 } else {
2408 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002409 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002410 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002411 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002412 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2413 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002414 }
Greg Claytoncddab272016-10-31 16:46:02 +00002415 return U.getRefAddrByteSize();
Frederic Riss9833de62015-03-06 23:22:53 +00002416 }
2417
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002418 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2419 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002420 return AttrSize;
2421}
2422
Adrian Prantl3565af42015-09-14 16:46:10 +00002423unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2424 AttributeSpec AttrSpec,
2425 const DWARFFormValue &Val,
2426 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002427 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002428 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002429 DIELoc *Loc = nullptr;
2430 DIEBlock *Block = nullptr;
2431 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002432 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002433 Loc = new (DIEAlloc) DIELoc;
Adrian Prantl3565af42015-09-14 16:46:10 +00002434 Linker.DIELocs.push_back(Loc);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002435 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002436 Block = new (DIEAlloc) DIEBlock;
Adrian Prantl3565af42015-09-14 16:46:10 +00002437 Linker.DIEBlocks.push_back(Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002438 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002439 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2440 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002441
2442 if (Loc)
2443 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2444 dwarf::Form(AttrSpec.Form), Loc);
2445 else
2446 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2447 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002448 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2449 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002450 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2451 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002452 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2453 // the DIE class, this if could be replaced by
2454 // Attr->setSize(Bytes.size()).
Adrian Prantl3565af42015-09-14 16:46:10 +00002455 if (Linker.Streamer) {
2456 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002457 if (Loc)
Adrian Prantl3565af42015-09-14 16:46:10 +00002458 Loc->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002459 else
Adrian Prantl3565af42015-09-14 16:46:10 +00002460 Block->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002461 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002462 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002463 return AttrSize;
2464}
2465
Adrian Prantl3565af42015-09-14 16:46:10 +00002466unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2467 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2468 const CompileUnit &Unit, AttributesInfo &Info) {
Greg Claytoncddab272016-10-31 16:46:02 +00002469 uint64_t Addr = *Val.getAsAddress();
Frederic Riss31da3242015-03-11 18:45:52 +00002470 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2471 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2472 Die.getTag() == dwarf::DW_TAG_lexical_block)
Frederic Riss7b5563a2015-08-31 01:43:14 +00002473 // The low_pc of a block or inline subroutine might get
2474 // relocated because it happens to match the low_pc of the
2475 // enclosing subprogram. To prevent issues with that, always use
2476 // the low_pc from the input DIE if relocations have been applied.
2477 Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2478 Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002479 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2480 Addr = Unit.getLowPc();
2481 if (Addr == UINT64_MAX)
2482 return 0;
2483 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002484 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002485 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002486 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2487 if (uint64_t HighPc = Unit.getHighPc())
2488 Addr = HighPc;
2489 else
2490 return 0;
2491 } else
2492 // If we have a high_pc recorded for the input DIE, use
2493 // it. Otherwise (when no relocations where applied) just use the
2494 // one we just decoded.
2495 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002496 }
2497
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002498 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002499 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002500 return Unit.getOrigUnit().getAddressByteSize();
2501}
2502
Adrian Prantl3565af42015-09-14 16:46:10 +00002503unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
Greg Claytonc8c10322016-12-13 18:25:19 +00002504 DIE &Die, const DWARFDie &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002505 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002506 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002507 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002508 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2509 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2510 if (Unit.getLowPc() == -1ULL)
2511 return 0;
2512 // Dwarf >= 4 high_pc is an size, not an address.
2513 Value = Unit.getHighPc() - Unit.getLowPc();
2514 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002515 Value = *Val.getAsSectionOffset();
2516 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2517 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002518 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2519 Value = *OptionalValue;
2520 else {
Adrian Prantl3565af42015-09-14 16:46:10 +00002521 Linker.reportWarning(
2522 "Unsupported scalar attribute form. Dropping attribute.",
Greg Claytonc8c10322016-12-13 18:25:19 +00002523 &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002524 return 0;
2525 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002526 PatchLocation Patch =
2527 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2528 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002529 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002530 Unit.noteRangeAttribute(Die, Patch);
Frederic Riss29eedc72015-09-11 04:17:30 +00002531
Frederic Rissdfb97902015-03-14 15:49:07 +00002532 // A more generic way to check for location attributes would be
2533 // nice, but it's very unlikely that any other attribute needs a
2534 // location list.
2535 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2536 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002537 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002538 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2539 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002540
Frederic Rissb8b43d52015-03-04 22:07:44 +00002541 return AttrSize;
2542}
2543
2544/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2545/// value \p Val, and add it to \p Die.
2546/// \returns the size of the cloned attribute.
Adrian Prantl3565af42015-09-14 16:46:10 +00002547unsigned DwarfLinker::DIECloner::cloneAttribute(
Greg Claytonc8c10322016-12-13 18:25:19 +00002548 DIE &Die, const DWARFDie &InputDIE, CompileUnit &Unit,
Adrian Prantl3565af42015-09-14 16:46:10 +00002549 const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2550 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002551 const DWARFUnit &U = Unit.getOrigUnit();
2552
2553 switch (AttrSpec.Form) {
2554 case dwarf::DW_FORM_strp:
2555 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002556 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002557 case dwarf::DW_FORM_ref_addr:
2558 case dwarf::DW_FORM_ref1:
2559 case dwarf::DW_FORM_ref2:
2560 case dwarf::DW_FORM_ref4:
2561 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002562 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002563 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002564 case dwarf::DW_FORM_block:
2565 case dwarf::DW_FORM_block1:
2566 case dwarf::DW_FORM_block2:
2567 case dwarf::DW_FORM_block4:
2568 case dwarf::DW_FORM_exprloc:
2569 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2570 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002571 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002572 case dwarf::DW_FORM_data1:
2573 case dwarf::DW_FORM_data2:
2574 case dwarf::DW_FORM_data4:
2575 case dwarf::DW_FORM_data8:
2576 case dwarf::DW_FORM_udata:
2577 case dwarf::DW_FORM_sdata:
2578 case dwarf::DW_FORM_sec_offset:
2579 case dwarf::DW_FORM_flag:
2580 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002581 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2582 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002583 default:
Adrian Prantl3565af42015-09-14 16:46:10 +00002584 Linker.reportWarning(
Greg Claytonc8c10322016-12-13 18:25:19 +00002585 "Unsupported attribute form in cloneAttribute. Dropping.", &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002586 }
2587
2588 return 0;
2589}
2590
Frederic Riss23e20e92015-03-07 01:25:09 +00002591/// \brief Apply the valid relocations found by findValidRelocs() to
2592/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2593/// in the debug_info section.
2594///
2595/// Like for findValidRelocs(), this function must be called with
2596/// monotonic \p BaseOffset values.
2597///
2598/// \returns wether any reloc has been applied.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002599bool DwarfLinker::RelocationManager::
2600applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2601 bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002602 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002603 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2604 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002605 if (NextValidReloc >= ValidRelocs.size())
2606 return false;
2607
2608 // Skip relocs that haven't been applied.
2609 while (NextValidReloc < ValidRelocs.size() &&
2610 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2611 ++NextValidReloc;
2612
2613 bool Applied = false;
2614 uint64_t EndOffset = BaseOffset + Data.size();
2615 while (NextValidReloc < ValidRelocs.size() &&
2616 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2617 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2618 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2619 assert(ValidReloc.Offset - BaseOffset < Data.size());
2620 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2621 char Buf[8];
2622 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2623 Value += ValidReloc.Addend;
2624 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2625 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2626 Buf[i] = uint8_t(Value >> (Index * 8));
2627 }
2628 assert(ValidReloc.Size <= sizeof(Buf));
2629 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2630 Applied = true;
2631 }
2632
2633 return Applied;
2634}
2635
Frederic Rissbce93ff2015-03-16 02:05:10 +00002636static bool isTypeTag(uint16_t Tag) {
2637 switch (Tag) {
2638 case dwarf::DW_TAG_array_type:
2639 case dwarf::DW_TAG_class_type:
2640 case dwarf::DW_TAG_enumeration_type:
2641 case dwarf::DW_TAG_pointer_type:
2642 case dwarf::DW_TAG_reference_type:
2643 case dwarf::DW_TAG_string_type:
2644 case dwarf::DW_TAG_structure_type:
2645 case dwarf::DW_TAG_subroutine_type:
2646 case dwarf::DW_TAG_typedef:
2647 case dwarf::DW_TAG_union_type:
2648 case dwarf::DW_TAG_ptr_to_member_type:
2649 case dwarf::DW_TAG_set_type:
2650 case dwarf::DW_TAG_subrange_type:
2651 case dwarf::DW_TAG_base_type:
2652 case dwarf::DW_TAG_const_type:
2653 case dwarf::DW_TAG_constant:
2654 case dwarf::DW_TAG_file_type:
2655 case dwarf::DW_TAG_namelist:
2656 case dwarf::DW_TAG_packed_type:
2657 case dwarf::DW_TAG_volatile_type:
2658 case dwarf::DW_TAG_restrict_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00002659 case dwarf::DW_TAG_atomic_type:
Frederic Rissbce93ff2015-03-16 02:05:10 +00002660 case dwarf::DW_TAG_interface_type:
2661 case dwarf::DW_TAG_unspecified_type:
2662 case dwarf::DW_TAG_shared_type:
2663 return true;
2664 default:
2665 break;
2666 }
2667 return false;
2668}
2669
Frederic Riss29eedc72015-09-11 04:17:30 +00002670static bool
2671shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2672 uint16_t Tag, bool InDebugMap, bool SkipPC,
2673 bool InFunctionScope) {
2674 switch (AttrSpec.Attr) {
2675 default:
2676 return false;
2677 case dwarf::DW_AT_low_pc:
2678 case dwarf::DW_AT_high_pc:
2679 case dwarf::DW_AT_ranges:
2680 return SkipPC;
2681 case dwarf::DW_AT_location:
2682 case dwarf::DW_AT_frame_base:
2683 // FIXME: for some reason dsymutil-classic keeps the location
2684 // attributes when they are of block type (ie. not location
2685 // lists). This is totally wrong for globals where we will keep a
2686 // wrong address. It is mostly harmless for locals, but there is
2687 // no point in keeping these anyway when the function wasn't linked.
2688 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2689 !InDebugMap)) &&
2690 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2691 }
2692}
2693
Adrian Prantl3565af42015-09-14 16:46:10 +00002694DIE *DwarfLinker::DIECloner::cloneDIE(
Greg Claytonc8c10322016-12-13 18:25:19 +00002695 const DWARFDie &InputDIE, CompileUnit &Unit,
Greg Clayton35630c32016-12-01 18:56:29 +00002696 int64_t PCOffset, uint32_t OutOffset, unsigned Flags, DIE *Die) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002697 DWARFUnit &U = Unit.getOrigUnit();
Greg Claytonc8c10322016-12-13 18:25:19 +00002698 unsigned Idx = U.getDIEIndex(InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002699 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002700
2701 // Should the DIE appear in the output?
2702 if (!Unit.getInfo(Idx).Keep)
2703 return nullptr;
2704
2705 uint32_t Offset = InputDIE.getOffset();
Greg Clayton35630c32016-12-01 18:56:29 +00002706 assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
2707 if (!Die) {
2708 // The DIE might have been already created by a forward reference
2709 // (see cloneDieReferenceAttribute()).
David Blaikie4aa81752016-12-01 22:04:16 +00002710 if (!Info.Clone)
2711 Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
2712 Die = Info.Clone;
Greg Clayton35630c32016-12-01 18:56:29 +00002713 }
2714
Frederic Riss9833de62015-03-06 23:22:53 +00002715 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002716 Die->setOffset(OutOffset);
Adrian Prantla112ef92015-09-23 17:35:52 +00002717 if ((Unit.hasODR() || Unit.isClangModule()) &&
2718 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
Frederic Riss1c650942015-07-21 22:41:43 +00002719 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2720 !Info.Ctxt->getCanonicalDIEOffset()) {
2721 // We are about to emit a DIE that is the root of its own valid
2722 // DeclContext tree. Make the current offset the canonical offset
2723 // for this context.
2724 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2725 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002726
2727 // Extract and clone every attribute.
2728 DataExtractor Data = U.getDebugInfoExtractor();
Adrian Prantle5162db2015-09-22 22:20:50 +00002729 // Point to the next DIE (generally there is always at least a NULL
2730 // entry after the current one). If this is a lone
2731 // DW_TAG_compile_unit without any children, point to the next unit.
2732 uint32_t NextOffset =
2733 (Idx + 1 < U.getNumDIEs())
Greg Claytonc8c10322016-12-13 18:25:19 +00002734 ? U.getDIEAtIndex(Idx + 1).getOffset()
Adrian Prantle5162db2015-09-22 22:20:50 +00002735 : U.getNextUnitOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002736 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002737
2738 // We could copy the data only if we need to aply a relocation to
2739 // it. After testing, it seems there is no performance downside to
2740 // doing the copy unconditionally, and it makes the code simpler.
2741 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2742 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2743 // Modify the copy with relocated addresses.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002744 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
Frederic Riss31da3242015-03-11 18:45:52 +00002745 // If we applied relocations, we store the value of high_pc that was
2746 // potentially stored in the input DIE. If high_pc is an address
2747 // (Dwarf version == 2), then it might have been relocated to a
2748 // totally unrelated value (because the end address in the object
2749 // file might be start address of another function which got moved
2750 // independantly by the linker). The computation of the actual
2751 // high_pc value is done in cloneAddressAttribute().
2752 AttrInfo.OrigHighPc =
Greg Claytonc8c10322016-12-13 18:25:19 +00002753 InputDIE.getAttributeValueAsAddress(dwarf::DW_AT_high_pc, 0);
Frederic Riss7b5563a2015-08-31 01:43:14 +00002754 // Also store the low_pc. It might get relocated in an
2755 // inline_subprogram that happens at the beginning of its
2756 // inlining function.
2757 AttrInfo.OrigLowPc =
Greg Claytonc8c10322016-12-13 18:25:19 +00002758 InputDIE.getAttributeValueAsAddress(dwarf::DW_AT_low_pc, UINT64_MAX);
Frederic Riss31da3242015-03-11 18:45:52 +00002759 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002760
2761 // Reset the Offset to 0 as we will be working on the local copy of
2762 // the data.
2763 Offset = 0;
2764
Frederic Rissb8b43d52015-03-04 22:07:44 +00002765 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2766 Offset += getULEB128Size(Abbrev->getCode());
2767
Frederic Riss31da3242015-03-11 18:45:52 +00002768 // We are entering a subprogram. Get and propagate the PCOffset.
2769 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2770 PCOffset = Info.AddrAdjust;
2771 AttrInfo.PCOffset = PCOffset;
2772
Frederic Riss29eedc72015-09-11 04:17:30 +00002773 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2774 Flags |= TF_InFunctionScope;
2775 if (!Info.InDebugMap)
2776 Flags |= TF_SkipPC;
2777 }
2778
2779 bool Copied = false;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002780 for (const auto &AttrSpec : Abbrev->attributes()) {
Frederic Riss29eedc72015-09-11 04:17:30 +00002781 if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2782 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2783 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2784 // FIXME: dsymutil-classic keeps the old abbreviation around
2785 // even if it's not used. We can remove this (and the copyAbbrev
2786 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2787 if (!Copied) {
2788 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2789 Copied = true;
2790 }
2791 continue;
2792 }
2793
Frederic Rissb8b43d52015-03-04 22:07:44 +00002794 DWARFFormValue Val(AttrSpec.Form);
2795 uint32_t AttrSize = Offset;
2796 Val.extractValue(Data, &Offset, &U);
2797 AttrSize = Offset - AttrSize;
2798
Frederic Riss31da3242015-03-11 18:45:52 +00002799 OutOffset +=
2800 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002801 }
2802
Frederic Rissbce93ff2015-03-16 02:05:10 +00002803 // Look for accelerator entries.
2804 uint16_t Tag = InputDIE.getTag();
2805 // FIXME: This is slightly wrong. An inline_subroutine without a
2806 // low_pc, but with AT_ranges might be interesting to get into the
2807 // accelerator tables too. For now stick with dsymutil's behavior.
2808 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2809 Tag != dwarf::DW_TAG_compile_unit &&
Greg Claytonc8c10322016-12-13 18:25:19 +00002810 getDIENames(InputDIE, AttrInfo)) {
Frederic Rissbce93ff2015-03-16 02:05:10 +00002811 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2812 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2813 AttrInfo.MangledNameOffset,
2814 Tag == dwarf::DW_TAG_inlined_subroutine);
2815 if (AttrInfo.Name)
2816 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2817 Tag == dwarf::DW_TAG_inlined_subroutine);
2818 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
Greg Claytonc8c10322016-12-13 18:25:19 +00002819 getDIENames(InputDIE, AttrInfo)) {
Frederic Rissbce93ff2015-03-16 02:05:10 +00002820 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2821 }
2822
Adrian Prantle39475d2015-11-10 21:31:05 +00002823 // Determine whether there are any children that we want to keep.
2824 bool HasChildren = false;
Greg Claytonc8c10322016-12-13 18:25:19 +00002825 for (auto Child = InputDIE.getFirstChild(); Child && !Child.isNULL();
2826 Child = Child.getSibling()) {
Adrian Prantle39475d2015-11-10 21:31:05 +00002827 unsigned Idx = U.getDIEIndex(Child);
2828 if (Unit.getInfo(Idx).Keep) {
2829 HasChildren = true;
2830 break;
2831 }
2832 }
2833
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002834 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Adrian Prantle39475d2015-11-10 21:31:05 +00002835 if (HasChildren)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002836 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2837 // Assign a permanent abbrev number
Adrian Prantl3565af42015-09-14 16:46:10 +00002838 Linker.AssignAbbrev(NewAbbrev);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002839 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002840
2841 // Add the size of the abbreviation number to the output offset.
2842 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2843
Adrian Prantle39475d2015-11-10 21:31:05 +00002844 if (!HasChildren) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002845 // Update our size.
2846 Die->setSize(OutOffset - Die->getOffset());
2847 return Die;
2848 }
2849
2850 // Recursively clone children.
Greg Claytonc8c10322016-12-13 18:25:19 +00002851 for (auto Child = InputDIE.getFirstChild(); Child && !Child.isNULL();
2852 Child = Child.getSibling()) {
2853 if (DIE *Clone = cloneDIE(Child, Unit, PCOffset, OutOffset, Flags)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002854 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002855 OutOffset = Clone->getOffset() + Clone->getSize();
2856 }
2857 }
2858
2859 // Account for the end of children marker.
2860 OutOffset += sizeof(int8_t);
2861 // Update our size.
2862 Die->setSize(OutOffset - Die->getOffset());
2863 return Die;
2864}
2865
Frederic Riss25440872015-03-13 23:30:31 +00002866/// \brief Patch the input object file relevant debug_ranges entries
2867/// and emit them in the output file. Update the relevant attributes
2868/// to point at the new entries.
2869void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2870 DWARFContext &OrigDwarf) const {
2871 DWARFDebugRangeList RangeList;
2872 const auto &FunctionRanges = Unit.getFunctionRanges();
2873 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2874 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2875 OrigDwarf.isLittleEndian(), AddressSize);
2876 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2877 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Greg Claytonc8c10322016-12-13 18:25:19 +00002878 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
2879 uint64_t OrigLowPc = OrigUnitDie.getAttributeValueAsAddress(
2880 dwarf::DW_AT_low_pc, -1ULL);
Frederic Riss25440872015-03-13 23:30:31 +00002881 // Ranges addresses are based on the unit's low_pc. Compute the
Sanjay Patele4b9f502015-12-07 19:21:39 +00002882 // offset we need to apply to adapt to the new unit's low_pc.
Frederic Riss25440872015-03-13 23:30:31 +00002883 int64_t UnitPcOffset = 0;
2884 if (OrigLowPc != -1ULL)
2885 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2886
2887 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002888 uint32_t Offset = RangeAttribute.get();
2889 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002890 RangeList.extract(RangeExtractor, &Offset);
2891 const auto &Entries = RangeList.getEntries();
Frederic Riss94546202015-08-31 05:09:32 +00002892 if (!Entries.empty()) {
2893 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
Frederic Riss25440872015-03-13 23:30:31 +00002894
Frederic Riss25440872015-03-13 23:30:31 +00002895 if (CurrRange == InvalidRange ||
Frederic Riss94546202015-08-31 05:09:32 +00002896 First.StartAddress + OrigLowPc < CurrRange.start() ||
2897 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2898 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2899 if (CurrRange == InvalidRange ||
2900 CurrRange.start() > First.StartAddress + OrigLowPc) {
2901 reportWarning("no mapping for range.");
2902 continue;
2903 }
Frederic Riss25440872015-03-13 23:30:31 +00002904 }
2905 }
2906
2907 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2908 AddressSize);
2909 }
2910}
2911
Frederic Riss563b1b02015-03-14 03:46:51 +00002912/// \brief Generate the debug_aranges entries for \p Unit and if the
2913/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2914/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002915/// FIXME: this could actually be done right in patchRangesForUnit,
2916/// but for the sake of initial bit-for-bit compatibility with legacy
2917/// dsymutil, we have to do it in a delayed pass.
2918void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002919 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002920 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002921 Attr->set(Streamer->getRangesSectionSize());
2922 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002923}
2924
Frederic Riss63786b02015-03-15 20:45:43 +00002925/// \brief Insert the new line info sequence \p Seq into the current
2926/// set of already linked line info \p Rows.
2927static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2928 std::vector<DWARFDebugLine::Row> &Rows) {
2929 if (Seq.empty())
2930 return;
2931
2932 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2933 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2934 Seq.clear();
2935 return;
2936 }
2937
2938 auto InsertPoint = std::lower_bound(
2939 Rows.begin(), Rows.end(), Seq.front(),
2940 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2941 return LHS.Address < RHS.Address;
2942 });
2943
2944 // FIXME: this only removes the unneeded end_sequence if the
2945 // sequences have been inserted in order. using a global sort like
2946 // described in patchLineTableForUnit() and delaying the end_sequene
2947 // elimination to emitLineTableForUnit() we can get rid of all of them.
2948 if (InsertPoint != Rows.end() &&
2949 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2950 *InsertPoint = Seq.front();
2951 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2952 } else {
2953 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2954 }
2955
2956 Seq.clear();
2957}
2958
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002959static void patchStmtList(DIE &Die, DIEInteger Offset) {
2960 for (auto &V : Die.values())
2961 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002962 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002963 return;
2964 }
2965
2966 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2967}
2968
Frederic Riss63786b02015-03-15 20:45:43 +00002969/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2970/// recreate a relocated version of these for the address ranges that
2971/// are present in the binary.
2972void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2973 DWARFContext &OrigDwarf) {
Greg Claytonc8c10322016-12-13 18:25:19 +00002974 DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
Greg Clayton52fe1f62016-12-14 22:38:08 +00002975 auto StmtList = CUDie.getAttributeValueAsSectionOffset(dwarf::DW_AT_stmt_list);
2976 if (!StmtList)
Frederic Riss63786b02015-03-15 20:45:43 +00002977 return;
2978
2979 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002980 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2981 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002982
2983 // Parse the original line info for the unit.
2984 DWARFDebugLine::LineTable LineTable;
Greg Clayton52fe1f62016-12-14 22:38:08 +00002985 uint32_t StmtOffset = *StmtList;
Frederic Riss63786b02015-03-15 20:45:43 +00002986 StringRef LineData = OrigDwarf.getLineSection().Data;
2987 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2988 Unit.getOrigUnit().getAddressByteSize());
2989 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2990 &StmtOffset);
2991
2992 // This vector is the output line table.
2993 std::vector<DWARFDebugLine::Row> NewRows;
2994 NewRows.reserve(LineTable.Rows.size());
2995
2996 // Current sequence of rows being extracted, before being inserted
2997 // in NewRows.
2998 std::vector<DWARFDebugLine::Row> Seq;
2999 const auto &FunctionRanges = Unit.getFunctionRanges();
3000 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
3001
3002 // FIXME: This logic is meant to generate exactly the same output as
3003 // Darwin's classic dsynutil. There is a nicer way to implement this
3004 // by simply putting all the relocated line info in NewRows and simply
3005 // sorting NewRows before passing it to emitLineTableForUnit. This
3006 // should be correct as sequences for a function should stay
3007 // together in the sorted output. There are a few corner cases that
3008 // look suspicious though, and that required to implement the logic
3009 // this way. Revisit that once initial validation is finished.
3010
3011 // Iterate over the object file line info and extract the sequences
3012 // that correspond to linked functions.
3013 for (auto &Row : LineTable.Rows) {
3014 // Check wether we stepped out of the range. The range is
3015 // half-open, but consider accept the end address of the range if
3016 // it is marked as end_sequence in the input (because in that
3017 // case, the relocation offset is accurate and that entry won't
3018 // serve as the start of another function).
3019 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
3020 Row.Address > CurrRange.stop() ||
3021 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
3022 // We just stepped out of a known range. Insert a end_sequence
3023 // corresponding to the end of the range.
3024 uint64_t StopAddress = CurrRange != InvalidRange
3025 ? CurrRange.stop() + CurrRange.value()
3026 : -1ULL;
3027 CurrRange = FunctionRanges.find(Row.Address);
3028 bool CurrRangeValid =
3029 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
3030 if (!CurrRangeValid) {
3031 CurrRange = InvalidRange;
3032 if (StopAddress != -1ULL) {
3033 // Try harder by looking in the DebugMapObject function
3034 // ranges map. There are corner cases where this finds a
3035 // valid entry. It's unclear if this is right or wrong, but
3036 // for now do as dsymutil.
3037 // FIXME: Understand exactly what cases this addresses and
3038 // potentially remove it along with the Ranges map.
3039 auto Range = Ranges.lower_bound(Row.Address);
3040 if (Range != Ranges.begin() && Range != Ranges.end())
3041 --Range;
3042
3043 if (Range != Ranges.end() && Range->first <= Row.Address &&
3044 Range->second.first >= Row.Address) {
3045 StopAddress = Row.Address + Range->second.second;
3046 }
3047 }
3048 }
3049 if (StopAddress != -1ULL && !Seq.empty()) {
3050 // Insert end sequence row with the computed end address, but
3051 // the same line as the previous one.
Yaron Kerene3c07062015-08-10 16:15:51 +00003052 auto NextLine = Seq.back();
Yaron Keren2ad3b332015-08-10 18:27:51 +00003053 NextLine.Address = StopAddress;
3054 NextLine.EndSequence = 1;
3055 NextLine.PrologueEnd = 0;
3056 NextLine.BasicBlock = 0;
3057 NextLine.EpilogueBegin = 0;
Yaron Kerenf850d982015-08-10 18:03:35 +00003058 Seq.push_back(NextLine);
Frederic Riss63786b02015-03-15 20:45:43 +00003059 insertLineSequence(Seq, NewRows);
3060 }
3061
3062 if (!CurrRangeValid)
3063 continue;
3064 }
3065
3066 // Ignore empty sequences.
3067 if (Row.EndSequence && Seq.empty())
3068 continue;
3069
3070 // Relocate row address and add it to the current sequence.
3071 Row.Address += CurrRange.value();
3072 Seq.emplace_back(Row);
3073
3074 if (Row.EndSequence)
3075 insertLineSequence(Seq, NewRows);
3076 }
3077
3078 // Finished extracting, now emit the line tables.
Greg Clayton52fe1f62016-12-14 22:38:08 +00003079 uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength;
Frederic Riss63786b02015-03-15 20:45:43 +00003080 // FIXME: LLVM hardcodes it's prologue values. We just copy the
3081 // prologue over and that works because we act as both producer and
3082 // consumer. It would be nicer to have a real configurable line
3083 // table emitter.
3084 if (LineTable.Prologue.Version != 2 ||
3085 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00003086 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00003087 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00003088 else {
3089 MCDwarfLineTableParams Params;
3090 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
3091 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
3092 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
3093 Streamer->emitLineTableForUnit(Params,
Greg Clayton52fe1f62016-12-14 22:38:08 +00003094 LineData.slice(*StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00003095 LineTable.Prologue.MinInstLength, NewRows,
3096 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00003097 }
Frederic Riss63786b02015-03-15 20:45:43 +00003098}
3099
Frederic Rissbce93ff2015-03-16 02:05:10 +00003100void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
3101 Streamer->emitPubNamesForUnit(Unit);
3102 Streamer->emitPubTypesForUnit(Unit);
3103}
3104
Frederic Riss5a642072015-06-05 23:06:11 +00003105/// \brief Read the frame info stored in the object, and emit the
3106/// patched frame descriptions for the linked binary.
3107///
3108/// This is actually pretty easy as the data of the CIEs and FDEs can
3109/// be considered as black boxes and moved as is. The only thing to do
3110/// is to patch the addresses in the headers.
3111void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
3112 DWARFContext &OrigDwarf,
3113 unsigned AddrSize) {
3114 StringRef FrameData = OrigDwarf.getDebugFrameSection();
3115 if (FrameData.empty())
3116 return;
3117
3118 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
3119 uint32_t InputOffset = 0;
3120
3121 // Store the data of the CIEs defined in this object, keyed by their
3122 // offsets.
3123 DenseMap<uint32_t, StringRef> LocalCIES;
3124
3125 while (Data.isValidOffset(InputOffset)) {
3126 uint32_t EntryOffset = InputOffset;
3127 uint32_t InitialLength = Data.getU32(&InputOffset);
3128 if (InitialLength == 0xFFFFFFFF)
3129 return reportWarning("Dwarf64 bits no supported");
3130
3131 uint32_t CIEId = Data.getU32(&InputOffset);
3132 if (CIEId == 0xFFFFFFFF) {
3133 // This is a CIE, store it.
3134 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
3135 LocalCIES[EntryOffset] = CIEData;
3136 // The -4 is to account for the CIEId we just read.
3137 InputOffset += InitialLength - 4;
3138 continue;
3139 }
3140
3141 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
3142
3143 // Some compilers seem to emit frame info that doesn't start at
3144 // the function entry point, thus we can't just lookup the address
3145 // in the debug map. Use the linker's range map to see if the FDE
3146 // describes something that we can relocate.
3147 auto Range = Ranges.upper_bound(Loc);
3148 if (Range != Ranges.begin())
3149 --Range;
3150 if (Range == Ranges.end() || Range->first > Loc ||
3151 Range->second.first <= Loc) {
3152 // The +4 is to account for the size of the InitialLength field itself.
3153 InputOffset = EntryOffset + InitialLength + 4;
3154 continue;
3155 }
3156
3157 // This is an FDE, and we have a mapping.
3158 // Have we already emitted a corresponding CIE?
3159 StringRef CIEData = LocalCIES[CIEId];
3160 if (CIEData.empty())
3161 return reportWarning("Inconsistent debug_frame content. Dropping.");
3162
3163 // Look if we already emitted a CIE that corresponds to the
3164 // referenced one (the CIE data is the key of that lookup).
3165 auto IteratorInserted = EmittedCIEs.insert(
3166 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3167 // If there is no CIE yet for this ID, emit it.
3168 if (IteratorInserted.second ||
3169 // FIXME: dsymutil-classic only caches the last used CIE for
3170 // reuse. Mimic that behavior for now. Just removing that
3171 // second half of the condition and the LastCIEOffset variable
3172 // makes the code DTRT.
3173 LastCIEOffset != IteratorInserted.first->getValue()) {
3174 LastCIEOffset = Streamer->getFrameSectionSize();
3175 IteratorInserted.first->getValue() = LastCIEOffset;
3176 Streamer->emitCIE(CIEData);
3177 }
3178
3179 // Emit the FDE with updated address and CIE pointer.
3180 // (4 + AddrSize) is the size of the CIEId + initial_location
3181 // fields that will get reconstructed by emitFDE().
3182 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3183 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3184 Loc + Range->second.second,
3185 FrameData.substr(InputOffset, FDERemainingBytes));
3186 InputOffset += FDERemainingBytes;
3187 }
3188}
3189
Adrian Prantl3565af42015-09-14 16:46:10 +00003190void DwarfLinker::DIECloner::copyAbbrev(
3191 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
Frederic Riss29eedc72015-09-11 04:17:30 +00003192 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3193 dwarf::Form(Abbrev.hasChildren()));
3194
3195 for (const auto &Attr : Abbrev.attributes()) {
3196 uint16_t Form = Attr.Form;
3197 if (hasODR && isODRAttribute(Attr.Attr))
3198 Form = dwarf::DW_FORM_ref_addr;
3199 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3200 }
3201
Adrian Prantl3565af42015-09-14 16:46:10 +00003202 Linker.AssignAbbrev(Copy);
Frederic Riss29eedc72015-09-11 04:17:30 +00003203}
3204
Greg Claytonc8c10322016-12-13 18:25:19 +00003205static uint64_t getDwoId(const DWARFDie &CUDie,
Adrian Prantl20937022015-09-23 17:11:10 +00003206 const DWARFUnit &Unit) {
Greg Clayton52fe1f62016-12-14 22:38:08 +00003207 auto DwoId = CUDie.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_dwo_id);
3208 if (DwoId)
3209 return *DwoId;
3210 DwoId = CUDie.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_GNU_dwo_id);
3211 if (DwoId)
3212 return *DwoId;
3213 return 0;
Adrian Prantl20937022015-09-23 17:11:10 +00003214}
3215
Adrian Prantle5162db2015-09-22 22:20:50 +00003216bool DwarfLinker::registerModuleReference(
Greg Claytonc8c10322016-12-13 18:25:19 +00003217 const DWARFDie &CUDie, const DWARFUnit &Unit,
Adrian Prantle5162db2015-09-22 22:20:50 +00003218 DebugMap &ModuleMap, unsigned Indent) {
3219 std::string PCMfile =
Greg Claytonc8c10322016-12-13 18:25:19 +00003220 CUDie.getAttributeValueAsString(dwarf::DW_AT_dwo_name, "");
Adrian Prantl20937022015-09-23 17:11:10 +00003221 if (PCMfile.empty())
3222 PCMfile =
Greg Claytonc8c10322016-12-13 18:25:19 +00003223 CUDie.getAttributeValueAsString(dwarf::DW_AT_GNU_dwo_name, "");
Adrian Prantle5162db2015-09-22 22:20:50 +00003224 if (PCMfile.empty())
3225 return false;
3226
3227 // Clang module DWARF skeleton CUs abuse this for the path to the module.
3228 std::string PCMpath =
Greg Claytonc8c10322016-12-13 18:25:19 +00003229 CUDie.getAttributeValueAsString(dwarf::DW_AT_comp_dir, "");
Adrian Prantl20937022015-09-23 17:11:10 +00003230 uint64_t DwoId = getDwoId(CUDie, Unit);
Adrian Prantle5162db2015-09-22 22:20:50 +00003231
Adrian Prantla112ef92015-09-23 17:35:52 +00003232 std::string Name =
Greg Claytonc8c10322016-12-13 18:25:19 +00003233 CUDie.getAttributeValueAsString(dwarf::DW_AT_name, "");
Adrian Prantla112ef92015-09-23 17:35:52 +00003234 if (Name.empty()) {
3235 reportWarning("Anonymous module skeleton CU for " + PCMfile);
3236 return true;
3237 }
3238
Adrian Prantle5162db2015-09-22 22:20:50 +00003239 if (Options.Verbose) {
3240 outs().indent(Indent);
3241 outs() << "Found clang module reference " << PCMfile;
3242 }
3243
Adrian Prantl20937022015-09-23 17:11:10 +00003244 auto Cached = ClangModules.find(PCMfile);
3245 if (Cached != ClangModules.end()) {
Adrian Prantle1bc3e22016-05-13 00:17:58 +00003246 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
3247 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
3248 // ASTFileSignatures will change randomly when a module is rebuilt.
3249 if (Options.Verbose && (Cached->second != DwoId))
Adrian Prantl20937022015-09-23 17:11:10 +00003250 reportWarning(Twine("hash mismatch: this object file was built against a "
3251 "different version of the module ") + PCMfile);
Adrian Prantle5162db2015-09-22 22:20:50 +00003252 if (Options.Verbose)
3253 outs() << " [cached].\n";
3254 return true;
3255 }
3256 if (Options.Verbose)
3257 outs() << " ...\n";
3258
3259 // Cyclic dependencies are disallowed by Clang, but we still
3260 // shouldn't run into an infinite loop, so mark it as processed now.
Adrian Prantl20937022015-09-23 17:11:10 +00003261 ClangModules.insert({PCMfile, DwoId});
Adrian Prantla112ef92015-09-23 17:35:52 +00003262 loadClangModule(PCMfile, PCMpath, Name, DwoId, ModuleMap, Indent + 2);
Adrian Prantle5162db2015-09-22 22:20:50 +00003263 return true;
3264}
3265
Frederic Risseb85c8f2015-07-24 06:41:11 +00003266ErrorOr<const object::ObjectFile &>
3267DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3268 const DebugMap &Map) {
3269 auto ErrOrObjs =
3270 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
Frederic Rissafeac302015-08-31 05:16:35 +00003271 if (std::error_code EC = ErrOrObjs.getError()) {
Frederic Risseb85c8f2015-07-24 06:41:11 +00003272 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
Frederic Rissafeac302015-08-31 05:16:35 +00003273 return EC;
3274 }
Frederic Risseb85c8f2015-07-24 06:41:11 +00003275 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3276 if (std::error_code EC = ErrOrObj.getError())
3277 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3278 return ErrOrObj;
3279}
3280
Adrian Prantle5162db2015-09-22 22:20:50 +00003281void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
Adrian Prantla112ef92015-09-23 17:35:52 +00003282 StringRef ModuleName, uint64_t DwoId,
3283 DebugMap &ModuleMap, unsigned Indent) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003284 SmallString<80> Path(Options.PrependPath);
3285 if (sys::path::is_relative(Filename))
3286 sys::path::append(Path, ModulePath, Filename);
3287 else
3288 sys::path::append(Path, Filename);
3289 BinaryHolder ObjHolder(Options.Verbose);
3290 auto &Obj =
Pavel Labath62d72042016-11-09 11:43:52 +00003291 ModuleMap.addDebugMapObject(Path, sys::TimePoint<std::chrono::seconds>());
Adrian Prantle5162db2015-09-22 22:20:50 +00003292 auto ErrOrObj = loadObject(ObjHolder, Obj, ModuleMap);
Adrian Prantla9e23832016-01-14 18:31:07 +00003293 if (!ErrOrObj) {
3294 // Try and emit more helpful warnings by applying some heuristics.
3295 StringRef ObjFile = CurrentDebugObject->getObjectFilename();
3296 bool isClangModule = sys::path::extension(Filename).equals(".pcm");
3297 bool isArchive = ObjFile.endswith(")");
3298 if (isClangModule) {
Adrian Prantla9e23832016-01-14 18:31:07 +00003299 StringRef ModuleCacheDir = sys::path::parent_path(Path);
3300 if (sys::fs::exists(ModuleCacheDir)) {
3301 // If the module's parent directory exists, we assume that the module
3302 // cache has expired and was pruned by clang. A more adventurous
3303 // dsymutil would invoke clang to rebuild the module now.
3304 if (!ModuleCacheHintDisplayed) {
3305 errs() << "note: The clang module cache may have expired since this "
3306 "object file was built. Rebuilding the object file will "
3307 "rebuild the module cache.\n";
3308 ModuleCacheHintDisplayed = true;
3309 }
3310 } else if (isArchive) {
3311 // If the module cache directory doesn't exist at all and the object
3312 // file is inside a static library, we assume that the static library
3313 // was built on a different machine. We don't want to discourage module
3314 // debugging for convenience libraries within a project though.
3315 if (!ArchiveHintDisplayed) {
Adrian Prantl9e7e8832016-05-20 20:36:06 +00003316 errs() << "note: Linking a static library that was built with "
3317 "-gmodules, but the module cache was not found. "
3318 "Redistributable static libraries should never be built "
3319 "with module debugging enabled. The debug experience will "
3320 "be degraded due to incomplete debug information.\n";
Adrian Prantla9e23832016-01-14 18:31:07 +00003321 ArchiveHintDisplayed = true;
3322 }
3323 }
3324 }
Adrian Prantle5162db2015-09-22 22:20:50 +00003325 return;
Adrian Prantla9e23832016-01-14 18:31:07 +00003326 }
Adrian Prantle5162db2015-09-22 22:20:50 +00003327
Benjamin Kramer008f4be2015-09-23 10:38:59 +00003328 std::unique_ptr<CompileUnit> Unit;
Adrian Prantle5162db2015-09-22 22:20:50 +00003329
3330 // Setup access to the debug info.
3331 DWARFContextInMemory DwarfContext(*ErrOrObj);
3332 RelocationManager RelocMgr(*this);
3333 for (const auto &CU : DwarfContext.compile_units()) {
Greg Claytonc8c10322016-12-13 18:25:19 +00003334 auto CUDie = CU->getUnitDIE(false);
Adrian Prantle5162db2015-09-22 22:20:50 +00003335 // Recursively get all modules imported by this one.
Greg Claytonc8c10322016-12-13 18:25:19 +00003336 if (!registerModuleReference(CUDie, *CU, ModuleMap, Indent)) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003337 if (Unit) {
3338 errs() << Filename << ": Clang modules are expected to have exactly"
3339 << " 1 compile unit.\n";
3340 exitDsymutil(1);
3341 }
Adrian Prantl2c0b0ab2016-04-25 17:04:32 +00003342 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
3343 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
3344 // ASTFileSignatures will change randomly when a module is rebuilt.
Greg Claytonc8c10322016-12-13 18:25:19 +00003345 uint64_t PCMDwoId = getDwoId(CUDie, *CU);
Adrian Prantle1bc3e22016-05-13 00:17:58 +00003346 if (PCMDwoId != DwoId) {
3347 if (Options.Verbose)
3348 reportWarning(
3349 Twine("hash mismatch: this object file was built against a "
3350 "different version of the module ") + Filename);
3351 // Update the cache entry with the DwoId of the module loaded from disk.
3352 ClangModules[Filename] = PCMDwoId;
3353 }
Adrian Prantl20937022015-09-23 17:11:10 +00003354
3355 // Add this module.
Adrian Prantla112ef92015-09-23 17:35:52 +00003356 Unit = llvm::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
3357 ModuleName);
Adrian Prantle5162db2015-09-22 22:20:50 +00003358 Unit->setHasInterestingContent();
Adrian Prantla112ef92015-09-23 17:35:52 +00003359 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), StringPool,
3360 ODRContexts);
Adrian Prantle5162db2015-09-22 22:20:50 +00003361 // Keep everything.
3362 Unit->markEverythingAsKept();
3363 }
3364 }
3365 if (Options.Verbose) {
3366 outs().indent(Indent);
3367 outs() << "cloning .debug_info from " << Filename << "\n";
3368 }
3369
Greg Clayton35630c32016-12-01 18:56:29 +00003370 std::vector<std::unique_ptr<CompileUnit>> CompileUnits;
3371 CompileUnits.push_back(std::move(Unit));
3372 DIECloner(*this, RelocMgr, DIEAlloc, CompileUnits, Options)
Adrian Prantle5162db2015-09-22 22:20:50 +00003373 .cloneAllCompileUnits(DwarfContext);
3374}
3375
Adrian Prantl3565af42015-09-14 16:46:10 +00003376void DwarfLinker::DIECloner::cloneAllCompileUnits(
3377 DWARFContextInMemory &DwarfContext) {
3378 if (!Linker.Streamer)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003379 return;
3380
3381 for (auto &CurrentUnit : CompileUnits) {
Greg Claytonc8c10322016-12-13 18:25:19 +00003382 auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
Greg Clayton35630c32016-12-01 18:56:29 +00003383 CurrentUnit->setStartOffset(Linker.OutputDebugInfoSize);
3384 // Clonse the InputDIE into your Unit DIE in our compile unit since it
3385 // already has a DIE inside of it.
Greg Claytonc8c10322016-12-13 18:25:19 +00003386 if (!cloneDIE(InputDIE, *CurrentUnit, 0 /* PC offset */,
Greg Clayton35630c32016-12-01 18:56:29 +00003387 11 /* Unit Header size */, 0,
3388 CurrentUnit->getOutputUnitDIE()))
3389 continue;
3390 Linker.OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset();
Adrian Prantl3565af42015-09-14 16:46:10 +00003391 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003392 continue;
3393 // FIXME: for compatibility with the classic dsymutil, we emit
3394 // an empty line table for the unit, even if the unit doesn't
3395 // actually exist in the DIE tree.
Greg Clayton35630c32016-12-01 18:56:29 +00003396 Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext);
3397 Linker.patchRangesForUnit(*CurrentUnit, DwarfContext);
3398 Linker.Streamer->emitLocationsForUnit(*CurrentUnit, DwarfContext);
3399 Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003400 }
3401
Adrian Prantl3565af42015-09-14 16:46:10 +00003402 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003403 return;
3404
3405 // Emit all the compile unit's debug information.
3406 for (auto &CurrentUnit : CompileUnits) {
Greg Clayton35630c32016-12-01 18:56:29 +00003407 Linker.generateUnitRanges(*CurrentUnit);
3408 CurrentUnit->fixupForwardReferences();
3409 Linker.Streamer->emitCompileUnitHeader(*CurrentUnit);
3410 if (!CurrentUnit->getOutputUnitDIE())
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003411 continue;
Greg Clayton35630c32016-12-01 18:56:29 +00003412 Linker.Streamer->emitDIE(*CurrentUnit->getOutputUnitDIE());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003413 }
3414}
3415
Frederic Rissd3455182015-01-28 18:27:01 +00003416bool DwarfLinker::link(const DebugMap &Map) {
3417
Frederic Rissc99ea202015-02-28 00:29:11 +00003418 if (!createStreamer(Map.getTriple(), OutputFilename))
3419 return false;
3420
Frederic Rissb8b43d52015-03-04 22:07:44 +00003421 // Size of the DIEs (and headers) generated for the linked output.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003422 OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00003423 // A unique ID that identifies each compile unit.
Adrian Prantle5162db2015-09-22 22:20:50 +00003424 UnitID = 0;
3425 DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
3426
Frederic Rissd3455182015-01-28 18:27:01 +00003427 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00003428 CurrentDebugObject = Obj.get();
3429
Frederic Rissb9818322015-02-28 00:29:07 +00003430 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00003431 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00003432 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3433 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00003434 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00003435
Frederic Riss1036e642015-02-13 23:18:22 +00003436 // Look for relocations that correspond to debug map entries.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003437 RelocationManager RelocMgr(*this);
3438 if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00003439 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00003440 outs() << "No valid relocations found. Skipping.\n";
3441 continue;
3442 }
3443
Frederic Riss563cba62015-01-28 22:15:14 +00003444 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00003445 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00003446 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00003447
Adrian Prantld2793a02015-10-05 23:11:20 +00003448 // In a first phase, just read in the debug info and load all clang modules.
Frederic Rissd3455182015-01-28 18:27:01 +00003449 for (const auto &CU : DwarfContext.compile_units()) {
Greg Claytonc8c10322016-12-13 18:25:19 +00003450 auto CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00003451 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00003452 outs() << "Input compilation unit:";
Greg Claytonc8c10322016-12-13 18:25:19 +00003453 CUDie.dump(outs(), 0);
Frederic Rissd3455182015-01-28 18:27:01 +00003454 }
Adrian Prantld2793a02015-10-05 23:11:20 +00003455
Greg Claytonc8c10322016-12-13 18:25:19 +00003456 if (!registerModuleReference(CUDie, *CU, ModuleMap))
Greg Clayton35630c32016-12-01 18:56:29 +00003457 Units.push_back(llvm::make_unique<CompileUnit>(*CU, UnitID++,
3458 !Options.NoODR, ""));
Frederic Rissd3455182015-01-28 18:27:01 +00003459 }
Frederic Riss563cba62015-01-28 22:15:14 +00003460
Adrian Prantld2793a02015-10-05 23:11:20 +00003461 // Now build the DIE parent links that we will use during the next phase.
3462 for (auto &CurrentUnit : Units)
Greg Clayton35630c32016-12-01 18:56:29 +00003463 analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0, *CurrentUnit,
Adrian Prantld2793a02015-10-05 23:11:20 +00003464 &ODRContexts.getRoot(), StringPool, ODRContexts);
3465
Frederic Riss84c09a52015-02-13 23:18:34 +00003466 // Then mark all the DIEs that need to be present in the linked
3467 // output and collect some information about them. Note that this
3468 // loop can not be merged with the previous one becaue cross-cu
3469 // references require the ParentIdx to be setup for every CU in
3470 // the object file before calling this.
3471 for (auto &CurrentUnit : Units)
Greg Claytonc8c10322016-12-13 18:25:19 +00003472 lookForDIEsToKeep(RelocMgr, CurrentUnit->getOrigUnit().getUnitDIE(), *Obj,
Greg Clayton35630c32016-12-01 18:56:29 +00003473 *CurrentUnit, 0);
Frederic Riss84c09a52015-02-13 23:18:34 +00003474
Frederic Riss23e20e92015-03-07 01:25:09 +00003475 // The calls to applyValidRelocs inside cloneDIE will walk the
3476 // reloc array again (in the same way findValidRelocsInDebugInfo()
3477 // did). We need to reset the NextValidReloc index to the beginning.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003478 RelocMgr.resetValidRelocs();
3479 if (RelocMgr.hasValidRelocs())
Adrian Prantl3565af42015-09-14 16:46:10 +00003480 DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3481 .cloneAllCompileUnits(DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003482 if (!Options.NoOutput && !Units.empty())
Frederic Riss5a642072015-06-05 23:06:11 +00003483 patchFrameInfoForObject(*Obj, DwarfContext,
Greg Clayton35630c32016-12-01 18:56:29 +00003484 Units[0]->getOrigUnit().getAddressByteSize());
Frederic Riss5a642072015-06-05 23:06:11 +00003485
Frederic Riss563cba62015-01-28 22:15:14 +00003486 // Clean-up before starting working on the next object.
3487 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003488 }
3489
Frederic Rissb8b43d52015-03-04 22:07:44 +00003490 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003491 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003492 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003493 Streamer->emitStrings(StringPool);
3494 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003495
Frederic Riss24faade2015-09-02 16:49:13 +00003496 return Options.NoOutput ? true : Streamer->finish(Map);
Frederic Riss231f7142014-12-12 17:31:24 +00003497}
3498}
Frederic Rissd3455182015-01-28 18:27:01 +00003499
Frederic Riss30711fb2015-08-26 05:09:52 +00003500/// \brief Get the offset of string \p S in the string table. This
3501/// can insert a new element or return the offset of a preexisitng
3502/// one.
3503uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3504 if (S.empty() && !Strings.empty())
3505 return 0;
3506
3507 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3508 MapTy::iterator It;
3509 bool Inserted;
3510
3511 // A non-empty string can't be at offset 0, so if we have an entry
3512 // with a 0 offset, it must be a previously interned string.
3513 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3514 if (Inserted || It->getValue().first == 0) {
3515 // Set offset and chain at the end of the entries list.
3516 It->getValue().first = CurrentEndOffset;
3517 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3518 Last->getValue().second = &*It;
3519 Last = &*It;
3520 }
3521 return It->getValue().first;
3522}
3523
3524/// \brief Put \p S into the StringMap so that it gets permanent
3525/// storage, but do not actually link it in the chain of elements
3526/// that go into the output section. A latter call to
3527/// getStringOffset() with the same string will chain it though.
3528StringRef NonRelocatableStringpool::internString(StringRef S) {
3529 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3530 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3531 return InsertResult.first->getKey();
3532}
3533
Frederic Riss65e145c2015-08-26 05:09:55 +00003534void warn(const Twine &Warning, const Twine &Context) {
3535 errs() << Twine("while processing ") + Context + ":\n";
3536 errs() << Twine("warning: ") + Warning + "\n";
3537}
3538
3539bool error(const Twine &Error, const Twine &Context) {
3540 errs() << Twine("while processing ") + Context + ":\n";
3541 errs() << Twine("error: ") + Error + "\n";
3542 return false;
3543}
3544
Frederic Rissb9818322015-02-28 00:29:07 +00003545bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3546 const LinkOptions &Options) {
3547 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003548 return Linker.link(DM);
3549}
3550}
Frederic Riss231f7142014-12-12 17:31:24 +00003551}