blob: f1ec8a62267128983367fceee0134eddf0f9abe4 [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);
Greg Claytond1efea82017-01-11 17:43:37 +0000208 unsigned Lang =
209 CUDie.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_language)
210 .getValueOr(0);
Frederic Riss1c650942015-07-21 22:41:43 +0000211 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
212 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
213 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
214 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
215 Lang == dwarf::DW_LANG_ObjC_plus_plus);
Frederic Riss563cba62015-01-28 22:15:14 +0000216 }
217
Frederic Rissc3349d42015-02-13 23:18:27 +0000218 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000219
Frederic Riss3cced052015-03-14 03:46:40 +0000220 unsigned getUniqueID() const { return ID; }
221
Greg Clayton35630c32016-12-01 18:56:29 +0000222 DIE *getOutputUnitDIE() const {
223 return &const_cast<DIEUnit &>(NewUnit).getUnitDie();
224 }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000225
Frederic Riss1c650942015-07-21 22:41:43 +0000226 bool hasODR() const { return HasODR; }
Adrian Prantla112ef92015-09-23 17:35:52 +0000227 bool isClangModule() const { return !ClangModuleName.empty(); }
228 const std::string &getClangModuleName() const { return ClangModuleName; }
Frederic Riss1c650942015-07-21 22:41:43 +0000229
Frederic Riss563cba62015-01-28 22:15:14 +0000230 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
231 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
232
Frederic Rissb8b43d52015-03-04 22:07:44 +0000233 uint64_t getStartOffset() const { return StartOffset; }
234 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000235 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000236
Frederic Riss5a62dc32015-03-13 18:35:54 +0000237 uint64_t getLowPc() const { return LowPc; }
238 uint64_t getHighPc() const { return HighPc; }
239
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000240 Optional<PatchLocation> getUnitRangesAttribute() const {
241 return UnitRangeAttribute;
242 }
Frederic Riss25440872015-03-13 23:30:31 +0000243 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000244 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000245 return RangeAttributes;
246 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000247
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000248 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000249 getLocationAttributes() const {
250 return LocationAttributes;
251 }
252
Adrian Prantle5162db2015-09-22 22:20:50 +0000253 void setHasInterestingContent() { HasInterestingContent = true; }
254 bool hasInterestingContent() { return HasInterestingContent; }
255
256 /// Mark every DIE in this unit as kept. This function also
257 /// marks variables as InDebugMap so that they appear in the
258 /// reconstructed accelerator tables.
259 void markEverythingAsKept();
260
Frederic Riss9d441b62015-03-06 23:22:50 +0000261 /// \brief Compute the end offset for this unit. Must be
262 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000263 /// \returns the next unit offset (which is also the current
264 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000265 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000266
Frederic Riss6afcfce2015-03-13 18:35:57 +0000267 /// \brief Keep track of a forward reference to DIE \p Die in \p
268 /// RefUnit by \p Attr. The attribute should be fixed up later to
Frederic Riss1c650942015-07-21 22:41:43 +0000269 /// point to the absolute offset of \p Die in the debug_info section
270 /// or to the canonical offset of \p Ctxt if it is non-null.
Frederic Riss6afcfce2015-03-13 18:35:57 +0000271 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000272 DeclContext *Ctxt, PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000273
274 /// \brief Apply all fixups recored by noteForwardReference().
275 void fixupForwardReferences();
276
Frederic Riss1af75f72015-03-12 18:45:10 +0000277 /// \brief Add a function range [\p LowPC, \p HighPC) that is
278 /// relocatad by applying offset \p PCOffset.
279 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
280
Frederic Riss5c9c7062015-03-13 23:55:29 +0000281 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000282 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000283 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000284
Frederic Rissdfb97902015-03-14 15:49:07 +0000285 /// \brief Keep track of a location attribute pointing to a location
286 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000287 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000288
Frederic Rissbce93ff2015-03-16 02:05:10 +0000289 /// \brief Add a name accelerator entry for \p Die with \p Name
290 /// which is stored in the string table at \p Offset.
291 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
292 bool SkipPubnamesSection = false);
293
294 /// \brief Add a type accelerator entry for \p Die with \p Name
295 /// which is stored in the string table at \p Offset.
296 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
297
298 struct AccelInfo {
Frederic Rissf37964c2015-06-05 20:27:07 +0000299 StringRef Name; ///< Name of the entry.
300 const DIE *Die; ///< DIE this entry describes.
Frederic Rissbce93ff2015-03-16 02:05:10 +0000301 uint32_t NameOffset; ///< Offset of Name in the string pool.
302 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
303
304 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
305 bool SkipPubSection = false)
306 : Name(Name), Die(Die), NameOffset(NameOffset),
307 SkipPubSection(SkipPubSection) {}
308 };
309
310 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
311 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
312
Frederic Riss1c650942015-07-21 22:41:43 +0000313 /// Get the full path for file \a FileNum in the line table
Pete Cooperef4e36a2016-03-18 03:48:09 +0000314 StringRef getResolvedPath(unsigned FileNum) {
Frederic Riss1c650942015-07-21 22:41:43 +0000315 if (FileNum >= ResolvedPaths.size())
Pete Cooperef4e36a2016-03-18 03:48:09 +0000316 return StringRef();
317 return ResolvedPaths[FileNum];
Frederic Riss1c650942015-07-21 22:41:43 +0000318 }
319
320 /// Set the fully resolved path for the line-table's file \a FileNum
321 /// to \a Path.
Pete Cooperef4e36a2016-03-18 03:48:09 +0000322 void setResolvedPath(unsigned FileNum, StringRef Path) {
Frederic Riss1c650942015-07-21 22:41:43 +0000323 if (ResolvedPaths.size() <= FileNum)
324 ResolvedPaths.resize(FileNum + 1);
325 ResolvedPaths[FileNum] = Path;
326 }
327
Frederic Riss563cba62015-01-28 22:15:14 +0000328private:
329 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000330 unsigned ID;
Frederic Riss1c650942015-07-21 22:41:43 +0000331 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
Greg Clayton35630c32016-12-01 18:56:29 +0000332 DIEUnit NewUnit;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000333
334 uint64_t StartOffset;
335 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000336
Frederic Riss5a62dc32015-03-13 18:35:54 +0000337 uint64_t LowPc;
338 uint64_t HighPc;
339
Frederic Riss9833de62015-03-06 23:22:53 +0000340 /// \brief A list of attributes to fixup with the absolute offset of
341 /// a DIE in the debug_info section.
342 ///
343 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000344 /// cloning because for cross-cu forward refences the target DIE's
345 /// offset isn't known you emit the reference attribute.
Frederic Riss1c650942015-07-21 22:41:43 +0000346 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
347 PatchLocation>> ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000348
Frederic Riss25440872015-03-13 23:30:31 +0000349 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000350 /// \brief The ranges in that interval map are the PC ranges for
351 /// functions in this unit, associated with the PC offset to apply
352 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000353 FunctionIntervals Ranges;
354
355 /// \brief DW_AT_ranges attributes to patch after we have gathered
356 /// all the unit's function addresses.
357 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000358 std::vector<PatchLocation> RangeAttributes;
359 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000360 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000361
362 /// \brief Location attributes that need to be transfered from th
363 /// original debug_loc section to the liked one. They are stored
364 /// along with the PC offset that is to be applied to their
365 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000366 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000367
368 /// \brief Accelerator entries for the unit, both for the pub*
369 /// sections and the apple* ones.
370 /// @{
371 std::vector<AccelInfo> Pubnames;
372 std::vector<AccelInfo> Pubtypes;
373 /// @}
Frederic Riss1c650942015-07-21 22:41:43 +0000374
375 /// Cached resolved paths from the line table.
Pete Cooperef4e36a2016-03-18 03:48:09 +0000376 /// Note, the StringRefs here point in to the intern (uniquing) string pool.
377 /// This means that a StringRef returned here doesn't need to then be uniqued
378 /// for the purposes of getting a unique address for each string.
379 std::vector<StringRef> ResolvedPaths;
Frederic Riss1c650942015-07-21 22:41:43 +0000380
381 /// Is this unit subject to the ODR rule?
382 bool HasODR;
Adrian Prantle5162db2015-09-22 22:20:50 +0000383 /// Did a DIE actually contain a valid reloc?
384 bool HasInterestingContent;
Adrian Prantla112ef92015-09-23 17:35:52 +0000385 /// If this is a Clang module, this holds the module's name.
386 std::string ClangModuleName;
Frederic Riss563cba62015-01-28 22:15:14 +0000387};
388
Adrian Prantle5162db2015-09-22 22:20:50 +0000389void CompileUnit::markEverythingAsKept() {
390 for (auto &I : Info)
Adrian Prantla112ef92015-09-23 17:35:52 +0000391 // Mark everything that wasn't explicity marked for pruning.
392 I.Keep = !I.Prune;
Adrian Prantle5162db2015-09-22 22:20:50 +0000393}
394
Frederic Riss9d441b62015-03-06 23:22:50 +0000395uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000396 NextUnitOffset = StartOffset + 11 /* Header size */;
397 // The root DIE might be null, meaning that the Unit had nothing to
398 // contribute to the linked output. In that case, we will emit the
399 // unit header without any actual DIE.
Greg Clayton35630c32016-12-01 18:56:29 +0000400 NextUnitOffset += NewUnit.getUnitDie().getSize();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000401 return NextUnitOffset;
402}
403
Frederic Riss6afcfce2015-03-13 18:35:57 +0000404/// \brief Keep track of a forward cross-cu reference from this unit
405/// to \p Die that lives in \p RefUnit.
406void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000407 DeclContext *Ctxt, PatchLocation Attr) {
408 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000409}
410
411/// \brief Apply all fixups recorded by noteForwardReference().
412void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000413 for (const auto &Ref : ForwardDIEReferences) {
414 DIE *RefDie;
415 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000416 PatchLocation Attr;
Frederic Riss1c650942015-07-21 22:41:43 +0000417 DeclContext *Ctxt;
418 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
419 if (Ctxt && Ctxt->getCanonicalDIEOffset())
420 Attr.set(Ctxt->getCanonicalDIEOffset());
421 else
422 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000423 }
Frederic Riss9833de62015-03-06 23:22:53 +0000424}
425
Frederic Riss5a62dc32015-03-13 18:35:54 +0000426void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
427 int64_t PcOffset) {
428 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
429 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
430 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000431}
432
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000433void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000434 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
435 RangeAttributes.push_back(Attr);
436 else
437 UnitRangeAttribute = Attr;
438}
439
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000440void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000441 LocationAttributes.emplace_back(Attr, PcOffset);
442}
443
Frederic Rissbce93ff2015-03-16 02:05:10 +0000444/// \brief Add a name accelerator entry for \p Die with \p Name
445/// which is stored in the string table at \p Offset.
446void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
447 uint32_t Offset, bool SkipPubSection) {
448 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
449}
450
451/// \brief Add a type accelerator entry for \p Die with \p Name
452/// which is stored in the string table at \p Offset.
453void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
454 uint32_t Offset) {
455 Pubtypes.emplace_back(Name, Die, Offset, false);
456}
457
Frederic Rissc99ea202015-02-28 00:29:11 +0000458/// \brief The Dwarf streaming logic
459///
460/// All interactions with the MC layer that is used to build the debug
461/// information binary representation are handled in this class.
462class DwarfStreamer {
463 /// \defgroup MCObjects MC layer objects constructed by the streamer
464 /// @{
465 std::unique_ptr<MCRegisterInfo> MRI;
466 std::unique_ptr<MCAsmInfo> MAI;
467 std::unique_ptr<MCObjectFileInfo> MOFI;
468 std::unique_ptr<MCContext> MC;
469 MCAsmBackend *MAB; // Owned by MCStreamer
470 std::unique_ptr<MCInstrInfo> MII;
471 std::unique_ptr<MCSubtargetInfo> MSTI;
472 MCCodeEmitter *MCE; // Owned by MCStreamer
473 MCStreamer *MS; // Owned by AsmPrinter
474 std::unique_ptr<TargetMachine> TM;
475 std::unique_ptr<AsmPrinter> Asm;
476 /// @}
477
478 /// \brief the file we stream the linked Dwarf to.
479 std::unique_ptr<raw_fd_ostream> OutFile;
480
Frederic Riss25440872015-03-13 23:30:31 +0000481 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000482 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000483 uint32_t LineSectionSize;
Frederic Riss5a642072015-06-05 23:06:11 +0000484 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000485
Frederic Rissbce93ff2015-03-16 02:05:10 +0000486 /// \brief Emit the pubnames or pubtypes section contribution for \p
487 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000488 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000489 const CompileUnit &Unit,
490 const std::vector<CompileUnit::AccelInfo> &Names);
491
Frederic Rissc99ea202015-02-28 00:29:11 +0000492public:
493 /// \brief Actually create the streamer and the ouptut file.
494 ///
495 /// This could be done directly in the constructor, but it feels
496 /// more natural to handle errors through return value.
497 bool init(Triple TheTriple, StringRef OutputFilename);
498
Frederic Rissb8b43d52015-03-04 22:07:44 +0000499 /// \brief Dump the file to the disk.
Frederic Riss24faade2015-09-02 16:49:13 +0000500 bool finish(const DebugMap &);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000501
502 AsmPrinter &getAsmPrinter() const { return *Asm; }
503
504 /// \brief Set the current output section to debug_info and change
505 /// the MC Dwarf version to \p DwarfVersion.
506 void switchToDebugInfoSection(unsigned DwarfVersion);
507
508 /// \brief Emit the compilation unit header for \p Unit in the
509 /// debug_info section.
510 ///
511 /// As a side effect, this also switches the current Dwarf version
512 /// of the MC layer to the one of U.getOrigUnit().
513 void emitCompileUnitHeader(CompileUnit &Unit);
514
515 /// \brief Recursively emit the DIE tree rooted at \p Die.
516 void emitDIE(DIE &Die);
517
518 /// \brief Emit the abbreviation table \p Abbrevs to the
519 /// debug_abbrev section.
David Blaikie6196aa02015-11-18 00:34:10 +0000520 void emitAbbrevs(const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000521
522 /// \brief Emit the string table described by \p Pool.
523 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000524
525 /// \brief Emit debug_ranges for \p FuncRange by translating the
526 /// original \p Entries.
527 void emitRangesEntries(
528 int64_t UnitPcOffset, uint64_t OrigLowPc,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000529 const FunctionIntervals::const_iterator &FuncRange,
Frederic Riss25440872015-03-13 23:30:31 +0000530 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
531 unsigned AddressSize);
532
Frederic Riss563b1b02015-03-14 03:46:51 +0000533 /// \brief Emit debug_aranges entries for \p Unit and if \p
534 /// DoRangesSection is true, also emit the debug_ranges entries for
535 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
536 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000537
538 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000539
540 /// \brief Emit the debug_loc contribution for \p Unit by copying
541 /// the entries from \p Dwarf and offseting them. Update the
542 /// location attributes to point to the new entries.
543 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000544
545 /// \brief Emit the line table described in \p Rows into the
546 /// debug_line section.
Frederic Rissa5e14532015-08-07 15:14:13 +0000547 void emitLineTableForUnit(MCDwarfLineTableParams Params,
548 StringRef PrologueBytes, unsigned MinInstLength,
Frederic Riss63786b02015-03-15 20:45:43 +0000549 std::vector<DWARFDebugLine::Row> &Rows,
550 unsigned AdddressSize);
551
552 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000553
554 /// \brief Emit the .debug_pubnames contribution for \p Unit.
555 void emitPubNamesForUnit(const CompileUnit &Unit);
556
557 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
558 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000559
560 /// \brief Emit a CIE.
561 void emitCIE(StringRef CIEBytes);
562
563 /// \brief Emit an FDE with data \p Bytes.
564 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
565 StringRef Bytes);
566
567 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000568};
569
570bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
571 std::string ErrorStr;
572 std::string TripleName;
573 StringRef Context = "dwarf streamer init";
574
575 // Get the target.
576 const Target *TheTarget =
577 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
578 if (!TheTarget)
579 return error(ErrorStr, Context);
580 TripleName = TheTriple.getTriple();
581
582 // Create all the MC Objects.
583 MRI.reset(TheTarget->createMCRegInfo(TripleName));
584 if (!MRI)
585 return error(Twine("no register info for target ") + TripleName, Context);
586
587 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
588 if (!MAI)
589 return error("no asm info for target " + TripleName, Context);
590
591 MOFI.reset(new MCObjectFileInfo);
592 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Rafael Espindola699281c2016-05-18 11:58:50 +0000593 MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, CodeModel::Default, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000594
Joel Jones373d7d32016-07-25 17:18:28 +0000595 MCTargetOptions Options;
596 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "", Options);
Frederic Rissc99ea202015-02-28 00:29:11 +0000597 if (!MAB)
598 return error("no asm backend for target " + TripleName, Context);
599
600 MII.reset(TheTarget->createMCInstrInfo());
601 if (!MII)
602 return error("no instr info info for target " + TripleName, Context);
603
604 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
605 if (!MSTI)
606 return error("no subtarget info for target " + TripleName, Context);
607
Eric Christopher0169e422015-03-10 22:03:14 +0000608 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000609 if (!MCE)
610 return error("no code emitter for target " + TripleName, Context);
611
612 // Create the output file.
613 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000614 OutFile =
615 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000616 if (EC)
617 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
618
David Majnemer03e2cc32015-12-21 22:09:27 +0000619 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
620 MS = TheTarget->createMCObjectStreamer(
621 TheTriple, *MC, *MAB, *OutFile, MCE, *MSTI, MCOptions.MCRelaxAll,
622 MCOptions.MCIncrementalLinkerCompatible,
623 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000624 if (!MS)
625 return error("no object streamer for target " + TripleName, Context);
626
627 // Finally create the AsmPrinter we'll use to emit the DIEs.
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000628 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
629 None));
Frederic Rissc99ea202015-02-28 00:29:11 +0000630 if (!TM)
631 return error("no target machine for target " + TripleName, Context);
632
633 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
634 if (!Asm)
635 return error("no asm printer for target " + TripleName, Context);
636
Frederic Riss25440872015-03-13 23:30:31 +0000637 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000638 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000639 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000640 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000641
Frederic Rissc99ea202015-02-28 00:29:11 +0000642 return true;
643}
644
Frederic Riss24faade2015-09-02 16:49:13 +0000645bool DwarfStreamer::finish(const DebugMap &DM) {
646 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
647 return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
648
Frederic Rissc99ea202015-02-28 00:29:11 +0000649 MS->Finish();
650 return true;
651}
652
Frederic Rissb8b43d52015-03-04 22:07:44 +0000653/// \brief Set the current output section to debug_info and change
654/// the MC Dwarf version to \p DwarfVersion.
655void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
656 MS->SwitchSection(MOFI->getDwarfInfoSection());
657 MC->setDwarfVersion(DwarfVersion);
658}
659
660/// \brief Emit the compilation unit header for \p Unit in the
661/// debug_info section.
662///
663/// A Dwarf scetion header is encoded as:
664/// uint32_t Unit length (omiting this field)
665/// uint16_t Version
666/// uint32_t Abbreviation table offset
667/// uint8_t Address size
668///
669/// Leading to a total of 11 bytes.
670void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
671 unsigned Version = Unit.getOrigUnit().getVersion();
672 switchToDebugInfoSection(Version);
673
674 // Emit size of content not including length itself. The size has
675 // already been computed in CompileUnit::computeOffsets(). Substract
676 // 4 to that size to account for the length field.
677 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
678 Asm->EmitInt16(Version);
679 // We share one abbreviations table across all units so it's always at the
680 // start of the section.
681 Asm->EmitInt32(0);
682 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
683}
684
685/// \brief Emit the \p Abbrevs array as the shared abbreviation table
686/// for the linked Dwarf file.
David Blaikie6196aa02015-11-18 00:34:10 +0000687void DwarfStreamer::emitAbbrevs(
688 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs) {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000689 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
690 Asm->emitDwarfAbbrevs(Abbrevs);
691}
692
693/// \brief Recursively emit the DIE tree rooted at \p Die.
694void DwarfStreamer::emitDIE(DIE &Die) {
695 MS->SwitchSection(MOFI->getDwarfInfoSection());
696 Asm->emitDwarfDIE(Die);
697}
698
Frederic Rissef648462015-03-06 17:56:30 +0000699/// \brief Emit the debug_str section stored in \p Pool.
700void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000701 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000702 for (auto *Entry = Pool.getFirstEntry(); Entry;
703 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000704 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000705 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
706}
707
Frederic Riss25440872015-03-13 23:30:31 +0000708/// \brief Emit the debug_range section contents for \p FuncRange by
709/// translating the original \p Entries. The debug_range section
710/// format is totally trivial, consisting just of pairs of address
711/// sized addresses describing the ranges.
712void DwarfStreamer::emitRangesEntries(
713 int64_t UnitPcOffset, uint64_t OrigLowPc,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000714 const FunctionIntervals::const_iterator &FuncRange,
Frederic Riss25440872015-03-13 23:30:31 +0000715 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
716 unsigned AddressSize) {
717 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
718
719 // Offset each range by the right amount.
Frederic Riss94546202015-08-31 05:09:32 +0000720 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
Frederic Riss25440872015-03-13 23:30:31 +0000721 for (const auto &Range : Entries) {
722 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
723 warn("unsupported base address selection operation",
724 "emitting debug_ranges");
725 break;
726 }
727 // Do not emit empty ranges.
728 if (Range.StartAddress == Range.EndAddress)
729 continue;
730
731 // All range entries should lie in the function range.
732 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
733 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
734 warn("inconsistent range data.", "emitting debug_ranges");
735 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
736 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
737 RangesSectionSize += 2 * AddressSize;
738 }
739
740 // Add the terminator entry.
741 MS->EmitIntValue(0, AddressSize);
742 MS->EmitIntValue(0, AddressSize);
743 RangesSectionSize += 2 * AddressSize;
744}
745
Frederic Riss563b1b02015-03-14 03:46:51 +0000746/// \brief Emit the debug_aranges contribution of a unit and
747/// if \p DoDebugRanges is true the debug_range contents for a
748/// compile_unit level DW_AT_ranges attribute (Which are basically the
749/// same thing with a different base address).
750/// Just aggregate all the ranges gathered inside that unit.
751void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
752 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000753 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
754 // Gather the ranges in a vector, so that we can simplify them. The
755 // IntervalMap will have coalesced the non-linked ranges, but here
756 // we want to coalesce the linked addresses.
757 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
758 const auto &FunctionRanges = Unit.getFunctionRanges();
759 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
760 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000761 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
762 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000763
764 // The object addresses where sorted, but again, the linked
765 // addresses might end up in a different order.
766 std::sort(Ranges.begin(), Ranges.end());
767
Frederic Riss563b1b02015-03-14 03:46:51 +0000768 if (!Ranges.empty()) {
769 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
770
Rafael Espindola9ab09232015-03-17 20:07:06 +0000771 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
772 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000773
774 unsigned HeaderSize =
775 sizeof(int32_t) + // Size of contents (w/o this field
776 sizeof(int16_t) + // DWARF ARange version number
777 sizeof(int32_t) + // Offset of CU in the .debug_info section
778 sizeof(int8_t) + // Pointer Size (in bytes)
779 sizeof(int8_t); // Segment Size (in bytes)
780
781 unsigned TupleSize = AddressSize * 2;
782 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
783
784 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000785 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000786 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
787 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
788 Asm->EmitInt8(AddressSize); // Address size
789 Asm->EmitInt8(0); // Segment size
790
Petr Hosekfaef3202016-06-01 01:59:58 +0000791 Asm->OutStreamer->emitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000792
793 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
794 ++Range) {
795 uint64_t RangeStart = Range->first;
796 MS->EmitIntValue(RangeStart, AddressSize);
797 while ((Range + 1) != End && Range->second == (Range + 1)->first)
798 ++Range;
799 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
800 }
801
802 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000803 Asm->OutStreamer->EmitIntValue(0, AddressSize);
804 Asm->OutStreamer->EmitIntValue(0, AddressSize);
805 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000806 }
807
808 if (!DoDebugRanges)
809 return;
810
811 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
812 // Offset each range by the right amount.
813 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000814 // Emit coalesced ranges.
815 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000816 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000817 while (Range + 1 != End && Range->second == (Range + 1)->first)
818 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000819 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000820 RangesSectionSize += 2 * AddressSize;
821 }
822
823 // Add the terminator entry.
824 MS->EmitIntValue(0, AddressSize);
825 MS->EmitIntValue(0, AddressSize);
826 RangesSectionSize += 2 * AddressSize;
827}
828
Frederic Rissdfb97902015-03-14 15:49:07 +0000829/// \brief Emit location lists for \p Unit and update attribtues to
830/// point to the new entries.
831void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
832 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000833 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000834
835 if (Attributes.empty())
836 return;
837
838 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
839
840 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
841 const DWARFSection &InputSec = Dwarf.getLocSection();
842 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
843 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Greg Claytonc8c10322016-12-13 18:25:19 +0000844 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000845 int64_t UnitPcOffset = 0;
Greg Clayton52fe1f62016-12-14 22:38:08 +0000846 auto OrigLowPc = OrigUnitDie.getAttributeValueAsAddress(dwarf::DW_AT_low_pc);
847 if (OrigLowPc)
848 UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc();
Frederic Rissdfb97902015-03-14 15:49:07 +0000849
850 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000851 uint32_t Offset = Attr.first.get();
852 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000853 // This is the quantity to add to the old location address to get
854 // the correct address for the new one.
855 int64_t LocPcOffset = Attr.second + UnitPcOffset;
856 while (Data.isValidOffset(Offset)) {
857 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
858 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
859 LocSectionSize += 2 * AddressSize;
860 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000861 Asm->OutStreamer->EmitIntValue(0, AddressSize);
862 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000863 break;
864 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000865 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
866 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000867 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000868 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000869 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000870 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000871 StringRef(InputSec.Data.substr(Offset, Length)));
872 Offset += Length;
873 LocSectionSize += Length + 2;
874 }
875 }
876}
877
Frederic Rissa5e14532015-08-07 15:14:13 +0000878void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
879 StringRef PrologueBytes,
Frederic Riss63786b02015-03-15 20:45:43 +0000880 unsigned MinInstLength,
881 std::vector<DWARFDebugLine::Row> &Rows,
882 unsigned PointerSize) {
883 // Switch to the section where the table will be emitted into.
884 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000885 MCSymbol *LineStartSym = MC->createTempSymbol();
886 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000887
888 // The first 4 bytes is the total length of the information for this
889 // compilation unit (not including these 4 bytes for the length).
890 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000891 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000892 // Copy Prologue.
893 MS->EmitBytes(PrologueBytes);
894 LineSectionSize += PrologueBytes.size() + 4;
895
Frederic Rissc3820d02015-03-15 22:20:28 +0000896 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000897 raw_svector_ostream EncodingOS(EncodingBuffer);
898
899 if (Rows.empty()) {
900 // We only have the dummy entry, dsymutil emits an entry with a 0
901 // address in that case.
Frederic Rissa5e14532015-08-07 15:14:13 +0000902 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000903 MS->EmitBytes(EncodingOS.str());
904 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000905 MS->EmitLabel(LineEndSym);
906 return;
907 }
908
909 // Line table state machine fields
910 unsigned FileNum = 1;
911 unsigned LastLine = 1;
912 unsigned Column = 0;
913 unsigned IsStatement = 1;
914 unsigned Isa = 0;
915 uint64_t Address = -1ULL;
916
917 unsigned RowsSinceLastSequence = 0;
918
919 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
920 auto &Row = Rows[Idx];
921
922 int64_t AddressDelta;
923 if (Address == -1ULL) {
924 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
925 MS->EmitULEB128IntValue(PointerSize + 1);
926 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
927 MS->EmitIntValue(Row.Address, PointerSize);
928 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
929 AddressDelta = 0;
930 } else {
931 AddressDelta = (Row.Address - Address) / MinInstLength;
932 }
933
934 // FIXME: code copied and transfromed from
935 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
936 // this code, but the current compatibility requirement with
937 // classic dsymutil makes it hard. Revisit that once this
938 // requirement is dropped.
939
940 if (FileNum != Row.File) {
941 FileNum = Row.File;
942 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
943 MS->EmitULEB128IntValue(FileNum);
944 LineSectionSize += 1 + getULEB128Size(FileNum);
945 }
946 if (Column != Row.Column) {
947 Column = Row.Column;
948 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
949 MS->EmitULEB128IntValue(Column);
950 LineSectionSize += 1 + getULEB128Size(Column);
951 }
952
953 // FIXME: We should handle the discriminator here, but dsymutil
954 // doesn' consider it, thus ignore it for now.
955
956 if (Isa != Row.Isa) {
957 Isa = Row.Isa;
958 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
959 MS->EmitULEB128IntValue(Isa);
960 LineSectionSize += 1 + getULEB128Size(Isa);
961 }
962 if (IsStatement != Row.IsStmt) {
963 IsStatement = Row.IsStmt;
964 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
965 LineSectionSize += 1;
966 }
967 if (Row.BasicBlock) {
968 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
969 LineSectionSize += 1;
970 }
971
972 if (Row.PrologueEnd) {
973 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
974 LineSectionSize += 1;
975 }
976
977 if (Row.EpilogueBegin) {
978 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
979 LineSectionSize += 1;
980 }
981
982 int64_t LineDelta = int64_t(Row.Line) - LastLine;
983 if (!Row.EndSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000984 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000985 MS->EmitBytes(EncodingOS.str());
986 LineSectionSize += EncodingBuffer.size();
987 EncodingBuffer.resize(0);
988 Address = Row.Address;
989 LastLine = Row.Line;
990 RowsSinceLastSequence++;
991 } else {
992 if (LineDelta) {
993 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
994 MS->EmitSLEB128IntValue(LineDelta);
995 LineSectionSize += 1 + getSLEB128Size(LineDelta);
996 }
997 if (AddressDelta) {
998 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
999 MS->EmitULEB128IntValue(AddressDelta);
1000 LineSectionSize += 1 + getULEB128Size(AddressDelta);
1001 }
Frederic Rissa5e14532015-08-07 15:14:13 +00001002 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001003 MS->EmitBytes(EncodingOS.str());
1004 LineSectionSize += EncodingBuffer.size();
1005 EncodingBuffer.resize(0);
Frederic Riss63786b02015-03-15 20:45:43 +00001006 Address = -1ULL;
1007 LastLine = FileNum = IsStatement = 1;
1008 RowsSinceLastSequence = Column = Isa = 0;
1009 }
1010 }
1011
1012 if (RowsSinceLastSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +00001013 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001014 MS->EmitBytes(EncodingOS.str());
1015 LineSectionSize += EncodingBuffer.size();
1016 EncodingBuffer.resize(0);
1017 }
1018
1019 MS->EmitLabel(LineEndSym);
1020}
1021
Frederic Rissbce93ff2015-03-16 02:05:10 +00001022/// \brief Emit the pubnames or pubtypes section contribution for \p
1023/// Unit into \p Sec. The data is provided in \p Names.
1024void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001025 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001026 const std::vector<CompileUnit::AccelInfo> &Names) {
1027 if (Names.empty())
1028 return;
1029
1030 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001031 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001032 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1033 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001034
1035 bool HeaderEmitted = false;
1036 // Emit the pubnames for this compilation unit.
1037 for (const auto &Name : Names) {
1038 if (Name.SkipPubSection)
1039 continue;
1040
1041 if (!HeaderEmitted) {
1042 // Emit the header.
1043 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001044 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001045 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001046 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001047 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1048 HeaderEmitted = true;
1049 }
1050 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001051 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001052 StringRef(Name.Name.data(), Name.Name.size() + 1));
1053 }
1054
1055 if (!HeaderEmitted)
1056 return;
1057 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001058 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001059}
1060
1061/// \brief Emit .debug_pubnames for \p Unit.
1062void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1063 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1064 "names", Unit, Unit.getPubnames());
1065}
1066
1067/// \brief Emit .debug_pubtypes for \p Unit.
1068void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1069 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1070 "types", Unit, Unit.getPubtypes());
1071}
1072
Frederic Riss5a642072015-06-05 23:06:11 +00001073/// \brief Emit a CIE into the debug_frame section.
1074void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1075 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1076
1077 MS->EmitBytes(CIEBytes);
1078 FrameSectionSize += CIEBytes.size();
1079}
1080
1081/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1082/// contains the FDE data without the length, CIE offset and address
1083/// which will be replaced with the paramter values.
1084void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1085 uint32_t Address, StringRef FDEBytes) {
1086 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1087
1088 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1089 MS->EmitIntValue(CIEOffset, 4);
1090 MS->EmitIntValue(Address, AddrSize);
1091 MS->EmitBytes(FDEBytes);
1092 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1093}
1094
Frederic Rissd3455182015-01-28 18:27:01 +00001095/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001096///
1097/// The link of the dwarf information from the object files will be
1098/// driven by the selection of 'root DIEs', which are DIEs that
1099/// describe variables or functions that are present in the linked
1100/// binary (and thus have entries in the debug map). All the debug
1101/// information that will be linked (the DIEs, but also the line
1102/// tables, ranges, ...) is derived from that set of root DIEs.
1103///
1104/// The root DIEs are identified because they contain relocations that
1105/// correspond to a debug map entry at specific places (the low_pc for
1106/// a function, the location for a variable). These relocations are
1107/// called ValidRelocs in the DwarfLinker and are gathered as a very
1108/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001109class DwarfLinker {
1110public:
Frederic Rissb9818322015-02-28 00:29:07 +00001111 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1112 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001113 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001114
1115 /// \brief Link the contents of the DebugMap.
1116 bool link(const DebugMap &);
1117
Greg Claytonc8c10322016-12-13 18:25:19 +00001118 void reportWarning(const Twine &Warning,
1119 const DWARFDie *DIE = nullptr) const;
Adrian Prantlc3021ee2015-09-22 18:50:51 +00001120
Frederic Rissd3455182015-01-28 18:27:01 +00001121private:
Frederic Riss563cba62015-01-28 22:15:14 +00001122 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001123 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001124
1125 /// \brief Called at the end of a debug object link.
1126 void endDebugObject();
1127
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001128 /// Keeps track of relocations.
1129 class RelocationManager {
1130 struct ValidReloc {
1131 uint32_t Offset;
1132 uint32_t Size;
1133 uint64_t Addend;
1134 const DebugMapObject::DebugMapEntry *Mapping;
Frederic Riss1036e642015-02-13 23:18:22 +00001135
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001136 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1137 const DebugMapObject::DebugMapEntry *Mapping)
1138 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
Frederic Riss1036e642015-02-13 23:18:22 +00001139
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001140 bool operator<(const ValidReloc &RHS) const {
1141 return Offset < RHS.Offset;
1142 }
1143 };
1144
1145 DwarfLinker &Linker;
1146
1147 /// \brief The valid relocations for the current DebugMapObject.
1148 /// This vector is sorted by relocation offset.
1149 std::vector<ValidReloc> ValidRelocs;
1150
1151 /// \brief Index into ValidRelocs of the next relocation to
1152 /// consider. As we walk the DIEs in acsending file offset and as
1153 /// ValidRelocs is sorted by file offset, keeping this index
1154 /// uptodate is all we have to do to have a cheap lookup during the
1155 /// root DIE selection and during DIE cloning.
1156 unsigned NextValidReloc;
1157
1158 public:
1159 RelocationManager(DwarfLinker &Linker)
1160 : Linker(Linker), NextValidReloc(0) {}
1161
1162 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1163 /// \brief Reset the NextValidReloc counter.
1164 void resetValidRelocs() { NextValidReloc = 0; }
1165
1166 /// \defgroup FindValidRelocations Translate debug map into a list
1167 /// of relevant relocations
1168 ///
1169 /// @{
1170 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1171 const DebugMapObject &DMO);
1172
1173 bool findValidRelocs(const object::SectionRef &Section,
1174 const object::ObjectFile &Obj,
1175 const DebugMapObject &DMO);
1176
1177 void findValidRelocsMachO(const object::SectionRef &Section,
1178 const object::MachOObjectFile &Obj,
1179 const DebugMapObject &DMO);
1180 /// @}
1181
1182 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1183 CompileUnit::DIEInfo &Info);
1184
1185 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1186 bool isLittleEndian);
Frederic Riss1036e642015-02-13 23:18:22 +00001187 };
1188
Frederic Riss84c09a52015-02-13 23:18:34 +00001189 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1190 ///
1191 /// @{
1192 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1193 /// keep. Store that information in \p CU's DIEInfo.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001194 void lookForDIEsToKeep(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00001195 const DWARFDie &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001196 const DebugMapObject &DMO, CompileUnit &CU,
1197 unsigned Flags);
1198
Adrian Prantle5162db2015-09-22 22:20:50 +00001199 /// If this compile unit is really a skeleton CU that points to a
1200 /// clang module, register it in ClangModules and return true.
1201 ///
1202 /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
1203 /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
1204 /// hash.
Greg Claytonc8c10322016-12-13 18:25:19 +00001205 bool registerModuleReference(const DWARFDie &CUDie,
Adrian Prantle5162db2015-09-22 22:20:50 +00001206 const DWARFUnit &Unit, DebugMap &ModuleMap,
1207 unsigned Indent = 0);
1208
1209 /// Recursively add the debug info in this clang module .pcm
1210 /// file (and all the modules imported by it in a bottom-up fashion)
1211 /// to Units.
Adrian Prantla112ef92015-09-23 17:35:52 +00001212 void loadClangModule(StringRef Filename, StringRef ModulePath,
1213 StringRef ModuleName, uint64_t DwoId,
Adrian Prantle5162db2015-09-22 22:20:50 +00001214 DebugMap &ModuleMap, unsigned Indent = 0);
1215
Frederic Riss84c09a52015-02-13 23:18:34 +00001216 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1217 enum TravesalFlags {
1218 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1219 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1220 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1221 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001222 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss29eedc72015-09-11 04:17:30 +00001223 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
Frederic Riss84c09a52015-02-13 23:18:34 +00001224 };
1225
1226 /// \brief Mark the passed DIE as well as all the ones it depends on
1227 /// as kept.
Adrian Prantl6ec47122015-09-22 15:31:14 +00001228 void keepDIEAndDependencies(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00001229 const DWARFDie &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001230 CompileUnit::DIEInfo &MyInfo,
1231 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001232 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001233
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001234 unsigned shouldKeepDIE(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00001235 const DWARFDie &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001236 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1237 unsigned Flags);
1238
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001239 unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00001240 const DWARFDie &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001241 CompileUnit &Unit,
1242 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1243
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001244 unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00001245 const DWARFDie &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001246 CompileUnit &Unit,
1247 CompileUnit::DIEInfo &MyInfo,
1248 unsigned Flags);
1249
1250 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1251 CompileUnit::DIEInfo &Info);
1252 /// @}
1253
Frederic Rissb8b43d52015-03-04 22:07:44 +00001254 /// \defgroup Linking Methods used to link the debug information
1255 ///
1256 /// @{
Frederic Rissb8b43d52015-03-04 22:07:44 +00001257
Adrian Prantl3565af42015-09-14 16:46:10 +00001258 class DIECloner {
1259 DwarfLinker &Linker;
1260 RelocationManager &RelocMgr;
1261 /// Allocator used for all the DIEValue objects.
1262 BumpPtrAllocator &DIEAlloc;
Greg Clayton35630c32016-12-01 18:56:29 +00001263 std::vector<std::unique_ptr<CompileUnit>> &CompileUnits;
Adrian Prantl3565af42015-09-14 16:46:10 +00001264 LinkOptions Options;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001265
Adrian Prantl3565af42015-09-14 16:46:10 +00001266 public:
1267 DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1268 BumpPtrAllocator &DIEAlloc,
Greg Clayton35630c32016-12-01 18:56:29 +00001269 std::vector<std::unique_ptr<CompileUnit>> &CompileUnits,
1270 LinkOptions &Options)
Adrian Prantl3565af42015-09-14 16:46:10 +00001271 : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1272 CompileUnits(CompileUnits), Options(Options) {}
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001273
Adrian Prantl3565af42015-09-14 16:46:10 +00001274 /// Recursively clone \p InputDIE into an tree of DIE objects
1275 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1276 /// stripped out and addresses have been rewritten according to the
1277 /// debug map.
1278 ///
1279 /// \param OutOffset is the offset the cloned DIE in the output
1280 /// compile unit.
1281 /// \param PCOffset (while cloning a function scope) is the offset
1282 /// applied to the entry point of the function to get the linked address.
Greg Clayton35630c32016-12-01 18:56:29 +00001283 /// \param Die the output DIE to use, pass NULL to create one.
Adrian Prantl3565af42015-09-14 16:46:10 +00001284 /// \returns the root of the cloned tree or null if nothing was selected.
Greg Claytonc8c10322016-12-13 18:25:19 +00001285 DIE *cloneDIE(const DWARFDie &InputDIE, CompileUnit &U,
Greg Clayton35630c32016-12-01 18:56:29 +00001286 int64_t PCOffset, uint32_t OutOffset, unsigned Flags,
1287 DIE *Die = nullptr);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001288
Adrian Prantl3565af42015-09-14 16:46:10 +00001289 /// Construct the output DIE tree by cloning the DIEs we
1290 /// chose to keep above. If there are no valid relocs, then there's
1291 /// nothing to clone/emit.
1292 void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001293
Adrian Prantl3565af42015-09-14 16:46:10 +00001294 private:
1295 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
Frederic Rissbce93ff2015-03-16 02:05:10 +00001296
Adrian Prantl3565af42015-09-14 16:46:10 +00001297 /// Information gathered and exchanged between the various
1298 /// clone*Attributes helpers about the attributes of a particular DIE.
1299 struct AttributesInfo {
1300 const char *Name, *MangledName; ///< Names.
1301 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
Frederic Riss31da3242015-03-11 18:45:52 +00001302
Adrian Prantl3565af42015-09-14 16:46:10 +00001303 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1304 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1305 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
Frederic Rissbce93ff2015-03-16 02:05:10 +00001306
Adrian Prantl3565af42015-09-14 16:46:10 +00001307 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1308 bool IsDeclaration; ///< Is this DIE only a declaration?
1309
1310 AttributesInfo()
1311 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1312 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1313 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1314 };
1315
1316 /// Helper for cloneDIE.
1317 unsigned cloneAttribute(DIE &Die,
Greg Claytonc8c10322016-12-13 18:25:19 +00001318 const DWARFDie &InputDIE,
Adrian Prantl3565af42015-09-14 16:46:10 +00001319 CompileUnit &U, const DWARFFormValue &Val,
1320 const AttributeSpec AttrSpec, unsigned AttrSize,
1321 AttributesInfo &AttrInfo);
1322
1323 /// Clone a string attribute described by \p AttrSpec and add
1324 /// it to \p Die.
1325 /// \returns the size of the new attribute.
1326 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1327 const DWARFFormValue &Val,
1328 const DWARFUnit &U);
1329
1330 /// Clone an attribute referencing another DIE and add
1331 /// it to \p Die.
1332 /// \returns the size of the new attribute.
1333 unsigned
1334 cloneDieReferenceAttribute(DIE &Die,
Greg Claytonc8c10322016-12-13 18:25:19 +00001335 const DWARFDie &InputDIE,
Adrian Prantl3565af42015-09-14 16:46:10 +00001336 AttributeSpec AttrSpec, unsigned AttrSize,
1337 const DWARFFormValue &Val, CompileUnit &Unit);
1338
1339 /// Clone an attribute referencing another DIE and add
1340 /// it to \p Die.
1341 /// \returns the size of the new attribute.
1342 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1343 const DWARFFormValue &Val, unsigned AttrSize);
1344
1345 /// Clone an attribute referencing another DIE and add
1346 /// it to \p Die.
1347 /// \returns the size of the new attribute.
1348 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1349 const DWARFFormValue &Val,
1350 const CompileUnit &Unit,
1351 AttributesInfo &Info);
1352
1353 /// Clone a scalar attribute and add it to \p Die.
1354 /// \returns the size of the new attribute.
1355 unsigned cloneScalarAttribute(DIE &Die,
Greg Claytonc8c10322016-12-13 18:25:19 +00001356 const DWARFDie &InputDIE,
Adrian Prantl3565af42015-09-14 16:46:10 +00001357 CompileUnit &U, AttributeSpec AttrSpec,
1358 const DWARFFormValue &Val, unsigned AttrSize,
1359 AttributesInfo &Info);
1360
1361 /// Get the potential name and mangled name for the entity
1362 /// described by \p Die and store them in \Info if they are not
1363 /// already there.
1364 /// \returns is a name was found.
Greg Claytonc8c10322016-12-13 18:25:19 +00001365 bool getDIENames(const DWARFDie &Die, AttributesInfo &Info);
Adrian Prantl3565af42015-09-14 16:46:10 +00001366
1367 /// Create a copy of abbreviation Abbrev.
1368 void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
Frederic Riss31da3242015-03-11 18:45:52 +00001369 };
1370
Frederic Rissb8b43d52015-03-04 22:07:44 +00001371 /// \brief Assign an abbreviation number to \p Abbrev
1372 void AssignAbbrev(DIEAbbrev &Abbrev);
1373
1374 /// \brief FoldingSet that uniques the abbreviations.
1375 FoldingSet<DIEAbbrev> AbbreviationsSet;
1376 /// \brief Storage for the unique Abbreviations.
1377 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1378 /// be changed to a vecot of unique_ptrs.
David Blaikie6196aa02015-11-18 00:34:10 +00001379 std::vector<std::unique_ptr<DIEAbbrev>> Abbreviations;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001380
Frederic Riss25440872015-03-13 23:30:31 +00001381 /// \brief Compute and emit debug_ranges section for \p Unit, and
1382 /// patch the attributes referencing it.
1383 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1384
1385 /// \brief Generate and emit the DW_AT_ranges attribute for a
1386 /// compile_unit if it had one.
1387 void generateUnitRanges(CompileUnit &Unit) const;
1388
Frederic Riss63786b02015-03-15 20:45:43 +00001389 /// \brief Extract the line tables fromt he original dwarf, extract
1390 /// the relevant parts according to the linked function ranges and
1391 /// emit the result in the debug_line section.
1392 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1393
Frederic Rissbce93ff2015-03-16 02:05:10 +00001394 /// \brief Emit the accelerator entries for \p Unit.
1395 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1396
Frederic Riss5a642072015-06-05 23:06:11 +00001397 /// \brief Patch the frame info for an object file and emit it.
1398 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1399 unsigned AddressSize);
1400
Frederic Rissb8b43d52015-03-04 22:07:44 +00001401 /// \brief DIELoc objects that need to be destructed (but not freed!).
1402 std::vector<DIELoc *> DIELocs;
1403 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1404 std::vector<DIEBlock *> DIEBlocks;
1405 /// \brief Allocator used for all the DIEValue objects.
1406 BumpPtrAllocator DIEAlloc;
1407 /// @}
1408
Frederic Riss1c650942015-07-21 22:41:43 +00001409 /// ODR Contexts for that link.
1410 DeclContextTree ODRContexts;
1411
Frederic Riss1b9da422015-02-13 23:18:29 +00001412 /// \defgroup Helpers Various helper methods.
1413 ///
1414 /// @{
Benjamin Kramerc321e532016-06-08 19:09:22 +00001415 bool createStreamer(const Triple &TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001416
1417 /// \brief Attempt to load a debug object from disk.
1418 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1419 DebugMapObject &Obj,
1420 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001421 /// @}
1422
Frederic Rissd3455182015-01-28 18:27:01 +00001423 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001424 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001425 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001426 std::unique_ptr<DwarfStreamer> Streamer;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001427 uint64_t OutputDebugInfoSize;
Adrian Prantle5162db2015-09-22 22:20:50 +00001428 unsigned UnitID; ///< A unique ID that identifies each compile unit.
Frederic Riss563cba62015-01-28 22:15:14 +00001429
1430 /// The units of the current debug map object.
Greg Clayton35630c32016-12-01 18:56:29 +00001431 std::vector<std::unique_ptr<CompileUnit>> Units;
1432
Frederic Riss1b9da422015-02-13 23:18:29 +00001433
Oleg Ranevskyy5f78c5c2015-10-23 17:10:44 +00001434 /// The debug map object currently under consideration.
Frederic Riss1b9da422015-02-13 23:18:29 +00001435 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001436
1437 /// \brief The Dwarf string pool
1438 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001439
1440 /// \brief This map is keyed by the entry PC of functions in that
1441 /// debug object and the associated value is a pair storing the
1442 /// corresponding end PC and the offset to apply to get the linked
1443 /// address.
1444 ///
1445 /// See startDebugObject() for a more complete description of its use.
1446 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001447
1448 /// \brief The CIEs that have been emitted in the output
1449 /// section. The actual CIE data serves a the key to this StringMap,
1450 /// this takes care of comparing the semantics of CIEs defined in
1451 /// different object files.
1452 StringMap<uint32_t> EmittedCIEs;
1453
1454 /// Offset of the last CIE that has been emitted in the output
1455 /// debug_frame section.
1456 uint32_t LastCIEOffset;
Adrian Prantle5162db2015-09-22 22:20:50 +00001457
Adrian Prantl20937022015-09-23 17:11:10 +00001458 /// Mapping the PCM filename to the DwoId.
1459 StringMap<uint64_t> ClangModules;
Adrian Prantla9e23832016-01-14 18:31:07 +00001460
1461 bool ModuleCacheHintDisplayed = false;
1462 bool ArchiveHintDisplayed = false;
Frederic Rissd3455182015-01-28 18:27:01 +00001463};
1464
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001465/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
1466/// CompileUnit object instead.
Greg Clayton35630c32016-12-01 18:56:29 +00001467static CompileUnit *getUnitForOffset(
1468 std::vector<std::unique_ptr<CompileUnit>> &Units, unsigned Offset) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001469 auto CU =
1470 std::upper_bound(Units.begin(), Units.end(), Offset,
Greg Clayton35630c32016-12-01 18:56:29 +00001471 [](uint32_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
1472 return LHS < RHS->getOrigUnit().getNextUnitOffset();
Frederic Riss1b9da422015-02-13 23:18:29 +00001473 });
Greg Clayton35630c32016-12-01 18:56:29 +00001474 return CU != Units.end() ? CU->get() : nullptr;
Frederic Riss1b9da422015-02-13 23:18:29 +00001475}
1476
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001477/// Resolve the DIE attribute reference that has been
Frederic Riss1b9da422015-02-13 23:18:29 +00001478/// extracted in \p RefValue. The resulting DIE migh be in another
1479/// CompileUnit which is stored into \p ReferencedCU.
1480/// \returns null if resolving fails for any reason.
Greg Claytonc8c10322016-12-13 18:25:19 +00001481static DWARFDie resolveDIEReference(
Greg Clayton35630c32016-12-01 18:56:29 +00001482 const DwarfLinker &Linker, std::vector<std::unique_ptr<CompileUnit>> &Units,
Frederic Riss1c650942015-07-21 22:41:43 +00001483 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Greg Claytonc8c10322016-12-13 18:25:19 +00001484 const DWARFDie &DIE, CompileUnit *&RefCU) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001485 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
Greg Claytoncddab272016-10-31 16:46:02 +00001486 uint64_t RefOffset = *RefValue.getAsReference();
Frederic Riss1b9da422015-02-13 23:18:29 +00001487
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001488 if ((RefCU = getUnitForOffset(Units, RefOffset)))
Greg Claytonc8c10322016-12-13 18:25:19 +00001489 if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
Frederic Riss1b9da422015-02-13 23:18:29 +00001490 return RefDie;
1491
Greg Claytonc8c10322016-12-13 18:25:19 +00001492 Linker.reportWarning("could not find referenced DIE", &DIE);
1493 return DWARFDie();
Frederic Riss1b9da422015-02-13 23:18:29 +00001494}
1495
Frederic Riss1c650942015-07-21 22:41:43 +00001496/// \returns whether the passed \a Attr type might contain a DIE
1497/// reference suitable for ODR uniquing.
1498static bool isODRAttribute(uint16_t Attr) {
1499 switch (Attr) {
1500 default:
1501 return false;
1502 case dwarf::DW_AT_type:
1503 case dwarf::DW_AT_containing_type:
1504 case dwarf::DW_AT_specification:
1505 case dwarf::DW_AT_abstract_origin:
1506 case dwarf::DW_AT_import:
1507 return true;
1508 }
1509 llvm_unreachable("Improper attribute.");
1510}
1511
1512/// Set the last DIE/CU a context was seen in and, possibly invalidate
1513/// the context if it is ambiguous.
1514///
1515/// In the current implementation, we don't handle overloaded
1516/// functions well, because the argument types are not taken into
1517/// account when computing the DeclContext tree.
1518///
1519/// Some of this is mitigated byt using mangled names that do contain
1520/// the arguments types, but sometimes (eg. with function templates)
1521/// we don't have that. In that case, just do not unique anything that
1522/// refers to the contexts we are not able to distinguish.
1523///
1524/// If a context that is not a namespace appears twice in the same CU,
1525/// we know it is ambiguous. Make it invalid.
1526bool DeclContext::setLastSeenDIE(CompileUnit &U,
Greg Claytonc8c10322016-12-13 18:25:19 +00001527 const DWARFDie &Die) {
Frederic Riss1c650942015-07-21 22:41:43 +00001528 if (LastSeenCompileUnitID == U.getUniqueID()) {
1529 DWARFUnit &OrigUnit = U.getOrigUnit();
1530 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1531 U.getInfo(FirstIdx).Ctxt = nullptr;
1532 return false;
1533 }
1534
1535 LastSeenCompileUnitID = U.getUniqueID();
1536 LastSeenDIE = Die;
1537 return true;
1538}
1539
Frederic Riss1c650942015-07-21 22:41:43 +00001540PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
Greg Claytonc8c10322016-12-13 18:25:19 +00001541 DeclContext &Context, const DWARFDie &DIE, CompileUnit &U,
Adrian Prantl42562c32015-10-02 00:27:08 +00001542 NonRelocatableStringpool &StringPool, bool InClangModule) {
Greg Claytonc8c10322016-12-13 18:25:19 +00001543 unsigned Tag = DIE.getTag();
Frederic Riss1c650942015-07-21 22:41:43 +00001544
1545 // FIXME: dsymutil-classic compat: We should bail out here if we
1546 // have a specification or an abstract_origin. We will get the
1547 // parent context wrong here.
1548
1549 switch (Tag) {
1550 default:
1551 // By default stop gathering child contexts.
1552 return PointerIntPair<DeclContext *, 1>(nullptr);
Adrian Prantla112ef92015-09-23 17:35:52 +00001553 case dwarf::DW_TAG_module:
1554 break;
Frederic Riss1c650942015-07-21 22:41:43 +00001555 case dwarf::DW_TAG_compile_unit:
Frederic Riss1c650942015-07-21 22:41:43 +00001556 return PointerIntPair<DeclContext *, 1>(&Context);
1557 case dwarf::DW_TAG_subprogram:
1558 // Do not unique anything inside CU local functions.
1559 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1560 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
Greg Claytond1efea82017-01-11 17:43:37 +00001561 !DIE.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_external)
1562 .getValueOr(0))
Frederic Riss1c650942015-07-21 22:41:43 +00001563 return PointerIntPair<DeclContext *, 1>(nullptr);
Justin Bognerb03fd122016-08-17 05:10:15 +00001564 LLVM_FALLTHROUGH;
Frederic Riss1c650942015-07-21 22:41:43 +00001565 case dwarf::DW_TAG_member:
1566 case dwarf::DW_TAG_namespace:
1567 case dwarf::DW_TAG_structure_type:
1568 case dwarf::DW_TAG_class_type:
1569 case dwarf::DW_TAG_union_type:
1570 case dwarf::DW_TAG_enumeration_type:
1571 case dwarf::DW_TAG_typedef:
1572 // Artificial things might be ambiguous, because they might be
1573 // created on demand. For example implicitely defined constructors
1574 // are ambiguous because of the way we identify contexts, and they
1575 // won't be generated everytime everywhere.
Greg Claytond1efea82017-01-11 17:43:37 +00001576 if (DIE.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_artificial)
1577 .getValueOr(0))
Frederic Riss1c650942015-07-21 22:41:43 +00001578 return PointerIntPair<DeclContext *, 1>(nullptr);
1579 break;
1580 }
1581
Greg Claytonc8c10322016-12-13 18:25:19 +00001582 const char *Name = DIE.getName(DINameKind::LinkageName);
1583 const char *ShortName = DIE.getName(DINameKind::ShortName);
Frederic Riss1c650942015-07-21 22:41:43 +00001584 StringRef NameRef;
1585 StringRef ShortNameRef;
1586 StringRef FileRef;
1587
1588 if (Name)
1589 NameRef = StringPool.internString(Name);
1590 else if (Tag == dwarf::DW_TAG_namespace)
1591 // FIXME: For dsymutil-classic compatibility. I think uniquing
1592 // within anonymous namespaces is wrong. There is no ODR guarantee
1593 // there.
1594 NameRef = StringPool.internString("(anonymous namespace)");
1595
1596 if (ShortName && ShortName != Name)
1597 ShortNameRef = StringPool.internString(ShortName);
1598 else
1599 ShortNameRef = NameRef;
1600
1601 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1602 Tag != dwarf::DW_TAG_union_type &&
1603 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1604 return PointerIntPair<DeclContext *, 1>(nullptr);
1605
Frederic Riss1c650942015-07-21 22:41:43 +00001606 unsigned Line = 0;
Adrian Prantl42562c32015-10-02 00:27:08 +00001607 unsigned ByteSize = UINT32_MAX;
Frederic Riss1c650942015-07-21 22:41:43 +00001608
Adrian Prantl42562c32015-10-02 00:27:08 +00001609 if (!InClangModule) {
1610 // Gather some discriminating data about the DeclContext we will be
1611 // creating: File, line number and byte size. This shouldn't be
1612 // necessary, because the ODR is just about names, but given that we
1613 // do some approximations with overloaded functions and anonymous
1614 // namespaces, use these additional data points to make the process
1615 // safer. This is disabled for clang modules, because forward
1616 // declarations of module-defined types do not have a file and line.
Greg Claytond1efea82017-01-11 17:43:37 +00001617 ByteSize = DIE.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_byte_size)
1618 .getValueOr(UINT64_MAX);
Adrian Prantl42562c32015-10-02 00:27:08 +00001619 if (Tag != dwarf::DW_TAG_namespace || !Name) {
Greg Claytond1efea82017-01-11 17:43:37 +00001620 if (unsigned FileNum =
1621 DIE.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_decl_file)
1622 .getValueOr(0)) {
Adrian Prantl42562c32015-10-02 00:27:08 +00001623 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1624 &U.getOrigUnit())) {
1625 // FIXME: dsymutil-classic compatibility. I'd rather not
1626 // unique anything in anonymous namespaces, but if we do, then
1627 // verify that the file and line correspond.
1628 if (!Name && Tag == dwarf::DW_TAG_namespace)
1629 FileNum = 1;
Frederic Riss1c650942015-07-21 22:41:43 +00001630
Adrian Prantl42562c32015-10-02 00:27:08 +00001631 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1632 // instead of "" would allow more uniquing, but for now, do
1633 // it this way to match dsymutil-classic.
Pete Cooperb2ba7762016-07-22 01:41:32 +00001634 if (LT->hasFileAtIndex(FileNum)) {
Greg Claytond1efea82017-01-11 17:43:37 +00001635 Line =
1636 DIE.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_decl_line)
1637 .getValueOr(0);
Adrian Prantl42562c32015-10-02 00:27:08 +00001638 // Cache the resolved paths, because calling realpath is expansive.
Pete Cooperef4e36a2016-03-18 03:48:09 +00001639 StringRef ResolvedPath = U.getResolvedPath(FileNum);
1640 if (!ResolvedPath.empty()) {
1641 FileRef = ResolvedPath;
Adrian Prantl42562c32015-10-02 00:27:08 +00001642 } else {
Pete Cooperb2ba7762016-07-22 01:41:32 +00001643 std::string File;
1644 bool gotFileName =
1645 LT->getFileNameByIndex(FileNum, "",
1646 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1647 File);
1648 (void)gotFileName;
1649 assert(gotFileName && "Must get file name from line table");
Pete Coopercadadaa2016-07-22 01:52:58 +00001650#ifdef HAVE_REALPATH
Adrian Prantl42562c32015-10-02 00:27:08 +00001651 char RealPath[PATH_MAX + 1];
1652 RealPath[PATH_MAX] = 0;
1653 if (::realpath(File.c_str(), RealPath))
1654 File = RealPath;
Pete Cooper64d075e2016-03-18 05:04:04 +00001655#endif
Pete Cooperef4e36a2016-03-18 03:48:09 +00001656 FileRef = StringPool.internString(File);
1657 U.setResolvedPath(FileNum, FileRef);
Adrian Prantl42562c32015-10-02 00:27:08 +00001658 }
Adrian Prantl42562c32015-10-02 00:27:08 +00001659 }
Frederic Riss1c650942015-07-21 22:41:43 +00001660 }
1661 }
1662 }
1663 }
1664
1665 if (!Line && NameRef.empty())
1666 return PointerIntPair<DeclContext *, 1>(nullptr);
1667
Frederic Riss1c650942015-07-21 22:41:43 +00001668 // We hash NameRef, which is the mangled name, in order to get most
Adrian Prantla112ef92015-09-23 17:35:52 +00001669 // overloaded functions resolve correctly.
1670 //
1671 // Strictly speaking, hashing the Tag is only necessary for a
1672 // DW_TAG_module, to prevent uniquing of a module and a namespace
1673 // with the same name.
1674 //
1675 // FIXME: dsymutil-classic won't unique the same type presented
1676 // once as a struct and once as a class. Using the Tag in the fully
1677 // qualified name hash to get the same effect.
Frederic Riss1c650942015-07-21 22:41:43 +00001678 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1679
1680 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1681 // use the filename.
1682 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1683 Hash = hash_combine(Hash, FileRef);
1684
1685 // Now look if this context already exists.
1686 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1687 auto ContextIter = Contexts.find(&Key);
1688
1689 if (ContextIter == Contexts.end()) {
1690 // The context wasn't found.
1691 bool Inserted;
1692 DeclContext *NewContext =
1693 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1694 Context, DIE, U.getUniqueID());
1695 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1696 assert(Inserted && "Failed to insert DeclContext");
1697 (void)Inserted;
1698 } else if (Tag != dwarf::DW_TAG_namespace &&
1699 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1700 // The context was found, but it is ambiguous with another context
1701 // in the same file. Mark it invalid.
1702 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1703 }
1704
1705 assert(ContextIter != Contexts.end());
1706 // FIXME: dsymutil-classic compatibility. Union types aren't
1707 // uniques, but their children might be.
1708 if ((Tag == dwarf::DW_TAG_subprogram &&
1709 Context.getTag() != dwarf::DW_TAG_structure_type &&
1710 Context.getTag() != dwarf::DW_TAG_class_type) ||
1711 (Tag == dwarf::DW_TAG_union_type))
1712 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1713
1714 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1715}
1716
Greg Claytonc8c10322016-12-13 18:25:19 +00001717bool DwarfLinker::DIECloner::getDIENames(const DWARFDie &Die,
1718 AttributesInfo &Info) {
Adrian Prantl3565af42015-09-14 16:46:10 +00001719 // FIXME: a bit wasteful as the first getName might return the
Frederic Rissbce93ff2015-03-16 02:05:10 +00001720 // short name.
1721 if (!Info.MangledName &&
Greg Claytonc8c10322016-12-13 18:25:19 +00001722 (Info.MangledName = Die.getName(DINameKind::LinkageName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001723 Info.MangledNameOffset =
1724 Linker.StringPool.getStringOffset(Info.MangledName);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001725
Greg Claytonc8c10322016-12-13 18:25:19 +00001726 if (!Info.Name && (Info.Name = Die.getName(DINameKind::ShortName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001727 Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001728
1729 return Info.Name || Info.MangledName;
1730}
1731
Frederic Riss1b9da422015-02-13 23:18:29 +00001732/// \brief Report a warning to the user, optionaly including
1733/// information about a specific \p DIE related to the warning.
Greg Claytonc8c10322016-12-13 18:25:19 +00001734void DwarfLinker::reportWarning(const Twine &Warning,
1735 const DWARFDie *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001736 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001737 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001738 Context = CurrentDebugObject->getObjectFilename();
1739 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001740
Frederic Rissb9818322015-02-28 00:29:07 +00001741 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001742 return;
1743
1744 errs() << " in DIE:\n";
Greg Claytonc8c10322016-12-13 18:25:19 +00001745 DIE->dump(errs(), 0 /* RecurseDepth */, 6 /* Indent */);
Frederic Riss1b9da422015-02-13 23:18:29 +00001746}
1747
Benjamin Kramerc321e532016-06-08 19:09:22 +00001748bool DwarfLinker::createStreamer(const Triple &TheTriple,
1749 StringRef OutputFilename) {
Frederic Rissc99ea202015-02-28 00:29:11 +00001750 if (Options.NoOutput)
1751 return true;
1752
Frederic Rissb52cf522015-02-28 00:42:37 +00001753 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001754 return Streamer->init(TheTriple, OutputFilename);
1755}
1756
Adrian Prantla112ef92015-09-23 17:35:52 +00001757/// Recursive helper to build the global DeclContext information and
1758/// gather the child->parent relationships in the original compile unit.
1759///
1760/// \return true when this DIE and all of its children are only
1761/// forward declarations to types defined in external clang modules
1762/// (i.e., forward declarations that are children of a DW_TAG_module).
Greg Claytonc8c10322016-12-13 18:25:19 +00001763static bool analyzeContextInfo(const DWARFDie &DIE,
Adrian Prantla112ef92015-09-23 17:35:52 +00001764 unsigned ParentIdx, CompileUnit &CU,
1765 DeclContext *CurrentDeclContext,
1766 NonRelocatableStringpool &StringPool,
1767 DeclContextTree &Contexts,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001768 bool InImportedModule = false) {
Frederic Riss563cba62015-01-28 22:15:14 +00001769 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001770 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1771
Adrian Prantla112ef92015-09-23 17:35:52 +00001772 // Clang imposes an ODR on modules(!) regardless of the language:
1773 // "The module-id should consist of only a single identifier,
1774 // which provides the name of the module being defined. Each
1775 // module shall have a single definition."
1776 //
1777 // This does not extend to the types inside the modules:
1778 // "[I]n C, this implies that if two structs are defined in
1779 // different submodules with the same name, those two types are
1780 // distinct types (but may be compatible types if their
1781 // definitions match)."
1782 //
1783 // We treat non-C++ modules like namespaces for this reason.
Greg Claytonc8c10322016-12-13 18:25:19 +00001784 if (DIE.getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
1785 DIE.getAttributeValueAsString(dwarf::DW_AT_name,
1786 "") != CU.getClangModuleName()) {
Adrian Prantlea8a7242015-09-23 20:44:37 +00001787 InImportedModule = true;
1788 }
Adrian Prantla112ef92015-09-23 17:35:52 +00001789
Frederic Riss1c650942015-07-21 22:41:43 +00001790 Info.ParentIdx = ParentIdx;
Adrian Prantl42562c32015-10-02 00:27:08 +00001791 bool InClangModule = CU.isClangModule() || InImportedModule;
1792 if (CU.hasODR() || InClangModule) {
Frederic Riss1c650942015-07-21 22:41:43 +00001793 if (CurrentDeclContext) {
Adrian Prantl42562c32015-10-02 00:27:08 +00001794 auto PtrInvalidPair = Contexts.getChildDeclContext(
1795 *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
Frederic Riss1c650942015-07-21 22:41:43 +00001796 CurrentDeclContext = PtrInvalidPair.getPointer();
1797 Info.Ctxt =
1798 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1799 } else
1800 Info.Ctxt = CurrentDeclContext = nullptr;
1801 }
Frederic Riss563cba62015-01-28 22:15:14 +00001802
Adrian Prantlea8a7242015-09-23 20:44:37 +00001803 Info.Prune = InImportedModule;
Greg Claytonc8c10322016-12-13 18:25:19 +00001804 if (DIE.hasChildren())
Greg Clayton93e4fe82017-01-05 23:47:37 +00001805 for (auto Child: DIE.children())
Adrian Prantla112ef92015-09-23 17:35:52 +00001806 Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001807 StringPool, Contexts, InImportedModule);
Adrian Prantla112ef92015-09-23 17:35:52 +00001808
1809 // Prune this DIE if it is either a forward declaration inside a
1810 // DW_TAG_module or a DW_TAG_module that contains nothing but
1811 // forward declarations.
Greg Claytond1efea82017-01-11 17:43:37 +00001812 Info.Prune &=
1813 (DIE.getTag() == dwarf::DW_TAG_module) ||
1814 DIE.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_declaration)
1815 .getValueOr(0);
Adrian Prantla112ef92015-09-23 17:35:52 +00001816
Adrian Prantld2793a02015-10-05 23:11:20 +00001817 // Don't prune it if there is no definition for the DIE.
1818 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
1819
Adrian Prantla112ef92015-09-23 17:35:52 +00001820 return Info.Prune;
Frederic Riss563cba62015-01-28 22:15:14 +00001821}
1822
Frederic Riss84c09a52015-02-13 23:18:34 +00001823static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1824 switch (Tag) {
1825 default:
1826 return false;
1827 case dwarf::DW_TAG_subprogram:
1828 case dwarf::DW_TAG_lexical_block:
1829 case dwarf::DW_TAG_subroutine_type:
1830 case dwarf::DW_TAG_structure_type:
1831 case dwarf::DW_TAG_class_type:
1832 case dwarf::DW_TAG_union_type:
1833 return true;
1834 }
1835 llvm_unreachable("Invalid Tag");
1836}
1837
Frederic Riss63786b02015-03-15 20:45:43 +00001838void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss63786b02015-03-15 20:45:43 +00001839 // Iterate over the debug map entries and put all the ones that are
1840 // functions (because they have a size) into the Ranges map. This
1841 // map is very similar to the FunctionRanges that are stored in each
1842 // unit, with 2 notable differences:
1843 // - obviously this one is global, while the other ones are per-unit.
1844 // - this one contains not only the functions described in the DIE
1845 // tree, but also the ones that are only in the debug map.
1846 // The latter information is required to reproduce dsymutil's logic
1847 // while linking line tables. The cases where this information
1848 // matters look like bugs that need to be investigated, but for now
1849 // we need to reproduce dsymutil's behavior.
1850 // FIXME: Once we understood exactly if that information is needed,
1851 // maybe totally remove this (or try to use it to do a real
1852 // -gline-tables-only on Darwin.
1853 for (const auto &Entry : Obj.symbols()) {
1854 const auto &Mapping = Entry.getValue();
Frederic Rissd8c33dc2016-01-31 04:29:22 +00001855 if (Mapping.Size && Mapping.ObjectAddress)
1856 Ranges[*Mapping.ObjectAddress] = std::make_pair(
1857 *Mapping.ObjectAddress + Mapping.Size,
1858 int64_t(Mapping.BinaryAddress) - *Mapping.ObjectAddress);
Frederic Riss63786b02015-03-15 20:45:43 +00001859 }
Frederic Riss563cba62015-01-28 22:15:14 +00001860}
1861
Frederic Riss1036e642015-02-13 23:18:22 +00001862void DwarfLinker::endDebugObject() {
1863 Units.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001864 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001865
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001866 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1867 (*I)->~DIEBlock();
1868 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1869 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001870
1871 DIEBlocks.clear();
1872 DIELocs.clear();
1873 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001874}
1875
Frederic Riss1d536582016-02-01 04:43:14 +00001876static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
1877 switch (Arch) {
1878 case Triple::x86:
1879 return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
1880 RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
1881 case Triple::x86_64:
1882 return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
1883 case Triple::arm:
1884 case Triple::thumb:
1885 return RelocType == MachO::ARM_RELOC_SECTDIFF ||
1886 RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1887 RelocType == MachO::ARM_RELOC_HALF ||
1888 RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
1889 case Triple::aarch64:
1890 return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
1891 default:
1892 return false;
1893 }
1894}
1895
Frederic Riss1036e642015-02-13 23:18:22 +00001896/// \brief Iterate over the relocations of the given \p Section and
1897/// store the ones that correspond to debug map entries into the
1898/// ValidRelocs array.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001899void DwarfLinker::RelocationManager::
1900findValidRelocsMachO(const object::SectionRef &Section,
1901 const object::MachOObjectFile &Obj,
1902 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001903 StringRef Contents;
1904 Section.getContents(Contents);
1905 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
Frederic Riss1d536582016-02-01 04:43:14 +00001906 bool SkipNext = false;
Frederic Riss1036e642015-02-13 23:18:22 +00001907
1908 for (const object::RelocationRef &Reloc : Section.relocations()) {
Frederic Riss1d536582016-02-01 04:43:14 +00001909 if (SkipNext) {
1910 SkipNext = false;
1911 continue;
1912 }
1913
Frederic Riss1036e642015-02-13 23:18:22 +00001914 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1915 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
Frederic Riss1d536582016-02-01 04:43:14 +00001916
1917 if (isMachOPairedReloc(Obj.getAnyRelocationType(MachOReloc),
1918 Obj.getArch())) {
1919 SkipNext = true;
1920 Linker.reportWarning(" unsupported relocation in debug_info section.");
1921 continue;
1922 }
1923
Frederic Riss1036e642015-02-13 23:18:22 +00001924 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001925 uint64_t Offset64 = Reloc.getOffset();
1926 if ((RelocSize != 4 && RelocSize != 8)) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001927 Linker.reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001928 continue;
1929 }
1930 uint32_t Offset = Offset64;
1931 // Mach-o uses REL relocations, the addend is at the relocation offset.
1932 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
Frederic Riss0314e1e2016-02-01 03:44:22 +00001933 uint64_t SymAddress;
1934 int64_t SymOffset;
1935
1936 if (Obj.isRelocationScattered(MachOReloc)) {
1937 // The address of the base symbol for scattered relocations is
1938 // stored in the reloc itself. The actual addend will store the
1939 // base address plus the offset.
1940 SymAddress = Obj.getScatteredRelocationValue(MachOReloc);
1941 SymOffset = int64_t(Addend) - SymAddress;
1942 } else {
1943 SymAddress = Addend;
1944 SymOffset = 0;
1945 }
Frederic Riss1036e642015-02-13 23:18:22 +00001946
1947 auto Sym = Reloc.getSymbol();
1948 if (Sym != Obj.symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001949 Expected<StringRef> SymbolName = Sym->getName();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001950 if (!SymbolName) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001951 consumeError(SymbolName.takeError());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001952 Linker.reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001953 continue;
1954 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001955 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001956 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
Frederic Riss0314e1e2016-02-01 03:44:22 +00001957 } else if (const auto *Mapping = DMO.lookupObjectAddress(SymAddress)) {
Frederic Riss1036e642015-02-13 23:18:22 +00001958 // Do not store the addend. The addend was the address of the
1959 // symbol in the object file, the address in the binary that is
1960 // stored in the debug map doesn't need to be offseted.
Frederic Riss0314e1e2016-02-01 03:44:22 +00001961 ValidRelocs.emplace_back(Offset64, RelocSize, SymOffset, Mapping);
Frederic Riss1036e642015-02-13 23:18:22 +00001962 }
1963 }
1964}
1965
1966/// \brief Dispatch the valid relocation finding logic to the
1967/// appropriate handler depending on the object file format.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001968bool DwarfLinker::RelocationManager::findValidRelocs(
1969 const object::SectionRef &Section, const object::ObjectFile &Obj,
1970 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001971 // Dispatch to the right handler depending on the file type.
1972 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1973 findValidRelocsMachO(Section, *MachOObj, DMO);
1974 else
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001975 Linker.reportWarning(Twine("unsupported object file type: ") +
1976 Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001977
1978 if (ValidRelocs.empty())
1979 return false;
1980
1981 // Sort the relocations by offset. We will walk the DIEs linearly in
1982 // the file, this allows us to just keep an index in the relocation
1983 // array that we advance during our walk, rather than resorting to
1984 // some associative container. See DwarfLinker::NextValidReloc.
1985 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1986 return true;
1987}
1988
1989/// \brief Look for relocations in the debug_info section that match
1990/// entries in the debug map. These relocations will drive the Dwarf
1991/// link by indicating which DIEs refer to symbols present in the
1992/// linked binary.
1993/// \returns wether there are any valid relocations in the debug info.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001994bool DwarfLinker::RelocationManager::
1995findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1996 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001997 // Find the debug_info section.
1998 for (const object::SectionRef &Section : Obj.sections()) {
1999 StringRef SectionName;
2000 Section.getName(SectionName);
2001 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
2002 if (SectionName != "debug_info")
2003 continue;
2004 return findValidRelocs(Section, Obj, DMO);
2005 }
2006 return false;
2007}
Frederic Riss563cba62015-01-28 22:15:14 +00002008
Frederic Riss84c09a52015-02-13 23:18:34 +00002009/// \brief Checks that there is a relocation against an actual debug
2010/// map entry between \p StartOffset and \p NextOffset.
2011///
2012/// This function must be called with offsets in strictly ascending
2013/// order because it never looks back at relocations it already 'went past'.
2014/// \returns true and sets Info.InDebugMap if it is the case.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002015bool DwarfLinker::RelocationManager::
2016hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
2017 CompileUnit::DIEInfo &Info) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002018 assert(NextValidReloc == 0 ||
2019 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
2020 if (NextValidReloc >= ValidRelocs.size())
2021 return false;
2022
2023 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
2024
2025 // We might need to skip some relocs that we didn't consider. For
2026 // example the high_pc of a discarded DIE might contain a reloc that
2027 // is in the list because it actually corresponds to the start of a
2028 // function that is in the debug map.
2029 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
2030 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
2031
2032 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
2033 return false;
2034
2035 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00002036 const auto &Mapping = ValidReloc.Mapping->getValue();
Frederic Rissd8c33dc2016-01-31 04:29:22 +00002037 uint64_t ObjectAddress =
2038 Mapping.ObjectAddress ? uint64_t(*Mapping.ObjectAddress) : UINT64_MAX;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002039 if (Linker.Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002040 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
Frederic Rissd8c33dc2016-01-31 04:29:22 +00002041 << " " << format("\t%016" PRIx64 " => %016" PRIx64, ObjectAddress,
Frederic Riss08462f72015-06-01 21:12:45 +00002042 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00002043
Frederic Rissd8c33dc2016-01-31 04:29:22 +00002044 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend;
2045 if (Mapping.ObjectAddress)
2046 Info.AddrAdjust -= ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00002047 Info.InDebugMap = true;
2048 return true;
2049}
2050
2051/// \brief Get the starting and ending (exclusive) offset for the
2052/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
2053/// supposed to point to the position of the first attribute described
2054/// by \p Abbrev.
2055/// \return [StartOffset, EndOffset) as a pair.
2056static std::pair<uint32_t, uint32_t>
2057getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
2058 unsigned Offset, const DWARFUnit &Unit) {
2059 DataExtractor Data = Unit.getDebugInfoExtractor();
2060
2061 for (unsigned i = 0; i < Idx; ++i)
2062 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
2063
2064 uint32_t End = Offset;
2065 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
2066
2067 return std::make_pair(Offset, End);
2068}
2069
2070/// \brief Check if a variable describing DIE should be kept.
2071/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002072unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00002073 const DWARFDie &DIE,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002074 CompileUnit &Unit,
2075 CompileUnit::DIEInfo &MyInfo,
2076 unsigned Flags) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002077 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2078
2079 // Global variables with constant value can always be kept.
2080 if (!(Flags & TF_InFunctionScope) &&
Greg Clayton6f6e4db2016-11-15 01:23:06 +00002081 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002082 MyInfo.InDebugMap = true;
2083 return Flags | TF_Keep;
2084 }
2085
Greg Clayton6f6e4db2016-11-15 01:23:06 +00002086 Optional<uint32_t> LocationIdx =
2087 Abbrev->findAttributeIndex(dwarf::DW_AT_location);
2088 if (!LocationIdx)
Frederic Riss84c09a52015-02-13 23:18:34 +00002089 return Flags;
2090
2091 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2092 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2093 uint32_t LocationOffset, LocationEndOffset;
2094 std::tie(LocationOffset, LocationEndOffset) =
Greg Clayton6f6e4db2016-11-15 01:23:06 +00002095 getAttributeOffsets(Abbrev, *LocationIdx, Offset, OrigUnit);
Frederic Riss84c09a52015-02-13 23:18:34 +00002096
2097 // See if there is a relocation to a valid debug map entry inside
2098 // this variable's location. The order is important here. We want to
2099 // always check in the variable has a valid relocation, so that the
2100 // DIEInfo is filled. However, we don't want a static variable in a
2101 // function to force us to keep the enclosing function.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002102 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
Frederic Riss84c09a52015-02-13 23:18:34 +00002103 (Flags & TF_InFunctionScope))
2104 return Flags;
2105
Frederic Rissb9818322015-02-28 00:29:07 +00002106 if (Options.Verbose)
Greg Claytonc8c10322016-12-13 18:25:19 +00002107 DIE.dump(outs(), 0, 8 /* Indent */);
Frederic Riss84c09a52015-02-13 23:18:34 +00002108
2109 return Flags | TF_Keep;
2110}
2111
2112/// \brief Check if a function describing DIE should be kept.
2113/// \returns updated TraversalFlags.
2114unsigned DwarfLinker::shouldKeepSubprogramDIE(
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002115 RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00002116 const DWARFDie &DIE, CompileUnit &Unit,
Frederic Riss84c09a52015-02-13 23:18:34 +00002117 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2118 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2119
2120 Flags |= TF_InFunctionScope;
2121
Greg Clayton6f6e4db2016-11-15 01:23:06 +00002122 Optional<uint32_t> LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2123 if (!LowPcIdx)
Frederic Riss84c09a52015-02-13 23:18:34 +00002124 return Flags;
2125
2126 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2127 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2128 uint32_t LowPcOffset, LowPcEndOffset;
2129 std::tie(LowPcOffset, LowPcEndOffset) =
Greg Clayton6f6e4db2016-11-15 01:23:06 +00002130 getAttributeOffsets(Abbrev, *LowPcIdx, Offset, OrigUnit);
Frederic Riss84c09a52015-02-13 23:18:34 +00002131
Greg Clayton52fe1f62016-12-14 22:38:08 +00002132 auto LowPc = DIE.getAttributeValueAsAddress(dwarf::DW_AT_low_pc);
2133 assert(LowPc.hasValue() && "low_pc attribute is not an address.");
2134 if (!LowPc ||
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002135 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
Frederic Riss84c09a52015-02-13 23:18:34 +00002136 return Flags;
2137
Frederic Rissb9818322015-02-28 00:29:07 +00002138 if (Options.Verbose)
Greg Claytonc8c10322016-12-13 18:25:19 +00002139 DIE.dump(outs(), 0, 8 /* Indent */);
Frederic Riss84c09a52015-02-13 23:18:34 +00002140
Frederic Riss1af75f72015-03-12 18:45:10 +00002141 Flags |= TF_Keep;
2142
Greg Clayton2520c9e2016-12-19 20:36:41 +00002143 Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
2144 if (!HighPc) {
Frederic Riss1af75f72015-03-12 18:45:10 +00002145 reportWarning("Function without high_pc. Range will be discarded.\n",
Greg Claytonc8c10322016-12-13 18:25:19 +00002146 &DIE);
Frederic Riss1af75f72015-03-12 18:45:10 +00002147 return Flags;
2148 }
2149
Frederic Riss63786b02015-03-15 20:45:43 +00002150 // Replace the debug map range with a more accurate one.
Greg Clayton2520c9e2016-12-19 20:36:41 +00002151 Ranges[*LowPc] = std::make_pair(*HighPc, MyInfo.AddrAdjust);
2152 Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00002153 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00002154}
2155
2156/// \brief Check if a DIE should be kept.
2157/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002158unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00002159 const DWARFDie &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00002160 CompileUnit &Unit,
2161 CompileUnit::DIEInfo &MyInfo,
2162 unsigned Flags) {
2163 switch (DIE.getTag()) {
2164 case dwarf::DW_TAG_constant:
2165 case dwarf::DW_TAG_variable:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002166 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002167 case dwarf::DW_TAG_subprogram:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002168 return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002169 case dwarf::DW_TAG_module:
2170 case dwarf::DW_TAG_imported_module:
2171 case dwarf::DW_TAG_imported_declaration:
2172 case dwarf::DW_TAG_imported_unit:
2173 // We always want to keep these.
2174 return Flags | TF_Keep;
Greg Clayton35630c32016-12-01 18:56:29 +00002175 default:
2176 break;
Frederic Riss84c09a52015-02-13 23:18:34 +00002177 }
2178
2179 return Flags;
2180}
2181
Frederic Riss84c09a52015-02-13 23:18:34 +00002182/// \brief Mark the passed DIE as well as all the ones it depends on
2183/// as kept.
2184///
2185/// This function is called by lookForDIEsToKeep on DIEs that are
2186/// newly discovered to be needed in the link. It recursively calls
2187/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2188/// TraversalFlags to inform it that it's not doing the primary DIE
2189/// tree walk.
Adrian Prantl6ec47122015-09-22 15:31:14 +00002190void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00002191 const DWARFDie &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002192 CompileUnit::DIEInfo &MyInfo,
2193 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002194 CompileUnit &CU, bool UseODR) {
Greg Claytonc8c10322016-12-13 18:25:19 +00002195 DWARFUnit &Unit = CU.getOrigUnit();
Frederic Riss84c09a52015-02-13 23:18:34 +00002196 MyInfo.Keep = true;
2197
2198 // First mark all the parent chain as kept.
2199 unsigned AncestorIdx = MyInfo.ParentIdx;
2200 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002201 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Greg Claytonc8c10322016-12-13 18:25:19 +00002202 lookForDIEsToKeep(RelocMgr, Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002203 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002204 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2205 }
2206
2207 // Then we need to mark all the DIEs referenced by this DIE's
2208 // attributes as kept.
2209 DataExtractor Data = Unit.getDebugInfoExtractor();
Frederic Riss36c3cb82015-09-11 04:17:25 +00002210 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2211 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
Frederic Riss84c09a52015-02-13 23:18:34 +00002212
2213 // Mark all DIEs referenced through atttributes as kept.
2214 for (const auto &AttrSpec : Abbrev->attributes()) {
2215 DWARFFormValue Val(AttrSpec.Form);
2216
2217 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2218 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2219 continue;
2220 }
2221
2222 Val.extractValue(Data, &Offset, &Unit);
2223 CompileUnit *ReferencedCU;
Greg Claytonc8c10322016-12-13 18:25:19 +00002224 if (auto RefDIE =
Greg Clayton35630c32016-12-01 18:56:29 +00002225 resolveDIEReference(*this, Units, Val, Unit, Die, ReferencedCU)) {
Frederic Riss1c650942015-07-21 22:41:43 +00002226 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2227 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2228 // If the referenced DIE has a DeclContext that has already been
2229 // emitted, then do not keep the one in this CU. We'll link to
2230 // the canonical DIE in cloneDieReferenceAttribute.
2231 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2232 // be necessary and could be advantageously replaced by
2233 // ReferencedCU->hasODR() && CU.hasODR().
2234 // FIXME: compatibility with dsymutil-classic. There is no
2235 // reason not to unique ref_addr references.
2236 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2237 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2238 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2239 continue;
2240
Adrian Prantle39475d2015-11-10 21:31:05 +00002241 // Keep a module forward declaration if there is no definition.
2242 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
2243 Info.Ctxt->getCanonicalDIEOffset()))
2244 Info.Prune = false;
2245
Frederic Riss1c650942015-07-21 22:41:43 +00002246 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Greg Claytonc8c10322016-12-13 18:25:19 +00002247 lookForDIEsToKeep(RelocMgr, RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002248 TF_Keep | TF_DependencyWalk | ODRFlag);
2249 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002250 }
2251}
2252
2253/// \brief Recursively walk the \p DIE tree and look for DIEs to
2254/// keep. Store that information in \p CU's DIEInfo.
2255///
2256/// This function is the entry point of the DIE selection
2257/// algorithm. It is expected to walk the DIE tree in file order and
2258/// (though the mediation of its helper) call hasValidRelocation() on
2259/// each DIE that might be a 'root DIE' (See DwarfLinker class
2260/// comment).
2261/// While walking the dependencies of root DIEs, this function is
2262/// also called, but during these dependency walks the file order is
2263/// not respected. The TF_DependencyWalk flag tells us which kind of
2264/// traversal we are currently doing.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002265void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
Greg Claytonc8c10322016-12-13 18:25:19 +00002266 const DWARFDie &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002267 const DebugMapObject &DMO, CompileUnit &CU,
2268 unsigned Flags) {
Greg Claytonc8c10322016-12-13 18:25:19 +00002269 unsigned Idx = CU.getOrigUnit().getDIEIndex(Die);
Frederic Riss84c09a52015-02-13 23:18:34 +00002270 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2271 bool AlreadyKept = MyInfo.Keep;
Adrian Prantla112ef92015-09-23 17:35:52 +00002272 if (MyInfo.Prune)
2273 return;
Frederic Riss84c09a52015-02-13 23:18:34 +00002274
2275 // If the Keep flag is set, we are marking a required DIE's
2276 // dependencies. If our target is already marked as kept, we're all
2277 // set.
2278 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2279 return;
2280
Adrian Prantl6ec47122015-09-22 15:31:14 +00002281 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
Frederic Riss84c09a52015-02-13 23:18:34 +00002282 // because it would screw up the relocation finding logic.
2283 if (!(Flags & TF_DependencyWalk))
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002284 Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002285
2286 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002287 if (!AlreadyKept && (Flags & TF_Keep)) {
2288 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
Adrian Prantl6ec47122015-09-22 15:31:14 +00002289 keepDIEAndDependencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
Frederic Riss1c650942015-07-21 22:41:43 +00002290 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002291 // The TF_ParentWalk flag tells us that we are currently walking up
2292 // the parent chain of a required DIE, and we don't want to mark all
2293 // the children of the parents as kept (consider for example a
2294 // DW_TAG_namespace node in the parent chain). There are however a
2295 // set of DIE types for which we want to ignore that directive and still
2296 // walk their children.
Frederic Riss36c3cb82015-09-11 04:17:25 +00002297 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
Frederic Riss84c09a52015-02-13 23:18:34 +00002298 Flags &= ~TF_ParentWalk;
2299
Frederic Riss36c3cb82015-09-11 04:17:25 +00002300 if (!Die.hasChildren() || (Flags & TF_ParentWalk))
Frederic Riss84c09a52015-02-13 23:18:34 +00002301 return;
2302
Greg Clayton93e4fe82017-01-05 23:47:37 +00002303 for (auto Child: Die.children())
Greg Claytonc8c10322016-12-13 18:25:19 +00002304 lookForDIEsToKeep(RelocMgr, Child, DMO, CU, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002305}
2306
Frederic Rissb8b43d52015-03-04 22:07:44 +00002307/// \brief Assign an abbreviation numer to \p Abbrev.
2308///
2309/// Our DIEs get freed after every DebugMapObject has been processed,
2310/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2311/// the instances hold by the DIEs. When we encounter an abbreviation
2312/// that we don't know, we create a permanent copy of it.
2313void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2314 // Check the set for priors.
2315 FoldingSetNodeID ID;
2316 Abbrev.Profile(ID);
2317 void *InsertToken;
2318 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2319
2320 // If it's newly added.
2321 if (InSet) {
2322 // Assign existing abbreviation number.
2323 Abbrev.setNumber(InSet->getNumber());
2324 } else {
2325 // Add to abbreviation list.
2326 Abbreviations.push_back(
David Blaikie6196aa02015-11-18 00:34:10 +00002327 llvm::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002328 for (const auto &Attr : Abbrev.getData())
2329 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
David Blaikie6196aa02015-11-18 00:34:10 +00002330 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002331 // Assign the unique abbreviation number.
2332 Abbrev.setNumber(Abbreviations.size());
2333 Abbreviations.back()->setNumber(Abbreviations.size());
2334 }
2335}
2336
Adrian Prantl3565af42015-09-14 16:46:10 +00002337unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2338 AttributeSpec AttrSpec,
2339 const DWARFFormValue &Val,
2340 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002341 // Switch everything to out of line strings.
Greg Claytoncddab272016-10-31 16:46:02 +00002342 const char *String = *Val.getAsCString();
Adrian Prantl3565af42015-09-14 16:46:10 +00002343 unsigned Offset = Linker.StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002344 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002345 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002346 return 4;
2347}
2348
Adrian Prantl3565af42015-09-14 16:46:10 +00002349unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
Greg Claytonc8c10322016-12-13 18:25:19 +00002350 DIE &Die, const DWARFDie &InputDIE,
Frederic Riss9833de62015-03-06 23:22:53 +00002351 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002352 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002353 const DWARFUnit &U = Unit.getOrigUnit();
Greg Claytoncddab272016-10-31 16:46:02 +00002354 uint32_t Ref = *Val.getAsReference();
Frederic Riss9833de62015-03-06 23:22:53 +00002355 DIE *NewRefDie = nullptr;
2356 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002357 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002358
Greg Claytonc8c10322016-12-13 18:25:19 +00002359 DWARFDie RefDie = resolveDIEReference(Linker, CompileUnits, Val, U, InputDIE,
2360 RefUnit);
Frederic Riss1c650942015-07-21 22:41:43 +00002361
2362 // If the referenced DIE is not found, drop the attribute.
2363 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002364 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002365
2366 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2367 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002368
2369 // If we already have emitted an equivalent DeclContext, just point
2370 // at it.
2371 if (isODRAttribute(AttrSpec.Attr)) {
2372 Ctxt = RefInfo.Ctxt;
2373 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2374 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2375 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2376 dwarf::DW_FORM_ref_addr, Attr);
Greg Claytoncddab272016-10-31 16:46:02 +00002377 return U.getRefAddrByteSize();
Frederic Riss1c650942015-07-21 22:41:43 +00002378 }
2379 }
2380
Frederic Riss9833de62015-03-06 23:22:53 +00002381 if (!RefInfo.Clone) {
2382 assert(Ref > InputDIE.getOffset());
2383 // We haven't cloned this DIE yet. Just create an empty one and
2384 // store it. It'll get really cloned when we process it.
Greg Claytonc8c10322016-12-13 18:25:19 +00002385 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002386 }
2387 NewRefDie = RefInfo.Clone;
2388
Frederic Riss1c650942015-07-21 22:41:43 +00002389 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2390 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002391 // We cannot currently rely on a DIEEntry to emit ref_addr
2392 // references, because the implementation calls back to DwarfDebug
2393 // to find the unit offset. (We don't have a DwarfDebug)
2394 // FIXME: we should be able to design DIEEntry reliance on
2395 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002396 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002397 if (Ref < InputDIE.getOffset()) {
2398 // We must have already cloned that DIE.
2399 uint32_t NewRefOffset =
2400 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002401 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002402 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2403 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002404 } else {
2405 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002406 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002407 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002408 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002409 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2410 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002411 }
Greg Claytoncddab272016-10-31 16:46:02 +00002412 return U.getRefAddrByteSize();
Frederic Riss9833de62015-03-06 23:22:53 +00002413 }
2414
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002415 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2416 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002417 return AttrSize;
2418}
2419
Adrian Prantl3565af42015-09-14 16:46:10 +00002420unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2421 AttributeSpec AttrSpec,
2422 const DWARFFormValue &Val,
2423 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002424 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002425 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002426 DIELoc *Loc = nullptr;
2427 DIEBlock *Block = nullptr;
2428 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002429 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002430 Loc = new (DIEAlloc) DIELoc;
Adrian Prantl3565af42015-09-14 16:46:10 +00002431 Linker.DIELocs.push_back(Loc);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002432 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002433 Block = new (DIEAlloc) DIEBlock;
Adrian Prantl3565af42015-09-14 16:46:10 +00002434 Linker.DIEBlocks.push_back(Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002435 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002436 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2437 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002438
2439 if (Loc)
2440 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2441 dwarf::Form(AttrSpec.Form), Loc);
2442 else
2443 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2444 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002445 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2446 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002447 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2448 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002449 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2450 // the DIE class, this if could be replaced by
2451 // Attr->setSize(Bytes.size()).
Adrian Prantl3565af42015-09-14 16:46:10 +00002452 if (Linker.Streamer) {
2453 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002454 if (Loc)
Adrian Prantl3565af42015-09-14 16:46:10 +00002455 Loc->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002456 else
Adrian Prantl3565af42015-09-14 16:46:10 +00002457 Block->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002458 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002459 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002460 return AttrSize;
2461}
2462
Adrian Prantl3565af42015-09-14 16:46:10 +00002463unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2464 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2465 const CompileUnit &Unit, AttributesInfo &Info) {
Greg Claytoncddab272016-10-31 16:46:02 +00002466 uint64_t Addr = *Val.getAsAddress();
Frederic Riss31da3242015-03-11 18:45:52 +00002467 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2468 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2469 Die.getTag() == dwarf::DW_TAG_lexical_block)
Frederic Riss7b5563a2015-08-31 01:43:14 +00002470 // The low_pc of a block or inline subroutine might get
2471 // relocated because it happens to match the low_pc of the
2472 // enclosing subprogram. To prevent issues with that, always use
2473 // the low_pc from the input DIE if relocations have been applied.
2474 Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2475 Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002476 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2477 Addr = Unit.getLowPc();
2478 if (Addr == UINT64_MAX)
2479 return 0;
2480 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002481 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002482 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002483 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2484 if (uint64_t HighPc = Unit.getHighPc())
2485 Addr = HighPc;
2486 else
2487 return 0;
2488 } else
2489 // If we have a high_pc recorded for the input DIE, use
2490 // it. Otherwise (when no relocations where applied) just use the
2491 // one we just decoded.
2492 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002493 }
2494
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002495 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002496 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002497 return Unit.getOrigUnit().getAddressByteSize();
2498}
2499
Adrian Prantl3565af42015-09-14 16:46:10 +00002500unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
Greg Claytonc8c10322016-12-13 18:25:19 +00002501 DIE &Die, const DWARFDie &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002502 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002503 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002504 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002505 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2506 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2507 if (Unit.getLowPc() == -1ULL)
2508 return 0;
2509 // Dwarf >= 4 high_pc is an size, not an address.
2510 Value = Unit.getHighPc() - Unit.getLowPc();
2511 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002512 Value = *Val.getAsSectionOffset();
2513 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2514 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002515 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2516 Value = *OptionalValue;
2517 else {
Adrian Prantl3565af42015-09-14 16:46:10 +00002518 Linker.reportWarning(
2519 "Unsupported scalar attribute form. Dropping attribute.",
Greg Claytonc8c10322016-12-13 18:25:19 +00002520 &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002521 return 0;
2522 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002523 PatchLocation Patch =
2524 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2525 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002526 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002527 Unit.noteRangeAttribute(Die, Patch);
Frederic Riss29eedc72015-09-11 04:17:30 +00002528
Frederic Rissdfb97902015-03-14 15:49:07 +00002529 // A more generic way to check for location attributes would be
2530 // nice, but it's very unlikely that any other attribute needs a
2531 // location list.
2532 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2533 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002534 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002535 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2536 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002537
Frederic Rissb8b43d52015-03-04 22:07:44 +00002538 return AttrSize;
2539}
2540
2541/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2542/// value \p Val, and add it to \p Die.
2543/// \returns the size of the cloned attribute.
Adrian Prantl3565af42015-09-14 16:46:10 +00002544unsigned DwarfLinker::DIECloner::cloneAttribute(
Greg Claytonc8c10322016-12-13 18:25:19 +00002545 DIE &Die, const DWARFDie &InputDIE, CompileUnit &Unit,
Adrian Prantl3565af42015-09-14 16:46:10 +00002546 const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2547 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002548 const DWARFUnit &U = Unit.getOrigUnit();
2549
2550 switch (AttrSpec.Form) {
2551 case dwarf::DW_FORM_strp:
2552 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002553 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002554 case dwarf::DW_FORM_ref_addr:
2555 case dwarf::DW_FORM_ref1:
2556 case dwarf::DW_FORM_ref2:
2557 case dwarf::DW_FORM_ref4:
2558 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002559 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002560 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002561 case dwarf::DW_FORM_block:
2562 case dwarf::DW_FORM_block1:
2563 case dwarf::DW_FORM_block2:
2564 case dwarf::DW_FORM_block4:
2565 case dwarf::DW_FORM_exprloc:
2566 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2567 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002568 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002569 case dwarf::DW_FORM_data1:
2570 case dwarf::DW_FORM_data2:
2571 case dwarf::DW_FORM_data4:
2572 case dwarf::DW_FORM_data8:
2573 case dwarf::DW_FORM_udata:
2574 case dwarf::DW_FORM_sdata:
2575 case dwarf::DW_FORM_sec_offset:
2576 case dwarf::DW_FORM_flag:
2577 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002578 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2579 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002580 default:
Adrian Prantl3565af42015-09-14 16:46:10 +00002581 Linker.reportWarning(
Greg Claytonc8c10322016-12-13 18:25:19 +00002582 "Unsupported attribute form in cloneAttribute. Dropping.", &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002583 }
2584
2585 return 0;
2586}
2587
Frederic Riss23e20e92015-03-07 01:25:09 +00002588/// \brief Apply the valid relocations found by findValidRelocs() to
2589/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2590/// in the debug_info section.
2591///
2592/// Like for findValidRelocs(), this function must be called with
2593/// monotonic \p BaseOffset values.
2594///
2595/// \returns wether any reloc has been applied.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002596bool DwarfLinker::RelocationManager::
2597applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2598 bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002599 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002600 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2601 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002602 if (NextValidReloc >= ValidRelocs.size())
2603 return false;
2604
2605 // Skip relocs that haven't been applied.
2606 while (NextValidReloc < ValidRelocs.size() &&
2607 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2608 ++NextValidReloc;
2609
2610 bool Applied = false;
2611 uint64_t EndOffset = BaseOffset + Data.size();
2612 while (NextValidReloc < ValidRelocs.size() &&
2613 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2614 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2615 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2616 assert(ValidReloc.Offset - BaseOffset < Data.size());
2617 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2618 char Buf[8];
2619 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2620 Value += ValidReloc.Addend;
2621 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2622 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2623 Buf[i] = uint8_t(Value >> (Index * 8));
2624 }
2625 assert(ValidReloc.Size <= sizeof(Buf));
2626 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2627 Applied = true;
2628 }
2629
2630 return Applied;
2631}
2632
Frederic Rissbce93ff2015-03-16 02:05:10 +00002633static bool isTypeTag(uint16_t Tag) {
2634 switch (Tag) {
2635 case dwarf::DW_TAG_array_type:
2636 case dwarf::DW_TAG_class_type:
2637 case dwarf::DW_TAG_enumeration_type:
2638 case dwarf::DW_TAG_pointer_type:
2639 case dwarf::DW_TAG_reference_type:
2640 case dwarf::DW_TAG_string_type:
2641 case dwarf::DW_TAG_structure_type:
2642 case dwarf::DW_TAG_subroutine_type:
2643 case dwarf::DW_TAG_typedef:
2644 case dwarf::DW_TAG_union_type:
2645 case dwarf::DW_TAG_ptr_to_member_type:
2646 case dwarf::DW_TAG_set_type:
2647 case dwarf::DW_TAG_subrange_type:
2648 case dwarf::DW_TAG_base_type:
2649 case dwarf::DW_TAG_const_type:
2650 case dwarf::DW_TAG_constant:
2651 case dwarf::DW_TAG_file_type:
2652 case dwarf::DW_TAG_namelist:
2653 case dwarf::DW_TAG_packed_type:
2654 case dwarf::DW_TAG_volatile_type:
2655 case dwarf::DW_TAG_restrict_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00002656 case dwarf::DW_TAG_atomic_type:
Frederic Rissbce93ff2015-03-16 02:05:10 +00002657 case dwarf::DW_TAG_interface_type:
2658 case dwarf::DW_TAG_unspecified_type:
2659 case dwarf::DW_TAG_shared_type:
2660 return true;
2661 default:
2662 break;
2663 }
2664 return false;
2665}
2666
Frederic Riss29eedc72015-09-11 04:17:30 +00002667static bool
2668shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2669 uint16_t Tag, bool InDebugMap, bool SkipPC,
2670 bool InFunctionScope) {
2671 switch (AttrSpec.Attr) {
2672 default:
2673 return false;
2674 case dwarf::DW_AT_low_pc:
2675 case dwarf::DW_AT_high_pc:
2676 case dwarf::DW_AT_ranges:
2677 return SkipPC;
2678 case dwarf::DW_AT_location:
2679 case dwarf::DW_AT_frame_base:
2680 // FIXME: for some reason dsymutil-classic keeps the location
2681 // attributes when they are of block type (ie. not location
2682 // lists). This is totally wrong for globals where we will keep a
2683 // wrong address. It is mostly harmless for locals, but there is
2684 // no point in keeping these anyway when the function wasn't linked.
2685 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2686 !InDebugMap)) &&
2687 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2688 }
2689}
2690
Adrian Prantl3565af42015-09-14 16:46:10 +00002691DIE *DwarfLinker::DIECloner::cloneDIE(
Greg Claytonc8c10322016-12-13 18:25:19 +00002692 const DWARFDie &InputDIE, CompileUnit &Unit,
Greg Clayton35630c32016-12-01 18:56:29 +00002693 int64_t PCOffset, uint32_t OutOffset, unsigned Flags, DIE *Die) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002694 DWARFUnit &U = Unit.getOrigUnit();
Greg Claytonc8c10322016-12-13 18:25:19 +00002695 unsigned Idx = U.getDIEIndex(InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002696 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002697
2698 // Should the DIE appear in the output?
2699 if (!Unit.getInfo(Idx).Keep)
2700 return nullptr;
2701
2702 uint32_t Offset = InputDIE.getOffset();
Greg Clayton35630c32016-12-01 18:56:29 +00002703 assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
2704 if (!Die) {
2705 // The DIE might have been already created by a forward reference
2706 // (see cloneDieReferenceAttribute()).
David Blaikie4aa81752016-12-01 22:04:16 +00002707 if (!Info.Clone)
2708 Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
2709 Die = Info.Clone;
Greg Clayton35630c32016-12-01 18:56:29 +00002710 }
2711
Frederic Riss9833de62015-03-06 23:22:53 +00002712 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002713 Die->setOffset(OutOffset);
Adrian Prantla112ef92015-09-23 17:35:52 +00002714 if ((Unit.hasODR() || Unit.isClangModule()) &&
2715 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
Frederic Riss1c650942015-07-21 22:41:43 +00002716 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2717 !Info.Ctxt->getCanonicalDIEOffset()) {
2718 // We are about to emit a DIE that is the root of its own valid
2719 // DeclContext tree. Make the current offset the canonical offset
2720 // for this context.
2721 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2722 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002723
2724 // Extract and clone every attribute.
2725 DataExtractor Data = U.getDebugInfoExtractor();
Adrian Prantle5162db2015-09-22 22:20:50 +00002726 // Point to the next DIE (generally there is always at least a NULL
2727 // entry after the current one). If this is a lone
2728 // DW_TAG_compile_unit without any children, point to the next unit.
2729 uint32_t NextOffset =
2730 (Idx + 1 < U.getNumDIEs())
Greg Claytonc8c10322016-12-13 18:25:19 +00002731 ? U.getDIEAtIndex(Idx + 1).getOffset()
Adrian Prantle5162db2015-09-22 22:20:50 +00002732 : U.getNextUnitOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002733 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002734
2735 // We could copy the data only if we need to aply a relocation to
2736 // it. After testing, it seems there is no performance downside to
2737 // doing the copy unconditionally, and it makes the code simpler.
2738 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2739 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2740 // Modify the copy with relocated addresses.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002741 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
Frederic Riss31da3242015-03-11 18:45:52 +00002742 // If we applied relocations, we store the value of high_pc that was
2743 // potentially stored in the input DIE. If high_pc is an address
2744 // (Dwarf version == 2), then it might have been relocated to a
2745 // totally unrelated value (because the end address in the object
2746 // file might be start address of another function which got moved
2747 // independantly by the linker). The computation of the actual
2748 // high_pc value is done in cloneAddressAttribute().
2749 AttrInfo.OrigHighPc =
Greg Claytond1efea82017-01-11 17:43:37 +00002750 InputDIE.getAttributeValueAsAddress(dwarf::DW_AT_high_pc).getValueOr(0);
Frederic Riss7b5563a2015-08-31 01:43:14 +00002751 // Also store the low_pc. It might get relocated in an
2752 // inline_subprogram that happens at the beginning of its
2753 // inlining function.
2754 AttrInfo.OrigLowPc =
Greg Claytond1efea82017-01-11 17:43:37 +00002755 InputDIE.getAttributeValueAsAddress(dwarf::DW_AT_low_pc)
2756 .getValueOr(UINT64_MAX);
Frederic Riss31da3242015-03-11 18:45:52 +00002757 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002758
2759 // Reset the Offset to 0 as we will be working on the local copy of
2760 // the data.
2761 Offset = 0;
2762
Frederic Rissb8b43d52015-03-04 22:07:44 +00002763 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2764 Offset += getULEB128Size(Abbrev->getCode());
2765
Frederic Riss31da3242015-03-11 18:45:52 +00002766 // We are entering a subprogram. Get and propagate the PCOffset.
2767 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2768 PCOffset = Info.AddrAdjust;
2769 AttrInfo.PCOffset = PCOffset;
2770
Frederic Riss29eedc72015-09-11 04:17:30 +00002771 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2772 Flags |= TF_InFunctionScope;
2773 if (!Info.InDebugMap)
2774 Flags |= TF_SkipPC;
2775 }
2776
2777 bool Copied = false;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002778 for (const auto &AttrSpec : Abbrev->attributes()) {
Frederic Riss29eedc72015-09-11 04:17:30 +00002779 if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2780 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2781 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2782 // FIXME: dsymutil-classic keeps the old abbreviation around
2783 // even if it's not used. We can remove this (and the copyAbbrev
2784 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2785 if (!Copied) {
2786 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2787 Copied = true;
2788 }
2789 continue;
2790 }
2791
Frederic Rissb8b43d52015-03-04 22:07:44 +00002792 DWARFFormValue Val(AttrSpec.Form);
2793 uint32_t AttrSize = Offset;
2794 Val.extractValue(Data, &Offset, &U);
2795 AttrSize = Offset - AttrSize;
2796
Frederic Riss31da3242015-03-11 18:45:52 +00002797 OutOffset +=
2798 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002799 }
2800
Frederic Rissbce93ff2015-03-16 02:05:10 +00002801 // Look for accelerator entries.
2802 uint16_t Tag = InputDIE.getTag();
2803 // FIXME: This is slightly wrong. An inline_subroutine without a
2804 // low_pc, but with AT_ranges might be interesting to get into the
2805 // accelerator tables too. For now stick with dsymutil's behavior.
2806 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2807 Tag != dwarf::DW_TAG_compile_unit &&
Greg Claytonc8c10322016-12-13 18:25:19 +00002808 getDIENames(InputDIE, AttrInfo)) {
Frederic Rissbce93ff2015-03-16 02:05:10 +00002809 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2810 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2811 AttrInfo.MangledNameOffset,
2812 Tag == dwarf::DW_TAG_inlined_subroutine);
2813 if (AttrInfo.Name)
2814 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2815 Tag == dwarf::DW_TAG_inlined_subroutine);
2816 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
Greg Claytonc8c10322016-12-13 18:25:19 +00002817 getDIENames(InputDIE, AttrInfo)) {
Frederic Rissbce93ff2015-03-16 02:05:10 +00002818 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2819 }
2820
Adrian Prantle39475d2015-11-10 21:31:05 +00002821 // Determine whether there are any children that we want to keep.
2822 bool HasChildren = false;
Greg Clayton93e4fe82017-01-05 23:47:37 +00002823 for (auto Child: InputDIE.children()) {
Adrian Prantle39475d2015-11-10 21:31:05 +00002824 unsigned Idx = U.getDIEIndex(Child);
2825 if (Unit.getInfo(Idx).Keep) {
2826 HasChildren = true;
2827 break;
2828 }
2829 }
2830
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002831 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Adrian Prantle39475d2015-11-10 21:31:05 +00002832 if (HasChildren)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002833 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2834 // Assign a permanent abbrev number
Adrian Prantl3565af42015-09-14 16:46:10 +00002835 Linker.AssignAbbrev(NewAbbrev);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002836 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002837
2838 // Add the size of the abbreviation number to the output offset.
2839 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2840
Adrian Prantle39475d2015-11-10 21:31:05 +00002841 if (!HasChildren) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002842 // Update our size.
2843 Die->setSize(OutOffset - Die->getOffset());
2844 return Die;
2845 }
2846
2847 // Recursively clone children.
Greg Clayton93e4fe82017-01-05 23:47:37 +00002848 for (auto Child: InputDIE.children()) {
Greg Claytonc8c10322016-12-13 18:25:19 +00002849 if (DIE *Clone = cloneDIE(Child, Unit, PCOffset, OutOffset, Flags)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002850 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002851 OutOffset = Clone->getOffset() + Clone->getSize();
2852 }
2853 }
2854
2855 // Account for the end of children marker.
2856 OutOffset += sizeof(int8_t);
2857 // Update our size.
2858 Die->setSize(OutOffset - Die->getOffset());
2859 return Die;
2860}
2861
Frederic Riss25440872015-03-13 23:30:31 +00002862/// \brief Patch the input object file relevant debug_ranges entries
2863/// and emit them in the output file. Update the relevant attributes
2864/// to point at the new entries.
2865void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2866 DWARFContext &OrigDwarf) const {
2867 DWARFDebugRangeList RangeList;
2868 const auto &FunctionRanges = Unit.getFunctionRanges();
2869 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2870 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2871 OrigDwarf.isLittleEndian(), AddressSize);
2872 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2873 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Greg Claytonc8c10322016-12-13 18:25:19 +00002874 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
Greg Claytond1efea82017-01-11 17:43:37 +00002875 uint64_t OrigLowPc =
2876 OrigUnitDie.getAttributeValueAsAddress(dwarf::DW_AT_low_pc)
2877 .getValueOr(-1ULL);
Frederic Riss25440872015-03-13 23:30:31 +00002878 // Ranges addresses are based on the unit's low_pc. Compute the
Sanjay Patele4b9f502015-12-07 19:21:39 +00002879 // offset we need to apply to adapt to the new unit's low_pc.
Frederic Riss25440872015-03-13 23:30:31 +00002880 int64_t UnitPcOffset = 0;
2881 if (OrigLowPc != -1ULL)
2882 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2883
2884 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002885 uint32_t Offset = RangeAttribute.get();
2886 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002887 RangeList.extract(RangeExtractor, &Offset);
2888 const auto &Entries = RangeList.getEntries();
Frederic Riss94546202015-08-31 05:09:32 +00002889 if (!Entries.empty()) {
2890 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
Frederic Riss25440872015-03-13 23:30:31 +00002891
Frederic Riss25440872015-03-13 23:30:31 +00002892 if (CurrRange == InvalidRange ||
Frederic Riss94546202015-08-31 05:09:32 +00002893 First.StartAddress + OrigLowPc < CurrRange.start() ||
2894 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2895 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2896 if (CurrRange == InvalidRange ||
2897 CurrRange.start() > First.StartAddress + OrigLowPc) {
2898 reportWarning("no mapping for range.");
2899 continue;
2900 }
Frederic Riss25440872015-03-13 23:30:31 +00002901 }
2902 }
2903
2904 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2905 AddressSize);
2906 }
2907}
2908
Frederic Riss563b1b02015-03-14 03:46:51 +00002909/// \brief Generate the debug_aranges entries for \p Unit and if the
2910/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2911/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002912/// FIXME: this could actually be done right in patchRangesForUnit,
2913/// but for the sake of initial bit-for-bit compatibility with legacy
2914/// dsymutil, we have to do it in a delayed pass.
2915void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002916 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002917 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002918 Attr->set(Streamer->getRangesSectionSize());
2919 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002920}
2921
Frederic Riss63786b02015-03-15 20:45:43 +00002922/// \brief Insert the new line info sequence \p Seq into the current
2923/// set of already linked line info \p Rows.
2924static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2925 std::vector<DWARFDebugLine::Row> &Rows) {
2926 if (Seq.empty())
2927 return;
2928
2929 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2930 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2931 Seq.clear();
2932 return;
2933 }
2934
2935 auto InsertPoint = std::lower_bound(
2936 Rows.begin(), Rows.end(), Seq.front(),
2937 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2938 return LHS.Address < RHS.Address;
2939 });
2940
2941 // FIXME: this only removes the unneeded end_sequence if the
2942 // sequences have been inserted in order. using a global sort like
2943 // described in patchLineTableForUnit() and delaying the end_sequene
2944 // elimination to emitLineTableForUnit() we can get rid of all of them.
2945 if (InsertPoint != Rows.end() &&
2946 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2947 *InsertPoint = Seq.front();
2948 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2949 } else {
2950 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2951 }
2952
2953 Seq.clear();
2954}
2955
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002956static void patchStmtList(DIE &Die, DIEInteger Offset) {
2957 for (auto &V : Die.values())
2958 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002959 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002960 return;
2961 }
2962
2963 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2964}
2965
Frederic Riss63786b02015-03-15 20:45:43 +00002966/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2967/// recreate a relocated version of these for the address ranges that
2968/// are present in the binary.
2969void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2970 DWARFContext &OrigDwarf) {
Greg Claytonc8c10322016-12-13 18:25:19 +00002971 DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
Greg Clayton52fe1f62016-12-14 22:38:08 +00002972 auto StmtList = CUDie.getAttributeValueAsSectionOffset(dwarf::DW_AT_stmt_list);
2973 if (!StmtList)
Frederic Riss63786b02015-03-15 20:45:43 +00002974 return;
2975
2976 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002977 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2978 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002979
2980 // Parse the original line info for the unit.
2981 DWARFDebugLine::LineTable LineTable;
Greg Clayton52fe1f62016-12-14 22:38:08 +00002982 uint32_t StmtOffset = *StmtList;
Frederic Riss63786b02015-03-15 20:45:43 +00002983 StringRef LineData = OrigDwarf.getLineSection().Data;
2984 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2985 Unit.getOrigUnit().getAddressByteSize());
2986 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2987 &StmtOffset);
2988
2989 // This vector is the output line table.
2990 std::vector<DWARFDebugLine::Row> NewRows;
2991 NewRows.reserve(LineTable.Rows.size());
2992
2993 // Current sequence of rows being extracted, before being inserted
2994 // in NewRows.
2995 std::vector<DWARFDebugLine::Row> Seq;
2996 const auto &FunctionRanges = Unit.getFunctionRanges();
2997 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2998
2999 // FIXME: This logic is meant to generate exactly the same output as
3000 // Darwin's classic dsynutil. There is a nicer way to implement this
3001 // by simply putting all the relocated line info in NewRows and simply
3002 // sorting NewRows before passing it to emitLineTableForUnit. This
3003 // should be correct as sequences for a function should stay
3004 // together in the sorted output. There are a few corner cases that
3005 // look suspicious though, and that required to implement the logic
3006 // this way. Revisit that once initial validation is finished.
3007
3008 // Iterate over the object file line info and extract the sequences
3009 // that correspond to linked functions.
3010 for (auto &Row : LineTable.Rows) {
3011 // Check wether we stepped out of the range. The range is
3012 // half-open, but consider accept the end address of the range if
3013 // it is marked as end_sequence in the input (because in that
3014 // case, the relocation offset is accurate and that entry won't
3015 // serve as the start of another function).
3016 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
3017 Row.Address > CurrRange.stop() ||
3018 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
3019 // We just stepped out of a known range. Insert a end_sequence
3020 // corresponding to the end of the range.
3021 uint64_t StopAddress = CurrRange != InvalidRange
3022 ? CurrRange.stop() + CurrRange.value()
3023 : -1ULL;
3024 CurrRange = FunctionRanges.find(Row.Address);
3025 bool CurrRangeValid =
3026 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
3027 if (!CurrRangeValid) {
3028 CurrRange = InvalidRange;
3029 if (StopAddress != -1ULL) {
3030 // Try harder by looking in the DebugMapObject function
3031 // ranges map. There are corner cases where this finds a
3032 // valid entry. It's unclear if this is right or wrong, but
3033 // for now do as dsymutil.
3034 // FIXME: Understand exactly what cases this addresses and
3035 // potentially remove it along with the Ranges map.
3036 auto Range = Ranges.lower_bound(Row.Address);
3037 if (Range != Ranges.begin() && Range != Ranges.end())
3038 --Range;
3039
3040 if (Range != Ranges.end() && Range->first <= Row.Address &&
3041 Range->second.first >= Row.Address) {
3042 StopAddress = Row.Address + Range->second.second;
3043 }
3044 }
3045 }
3046 if (StopAddress != -1ULL && !Seq.empty()) {
3047 // Insert end sequence row with the computed end address, but
3048 // the same line as the previous one.
Yaron Kerene3c07062015-08-10 16:15:51 +00003049 auto NextLine = Seq.back();
Yaron Keren2ad3b332015-08-10 18:27:51 +00003050 NextLine.Address = StopAddress;
3051 NextLine.EndSequence = 1;
3052 NextLine.PrologueEnd = 0;
3053 NextLine.BasicBlock = 0;
3054 NextLine.EpilogueBegin = 0;
Yaron Kerenf850d982015-08-10 18:03:35 +00003055 Seq.push_back(NextLine);
Frederic Riss63786b02015-03-15 20:45:43 +00003056 insertLineSequence(Seq, NewRows);
3057 }
3058
3059 if (!CurrRangeValid)
3060 continue;
3061 }
3062
3063 // Ignore empty sequences.
3064 if (Row.EndSequence && Seq.empty())
3065 continue;
3066
3067 // Relocate row address and add it to the current sequence.
3068 Row.Address += CurrRange.value();
3069 Seq.emplace_back(Row);
3070
3071 if (Row.EndSequence)
3072 insertLineSequence(Seq, NewRows);
3073 }
3074
3075 // Finished extracting, now emit the line tables.
Greg Clayton52fe1f62016-12-14 22:38:08 +00003076 uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength;
Frederic Riss63786b02015-03-15 20:45:43 +00003077 // FIXME: LLVM hardcodes it's prologue values. We just copy the
3078 // prologue over and that works because we act as both producer and
3079 // consumer. It would be nicer to have a real configurable line
3080 // table emitter.
3081 if (LineTable.Prologue.Version != 2 ||
3082 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00003083 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00003084 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00003085 else {
3086 MCDwarfLineTableParams Params;
3087 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
3088 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
3089 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
3090 Streamer->emitLineTableForUnit(Params,
Greg Clayton52fe1f62016-12-14 22:38:08 +00003091 LineData.slice(*StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00003092 LineTable.Prologue.MinInstLength, NewRows,
3093 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00003094 }
Frederic Riss63786b02015-03-15 20:45:43 +00003095}
3096
Frederic Rissbce93ff2015-03-16 02:05:10 +00003097void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
3098 Streamer->emitPubNamesForUnit(Unit);
3099 Streamer->emitPubTypesForUnit(Unit);
3100}
3101
Frederic Riss5a642072015-06-05 23:06:11 +00003102/// \brief Read the frame info stored in the object, and emit the
3103/// patched frame descriptions for the linked binary.
3104///
3105/// This is actually pretty easy as the data of the CIEs and FDEs can
3106/// be considered as black boxes and moved as is. The only thing to do
3107/// is to patch the addresses in the headers.
3108void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
3109 DWARFContext &OrigDwarf,
3110 unsigned AddrSize) {
3111 StringRef FrameData = OrigDwarf.getDebugFrameSection();
3112 if (FrameData.empty())
3113 return;
3114
3115 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
3116 uint32_t InputOffset = 0;
3117
3118 // Store the data of the CIEs defined in this object, keyed by their
3119 // offsets.
3120 DenseMap<uint32_t, StringRef> LocalCIES;
3121
3122 while (Data.isValidOffset(InputOffset)) {
3123 uint32_t EntryOffset = InputOffset;
3124 uint32_t InitialLength = Data.getU32(&InputOffset);
3125 if (InitialLength == 0xFFFFFFFF)
3126 return reportWarning("Dwarf64 bits no supported");
3127
3128 uint32_t CIEId = Data.getU32(&InputOffset);
3129 if (CIEId == 0xFFFFFFFF) {
3130 // This is a CIE, store it.
3131 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
3132 LocalCIES[EntryOffset] = CIEData;
3133 // The -4 is to account for the CIEId we just read.
3134 InputOffset += InitialLength - 4;
3135 continue;
3136 }
3137
3138 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
3139
3140 // Some compilers seem to emit frame info that doesn't start at
3141 // the function entry point, thus we can't just lookup the address
3142 // in the debug map. Use the linker's range map to see if the FDE
3143 // describes something that we can relocate.
3144 auto Range = Ranges.upper_bound(Loc);
3145 if (Range != Ranges.begin())
3146 --Range;
3147 if (Range == Ranges.end() || Range->first > Loc ||
3148 Range->second.first <= Loc) {
3149 // The +4 is to account for the size of the InitialLength field itself.
3150 InputOffset = EntryOffset + InitialLength + 4;
3151 continue;
3152 }
3153
3154 // This is an FDE, and we have a mapping.
3155 // Have we already emitted a corresponding CIE?
3156 StringRef CIEData = LocalCIES[CIEId];
3157 if (CIEData.empty())
3158 return reportWarning("Inconsistent debug_frame content. Dropping.");
3159
3160 // Look if we already emitted a CIE that corresponds to the
3161 // referenced one (the CIE data is the key of that lookup).
3162 auto IteratorInserted = EmittedCIEs.insert(
3163 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3164 // If there is no CIE yet for this ID, emit it.
3165 if (IteratorInserted.second ||
3166 // FIXME: dsymutil-classic only caches the last used CIE for
3167 // reuse. Mimic that behavior for now. Just removing that
3168 // second half of the condition and the LastCIEOffset variable
3169 // makes the code DTRT.
3170 LastCIEOffset != IteratorInserted.first->getValue()) {
3171 LastCIEOffset = Streamer->getFrameSectionSize();
3172 IteratorInserted.first->getValue() = LastCIEOffset;
3173 Streamer->emitCIE(CIEData);
3174 }
3175
3176 // Emit the FDE with updated address and CIE pointer.
3177 // (4 + AddrSize) is the size of the CIEId + initial_location
3178 // fields that will get reconstructed by emitFDE().
3179 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3180 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3181 Loc + Range->second.second,
3182 FrameData.substr(InputOffset, FDERemainingBytes));
3183 InputOffset += FDERemainingBytes;
3184 }
3185}
3186
Adrian Prantl3565af42015-09-14 16:46:10 +00003187void DwarfLinker::DIECloner::copyAbbrev(
3188 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
Frederic Riss29eedc72015-09-11 04:17:30 +00003189 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3190 dwarf::Form(Abbrev.hasChildren()));
3191
3192 for (const auto &Attr : Abbrev.attributes()) {
3193 uint16_t Form = Attr.Form;
3194 if (hasODR && isODRAttribute(Attr.Attr))
3195 Form = dwarf::DW_FORM_ref_addr;
3196 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3197 }
3198
Adrian Prantl3565af42015-09-14 16:46:10 +00003199 Linker.AssignAbbrev(Copy);
Frederic Riss29eedc72015-09-11 04:17:30 +00003200}
3201
Greg Claytonc8c10322016-12-13 18:25:19 +00003202static uint64_t getDwoId(const DWARFDie &CUDie,
Adrian Prantl20937022015-09-23 17:11:10 +00003203 const DWARFUnit &Unit) {
Greg Clayton52fe1f62016-12-14 22:38:08 +00003204 auto DwoId = CUDie.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_dwo_id);
3205 if (DwoId)
3206 return *DwoId;
3207 DwoId = CUDie.getAttributeValueAsUnsignedConstant(dwarf::DW_AT_GNU_dwo_id);
3208 if (DwoId)
3209 return *DwoId;
3210 return 0;
Adrian Prantl20937022015-09-23 17:11:10 +00003211}
3212
Adrian Prantle5162db2015-09-22 22:20:50 +00003213bool DwarfLinker::registerModuleReference(
Greg Claytonc8c10322016-12-13 18:25:19 +00003214 const DWARFDie &CUDie, const DWARFUnit &Unit,
Adrian Prantle5162db2015-09-22 22:20:50 +00003215 DebugMap &ModuleMap, unsigned Indent) {
3216 std::string PCMfile =
Greg Claytonc8c10322016-12-13 18:25:19 +00003217 CUDie.getAttributeValueAsString(dwarf::DW_AT_dwo_name, "");
Adrian Prantl20937022015-09-23 17:11:10 +00003218 if (PCMfile.empty())
3219 PCMfile =
Greg Claytonc8c10322016-12-13 18:25:19 +00003220 CUDie.getAttributeValueAsString(dwarf::DW_AT_GNU_dwo_name, "");
Adrian Prantle5162db2015-09-22 22:20:50 +00003221 if (PCMfile.empty())
3222 return false;
3223
3224 // Clang module DWARF skeleton CUs abuse this for the path to the module.
3225 std::string PCMpath =
Greg Claytonc8c10322016-12-13 18:25:19 +00003226 CUDie.getAttributeValueAsString(dwarf::DW_AT_comp_dir, "");
Adrian Prantl20937022015-09-23 17:11:10 +00003227 uint64_t DwoId = getDwoId(CUDie, Unit);
Adrian Prantle5162db2015-09-22 22:20:50 +00003228
Adrian Prantla112ef92015-09-23 17:35:52 +00003229 std::string Name =
Greg Claytonc8c10322016-12-13 18:25:19 +00003230 CUDie.getAttributeValueAsString(dwarf::DW_AT_name, "");
Adrian Prantla112ef92015-09-23 17:35:52 +00003231 if (Name.empty()) {
3232 reportWarning("Anonymous module skeleton CU for " + PCMfile);
3233 return true;
3234 }
3235
Adrian Prantle5162db2015-09-22 22:20:50 +00003236 if (Options.Verbose) {
3237 outs().indent(Indent);
3238 outs() << "Found clang module reference " << PCMfile;
3239 }
3240
Adrian Prantl20937022015-09-23 17:11:10 +00003241 auto Cached = ClangModules.find(PCMfile);
3242 if (Cached != ClangModules.end()) {
Adrian Prantle1bc3e22016-05-13 00:17:58 +00003243 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
3244 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
3245 // ASTFileSignatures will change randomly when a module is rebuilt.
3246 if (Options.Verbose && (Cached->second != DwoId))
Adrian Prantl20937022015-09-23 17:11:10 +00003247 reportWarning(Twine("hash mismatch: this object file was built against a "
3248 "different version of the module ") + PCMfile);
Adrian Prantle5162db2015-09-22 22:20:50 +00003249 if (Options.Verbose)
3250 outs() << " [cached].\n";
3251 return true;
3252 }
3253 if (Options.Verbose)
3254 outs() << " ...\n";
3255
3256 // Cyclic dependencies are disallowed by Clang, but we still
3257 // shouldn't run into an infinite loop, so mark it as processed now.
Adrian Prantl20937022015-09-23 17:11:10 +00003258 ClangModules.insert({PCMfile, DwoId});
Adrian Prantla112ef92015-09-23 17:35:52 +00003259 loadClangModule(PCMfile, PCMpath, Name, DwoId, ModuleMap, Indent + 2);
Adrian Prantle5162db2015-09-22 22:20:50 +00003260 return true;
3261}
3262
Frederic Risseb85c8f2015-07-24 06:41:11 +00003263ErrorOr<const object::ObjectFile &>
3264DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3265 const DebugMap &Map) {
3266 auto ErrOrObjs =
3267 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
Frederic Rissafeac302015-08-31 05:16:35 +00003268 if (std::error_code EC = ErrOrObjs.getError()) {
Frederic Risseb85c8f2015-07-24 06:41:11 +00003269 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
Frederic Rissafeac302015-08-31 05:16:35 +00003270 return EC;
3271 }
Frederic Risseb85c8f2015-07-24 06:41:11 +00003272 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3273 if (std::error_code EC = ErrOrObj.getError())
3274 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3275 return ErrOrObj;
3276}
3277
Adrian Prantle5162db2015-09-22 22:20:50 +00003278void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
Adrian Prantla112ef92015-09-23 17:35:52 +00003279 StringRef ModuleName, uint64_t DwoId,
3280 DebugMap &ModuleMap, unsigned Indent) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003281 SmallString<80> Path(Options.PrependPath);
3282 if (sys::path::is_relative(Filename))
3283 sys::path::append(Path, ModulePath, Filename);
3284 else
3285 sys::path::append(Path, Filename);
3286 BinaryHolder ObjHolder(Options.Verbose);
3287 auto &Obj =
Pavel Labath62d72042016-11-09 11:43:52 +00003288 ModuleMap.addDebugMapObject(Path, sys::TimePoint<std::chrono::seconds>());
Adrian Prantle5162db2015-09-22 22:20:50 +00003289 auto ErrOrObj = loadObject(ObjHolder, Obj, ModuleMap);
Adrian Prantla9e23832016-01-14 18:31:07 +00003290 if (!ErrOrObj) {
3291 // Try and emit more helpful warnings by applying some heuristics.
3292 StringRef ObjFile = CurrentDebugObject->getObjectFilename();
3293 bool isClangModule = sys::path::extension(Filename).equals(".pcm");
3294 bool isArchive = ObjFile.endswith(")");
3295 if (isClangModule) {
Adrian Prantla9e23832016-01-14 18:31:07 +00003296 StringRef ModuleCacheDir = sys::path::parent_path(Path);
3297 if (sys::fs::exists(ModuleCacheDir)) {
3298 // If the module's parent directory exists, we assume that the module
3299 // cache has expired and was pruned by clang. A more adventurous
3300 // dsymutil would invoke clang to rebuild the module now.
3301 if (!ModuleCacheHintDisplayed) {
3302 errs() << "note: The clang module cache may have expired since this "
3303 "object file was built. Rebuilding the object file will "
3304 "rebuild the module cache.\n";
3305 ModuleCacheHintDisplayed = true;
3306 }
3307 } else if (isArchive) {
3308 // If the module cache directory doesn't exist at all and the object
3309 // file is inside a static library, we assume that the static library
3310 // was built on a different machine. We don't want to discourage module
3311 // debugging for convenience libraries within a project though.
3312 if (!ArchiveHintDisplayed) {
Adrian Prantl9e7e8832016-05-20 20:36:06 +00003313 errs() << "note: Linking a static library that was built with "
3314 "-gmodules, but the module cache was not found. "
3315 "Redistributable static libraries should never be built "
3316 "with module debugging enabled. The debug experience will "
3317 "be degraded due to incomplete debug information.\n";
Adrian Prantla9e23832016-01-14 18:31:07 +00003318 ArchiveHintDisplayed = true;
3319 }
3320 }
3321 }
Adrian Prantle5162db2015-09-22 22:20:50 +00003322 return;
Adrian Prantla9e23832016-01-14 18:31:07 +00003323 }
Adrian Prantle5162db2015-09-22 22:20:50 +00003324
Benjamin Kramer008f4be2015-09-23 10:38:59 +00003325 std::unique_ptr<CompileUnit> Unit;
Adrian Prantle5162db2015-09-22 22:20:50 +00003326
3327 // Setup access to the debug info.
3328 DWARFContextInMemory DwarfContext(*ErrOrObj);
3329 RelocationManager RelocMgr(*this);
3330 for (const auto &CU : DwarfContext.compile_units()) {
Greg Claytonc8c10322016-12-13 18:25:19 +00003331 auto CUDie = CU->getUnitDIE(false);
Adrian Prantle5162db2015-09-22 22:20:50 +00003332 // Recursively get all modules imported by this one.
Greg Claytonc8c10322016-12-13 18:25:19 +00003333 if (!registerModuleReference(CUDie, *CU, ModuleMap, Indent)) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003334 if (Unit) {
3335 errs() << Filename << ": Clang modules are expected to have exactly"
3336 << " 1 compile unit.\n";
3337 exitDsymutil(1);
3338 }
Adrian Prantl2c0b0ab2016-04-25 17:04:32 +00003339 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
3340 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
3341 // ASTFileSignatures will change randomly when a module is rebuilt.
Greg Claytonc8c10322016-12-13 18:25:19 +00003342 uint64_t PCMDwoId = getDwoId(CUDie, *CU);
Adrian Prantle1bc3e22016-05-13 00:17:58 +00003343 if (PCMDwoId != DwoId) {
3344 if (Options.Verbose)
3345 reportWarning(
3346 Twine("hash mismatch: this object file was built against a "
3347 "different version of the module ") + Filename);
3348 // Update the cache entry with the DwoId of the module loaded from disk.
3349 ClangModules[Filename] = PCMDwoId;
3350 }
Adrian Prantl20937022015-09-23 17:11:10 +00003351
3352 // Add this module.
Adrian Prantla112ef92015-09-23 17:35:52 +00003353 Unit = llvm::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
3354 ModuleName);
Adrian Prantle5162db2015-09-22 22:20:50 +00003355 Unit->setHasInterestingContent();
Adrian Prantla112ef92015-09-23 17:35:52 +00003356 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), StringPool,
3357 ODRContexts);
Adrian Prantle5162db2015-09-22 22:20:50 +00003358 // Keep everything.
3359 Unit->markEverythingAsKept();
3360 }
3361 }
3362 if (Options.Verbose) {
3363 outs().indent(Indent);
3364 outs() << "cloning .debug_info from " << Filename << "\n";
3365 }
3366
Greg Clayton35630c32016-12-01 18:56:29 +00003367 std::vector<std::unique_ptr<CompileUnit>> CompileUnits;
3368 CompileUnits.push_back(std::move(Unit));
3369 DIECloner(*this, RelocMgr, DIEAlloc, CompileUnits, Options)
Adrian Prantle5162db2015-09-22 22:20:50 +00003370 .cloneAllCompileUnits(DwarfContext);
3371}
3372
Adrian Prantl3565af42015-09-14 16:46:10 +00003373void DwarfLinker::DIECloner::cloneAllCompileUnits(
3374 DWARFContextInMemory &DwarfContext) {
3375 if (!Linker.Streamer)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003376 return;
3377
3378 for (auto &CurrentUnit : CompileUnits) {
Greg Claytonc8c10322016-12-13 18:25:19 +00003379 auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
Greg Clayton35630c32016-12-01 18:56:29 +00003380 CurrentUnit->setStartOffset(Linker.OutputDebugInfoSize);
3381 // Clonse the InputDIE into your Unit DIE in our compile unit since it
3382 // already has a DIE inside of it.
Greg Claytonc8c10322016-12-13 18:25:19 +00003383 if (!cloneDIE(InputDIE, *CurrentUnit, 0 /* PC offset */,
Greg Clayton35630c32016-12-01 18:56:29 +00003384 11 /* Unit Header size */, 0,
3385 CurrentUnit->getOutputUnitDIE()))
3386 continue;
3387 Linker.OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset();
Adrian Prantl3565af42015-09-14 16:46:10 +00003388 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003389 continue;
3390 // FIXME: for compatibility with the classic dsymutil, we emit
3391 // an empty line table for the unit, even if the unit doesn't
3392 // actually exist in the DIE tree.
Greg Clayton35630c32016-12-01 18:56:29 +00003393 Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext);
3394 Linker.patchRangesForUnit(*CurrentUnit, DwarfContext);
3395 Linker.Streamer->emitLocationsForUnit(*CurrentUnit, DwarfContext);
3396 Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003397 }
3398
Adrian Prantl3565af42015-09-14 16:46:10 +00003399 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003400 return;
3401
3402 // Emit all the compile unit's debug information.
3403 for (auto &CurrentUnit : CompileUnits) {
Greg Clayton35630c32016-12-01 18:56:29 +00003404 Linker.generateUnitRanges(*CurrentUnit);
3405 CurrentUnit->fixupForwardReferences();
3406 Linker.Streamer->emitCompileUnitHeader(*CurrentUnit);
3407 if (!CurrentUnit->getOutputUnitDIE())
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003408 continue;
Greg Clayton35630c32016-12-01 18:56:29 +00003409 Linker.Streamer->emitDIE(*CurrentUnit->getOutputUnitDIE());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003410 }
3411}
3412
Frederic Rissd3455182015-01-28 18:27:01 +00003413bool DwarfLinker::link(const DebugMap &Map) {
3414
Frederic Rissc99ea202015-02-28 00:29:11 +00003415 if (!createStreamer(Map.getTriple(), OutputFilename))
3416 return false;
3417
Frederic Rissb8b43d52015-03-04 22:07:44 +00003418 // Size of the DIEs (and headers) generated for the linked output.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003419 OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00003420 // A unique ID that identifies each compile unit.
Adrian Prantle5162db2015-09-22 22:20:50 +00003421 UnitID = 0;
3422 DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
3423
Frederic Rissd3455182015-01-28 18:27:01 +00003424 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00003425 CurrentDebugObject = Obj.get();
3426
Frederic Rissb9818322015-02-28 00:29:07 +00003427 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00003428 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00003429 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3430 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00003431 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00003432
Frederic Riss1036e642015-02-13 23:18:22 +00003433 // Look for relocations that correspond to debug map entries.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003434 RelocationManager RelocMgr(*this);
3435 if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00003436 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00003437 outs() << "No valid relocations found. Skipping.\n";
3438 continue;
3439 }
3440
Frederic Riss563cba62015-01-28 22:15:14 +00003441 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00003442 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00003443 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00003444
Adrian Prantld2793a02015-10-05 23:11:20 +00003445 // In a first phase, just read in the debug info and load all clang modules.
Frederic Rissd3455182015-01-28 18:27:01 +00003446 for (const auto &CU : DwarfContext.compile_units()) {
Greg Claytonc8c10322016-12-13 18:25:19 +00003447 auto CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00003448 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00003449 outs() << "Input compilation unit:";
Greg Claytonc8c10322016-12-13 18:25:19 +00003450 CUDie.dump(outs(), 0);
Frederic Rissd3455182015-01-28 18:27:01 +00003451 }
Adrian Prantld2793a02015-10-05 23:11:20 +00003452
Greg Claytonc8c10322016-12-13 18:25:19 +00003453 if (!registerModuleReference(CUDie, *CU, ModuleMap))
Greg Clayton35630c32016-12-01 18:56:29 +00003454 Units.push_back(llvm::make_unique<CompileUnit>(*CU, UnitID++,
3455 !Options.NoODR, ""));
Frederic Rissd3455182015-01-28 18:27:01 +00003456 }
Frederic Riss563cba62015-01-28 22:15:14 +00003457
Adrian Prantld2793a02015-10-05 23:11:20 +00003458 // Now build the DIE parent links that we will use during the next phase.
3459 for (auto &CurrentUnit : Units)
Greg Clayton35630c32016-12-01 18:56:29 +00003460 analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0, *CurrentUnit,
Adrian Prantld2793a02015-10-05 23:11:20 +00003461 &ODRContexts.getRoot(), StringPool, ODRContexts);
3462
Frederic Riss84c09a52015-02-13 23:18:34 +00003463 // Then mark all the DIEs that need to be present in the linked
3464 // output and collect some information about them. Note that this
3465 // loop can not be merged with the previous one becaue cross-cu
3466 // references require the ParentIdx to be setup for every CU in
3467 // the object file before calling this.
3468 for (auto &CurrentUnit : Units)
Greg Claytonc8c10322016-12-13 18:25:19 +00003469 lookForDIEsToKeep(RelocMgr, CurrentUnit->getOrigUnit().getUnitDIE(), *Obj,
Greg Clayton35630c32016-12-01 18:56:29 +00003470 *CurrentUnit, 0);
Frederic Riss84c09a52015-02-13 23:18:34 +00003471
Frederic Riss23e20e92015-03-07 01:25:09 +00003472 // The calls to applyValidRelocs inside cloneDIE will walk the
3473 // reloc array again (in the same way findValidRelocsInDebugInfo()
3474 // did). We need to reset the NextValidReloc index to the beginning.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003475 RelocMgr.resetValidRelocs();
3476 if (RelocMgr.hasValidRelocs())
Adrian Prantl3565af42015-09-14 16:46:10 +00003477 DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3478 .cloneAllCompileUnits(DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003479 if (!Options.NoOutput && !Units.empty())
Frederic Riss5a642072015-06-05 23:06:11 +00003480 patchFrameInfoForObject(*Obj, DwarfContext,
Greg Clayton35630c32016-12-01 18:56:29 +00003481 Units[0]->getOrigUnit().getAddressByteSize());
Frederic Riss5a642072015-06-05 23:06:11 +00003482
Frederic Riss563cba62015-01-28 22:15:14 +00003483 // Clean-up before starting working on the next object.
3484 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003485 }
3486
Frederic Rissb8b43d52015-03-04 22:07:44 +00003487 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003488 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003489 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003490 Streamer->emitStrings(StringPool);
3491 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003492
Frederic Riss24faade2015-09-02 16:49:13 +00003493 return Options.NoOutput ? true : Streamer->finish(Map);
Frederic Riss231f7142014-12-12 17:31:24 +00003494}
3495}
Frederic Rissd3455182015-01-28 18:27:01 +00003496
Frederic Riss30711fb2015-08-26 05:09:52 +00003497/// \brief Get the offset of string \p S in the string table. This
3498/// can insert a new element or return the offset of a preexisitng
3499/// one.
3500uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3501 if (S.empty() && !Strings.empty())
3502 return 0;
3503
3504 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3505 MapTy::iterator It;
3506 bool Inserted;
3507
3508 // A non-empty string can't be at offset 0, so if we have an entry
3509 // with a 0 offset, it must be a previously interned string.
3510 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3511 if (Inserted || It->getValue().first == 0) {
3512 // Set offset and chain at the end of the entries list.
3513 It->getValue().first = CurrentEndOffset;
3514 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3515 Last->getValue().second = &*It;
3516 Last = &*It;
3517 }
3518 return It->getValue().first;
3519}
3520
3521/// \brief Put \p S into the StringMap so that it gets permanent
3522/// storage, but do not actually link it in the chain of elements
3523/// that go into the output section. A latter call to
3524/// getStringOffset() with the same string will chain it though.
3525StringRef NonRelocatableStringpool::internString(StringRef S) {
3526 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3527 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3528 return InsertResult.first->getKey();
3529}
3530
Frederic Riss65e145c2015-08-26 05:09:55 +00003531void warn(const Twine &Warning, const Twine &Context) {
3532 errs() << Twine("while processing ") + Context + ":\n";
3533 errs() << Twine("warning: ") + Warning + "\n";
3534}
3535
3536bool error(const Twine &Error, const Twine &Context) {
3537 errs() << Twine("while processing ") + Context + ":\n";
3538 errs() << Twine("error: ") + Error + "\n";
3539 return false;
3540}
3541
Frederic Rissb9818322015-02-28 00:29:07 +00003542bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3543 const LinkOptions &Options) {
3544 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003545 return Linker.link(DM);
3546}
3547}
Frederic Riss231f7142014-12-12 17:31:24 +00003548}