blob: fe971e9960784dce7b70b133311a37ae83d9e365 [file] [log] [blame]
Frederic Riss231f7142014-12-12 17:31:24 +00001//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "DebugMap.h"
Frederic Rissd3455182015-01-28 18:27:01 +000010#include "BinaryHolder.h"
11#include "DebugMap.h"
Frederic Riss231f7142014-12-12 17:31:24 +000012#include "dsymutil.h"
Frederic Riss24faade2015-09-02 16:49:13 +000013#include "MachOUtils.h"
Frederic Riss30711fb2015-08-26 05:09:52 +000014#include "NonRelocatableStringpool.h"
Frederic Riss1af75f72015-03-12 18:45:10 +000015#include "llvm/ADT/IntervalMap.h"
Adrian Prantl20937022015-09-23 17:11:10 +000016#include "llvm/ADT/StringMap.h"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000017#include "llvm/ADT/STLExtras.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000018#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000019#include "llvm/CodeGen/DIE.h"
Frederic Riss1c650942015-07-21 22:41:43 +000020#include "llvm/Config/config.h"
Zachary Turner82af9432015-01-30 18:07:45 +000021#include "llvm/DebugInfo/DWARF/DWARFContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000023#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000024#include "llvm/MC/MCAsmBackend.h"
25#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCContext.h"
27#include "llvm/MC/MCCodeEmitter.h"
Frederic Riss63786b02015-03-15 20:45:43 +000028#include "llvm/MC/MCDwarf.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000029#include "llvm/MC/MCInstrInfo.h"
30#include "llvm/MC/MCObjectFileInfo.h"
31#include "llvm/MC/MCRegisterInfo.h"
32#include "llvm/MC/MCStreamer.h"
Pete Cooper81902a32015-05-15 22:19:42 +000033#include "llvm/MC/MCSubtargetInfo.h"
David Majnemer03e2cc32015-12-21 22:09:27 +000034#include "llvm/MC/MCTargetOptionsCommandFlags.h"
Frederic Riss1036e642015-02-13 23:18:22 +000035#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000036#include "llvm/Support/Dwarf.h"
37#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000038#include "llvm/Support/TargetRegistry.h"
39#include "llvm/Target/TargetMachine.h"
40#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000041#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000042#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000043
44namespace llvm {
45namespace dsymutil {
46
Frederic Rissd3455182015-01-28 18:27:01 +000047namespace {
48
Frederic Riss1af75f72015-03-12 18:45:10 +000049template <typename KeyT, typename ValT>
50using HalfOpenIntervalMap =
51 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
52 IntervalMapHalfOpenInfo<KeyT>>;
53
Frederic Riss25440872015-03-13 23:30:31 +000054typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
55
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000056// FIXME: Delete this structure.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000057struct PatchLocation {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000058 DIE::value_iterator I;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000059
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000060 PatchLocation() = default;
61 PatchLocation(DIE::value_iterator I) : I(I) {}
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000062
63 void set(uint64_t New) const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000064 assert(I);
65 const auto &Old = *I;
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000066 assert(Old.getType() == DIEValue::isInteger);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000067 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000068 }
69
70 uint64_t get() const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000071 assert(I);
72 return I->getDIEInteger().getValue();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000073 }
74};
75
Frederic Riss1c650942015-07-21 22:41:43 +000076class CompileUnit;
77struct DeclMapInfo;
Frederic Riss1c650942015-07-21 22:41:43 +000078
79/// A DeclContext is a named program scope that is used for ODR
80/// uniquing of types.
81/// The set of DeclContext for the ODR-subject parts of a Dwarf link
82/// is expanded (and uniqued) with each new object file processed. We
83/// need to determine the context of each DIE in an linked object file
84/// to see if the corresponding type has already been emitted.
85///
86/// The contexts are conceptually organised as a tree (eg. a function
87/// scope is contained in a namespace scope that contains other
88/// scopes), but storing/accessing them in an actual tree is too
89/// inefficient: we need to be able to very quickly query a context
90/// for a given child context by name. Storing a StringMap in each
91/// DeclContext would be too space inefficient.
92/// The solution here is to give each DeclContext a link to its parent
93/// (this allows to walk up the tree), but to query the existance of a
94/// specific DeclContext using a separate DenseMap keyed on the hash
95/// of the fully qualified name of the context.
96class DeclContext {
97 unsigned QualifiedNameHash;
98 uint32_t Line;
99 uint32_t ByteSize;
100 uint16_t Tag;
101 StringRef Name;
102 StringRef File;
103 const DeclContext &Parent;
104 const DWARFDebugInfoEntryMinimal *LastSeenDIE;
105 uint32_t LastSeenCompileUnitID;
106 uint32_t CanonicalDIEOffset;
107
108 friend DeclMapInfo;
109
110public:
111 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
112
113 DeclContext()
114 : QualifiedNameHash(0), Line(0), ByteSize(0),
115 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
116 LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
117
118 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
119 StringRef Name, StringRef File, const DeclContext &Parent,
120 const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
121 unsigned CUId = 0)
122 : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
123 Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
124 LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
125
126 uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
127
128 bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
129
130 uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
131 void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
132
133 uint16_t getTag() const { return Tag; }
134 StringRef getName() const { return Name; }
135};
136
137/// Info type for the DenseMap storing the DeclContext pointers.
138struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
139 using DenseMapInfo<DeclContext *>::getEmptyKey;
140 using DenseMapInfo<DeclContext *>::getTombstoneKey;
141
142 static unsigned getHashValue(const DeclContext *Ctxt) {
143 return Ctxt->QualifiedNameHash;
144 }
145
146 static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
147 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
148 return RHS == LHS;
149 return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
150 LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
151 LHS->Name.data() == RHS->Name.data() &&
152 LHS->File.data() == RHS->File.data() &&
153 LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
154 }
155};
156
157/// This class gives a tree-like API to the DenseMap that stores the
158/// DeclContext objects. It also holds the BumpPtrAllocator where
159/// these objects will be allocated.
160class DeclContextTree {
161 BumpPtrAllocator Allocator;
162 DeclContext Root;
163 DeclContext::Map Contexts;
164
165public:
166 /// Get the child of \a Context described by \a DIE in \a Unit. The
167 /// required strings will be interned in \a StringPool.
168 /// \returns The child DeclContext along with one bit that is set if
169 /// this context is invalid.
Adrian Prantl42562c32015-10-02 00:27:08 +0000170 /// An invalid context means it shouldn't be considered for uniquing, but its
171 /// not returning null, because some children of that context might be
172 /// uniquing candidates. FIXME: The invalid bit along the return value is to
173 /// emulate some dsymutil-classic functionality.
Frederic Riss1c650942015-07-21 22:41:43 +0000174 PointerIntPair<DeclContext *, 1>
175 getChildDeclContext(DeclContext &Context,
176 const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
Adrian Prantl42562c32015-10-02 00:27:08 +0000177 NonRelocatableStringpool &StringPool, bool InClangModule);
Frederic Riss1c650942015-07-21 22:41:43 +0000178
179 DeclContext &getRoot() { return Root; }
180};
181
Frederic Riss563cba62015-01-28 22:15:14 +0000182/// \brief Stores all information relating to a compile unit, be it in
183/// its original instance in the object file to its brand new cloned
184/// and linked DIE tree.
185class CompileUnit {
186public:
187 /// \brief Information gathered about a DIE in the object file.
188 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +0000189 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss1c650942015-07-21 22:41:43 +0000190 DeclContext *Ctxt; ///< ODR Declaration context.
Frederic Riss9833de62015-03-06 23:22:53 +0000191 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +0000192 uint32_t ParentIdx; ///< The index of this DIE's parent.
Adrian Prantla112ef92015-09-23 17:35:52 +0000193 bool Keep : 1; ///< Is the DIE part of the linked output?
194 bool InDebugMap : 1;///< Was this DIE's entity found in the map?
195 bool Prune : 1; ///< Is this a pure forward declaration we can strip?
Frederic Riss563cba62015-01-28 22:15:14 +0000196 };
197
Adrian Prantla112ef92015-09-23 17:35:52 +0000198 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR,
199 StringRef ClangModuleName)
Frederic Riss3cced052015-03-14 03:46:40 +0000200 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Adrian Prantla112ef92015-09-23 17:35:52 +0000201 Ranges(RangeAlloc), ClangModuleName(ClangModuleName) {
Frederic Riss563cba62015-01-28 22:15:14 +0000202 Info.resize(OrigUnit.getNumDIEs());
Frederic Riss1c650942015-07-21 22:41:43 +0000203
204 const auto *CUDie = OrigUnit.getUnitDIE(false);
205 unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
206 &OrigUnit, dwarf::DW_AT_language, 0);
207 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
208 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
209 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
210 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
211 Lang == dwarf::DW_LANG_ObjC_plus_plus);
Frederic Riss563cba62015-01-28 22:15:14 +0000212 }
213
Frederic Riss2838f9e2015-03-05 05:29:05 +0000214 CompileUnit(CompileUnit &&RHS)
215 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
216 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +0000217 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
218 // The CompileUnit container has been 'reserve()'d with the right
219 // size. We cannot move the IntervalMap anyway.
220 llvm_unreachable("CompileUnits should not be moved.");
221 }
David Blaikiea8adc132015-03-04 22:20:52 +0000222
Frederic Rissc3349d42015-02-13 23:18:27 +0000223 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000224
Frederic Riss3cced052015-03-14 03:46:40 +0000225 unsigned getUniqueID() const { return ID; }
226
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +0000227 DIE *getOutputUnitDIE() const { return CUDie; }
228 void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000229
Frederic Riss1c650942015-07-21 22:41:43 +0000230 bool hasODR() const { return HasODR; }
Adrian Prantla112ef92015-09-23 17:35:52 +0000231 bool isClangModule() const { return !ClangModuleName.empty(); }
232 const std::string &getClangModuleName() const { return ClangModuleName; }
Frederic Riss1c650942015-07-21 22:41:43 +0000233
Frederic Riss563cba62015-01-28 22:15:14 +0000234 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
235 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
236
Frederic Rissb8b43d52015-03-04 22:07:44 +0000237 uint64_t getStartOffset() const { return StartOffset; }
238 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000239 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000240
Frederic Riss5a62dc32015-03-13 18:35:54 +0000241 uint64_t getLowPc() const { return LowPc; }
242 uint64_t getHighPc() const { return HighPc; }
243
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000244 Optional<PatchLocation> getUnitRangesAttribute() const {
245 return UnitRangeAttribute;
246 }
Frederic Riss25440872015-03-13 23:30:31 +0000247 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000248 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000249 return RangeAttributes;
250 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000251
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000252 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000253 getLocationAttributes() const {
254 return LocationAttributes;
255 }
256
Adrian Prantle5162db2015-09-22 22:20:50 +0000257 void setHasInterestingContent() { HasInterestingContent = true; }
258 bool hasInterestingContent() { return HasInterestingContent; }
259
260 /// Mark every DIE in this unit as kept. This function also
261 /// marks variables as InDebugMap so that they appear in the
262 /// reconstructed accelerator tables.
263 void markEverythingAsKept();
264
Frederic Riss9d441b62015-03-06 23:22:50 +0000265 /// \brief Compute the end offset for this unit. Must be
266 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000267 /// \returns the next unit offset (which is also the current
268 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000269 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000270
Frederic Riss6afcfce2015-03-13 18:35:57 +0000271 /// \brief Keep track of a forward reference to DIE \p Die in \p
272 /// RefUnit by \p Attr. The attribute should be fixed up later to
Frederic Riss1c650942015-07-21 22:41:43 +0000273 /// point to the absolute offset of \p Die in the debug_info section
274 /// or to the canonical offset of \p Ctxt if it is non-null.
Frederic Riss6afcfce2015-03-13 18:35:57 +0000275 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000276 DeclContext *Ctxt, PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000277
278 /// \brief Apply all fixups recored by noteForwardReference().
279 void fixupForwardReferences();
280
Frederic Riss1af75f72015-03-12 18:45:10 +0000281 /// \brief Add a function range [\p LowPC, \p HighPC) that is
282 /// relocatad by applying offset \p PCOffset.
283 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
284
Frederic Riss5c9c7062015-03-13 23:55:29 +0000285 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000286 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000287 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000288
Frederic Rissdfb97902015-03-14 15:49:07 +0000289 /// \brief Keep track of a location attribute pointing to a location
290 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000291 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000292
Frederic Rissbce93ff2015-03-16 02:05:10 +0000293 /// \brief Add a name accelerator entry for \p Die with \p Name
294 /// which is stored in the string table at \p Offset.
295 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
296 bool SkipPubnamesSection = false);
297
298 /// \brief Add a type accelerator entry for \p Die with \p Name
299 /// which is stored in the string table at \p Offset.
300 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
301
302 struct AccelInfo {
Frederic Rissf37964c2015-06-05 20:27:07 +0000303 StringRef Name; ///< Name of the entry.
304 const DIE *Die; ///< DIE this entry describes.
Frederic Rissbce93ff2015-03-16 02:05:10 +0000305 uint32_t NameOffset; ///< Offset of Name in the string pool.
306 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
307
308 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
309 bool SkipPubSection = false)
310 : Name(Name), Die(Die), NameOffset(NameOffset),
311 SkipPubSection(SkipPubSection) {}
312 };
313
314 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
315 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
316
Frederic Riss1c650942015-07-21 22:41:43 +0000317 /// Get the full path for file \a FileNum in the line table
318 const char *getResolvedPath(unsigned FileNum) {
319 if (FileNum >= ResolvedPaths.size())
320 return nullptr;
321 return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
322 : nullptr;
323 }
324
325 /// Set the fully resolved path for the line-table's file \a FileNum
326 /// to \a Path.
327 void setResolvedPath(unsigned FileNum, const std::string &Path) {
328 if (ResolvedPaths.size() <= FileNum)
329 ResolvedPaths.resize(FileNum + 1);
330 ResolvedPaths[FileNum] = Path;
331 }
332
Frederic Riss563cba62015-01-28 22:15:14 +0000333private:
334 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000335 unsigned ID;
Frederic Riss1c650942015-07-21 22:41:43 +0000336 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
337 DIE *CUDie; ///< Root of the linked DIE tree.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000338
339 uint64_t StartOffset;
340 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000341
Frederic Riss5a62dc32015-03-13 18:35:54 +0000342 uint64_t LowPc;
343 uint64_t HighPc;
344
Frederic Riss9833de62015-03-06 23:22:53 +0000345 /// \brief A list of attributes to fixup with the absolute offset of
346 /// a DIE in the debug_info section.
347 ///
348 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000349 /// cloning because for cross-cu forward refences the target DIE's
350 /// offset isn't known you emit the reference attribute.
Frederic Riss1c650942015-07-21 22:41:43 +0000351 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
352 PatchLocation>> ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000353
Frederic Riss25440872015-03-13 23:30:31 +0000354 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000355 /// \brief The ranges in that interval map are the PC ranges for
356 /// functions in this unit, associated with the PC offset to apply
357 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000358 FunctionIntervals Ranges;
359
360 /// \brief DW_AT_ranges attributes to patch after we have gathered
361 /// all the unit's function addresses.
362 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000363 std::vector<PatchLocation> RangeAttributes;
364 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000365 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000366
367 /// \brief Location attributes that need to be transfered from th
368 /// original debug_loc section to the liked one. They are stored
369 /// along with the PC offset that is to be applied to their
370 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000371 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000372
373 /// \brief Accelerator entries for the unit, both for the pub*
374 /// sections and the apple* ones.
375 /// @{
376 std::vector<AccelInfo> Pubnames;
377 std::vector<AccelInfo> Pubtypes;
378 /// @}
Frederic Riss1c650942015-07-21 22:41:43 +0000379
380 /// Cached resolved paths from the line table.
381 std::vector<std::string> ResolvedPaths;
382
383 /// Is this unit subject to the ODR rule?
384 bool HasODR;
Adrian Prantle5162db2015-09-22 22:20:50 +0000385 /// Did a DIE actually contain a valid reloc?
386 bool HasInterestingContent;
Adrian Prantla112ef92015-09-23 17:35:52 +0000387 /// If this is a Clang module, this holds the module's name.
388 std::string ClangModuleName;
Frederic Riss563cba62015-01-28 22:15:14 +0000389};
390
Adrian Prantle5162db2015-09-22 22:20:50 +0000391void CompileUnit::markEverythingAsKept() {
392 for (auto &I : Info)
Adrian Prantla112ef92015-09-23 17:35:52 +0000393 // Mark everything that wasn't explicity marked for pruning.
394 I.Keep = !I.Prune;
Adrian Prantle5162db2015-09-22 22:20:50 +0000395}
396
Frederic Riss9d441b62015-03-06 23:22:50 +0000397uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000398 NextUnitOffset = StartOffset + 11 /* Header size */;
399 // The root DIE might be null, meaning that the Unit had nothing to
400 // contribute to the linked output. In that case, we will emit the
401 // unit header without any actual DIE.
402 if (CUDie)
403 NextUnitOffset += CUDie->getSize();
404 return NextUnitOffset;
405}
406
Frederic Riss6afcfce2015-03-13 18:35:57 +0000407/// \brief Keep track of a forward cross-cu reference from this unit
408/// to \p Die that lives in \p RefUnit.
409void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000410 DeclContext *Ctxt, PatchLocation Attr) {
411 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000412}
413
414/// \brief Apply all fixups recorded by noteForwardReference().
415void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000416 for (const auto &Ref : ForwardDIEReferences) {
417 DIE *RefDie;
418 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000419 PatchLocation Attr;
Frederic Riss1c650942015-07-21 22:41:43 +0000420 DeclContext *Ctxt;
421 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
422 if (Ctxt && Ctxt->getCanonicalDIEOffset())
423 Attr.set(Ctxt->getCanonicalDIEOffset());
424 else
425 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000426 }
Frederic Riss9833de62015-03-06 23:22:53 +0000427}
428
Frederic Riss5a62dc32015-03-13 18:35:54 +0000429void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
430 int64_t PcOffset) {
431 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
432 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
433 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000434}
435
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000436void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000437 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
438 RangeAttributes.push_back(Attr);
439 else
440 UnitRangeAttribute = Attr;
441}
442
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000443void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000444 LocationAttributes.emplace_back(Attr, PcOffset);
445}
446
Frederic Rissbce93ff2015-03-16 02:05:10 +0000447/// \brief Add a name accelerator entry for \p Die with \p Name
448/// which is stored in the string table at \p Offset.
449void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
450 uint32_t Offset, bool SkipPubSection) {
451 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
452}
453
454/// \brief Add a type accelerator entry for \p Die with \p Name
455/// which is stored in the string table at \p Offset.
456void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
457 uint32_t Offset) {
458 Pubtypes.emplace_back(Name, Die, Offset, false);
459}
460
Frederic Rissc99ea202015-02-28 00:29:11 +0000461/// \brief The Dwarf streaming logic
462///
463/// All interactions with the MC layer that is used to build the debug
464/// information binary representation are handled in this class.
465class DwarfStreamer {
466 /// \defgroup MCObjects MC layer objects constructed by the streamer
467 /// @{
468 std::unique_ptr<MCRegisterInfo> MRI;
469 std::unique_ptr<MCAsmInfo> MAI;
470 std::unique_ptr<MCObjectFileInfo> MOFI;
471 std::unique_ptr<MCContext> MC;
472 MCAsmBackend *MAB; // Owned by MCStreamer
473 std::unique_ptr<MCInstrInfo> MII;
474 std::unique_ptr<MCSubtargetInfo> MSTI;
475 MCCodeEmitter *MCE; // Owned by MCStreamer
476 MCStreamer *MS; // Owned by AsmPrinter
477 std::unique_ptr<TargetMachine> TM;
478 std::unique_ptr<AsmPrinter> Asm;
479 /// @}
480
481 /// \brief the file we stream the linked Dwarf to.
482 std::unique_ptr<raw_fd_ostream> OutFile;
483
Frederic Riss25440872015-03-13 23:30:31 +0000484 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000485 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000486 uint32_t LineSectionSize;
Frederic Riss5a642072015-06-05 23:06:11 +0000487 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000488
Frederic Rissbce93ff2015-03-16 02:05:10 +0000489 /// \brief Emit the pubnames or pubtypes section contribution for \p
490 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000491 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000492 const CompileUnit &Unit,
493 const std::vector<CompileUnit::AccelInfo> &Names);
494
Frederic Rissc99ea202015-02-28 00:29:11 +0000495public:
496 /// \brief Actually create the streamer and the ouptut file.
497 ///
498 /// This could be done directly in the constructor, but it feels
499 /// more natural to handle errors through return value.
500 bool init(Triple TheTriple, StringRef OutputFilename);
501
Frederic Rissb8b43d52015-03-04 22:07:44 +0000502 /// \brief Dump the file to the disk.
Frederic Riss24faade2015-09-02 16:49:13 +0000503 bool finish(const DebugMap &);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000504
505 AsmPrinter &getAsmPrinter() const { return *Asm; }
506
507 /// \brief Set the current output section to debug_info and change
508 /// the MC Dwarf version to \p DwarfVersion.
509 void switchToDebugInfoSection(unsigned DwarfVersion);
510
511 /// \brief Emit the compilation unit header for \p Unit in the
512 /// debug_info section.
513 ///
514 /// As a side effect, this also switches the current Dwarf version
515 /// of the MC layer to the one of U.getOrigUnit().
516 void emitCompileUnitHeader(CompileUnit &Unit);
517
518 /// \brief Recursively emit the DIE tree rooted at \p Die.
519 void emitDIE(DIE &Die);
520
521 /// \brief Emit the abbreviation table \p Abbrevs to the
522 /// debug_abbrev section.
David Blaikie6196aa02015-11-18 00:34:10 +0000523 void emitAbbrevs(const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000524
525 /// \brief Emit the string table described by \p Pool.
526 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000527
528 /// \brief Emit debug_ranges for \p FuncRange by translating the
529 /// original \p Entries.
530 void emitRangesEntries(
531 int64_t UnitPcOffset, uint64_t OrigLowPc,
532 FunctionIntervals::const_iterator FuncRange,
533 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
534 unsigned AddressSize);
535
Frederic Riss563b1b02015-03-14 03:46:51 +0000536 /// \brief Emit debug_aranges entries for \p Unit and if \p
537 /// DoRangesSection is true, also emit the debug_ranges entries for
538 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
539 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000540
541 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000542
543 /// \brief Emit the debug_loc contribution for \p Unit by copying
544 /// the entries from \p Dwarf and offseting them. Update the
545 /// location attributes to point to the new entries.
546 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000547
548 /// \brief Emit the line table described in \p Rows into the
549 /// debug_line section.
Frederic Rissa5e14532015-08-07 15:14:13 +0000550 void emitLineTableForUnit(MCDwarfLineTableParams Params,
551 StringRef PrologueBytes, unsigned MinInstLength,
Frederic Riss63786b02015-03-15 20:45:43 +0000552 std::vector<DWARFDebugLine::Row> &Rows,
553 unsigned AdddressSize);
554
555 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000556
557 /// \brief Emit the .debug_pubnames contribution for \p Unit.
558 void emitPubNamesForUnit(const CompileUnit &Unit);
559
560 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
561 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000562
563 /// \brief Emit a CIE.
564 void emitCIE(StringRef CIEBytes);
565
566 /// \brief Emit an FDE with data \p Bytes.
567 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
568 StringRef Bytes);
569
570 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000571};
572
573bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
574 std::string ErrorStr;
575 std::string TripleName;
576 StringRef Context = "dwarf streamer init";
577
578 // Get the target.
579 const Target *TheTarget =
580 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
581 if (!TheTarget)
582 return error(ErrorStr, Context);
583 TripleName = TheTriple.getTriple();
584
585 // Create all the MC Objects.
586 MRI.reset(TheTarget->createMCRegInfo(TripleName));
587 if (!MRI)
588 return error(Twine("no register info for target ") + TripleName, Context);
589
590 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
591 if (!MAI)
592 return error("no asm info for target " + TripleName, Context);
593
594 MOFI.reset(new MCObjectFileInfo);
595 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000596 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
Frederic Rissc99ea202015-02-28 00:29:11 +0000597 *MC);
598
599 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
600 if (!MAB)
601 return error("no asm backend for target " + TripleName, Context);
602
603 MII.reset(TheTarget->createMCInstrInfo());
604 if (!MII)
605 return error("no instr info info for target " + TripleName, Context);
606
607 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
608 if (!MSTI)
609 return error("no subtarget info for target " + TripleName, Context);
610
Eric Christopher0169e422015-03-10 22:03:14 +0000611 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000612 if (!MCE)
613 return error("no code emitter for target " + TripleName, Context);
614
615 // Create the output file.
616 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000617 OutFile =
618 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000619 if (EC)
620 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
621
David Majnemer03e2cc32015-12-21 22:09:27 +0000622 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
623 MS = TheTarget->createMCObjectStreamer(
624 TheTriple, *MC, *MAB, *OutFile, MCE, *MSTI, MCOptions.MCRelaxAll,
625 MCOptions.MCIncrementalLinkerCompatible,
626 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000627 if (!MS)
628 return error("no object streamer for target " + TripleName, Context);
629
630 // Finally create the AsmPrinter we'll use to emit the DIEs.
631 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
632 if (!TM)
633 return error("no target machine for target " + TripleName, Context);
634
635 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
636 if (!Asm)
637 return error("no asm printer for target " + TripleName, Context);
638
Frederic Riss25440872015-03-13 23:30:31 +0000639 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000640 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000641 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000642 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000643
Frederic Rissc99ea202015-02-28 00:29:11 +0000644 return true;
645}
646
Frederic Riss24faade2015-09-02 16:49:13 +0000647bool DwarfStreamer::finish(const DebugMap &DM) {
648 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
649 return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
650
Frederic Rissc99ea202015-02-28 00:29:11 +0000651 MS->Finish();
652 return true;
653}
654
Frederic Rissb8b43d52015-03-04 22:07:44 +0000655/// \brief Set the current output section to debug_info and change
656/// the MC Dwarf version to \p DwarfVersion.
657void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
658 MS->SwitchSection(MOFI->getDwarfInfoSection());
659 MC->setDwarfVersion(DwarfVersion);
660}
661
662/// \brief Emit the compilation unit header for \p Unit in the
663/// debug_info section.
664///
665/// A Dwarf scetion header is encoded as:
666/// uint32_t Unit length (omiting this field)
667/// uint16_t Version
668/// uint32_t Abbreviation table offset
669/// uint8_t Address size
670///
671/// Leading to a total of 11 bytes.
672void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
673 unsigned Version = Unit.getOrigUnit().getVersion();
674 switchToDebugInfoSection(Version);
675
676 // Emit size of content not including length itself. The size has
677 // already been computed in CompileUnit::computeOffsets(). Substract
678 // 4 to that size to account for the length field.
679 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
680 Asm->EmitInt16(Version);
681 // We share one abbreviations table across all units so it's always at the
682 // start of the section.
683 Asm->EmitInt32(0);
684 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
685}
686
687/// \brief Emit the \p Abbrevs array as the shared abbreviation table
688/// for the linked Dwarf file.
David Blaikie6196aa02015-11-18 00:34:10 +0000689void DwarfStreamer::emitAbbrevs(
690 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs) {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000691 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
692 Asm->emitDwarfAbbrevs(Abbrevs);
693}
694
695/// \brief Recursively emit the DIE tree rooted at \p Die.
696void DwarfStreamer::emitDIE(DIE &Die) {
697 MS->SwitchSection(MOFI->getDwarfInfoSection());
698 Asm->emitDwarfDIE(Die);
699}
700
Frederic Rissef648462015-03-06 17:56:30 +0000701/// \brief Emit the debug_str section stored in \p Pool.
702void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000703 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000704 for (auto *Entry = Pool.getFirstEntry(); Entry;
705 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000706 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000707 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
708}
709
Frederic Riss25440872015-03-13 23:30:31 +0000710/// \brief Emit the debug_range section contents for \p FuncRange by
711/// translating the original \p Entries. The debug_range section
712/// format is totally trivial, consisting just of pairs of address
713/// sized addresses describing the ranges.
714void DwarfStreamer::emitRangesEntries(
715 int64_t UnitPcOffset, uint64_t OrigLowPc,
716 FunctionIntervals::const_iterator FuncRange,
717 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
718 unsigned AddressSize) {
719 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
720
721 // Offset each range by the right amount.
Frederic Riss94546202015-08-31 05:09:32 +0000722 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
Frederic Riss25440872015-03-13 23:30:31 +0000723 for (const auto &Range : Entries) {
724 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
725 warn("unsupported base address selection operation",
726 "emitting debug_ranges");
727 break;
728 }
729 // Do not emit empty ranges.
730 if (Range.StartAddress == Range.EndAddress)
731 continue;
732
733 // All range entries should lie in the function range.
734 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
735 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
736 warn("inconsistent range data.", "emitting debug_ranges");
737 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
738 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
739 RangesSectionSize += 2 * AddressSize;
740 }
741
742 // Add the terminator entry.
743 MS->EmitIntValue(0, AddressSize);
744 MS->EmitIntValue(0, AddressSize);
745 RangesSectionSize += 2 * AddressSize;
746}
747
Frederic Riss563b1b02015-03-14 03:46:51 +0000748/// \brief Emit the debug_aranges contribution of a unit and
749/// if \p DoDebugRanges is true the debug_range contents for a
750/// compile_unit level DW_AT_ranges attribute (Which are basically the
751/// same thing with a different base address).
752/// Just aggregate all the ranges gathered inside that unit.
753void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
754 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000755 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
756 // Gather the ranges in a vector, so that we can simplify them. The
757 // IntervalMap will have coalesced the non-linked ranges, but here
758 // we want to coalesce the linked addresses.
759 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
760 const auto &FunctionRanges = Unit.getFunctionRanges();
761 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
762 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000763 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
764 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000765
766 // The object addresses where sorted, but again, the linked
767 // addresses might end up in a different order.
768 std::sort(Ranges.begin(), Ranges.end());
769
Frederic Riss563b1b02015-03-14 03:46:51 +0000770 if (!Ranges.empty()) {
771 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
772
Rafael Espindola9ab09232015-03-17 20:07:06 +0000773 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
774 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000775
776 unsigned HeaderSize =
777 sizeof(int32_t) + // Size of contents (w/o this field
778 sizeof(int16_t) + // DWARF ARange version number
779 sizeof(int32_t) + // Offset of CU in the .debug_info section
780 sizeof(int8_t) + // Pointer Size (in bytes)
781 sizeof(int8_t); // Segment Size (in bytes)
782
783 unsigned TupleSize = AddressSize * 2;
784 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
785
786 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000787 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000788 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
789 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
790 Asm->EmitInt8(AddressSize); // Address size
791 Asm->EmitInt8(0); // Segment size
792
Lang Hames9ff69c82015-04-24 19:11:51 +0000793 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000794
795 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
796 ++Range) {
797 uint64_t RangeStart = Range->first;
798 MS->EmitIntValue(RangeStart, AddressSize);
799 while ((Range + 1) != End && Range->second == (Range + 1)->first)
800 ++Range;
801 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
802 }
803
804 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000805 Asm->OutStreamer->EmitIntValue(0, AddressSize);
806 Asm->OutStreamer->EmitIntValue(0, AddressSize);
807 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000808 }
809
810 if (!DoDebugRanges)
811 return;
812
813 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
814 // Offset each range by the right amount.
815 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000816 // Emit coalesced ranges.
817 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000818 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000819 while (Range + 1 != End && Range->second == (Range + 1)->first)
820 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000821 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000822 RangesSectionSize += 2 * AddressSize;
823 }
824
825 // Add the terminator entry.
826 MS->EmitIntValue(0, AddressSize);
827 MS->EmitIntValue(0, AddressSize);
828 RangesSectionSize += 2 * AddressSize;
829}
830
Frederic Rissdfb97902015-03-14 15:49:07 +0000831/// \brief Emit location lists for \p Unit and update attribtues to
832/// point to the new entries.
833void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
834 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000835 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000836
837 if (Attributes.empty())
838 return;
839
840 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
841
842 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
843 const DWARFSection &InputSec = Dwarf.getLocSection();
844 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
845 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000846 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000847 int64_t UnitPcOffset = 0;
848 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
849 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
850 if (OrigLowPc != -1ULL)
851 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
852
853 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000854 uint32_t Offset = Attr.first.get();
855 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000856 // This is the quantity to add to the old location address to get
857 // the correct address for the new one.
858 int64_t LocPcOffset = Attr.second + UnitPcOffset;
859 while (Data.isValidOffset(Offset)) {
860 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
861 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
862 LocSectionSize += 2 * AddressSize;
863 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000864 Asm->OutStreamer->EmitIntValue(0, AddressSize);
865 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000866 break;
867 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000868 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
869 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000870 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000871 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000872 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000873 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000874 StringRef(InputSec.Data.substr(Offset, Length)));
875 Offset += Length;
876 LocSectionSize += Length + 2;
877 }
878 }
879}
880
Frederic Rissa5e14532015-08-07 15:14:13 +0000881void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
882 StringRef PrologueBytes,
Frederic Riss63786b02015-03-15 20:45:43 +0000883 unsigned MinInstLength,
884 std::vector<DWARFDebugLine::Row> &Rows,
885 unsigned PointerSize) {
886 // Switch to the section where the table will be emitted into.
887 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000888 MCSymbol *LineStartSym = MC->createTempSymbol();
889 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000890
891 // The first 4 bytes is the total length of the information for this
892 // compilation unit (not including these 4 bytes for the length).
893 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000894 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000895 // Copy Prologue.
896 MS->EmitBytes(PrologueBytes);
897 LineSectionSize += PrologueBytes.size() + 4;
898
Frederic Rissc3820d02015-03-15 22:20:28 +0000899 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000900 raw_svector_ostream EncodingOS(EncodingBuffer);
901
902 if (Rows.empty()) {
903 // We only have the dummy entry, dsymutil emits an entry with a 0
904 // address in that case.
Frederic Rissa5e14532015-08-07 15:14:13 +0000905 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000906 MS->EmitBytes(EncodingOS.str());
907 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000908 MS->EmitLabel(LineEndSym);
909 return;
910 }
911
912 // Line table state machine fields
913 unsigned FileNum = 1;
914 unsigned LastLine = 1;
915 unsigned Column = 0;
916 unsigned IsStatement = 1;
917 unsigned Isa = 0;
918 uint64_t Address = -1ULL;
919
920 unsigned RowsSinceLastSequence = 0;
921
922 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
923 auto &Row = Rows[Idx];
924
925 int64_t AddressDelta;
926 if (Address == -1ULL) {
927 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
928 MS->EmitULEB128IntValue(PointerSize + 1);
929 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
930 MS->EmitIntValue(Row.Address, PointerSize);
931 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
932 AddressDelta = 0;
933 } else {
934 AddressDelta = (Row.Address - Address) / MinInstLength;
935 }
936
937 // FIXME: code copied and transfromed from
938 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
939 // this code, but the current compatibility requirement with
940 // classic dsymutil makes it hard. Revisit that once this
941 // requirement is dropped.
942
943 if (FileNum != Row.File) {
944 FileNum = Row.File;
945 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
946 MS->EmitULEB128IntValue(FileNum);
947 LineSectionSize += 1 + getULEB128Size(FileNum);
948 }
949 if (Column != Row.Column) {
950 Column = Row.Column;
951 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
952 MS->EmitULEB128IntValue(Column);
953 LineSectionSize += 1 + getULEB128Size(Column);
954 }
955
956 // FIXME: We should handle the discriminator here, but dsymutil
957 // doesn' consider it, thus ignore it for now.
958
959 if (Isa != Row.Isa) {
960 Isa = Row.Isa;
961 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
962 MS->EmitULEB128IntValue(Isa);
963 LineSectionSize += 1 + getULEB128Size(Isa);
964 }
965 if (IsStatement != Row.IsStmt) {
966 IsStatement = Row.IsStmt;
967 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
968 LineSectionSize += 1;
969 }
970 if (Row.BasicBlock) {
971 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
972 LineSectionSize += 1;
973 }
974
975 if (Row.PrologueEnd) {
976 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
977 LineSectionSize += 1;
978 }
979
980 if (Row.EpilogueBegin) {
981 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
982 LineSectionSize += 1;
983 }
984
985 int64_t LineDelta = int64_t(Row.Line) - LastLine;
986 if (!Row.EndSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000987 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000988 MS->EmitBytes(EncodingOS.str());
989 LineSectionSize += EncodingBuffer.size();
990 EncodingBuffer.resize(0);
991 Address = Row.Address;
992 LastLine = Row.Line;
993 RowsSinceLastSequence++;
994 } else {
995 if (LineDelta) {
996 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
997 MS->EmitSLEB128IntValue(LineDelta);
998 LineSectionSize += 1 + getSLEB128Size(LineDelta);
999 }
1000 if (AddressDelta) {
1001 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
1002 MS->EmitULEB128IntValue(AddressDelta);
1003 LineSectionSize += 1 + getULEB128Size(AddressDelta);
1004 }
Frederic Rissa5e14532015-08-07 15:14:13 +00001005 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001006 MS->EmitBytes(EncodingOS.str());
1007 LineSectionSize += EncodingBuffer.size();
1008 EncodingBuffer.resize(0);
Frederic Riss63786b02015-03-15 20:45:43 +00001009 Address = -1ULL;
1010 LastLine = FileNum = IsStatement = 1;
1011 RowsSinceLastSequence = Column = Isa = 0;
1012 }
1013 }
1014
1015 if (RowsSinceLastSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +00001016 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001017 MS->EmitBytes(EncodingOS.str());
1018 LineSectionSize += EncodingBuffer.size();
1019 EncodingBuffer.resize(0);
1020 }
1021
1022 MS->EmitLabel(LineEndSym);
1023}
1024
Frederic Rissbce93ff2015-03-16 02:05:10 +00001025/// \brief Emit the pubnames or pubtypes section contribution for \p
1026/// Unit into \p Sec. The data is provided in \p Names.
1027void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001028 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001029 const std::vector<CompileUnit::AccelInfo> &Names) {
1030 if (Names.empty())
1031 return;
1032
1033 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001034 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001035 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1036 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001037
1038 bool HeaderEmitted = false;
1039 // Emit the pubnames for this compilation unit.
1040 for (const auto &Name : Names) {
1041 if (Name.SkipPubSection)
1042 continue;
1043
1044 if (!HeaderEmitted) {
1045 // Emit the header.
1046 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001047 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001048 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001049 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001050 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1051 HeaderEmitted = true;
1052 }
1053 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001054 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001055 StringRef(Name.Name.data(), Name.Name.size() + 1));
1056 }
1057
1058 if (!HeaderEmitted)
1059 return;
1060 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001061 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001062}
1063
1064/// \brief Emit .debug_pubnames for \p Unit.
1065void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1066 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1067 "names", Unit, Unit.getPubnames());
1068}
1069
1070/// \brief Emit .debug_pubtypes for \p Unit.
1071void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1072 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1073 "types", Unit, Unit.getPubtypes());
1074}
1075
Frederic Riss5a642072015-06-05 23:06:11 +00001076/// \brief Emit a CIE into the debug_frame section.
1077void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1078 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1079
1080 MS->EmitBytes(CIEBytes);
1081 FrameSectionSize += CIEBytes.size();
1082}
1083
1084/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1085/// contains the FDE data without the length, CIE offset and address
1086/// which will be replaced with the paramter values.
1087void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1088 uint32_t Address, StringRef FDEBytes) {
1089 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1090
1091 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1092 MS->EmitIntValue(CIEOffset, 4);
1093 MS->EmitIntValue(Address, AddrSize);
1094 MS->EmitBytes(FDEBytes);
1095 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1096}
1097
Frederic Rissd3455182015-01-28 18:27:01 +00001098/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001099///
1100/// The link of the dwarf information from the object files will be
1101/// driven by the selection of 'root DIEs', which are DIEs that
1102/// describe variables or functions that are present in the linked
1103/// binary (and thus have entries in the debug map). All the debug
1104/// information that will be linked (the DIEs, but also the line
1105/// tables, ranges, ...) is derived from that set of root DIEs.
1106///
1107/// The root DIEs are identified because they contain relocations that
1108/// correspond to a debug map entry at specific places (the low_pc for
1109/// a function, the location for a variable). These relocations are
1110/// called ValidRelocs in the DwarfLinker and are gathered as a very
1111/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001112class DwarfLinker {
1113public:
Frederic Rissb9818322015-02-28 00:29:07 +00001114 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1115 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001116 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001117
1118 /// \brief Link the contents of the DebugMap.
1119 bool link(const DebugMap &);
1120
Adrian Prantlc3021ee2015-09-22 18:50:51 +00001121 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1122 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1123
Frederic Rissd3455182015-01-28 18:27:01 +00001124private:
Frederic Riss563cba62015-01-28 22:15:14 +00001125 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001126 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001127
1128 /// \brief Called at the end of a debug object link.
1129 void endDebugObject();
1130
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001131 /// Keeps track of relocations.
1132 class RelocationManager {
1133 struct ValidReloc {
1134 uint32_t Offset;
1135 uint32_t Size;
1136 uint64_t Addend;
1137 const DebugMapObject::DebugMapEntry *Mapping;
Frederic Riss1036e642015-02-13 23:18:22 +00001138
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001139 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1140 const DebugMapObject::DebugMapEntry *Mapping)
1141 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
Frederic Riss1036e642015-02-13 23:18:22 +00001142
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001143 bool operator<(const ValidReloc &RHS) const {
1144 return Offset < RHS.Offset;
1145 }
1146 };
1147
1148 DwarfLinker &Linker;
1149
1150 /// \brief The valid relocations for the current DebugMapObject.
1151 /// This vector is sorted by relocation offset.
1152 std::vector<ValidReloc> ValidRelocs;
1153
1154 /// \brief Index into ValidRelocs of the next relocation to
1155 /// consider. As we walk the DIEs in acsending file offset and as
1156 /// ValidRelocs is sorted by file offset, keeping this index
1157 /// uptodate is all we have to do to have a cheap lookup during the
1158 /// root DIE selection and during DIE cloning.
1159 unsigned NextValidReloc;
1160
1161 public:
1162 RelocationManager(DwarfLinker &Linker)
1163 : Linker(Linker), NextValidReloc(0) {}
1164
1165 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1166 /// \brief Reset the NextValidReloc counter.
1167 void resetValidRelocs() { NextValidReloc = 0; }
1168
1169 /// \defgroup FindValidRelocations Translate debug map into a list
1170 /// of relevant relocations
1171 ///
1172 /// @{
1173 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1174 const DebugMapObject &DMO);
1175
1176 bool findValidRelocs(const object::SectionRef &Section,
1177 const object::ObjectFile &Obj,
1178 const DebugMapObject &DMO);
1179
1180 void findValidRelocsMachO(const object::SectionRef &Section,
1181 const object::MachOObjectFile &Obj,
1182 const DebugMapObject &DMO);
1183 /// @}
1184
1185 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1186 CompileUnit::DIEInfo &Info);
1187
1188 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1189 bool isLittleEndian);
Frederic Riss1036e642015-02-13 23:18:22 +00001190 };
1191
Frederic Riss84c09a52015-02-13 23:18:34 +00001192 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1193 ///
1194 /// @{
1195 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1196 /// keep. Store that information in \p CU's DIEInfo.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001197 void lookForDIEsToKeep(RelocationManager &RelocMgr,
1198 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001199 const DebugMapObject &DMO, CompileUnit &CU,
1200 unsigned Flags);
1201
Adrian Prantle5162db2015-09-22 22:20:50 +00001202 /// If this compile unit is really a skeleton CU that points to a
1203 /// clang module, register it in ClangModules and return true.
1204 ///
1205 /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
1206 /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
1207 /// hash.
1208 bool registerModuleReference(const DWARFDebugInfoEntryMinimal &CUDie,
1209 const DWARFUnit &Unit, DebugMap &ModuleMap,
1210 unsigned Indent = 0);
1211
1212 /// Recursively add the debug info in this clang module .pcm
1213 /// file (and all the modules imported by it in a bottom-up fashion)
1214 /// to Units.
Adrian Prantla112ef92015-09-23 17:35:52 +00001215 void loadClangModule(StringRef Filename, StringRef ModulePath,
1216 StringRef ModuleName, uint64_t DwoId,
Adrian Prantle5162db2015-09-22 22:20:50 +00001217 DebugMap &ModuleMap, unsigned Indent = 0);
1218
Frederic Riss84c09a52015-02-13 23:18:34 +00001219 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1220 enum TravesalFlags {
1221 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1222 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1223 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1224 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001225 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss29eedc72015-09-11 04:17:30 +00001226 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
Frederic Riss84c09a52015-02-13 23:18:34 +00001227 };
1228
1229 /// \brief Mark the passed DIE as well as all the ones it depends on
1230 /// as kept.
Adrian Prantl6ec47122015-09-22 15:31:14 +00001231 void keepDIEAndDependencies(RelocationManager &RelocMgr,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001232 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001233 CompileUnit::DIEInfo &MyInfo,
1234 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001235 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001236
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001237 unsigned shouldKeepDIE(RelocationManager &RelocMgr,
1238 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001239 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1240 unsigned Flags);
1241
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001242 unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
1243 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001244 CompileUnit &Unit,
1245 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1246
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001247 unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
1248 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001249 CompileUnit &Unit,
1250 CompileUnit::DIEInfo &MyInfo,
1251 unsigned Flags);
1252
1253 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1254 CompileUnit::DIEInfo &Info);
1255 /// @}
1256
Frederic Rissb8b43d52015-03-04 22:07:44 +00001257 /// \defgroup Linking Methods used to link the debug information
1258 ///
1259 /// @{
Frederic Rissb8b43d52015-03-04 22:07:44 +00001260
Adrian Prantl3565af42015-09-14 16:46:10 +00001261 class DIECloner {
1262 DwarfLinker &Linker;
1263 RelocationManager &RelocMgr;
1264 /// Allocator used for all the DIEValue objects.
1265 BumpPtrAllocator &DIEAlloc;
1266 MutableArrayRef<CompileUnit> CompileUnits;
1267 LinkOptions Options;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001268
Adrian Prantl3565af42015-09-14 16:46:10 +00001269 public:
1270 DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1271 BumpPtrAllocator &DIEAlloc,
1272 MutableArrayRef<CompileUnit> CompileUnits, LinkOptions &Options)
1273 : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1274 CompileUnits(CompileUnits), Options(Options) {}
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001275
Adrian Prantl3565af42015-09-14 16:46:10 +00001276 /// Recursively clone \p InputDIE into an tree of DIE objects
1277 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1278 /// stripped out and addresses have been rewritten according to the
1279 /// debug map.
1280 ///
1281 /// \param OutOffset is the offset the cloned DIE in the output
1282 /// compile unit.
1283 /// \param PCOffset (while cloning a function scope) is the offset
1284 /// applied to the entry point of the function to get the linked address.
1285 ///
1286 /// \returns the root of the cloned tree or null if nothing was selected.
Adrian Prantl3abe18d2015-09-14 23:27:26 +00001287 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Adrian Prantl3565af42015-09-14 16:46:10 +00001288 int64_t PCOffset, uint32_t OutOffset, unsigned Flags);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001289
Adrian Prantl3565af42015-09-14 16:46:10 +00001290 /// Construct the output DIE tree by cloning the DIEs we
1291 /// chose to keep above. If there are no valid relocs, then there's
1292 /// nothing to clone/emit.
1293 void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001294
Adrian Prantl3565af42015-09-14 16:46:10 +00001295 private:
1296 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
Frederic Rissbce93ff2015-03-16 02:05:10 +00001297
Adrian Prantl3565af42015-09-14 16:46:10 +00001298 /// Information gathered and exchanged between the various
1299 /// clone*Attributes helpers about the attributes of a particular DIE.
1300 struct AttributesInfo {
1301 const char *Name, *MangledName; ///< Names.
1302 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
Frederic Riss31da3242015-03-11 18:45:52 +00001303
Adrian Prantl3565af42015-09-14 16:46:10 +00001304 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1305 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1306 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
Frederic Rissbce93ff2015-03-16 02:05:10 +00001307
Adrian Prantl3565af42015-09-14 16:46:10 +00001308 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1309 bool IsDeclaration; ///< Is this DIE only a declaration?
1310
1311 AttributesInfo()
1312 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1313 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1314 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1315 };
1316
1317 /// Helper for cloneDIE.
1318 unsigned cloneAttribute(DIE &Die,
1319 const DWARFDebugInfoEntryMinimal &InputDIE,
1320 CompileUnit &U, const DWARFFormValue &Val,
1321 const AttributeSpec AttrSpec, unsigned AttrSize,
1322 AttributesInfo &AttrInfo);
1323
1324 /// Clone a string attribute described by \p AttrSpec and add
1325 /// it to \p Die.
1326 /// \returns the size of the new attribute.
1327 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1328 const DWARFFormValue &Val,
1329 const DWARFUnit &U);
1330
1331 /// Clone an attribute referencing another DIE and add
1332 /// it to \p Die.
1333 /// \returns the size of the new attribute.
1334 unsigned
1335 cloneDieReferenceAttribute(DIE &Die,
1336 const DWARFDebugInfoEntryMinimal &InputDIE,
1337 AttributeSpec AttrSpec, unsigned AttrSize,
1338 const DWARFFormValue &Val, CompileUnit &Unit);
1339
1340 /// Clone an attribute referencing another DIE and add
1341 /// it to \p Die.
1342 /// \returns the size of the new attribute.
1343 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1344 const DWARFFormValue &Val, unsigned AttrSize);
1345
1346 /// Clone an attribute referencing another DIE and add
1347 /// it to \p Die.
1348 /// \returns the size of the new attribute.
1349 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1350 const DWARFFormValue &Val,
1351 const CompileUnit &Unit,
1352 AttributesInfo &Info);
1353
1354 /// Clone a scalar attribute and add it to \p Die.
1355 /// \returns the size of the new attribute.
1356 unsigned cloneScalarAttribute(DIE &Die,
1357 const DWARFDebugInfoEntryMinimal &InputDIE,
1358 CompileUnit &U, AttributeSpec AttrSpec,
1359 const DWARFFormValue &Val, unsigned AttrSize,
1360 AttributesInfo &Info);
1361
1362 /// Get the potential name and mangled name for the entity
1363 /// described by \p Die and store them in \Info if they are not
1364 /// already there.
1365 /// \returns is a name was found.
1366 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1367 AttributesInfo &Info);
1368
1369 /// Create a copy of abbreviation Abbrev.
1370 void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
Frederic Riss31da3242015-03-11 18:45:52 +00001371 };
1372
Frederic Rissb8b43d52015-03-04 22:07:44 +00001373 /// \brief Assign an abbreviation number to \p Abbrev
1374 void AssignAbbrev(DIEAbbrev &Abbrev);
1375
1376 /// \brief FoldingSet that uniques the abbreviations.
1377 FoldingSet<DIEAbbrev> AbbreviationsSet;
1378 /// \brief Storage for the unique Abbreviations.
1379 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1380 /// be changed to a vecot of unique_ptrs.
David Blaikie6196aa02015-11-18 00:34:10 +00001381 std::vector<std::unique_ptr<DIEAbbrev>> Abbreviations;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001382
Frederic Riss25440872015-03-13 23:30:31 +00001383 /// \brief Compute and emit debug_ranges section for \p Unit, and
1384 /// patch the attributes referencing it.
1385 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1386
1387 /// \brief Generate and emit the DW_AT_ranges attribute for a
1388 /// compile_unit if it had one.
1389 void generateUnitRanges(CompileUnit &Unit) const;
1390
Frederic Riss63786b02015-03-15 20:45:43 +00001391 /// \brief Extract the line tables fromt he original dwarf, extract
1392 /// the relevant parts according to the linked function ranges and
1393 /// emit the result in the debug_line section.
1394 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1395
Frederic Rissbce93ff2015-03-16 02:05:10 +00001396 /// \brief Emit the accelerator entries for \p Unit.
1397 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1398
Frederic Riss5a642072015-06-05 23:06:11 +00001399 /// \brief Patch the frame info for an object file and emit it.
1400 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1401 unsigned AddressSize);
1402
Frederic Rissb8b43d52015-03-04 22:07:44 +00001403 /// \brief DIELoc objects that need to be destructed (but not freed!).
1404 std::vector<DIELoc *> DIELocs;
1405 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1406 std::vector<DIEBlock *> DIEBlocks;
1407 /// \brief Allocator used for all the DIEValue objects.
1408 BumpPtrAllocator DIEAlloc;
1409 /// @}
1410
Frederic Riss1c650942015-07-21 22:41:43 +00001411 /// ODR Contexts for that link.
1412 DeclContextTree ODRContexts;
1413
Frederic Riss1b9da422015-02-13 23:18:29 +00001414 /// \defgroup Helpers Various helper methods.
1415 ///
1416 /// @{
Frederic Rissc99ea202015-02-28 00:29:11 +00001417 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001418
1419 /// \brief Attempt to load a debug object from disk.
1420 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1421 DebugMapObject &Obj,
1422 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001423 /// @}
1424
Frederic Rissd3455182015-01-28 18:27:01 +00001425 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001426 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001427 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001428 std::unique_ptr<DwarfStreamer> Streamer;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001429 uint64_t OutputDebugInfoSize;
Adrian Prantle5162db2015-09-22 22:20:50 +00001430 unsigned UnitID; ///< A unique ID that identifies each compile unit.
Frederic Riss563cba62015-01-28 22:15:14 +00001431
1432 /// The units of the current debug map object.
1433 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001434
Oleg Ranevskyy5f78c5c2015-10-23 17:10:44 +00001435 /// The debug map object currently under consideration.
Frederic Riss1b9da422015-02-13 23:18:29 +00001436 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001437
1438 /// \brief The Dwarf string pool
1439 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001440
1441 /// \brief This map is keyed by the entry PC of functions in that
1442 /// debug object and the associated value is a pair storing the
1443 /// corresponding end PC and the offset to apply to get the linked
1444 /// address.
1445 ///
1446 /// See startDebugObject() for a more complete description of its use.
1447 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001448
1449 /// \brief The CIEs that have been emitted in the output
1450 /// section. The actual CIE data serves a the key to this StringMap,
1451 /// this takes care of comparing the semantics of CIEs defined in
1452 /// different object files.
1453 StringMap<uint32_t> EmittedCIEs;
1454
1455 /// Offset of the last CIE that has been emitted in the output
1456 /// debug_frame section.
1457 uint32_t LastCIEOffset;
Adrian Prantle5162db2015-09-22 22:20:50 +00001458
Adrian Prantl20937022015-09-23 17:11:10 +00001459 /// Mapping the PCM filename to the DwoId.
1460 StringMap<uint64_t> ClangModules;
Adrian Prantla9e23832016-01-14 18:31:07 +00001461
1462 bool ModuleCacheHintDisplayed = false;
1463 bool ArchiveHintDisplayed = false;
Frederic Rissd3455182015-01-28 18:27:01 +00001464};
1465
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001466/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
1467/// CompileUnit object instead.
1468static CompileUnit *getUnitForOffset(MutableArrayRef<CompileUnit> Units,
1469 unsigned Offset) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001470 auto CU =
1471 std::upper_bound(Units.begin(), Units.end(), Offset,
1472 [](uint32_t LHS, const CompileUnit &RHS) {
1473 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1474 });
1475 return CU != Units.end() ? &*CU : nullptr;
1476}
1477
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001478/// Resolve the DIE attribute reference that has been
Frederic Riss1b9da422015-02-13 23:18:29 +00001479/// extracted in \p RefValue. The resulting DIE migh be in another
1480/// CompileUnit which is stored into \p ReferencedCU.
1481/// \returns null if resolving fails for any reason.
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001482static const DWARFDebugInfoEntryMinimal *resolveDIEReference(
1483 const DwarfLinker &Linker, MutableArrayRef<CompileUnit> Units,
Frederic Riss1c650942015-07-21 22:41:43 +00001484 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001485 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1486 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1487 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1488
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001489 if ((RefCU = getUnitForOffset(Units, RefOffset)))
Frederic Riss1b9da422015-02-13 23:18:29 +00001490 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1491 return RefDie;
1492
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001493 Linker.reportWarning("could not find referenced DIE", &Unit, &DIE);
Frederic Riss1b9da422015-02-13 23:18:29 +00001494 return nullptr;
1495}
1496
Frederic Riss1c650942015-07-21 22:41:43 +00001497/// \returns whether the passed \a Attr type might contain a DIE
1498/// reference suitable for ODR uniquing.
1499static bool isODRAttribute(uint16_t Attr) {
1500 switch (Attr) {
1501 default:
1502 return false;
1503 case dwarf::DW_AT_type:
1504 case dwarf::DW_AT_containing_type:
1505 case dwarf::DW_AT_specification:
1506 case dwarf::DW_AT_abstract_origin:
1507 case dwarf::DW_AT_import:
1508 return true;
1509 }
1510 llvm_unreachable("Improper attribute.");
1511}
1512
1513/// Set the last DIE/CU a context was seen in and, possibly invalidate
1514/// the context if it is ambiguous.
1515///
1516/// In the current implementation, we don't handle overloaded
1517/// functions well, because the argument types are not taken into
1518/// account when computing the DeclContext tree.
1519///
1520/// Some of this is mitigated byt using mangled names that do contain
1521/// the arguments types, but sometimes (eg. with function templates)
1522/// we don't have that. In that case, just do not unique anything that
1523/// refers to the contexts we are not able to distinguish.
1524///
1525/// If a context that is not a namespace appears twice in the same CU,
1526/// we know it is ambiguous. Make it invalid.
1527bool DeclContext::setLastSeenDIE(CompileUnit &U,
1528 const DWARFDebugInfoEntryMinimal *Die) {
1529 if (LastSeenCompileUnitID == U.getUniqueID()) {
1530 DWARFUnit &OrigUnit = U.getOrigUnit();
1531 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1532 U.getInfo(FirstIdx).Ctxt = nullptr;
1533 return false;
1534 }
1535
1536 LastSeenCompileUnitID = U.getUniqueID();
1537 LastSeenDIE = Die;
1538 return true;
1539}
1540
Frederic Riss1c650942015-07-21 22:41:43 +00001541PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1542 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
Adrian Prantl42562c32015-10-02 00:27:08 +00001543 NonRelocatableStringpool &StringPool, bool InClangModule) {
Frederic Riss1c650942015-07-21 22:41:43 +00001544 unsigned Tag = DIE->getTag();
1545
1546 // FIXME: dsymutil-classic compat: We should bail out here if we
1547 // have a specification or an abstract_origin. We will get the
1548 // parent context wrong here.
1549
1550 switch (Tag) {
1551 default:
1552 // By default stop gathering child contexts.
1553 return PointerIntPair<DeclContext *, 1>(nullptr);
Adrian Prantla112ef92015-09-23 17:35:52 +00001554 case dwarf::DW_TAG_module:
1555 break;
Frederic Riss1c650942015-07-21 22:41:43 +00001556 case dwarf::DW_TAG_compile_unit:
Frederic Riss1c650942015-07-21 22:41:43 +00001557 return PointerIntPair<DeclContext *, 1>(&Context);
1558 case dwarf::DW_TAG_subprogram:
1559 // Do not unique anything inside CU local functions.
1560 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1561 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1562 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1563 dwarf::DW_AT_external, 0))
1564 return PointerIntPair<DeclContext *, 1>(nullptr);
1565 // Fallthrough
1566 case dwarf::DW_TAG_member:
1567 case dwarf::DW_TAG_namespace:
1568 case dwarf::DW_TAG_structure_type:
1569 case dwarf::DW_TAG_class_type:
1570 case dwarf::DW_TAG_union_type:
1571 case dwarf::DW_TAG_enumeration_type:
1572 case dwarf::DW_TAG_typedef:
1573 // Artificial things might be ambiguous, because they might be
1574 // created on demand. For example implicitely defined constructors
1575 // are ambiguous because of the way we identify contexts, and they
1576 // won't be generated everytime everywhere.
1577 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1578 dwarf::DW_AT_artificial, 0))
1579 return PointerIntPair<DeclContext *, 1>(nullptr);
1580 break;
1581 }
1582
1583 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1584 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1585 StringRef NameRef;
1586 StringRef ShortNameRef;
1587 StringRef FileRef;
1588
1589 if (Name)
1590 NameRef = StringPool.internString(Name);
1591 else if (Tag == dwarf::DW_TAG_namespace)
1592 // FIXME: For dsymutil-classic compatibility. I think uniquing
1593 // within anonymous namespaces is wrong. There is no ODR guarantee
1594 // there.
1595 NameRef = StringPool.internString("(anonymous namespace)");
1596
1597 if (ShortName && ShortName != Name)
1598 ShortNameRef = StringPool.internString(ShortName);
1599 else
1600 ShortNameRef = NameRef;
1601
1602 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1603 Tag != dwarf::DW_TAG_union_type &&
1604 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1605 return PointerIntPair<DeclContext *, 1>(nullptr);
1606
1607 std::string File;
1608 unsigned Line = 0;
Adrian Prantl42562c32015-10-02 00:27:08 +00001609 unsigned ByteSize = UINT32_MAX;
Frederic Riss1c650942015-07-21 22:41:43 +00001610
Adrian Prantl42562c32015-10-02 00:27:08 +00001611 if (!InClangModule) {
1612 // Gather some discriminating data about the DeclContext we will be
1613 // creating: File, line number and byte size. This shouldn't be
1614 // necessary, because the ODR is just about names, but given that we
1615 // do some approximations with overloaded functions and anonymous
1616 // namespaces, use these additional data points to make the process
1617 // safer. This is disabled for clang modules, because forward
1618 // declarations of module-defined types do not have a file and line.
1619 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1620 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1621 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1622 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1623 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1624 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1625 &U.getOrigUnit())) {
1626 // FIXME: dsymutil-classic compatibility. I'd rather not
1627 // unique anything in anonymous namespaces, but if we do, then
1628 // verify that the file and line correspond.
1629 if (!Name && Tag == dwarf::DW_TAG_namespace)
1630 FileNum = 1;
Frederic Riss1c650942015-07-21 22:41:43 +00001631
Adrian Prantl42562c32015-10-02 00:27:08 +00001632 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1633 // instead of "" would allow more uniquing, but for now, do
1634 // it this way to match dsymutil-classic.
1635 if (LT->getFileNameByIndex(
1636 FileNum, "",
1637 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1638 File)) {
1639 Line = DIE->getAttributeValueAsUnsignedConstant(
1640 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
Frederic Riss1c650942015-07-21 22:41:43 +00001641#ifdef HAVE_REALPATH
Adrian Prantl42562c32015-10-02 00:27:08 +00001642 // Cache the resolved paths, because calling realpath is expansive.
1643 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1644 File = ResolvedPath;
1645 } else {
1646 char RealPath[PATH_MAX + 1];
1647 RealPath[PATH_MAX] = 0;
1648 if (::realpath(File.c_str(), RealPath))
1649 File = RealPath;
1650 U.setResolvedPath(FileNum, File);
1651 }
Frederic Riss1c650942015-07-21 22:41:43 +00001652#endif
Adrian Prantl42562c32015-10-02 00:27:08 +00001653 FileRef = StringPool.internString(File);
1654 }
Frederic Riss1c650942015-07-21 22:41:43 +00001655 }
1656 }
1657 }
1658 }
1659
1660 if (!Line && NameRef.empty())
1661 return PointerIntPair<DeclContext *, 1>(nullptr);
1662
Frederic Riss1c650942015-07-21 22:41:43 +00001663 // We hash NameRef, which is the mangled name, in order to get most
Adrian Prantla112ef92015-09-23 17:35:52 +00001664 // overloaded functions resolve correctly.
1665 //
1666 // Strictly speaking, hashing the Tag is only necessary for a
1667 // DW_TAG_module, to prevent uniquing of a module and a namespace
1668 // with the same name.
1669 //
1670 // FIXME: dsymutil-classic won't unique the same type presented
1671 // once as a struct and once as a class. Using the Tag in the fully
1672 // qualified name hash to get the same effect.
Frederic Riss1c650942015-07-21 22:41:43 +00001673 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1674
1675 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1676 // use the filename.
1677 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1678 Hash = hash_combine(Hash, FileRef);
1679
1680 // Now look if this context already exists.
1681 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1682 auto ContextIter = Contexts.find(&Key);
1683
1684 if (ContextIter == Contexts.end()) {
1685 // The context wasn't found.
1686 bool Inserted;
1687 DeclContext *NewContext =
1688 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1689 Context, DIE, U.getUniqueID());
1690 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1691 assert(Inserted && "Failed to insert DeclContext");
1692 (void)Inserted;
1693 } else if (Tag != dwarf::DW_TAG_namespace &&
1694 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1695 // The context was found, but it is ambiguous with another context
1696 // in the same file. Mark it invalid.
1697 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1698 }
1699
1700 assert(ContextIter != Contexts.end());
1701 // FIXME: dsymutil-classic compatibility. Union types aren't
1702 // uniques, but their children might be.
1703 if ((Tag == dwarf::DW_TAG_subprogram &&
1704 Context.getTag() != dwarf::DW_TAG_structure_type &&
1705 Context.getTag() != dwarf::DW_TAG_class_type) ||
1706 (Tag == dwarf::DW_TAG_union_type))
1707 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1708
1709 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1710}
1711
Adrian Prantl3565af42015-09-14 16:46:10 +00001712bool DwarfLinker::DIECloner::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1713 DWARFUnit &U, AttributesInfo &Info) {
1714 // FIXME: a bit wasteful as the first getName might return the
Frederic Rissbce93ff2015-03-16 02:05:10 +00001715 // short name.
1716 if (!Info.MangledName &&
1717 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001718 Info.MangledNameOffset =
1719 Linker.StringPool.getStringOffset(Info.MangledName);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001720
1721 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001722 Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001723
1724 return Info.Name || Info.MangledName;
1725}
1726
Frederic Riss1b9da422015-02-13 23:18:29 +00001727/// \brief Report a warning to the user, optionaly including
1728/// information about a specific \p DIE related to the warning.
1729void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001730 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001731 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001732 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001733 Context = CurrentDebugObject->getObjectFilename();
1734 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001735
Frederic Rissb9818322015-02-28 00:29:07 +00001736 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001737 return;
1738
1739 errs() << " in DIE:\n";
1740 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1741 6 /* Indent */);
1742}
1743
Frederic Rissc99ea202015-02-28 00:29:11 +00001744bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1745 if (Options.NoOutput)
1746 return true;
1747
Frederic Rissb52cf522015-02-28 00:42:37 +00001748 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001749 return Streamer->init(TheTriple, OutputFilename);
1750}
1751
Adrian Prantla112ef92015-09-23 17:35:52 +00001752/// Recursive helper to build the global DeclContext information and
1753/// gather the child->parent relationships in the original compile unit.
1754///
1755/// \return true when this DIE and all of its children are only
1756/// forward declarations to types defined in external clang modules
1757/// (i.e., forward declarations that are children of a DW_TAG_module).
1758static bool analyzeContextInfo(const DWARFDebugInfoEntryMinimal *DIE,
1759 unsigned ParentIdx, CompileUnit &CU,
1760 DeclContext *CurrentDeclContext,
1761 NonRelocatableStringpool &StringPool,
1762 DeclContextTree &Contexts,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001763 bool InImportedModule = false) {
Frederic Riss563cba62015-01-28 22:15:14 +00001764 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001765 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1766
Adrian Prantla112ef92015-09-23 17:35:52 +00001767 // Clang imposes an ODR on modules(!) regardless of the language:
1768 // "The module-id should consist of only a single identifier,
1769 // which provides the name of the module being defined. Each
1770 // module shall have a single definition."
1771 //
1772 // This does not extend to the types inside the modules:
1773 // "[I]n C, this implies that if two structs are defined in
1774 // different submodules with the same name, those two types are
1775 // distinct types (but may be compatible types if their
1776 // definitions match)."
1777 //
1778 // We treat non-C++ modules like namespaces for this reason.
Adrian Prantlf3e634b2015-09-24 16:10:14 +00001779 if (DIE->getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
Adrian Prantlea8a7242015-09-23 20:44:37 +00001780 DIE->getAttributeValueAsString(&CU.getOrigUnit(), dwarf::DW_AT_name,
1781 "") != CU.getClangModuleName()) {
1782 InImportedModule = true;
1783 }
Adrian Prantla112ef92015-09-23 17:35:52 +00001784
Frederic Riss1c650942015-07-21 22:41:43 +00001785 Info.ParentIdx = ParentIdx;
Adrian Prantl42562c32015-10-02 00:27:08 +00001786 bool InClangModule = CU.isClangModule() || InImportedModule;
1787 if (CU.hasODR() || InClangModule) {
Frederic Riss1c650942015-07-21 22:41:43 +00001788 if (CurrentDeclContext) {
Adrian Prantl42562c32015-10-02 00:27:08 +00001789 auto PtrInvalidPair = Contexts.getChildDeclContext(
1790 *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
Frederic Riss1c650942015-07-21 22:41:43 +00001791 CurrentDeclContext = PtrInvalidPair.getPointer();
1792 Info.Ctxt =
1793 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1794 } else
1795 Info.Ctxt = CurrentDeclContext = nullptr;
1796 }
Frederic Riss563cba62015-01-28 22:15:14 +00001797
Adrian Prantlea8a7242015-09-23 20:44:37 +00001798 Info.Prune = InImportedModule;
Frederic Riss563cba62015-01-28 22:15:14 +00001799 if (DIE->hasChildren())
1800 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1801 Child = Child->getSibling())
Adrian Prantla112ef92015-09-23 17:35:52 +00001802 Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001803 StringPool, Contexts, InImportedModule);
Adrian Prantla112ef92015-09-23 17:35:52 +00001804
1805 // Prune this DIE if it is either a forward declaration inside a
1806 // DW_TAG_module or a DW_TAG_module that contains nothing but
1807 // forward declarations.
1808 Info.Prune &= (DIE->getTag() == dwarf::DW_TAG_module) ||
1809 DIE->getAttributeValueAsUnsignedConstant(
1810 &CU.getOrigUnit(), dwarf::DW_AT_declaration, 0);
1811
Adrian Prantld2793a02015-10-05 23:11:20 +00001812 // Don't prune it if there is no definition for the DIE.
1813 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
1814
Adrian Prantla112ef92015-09-23 17:35:52 +00001815 return Info.Prune;
Frederic Riss563cba62015-01-28 22:15:14 +00001816}
1817
Frederic Riss84c09a52015-02-13 23:18:34 +00001818static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1819 switch (Tag) {
1820 default:
1821 return false;
1822 case dwarf::DW_TAG_subprogram:
1823 case dwarf::DW_TAG_lexical_block:
1824 case dwarf::DW_TAG_subroutine_type:
1825 case dwarf::DW_TAG_structure_type:
1826 case dwarf::DW_TAG_class_type:
1827 case dwarf::DW_TAG_union_type:
1828 return true;
1829 }
1830 llvm_unreachable("Invalid Tag");
1831}
1832
Frederic Riss1c650942015-07-21 22:41:43 +00001833static unsigned getRefAddrSize(const DWARFUnit &U) {
1834 if (U.getVersion() == 2)
1835 return U.getAddressByteSize();
1836 return 4;
1837}
1838
Frederic Riss63786b02015-03-15 20:45:43 +00001839void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001840 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss63786b02015-03-15 20:45:43 +00001841 // Iterate over the debug map entries and put all the ones that are
1842 // functions (because they have a size) into the Ranges map. This
1843 // map is very similar to the FunctionRanges that are stored in each
1844 // unit, with 2 notable differences:
1845 // - obviously this one is global, while the other ones are per-unit.
1846 // - this one contains not only the functions described in the DIE
1847 // tree, but also the ones that are only in the debug map.
1848 // The latter information is required to reproduce dsymutil's logic
1849 // while linking line tables. The cases where this information
1850 // matters look like bugs that need to be investigated, but for now
1851 // we need to reproduce dsymutil's behavior.
1852 // FIXME: Once we understood exactly if that information is needed,
1853 // maybe totally remove this (or try to use it to do a real
1854 // -gline-tables-only on Darwin.
1855 for (const auto &Entry : Obj.symbols()) {
1856 const auto &Mapping = Entry.getValue();
Frederic Rissd8c33dc2016-01-31 04:29:22 +00001857 if (Mapping.Size && Mapping.ObjectAddress)
1858 Ranges[*Mapping.ObjectAddress] = std::make_pair(
1859 *Mapping.ObjectAddress + Mapping.Size,
1860 int64_t(Mapping.BinaryAddress) - *Mapping.ObjectAddress);
Frederic Riss63786b02015-03-15 20:45:43 +00001861 }
Frederic Riss563cba62015-01-28 22:15:14 +00001862}
1863
Frederic Riss1036e642015-02-13 23:18:22 +00001864void DwarfLinker::endDebugObject() {
1865 Units.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001866 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001867
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001868 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1869 (*I)->~DIEBlock();
1870 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1871 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001872
1873 DIEBlocks.clear();
1874 DIELocs.clear();
1875 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001876}
1877
1878/// \brief Iterate over the relocations of the given \p Section and
1879/// store the ones that correspond to debug map entries into the
1880/// ValidRelocs array.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001881void DwarfLinker::RelocationManager::
1882findValidRelocsMachO(const object::SectionRef &Section,
1883 const object::MachOObjectFile &Obj,
1884 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001885 StringRef Contents;
1886 Section.getContents(Contents);
1887 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1888
1889 for (const object::RelocationRef &Reloc : Section.relocations()) {
1890 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1891 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1892 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001893 uint64_t Offset64 = Reloc.getOffset();
1894 if ((RelocSize != 4 && RelocSize != 8)) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001895 Linker.reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001896 continue;
1897 }
1898 uint32_t Offset = Offset64;
1899 // Mach-o uses REL relocations, the addend is at the relocation offset.
1900 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1901
1902 auto Sym = Reloc.getSymbol();
1903 if (Sym != Obj.symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001904 ErrorOr<StringRef> SymbolName = Sym->getName();
1905 if (!SymbolName) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001906 Linker.reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001907 continue;
1908 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001909 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001910 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1911 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1912 // Do not store the addend. The addend was the address of the
1913 // symbol in the object file, the address in the binary that is
1914 // stored in the debug map doesn't need to be offseted.
1915 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1916 }
1917 }
1918}
1919
1920/// \brief Dispatch the valid relocation finding logic to the
1921/// appropriate handler depending on the object file format.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001922bool DwarfLinker::RelocationManager::findValidRelocs(
1923 const object::SectionRef &Section, const object::ObjectFile &Obj,
1924 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001925 // Dispatch to the right handler depending on the file type.
1926 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1927 findValidRelocsMachO(Section, *MachOObj, DMO);
1928 else
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001929 Linker.reportWarning(Twine("unsupported object file type: ") +
1930 Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001931
1932 if (ValidRelocs.empty())
1933 return false;
1934
1935 // Sort the relocations by offset. We will walk the DIEs linearly in
1936 // the file, this allows us to just keep an index in the relocation
1937 // array that we advance during our walk, rather than resorting to
1938 // some associative container. See DwarfLinker::NextValidReloc.
1939 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1940 return true;
1941}
1942
1943/// \brief Look for relocations in the debug_info section that match
1944/// entries in the debug map. These relocations will drive the Dwarf
1945/// link by indicating which DIEs refer to symbols present in the
1946/// linked binary.
1947/// \returns wether there are any valid relocations in the debug info.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001948bool DwarfLinker::RelocationManager::
1949findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1950 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001951 // Find the debug_info section.
1952 for (const object::SectionRef &Section : Obj.sections()) {
1953 StringRef SectionName;
1954 Section.getName(SectionName);
1955 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1956 if (SectionName != "debug_info")
1957 continue;
1958 return findValidRelocs(Section, Obj, DMO);
1959 }
1960 return false;
1961}
Frederic Riss563cba62015-01-28 22:15:14 +00001962
Frederic Riss84c09a52015-02-13 23:18:34 +00001963/// \brief Checks that there is a relocation against an actual debug
1964/// map entry between \p StartOffset and \p NextOffset.
1965///
1966/// This function must be called with offsets in strictly ascending
1967/// order because it never looks back at relocations it already 'went past'.
1968/// \returns true and sets Info.InDebugMap if it is the case.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001969bool DwarfLinker::RelocationManager::
1970hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1971 CompileUnit::DIEInfo &Info) {
Frederic Riss84c09a52015-02-13 23:18:34 +00001972 assert(NextValidReloc == 0 ||
1973 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1974 if (NextValidReloc >= ValidRelocs.size())
1975 return false;
1976
1977 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1978
1979 // We might need to skip some relocs that we didn't consider. For
1980 // example the high_pc of a discarded DIE might contain a reloc that
1981 // is in the list because it actually corresponds to the start of a
1982 // function that is in the debug map.
1983 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1984 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1985
1986 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1987 return false;
1988
1989 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00001990 const auto &Mapping = ValidReloc.Mapping->getValue();
Frederic Rissd8c33dc2016-01-31 04:29:22 +00001991 uint64_t ObjectAddress =
1992 Mapping.ObjectAddress ? uint64_t(*Mapping.ObjectAddress) : UINT64_MAX;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001993 if (Linker.Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001994 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
Frederic Rissd8c33dc2016-01-31 04:29:22 +00001995 << " " << format("\t%016" PRIx64 " => %016" PRIx64, ObjectAddress,
Frederic Riss08462f72015-06-01 21:12:45 +00001996 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00001997
Frederic Rissd8c33dc2016-01-31 04:29:22 +00001998 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend;
1999 if (Mapping.ObjectAddress)
2000 Info.AddrAdjust -= ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00002001 Info.InDebugMap = true;
2002 return true;
2003}
2004
2005/// \brief Get the starting and ending (exclusive) offset for the
2006/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
2007/// supposed to point to the position of the first attribute described
2008/// by \p Abbrev.
2009/// \return [StartOffset, EndOffset) as a pair.
2010static std::pair<uint32_t, uint32_t>
2011getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
2012 unsigned Offset, const DWARFUnit &Unit) {
2013 DataExtractor Data = Unit.getDebugInfoExtractor();
2014
2015 for (unsigned i = 0; i < Idx; ++i)
2016 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
2017
2018 uint32_t End = Offset;
2019 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
2020
2021 return std::make_pair(Offset, End);
2022}
2023
2024/// \brief Check if a variable describing DIE should be kept.
2025/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002026unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
2027 const DWARFDebugInfoEntryMinimal &DIE,
2028 CompileUnit &Unit,
2029 CompileUnit::DIEInfo &MyInfo,
2030 unsigned Flags) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002031 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2032
2033 // Global variables with constant value can always be kept.
2034 if (!(Flags & TF_InFunctionScope) &&
2035 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
2036 MyInfo.InDebugMap = true;
2037 return Flags | TF_Keep;
2038 }
2039
2040 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
2041 if (LocationIdx == -1U)
2042 return Flags;
2043
2044 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2045 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2046 uint32_t LocationOffset, LocationEndOffset;
2047 std::tie(LocationOffset, LocationEndOffset) =
2048 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
2049
2050 // See if there is a relocation to a valid debug map entry inside
2051 // this variable's location. The order is important here. We want to
2052 // always check in the variable has a valid relocation, so that the
2053 // DIEInfo is filled. However, we don't want a static variable in a
2054 // function to force us to keep the enclosing function.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002055 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
Frederic Riss84c09a52015-02-13 23:18:34 +00002056 (Flags & TF_InFunctionScope))
2057 return Flags;
2058
Frederic Rissb9818322015-02-28 00:29:07 +00002059 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002060 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2061
2062 return Flags | TF_Keep;
2063}
2064
2065/// \brief Check if a function describing DIE should be kept.
2066/// \returns updated TraversalFlags.
2067unsigned DwarfLinker::shouldKeepSubprogramDIE(
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002068 RelocationManager &RelocMgr,
Frederic Riss84c09a52015-02-13 23:18:34 +00002069 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2070 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2071 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2072
2073 Flags |= TF_InFunctionScope;
2074
2075 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2076 if (LowPcIdx == -1U)
2077 return Flags;
2078
2079 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2080 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2081 uint32_t LowPcOffset, LowPcEndOffset;
2082 std::tie(LowPcOffset, LowPcEndOffset) =
2083 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2084
2085 uint64_t LowPc =
2086 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2087 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2088 if (LowPc == -1ULL ||
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002089 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
Frederic Riss84c09a52015-02-13 23:18:34 +00002090 return Flags;
2091
Frederic Rissb9818322015-02-28 00:29:07 +00002092 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002093 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2094
Frederic Riss1af75f72015-03-12 18:45:10 +00002095 Flags |= TF_Keep;
2096
2097 DWARFFormValue HighPcValue;
2098 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2099 reportWarning("Function without high_pc. Range will be discarded.\n",
2100 &OrigUnit, &DIE);
2101 return Flags;
2102 }
2103
2104 uint64_t HighPc;
2105 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2106 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2107 } else {
2108 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2109 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2110 }
2111
Frederic Riss63786b02015-03-15 20:45:43 +00002112 // Replace the debug map range with a more accurate one.
2113 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00002114 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2115 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00002116}
2117
2118/// \brief Check if a DIE should be kept.
2119/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002120unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
2121 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00002122 CompileUnit &Unit,
2123 CompileUnit::DIEInfo &MyInfo,
2124 unsigned Flags) {
2125 switch (DIE.getTag()) {
2126 case dwarf::DW_TAG_constant:
2127 case dwarf::DW_TAG_variable:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002128 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002129 case dwarf::DW_TAG_subprogram:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002130 return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002131 case dwarf::DW_TAG_module:
2132 case dwarf::DW_TAG_imported_module:
2133 case dwarf::DW_TAG_imported_declaration:
2134 case dwarf::DW_TAG_imported_unit:
2135 // We always want to keep these.
2136 return Flags | TF_Keep;
2137 }
2138
2139 return Flags;
2140}
2141
Frederic Riss84c09a52015-02-13 23:18:34 +00002142/// \brief Mark the passed DIE as well as all the ones it depends on
2143/// as kept.
2144///
2145/// This function is called by lookForDIEsToKeep on DIEs that are
2146/// newly discovered to be needed in the link. It recursively calls
2147/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2148/// TraversalFlags to inform it that it's not doing the primary DIE
2149/// tree walk.
Adrian Prantl6ec47122015-09-22 15:31:14 +00002150void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002151 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002152 CompileUnit::DIEInfo &MyInfo,
2153 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002154 CompileUnit &CU, bool UseODR) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002155 const DWARFUnit &Unit = CU.getOrigUnit();
2156 MyInfo.Keep = true;
2157
2158 // First mark all the parent chain as kept.
2159 unsigned AncestorIdx = MyInfo.ParentIdx;
2160 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002161 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002162 lookForDIEsToKeep(RelocMgr, *Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002163 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002164 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2165 }
2166
2167 // Then we need to mark all the DIEs referenced by this DIE's
2168 // attributes as kept.
2169 DataExtractor Data = Unit.getDebugInfoExtractor();
Frederic Riss36c3cb82015-09-11 04:17:25 +00002170 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2171 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
Frederic Riss84c09a52015-02-13 23:18:34 +00002172
2173 // Mark all DIEs referenced through atttributes as kept.
2174 for (const auto &AttrSpec : Abbrev->attributes()) {
2175 DWARFFormValue Val(AttrSpec.Form);
2176
2177 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2178 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2179 continue;
2180 }
2181
2182 Val.extractValue(Data, &Offset, &Unit);
2183 CompileUnit *ReferencedCU;
Frederic Riss1c650942015-07-21 22:41:43 +00002184 if (const auto *RefDIE =
Adrian Prantlfdd9a822015-09-22 18:50:58 +00002185 resolveDIEReference(*this, MutableArrayRef<CompileUnit>(Units), Val,
2186 Unit, Die, ReferencedCU)) {
Frederic Riss1c650942015-07-21 22:41:43 +00002187 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2188 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2189 // If the referenced DIE has a DeclContext that has already been
2190 // emitted, then do not keep the one in this CU. We'll link to
2191 // the canonical DIE in cloneDieReferenceAttribute.
2192 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2193 // be necessary and could be advantageously replaced by
2194 // ReferencedCU->hasODR() && CU.hasODR().
2195 // FIXME: compatibility with dsymutil-classic. There is no
2196 // reason not to unique ref_addr references.
2197 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2198 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2199 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2200 continue;
2201
Adrian Prantle39475d2015-11-10 21:31:05 +00002202 // Keep a module forward declaration if there is no definition.
2203 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
2204 Info.Ctxt->getCanonicalDIEOffset()))
2205 Info.Prune = false;
2206
Frederic Riss1c650942015-07-21 22:41:43 +00002207 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002208 lookForDIEsToKeep(RelocMgr, *RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002209 TF_Keep | TF_DependencyWalk | ODRFlag);
2210 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002211 }
2212}
2213
2214/// \brief Recursively walk the \p DIE tree and look for DIEs to
2215/// keep. Store that information in \p CU's DIEInfo.
2216///
2217/// This function is the entry point of the DIE selection
2218/// algorithm. It is expected to walk the DIE tree in file order and
2219/// (though the mediation of its helper) call hasValidRelocation() on
2220/// each DIE that might be a 'root DIE' (See DwarfLinker class
2221/// comment).
2222/// While walking the dependencies of root DIEs, this function is
2223/// also called, but during these dependency walks the file order is
2224/// not respected. The TF_DependencyWalk flag tells us which kind of
2225/// traversal we are currently doing.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002226void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
2227 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002228 const DebugMapObject &DMO, CompileUnit &CU,
2229 unsigned Flags) {
Frederic Riss36c3cb82015-09-11 04:17:25 +00002230 unsigned Idx = CU.getOrigUnit().getDIEIndex(&Die);
Frederic Riss84c09a52015-02-13 23:18:34 +00002231 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2232 bool AlreadyKept = MyInfo.Keep;
Adrian Prantla112ef92015-09-23 17:35:52 +00002233 if (MyInfo.Prune)
2234 return;
Frederic Riss84c09a52015-02-13 23:18:34 +00002235
2236 // If the Keep flag is set, we are marking a required DIE's
2237 // dependencies. If our target is already marked as kept, we're all
2238 // set.
2239 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2240 return;
2241
Adrian Prantl6ec47122015-09-22 15:31:14 +00002242 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
Frederic Riss84c09a52015-02-13 23:18:34 +00002243 // because it would screw up the relocation finding logic.
2244 if (!(Flags & TF_DependencyWalk))
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002245 Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002246
2247 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002248 if (!AlreadyKept && (Flags & TF_Keep)) {
2249 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
Adrian Prantl6ec47122015-09-22 15:31:14 +00002250 keepDIEAndDependencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
Frederic Riss1c650942015-07-21 22:41:43 +00002251 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002252 // The TF_ParentWalk flag tells us that we are currently walking up
2253 // the parent chain of a required DIE, and we don't want to mark all
2254 // the children of the parents as kept (consider for example a
2255 // DW_TAG_namespace node in the parent chain). There are however a
2256 // set of DIE types for which we want to ignore that directive and still
2257 // walk their children.
Frederic Riss36c3cb82015-09-11 04:17:25 +00002258 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
Frederic Riss84c09a52015-02-13 23:18:34 +00002259 Flags &= ~TF_ParentWalk;
2260
Frederic Riss36c3cb82015-09-11 04:17:25 +00002261 if (!Die.hasChildren() || (Flags & TF_ParentWalk))
Frederic Riss84c09a52015-02-13 23:18:34 +00002262 return;
2263
Frederic Riss36c3cb82015-09-11 04:17:25 +00002264 for (auto *Child = Die.getFirstChild(); Child && !Child->isNULL();
Frederic Riss84c09a52015-02-13 23:18:34 +00002265 Child = Child->getSibling())
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002266 lookForDIEsToKeep(RelocMgr, *Child, DMO, CU, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002267}
2268
Frederic Rissb8b43d52015-03-04 22:07:44 +00002269/// \brief Assign an abbreviation numer to \p Abbrev.
2270///
2271/// Our DIEs get freed after every DebugMapObject has been processed,
2272/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2273/// the instances hold by the DIEs. When we encounter an abbreviation
2274/// that we don't know, we create a permanent copy of it.
2275void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2276 // Check the set for priors.
2277 FoldingSetNodeID ID;
2278 Abbrev.Profile(ID);
2279 void *InsertToken;
2280 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2281
2282 // If it's newly added.
2283 if (InSet) {
2284 // Assign existing abbreviation number.
2285 Abbrev.setNumber(InSet->getNumber());
2286 } else {
2287 // Add to abbreviation list.
2288 Abbreviations.push_back(
David Blaikie6196aa02015-11-18 00:34:10 +00002289 llvm::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002290 for (const auto &Attr : Abbrev.getData())
2291 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
David Blaikie6196aa02015-11-18 00:34:10 +00002292 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002293 // Assign the unique abbreviation number.
2294 Abbrev.setNumber(Abbreviations.size());
2295 Abbreviations.back()->setNumber(Abbreviations.size());
2296 }
2297}
2298
Adrian Prantl3565af42015-09-14 16:46:10 +00002299unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2300 AttributeSpec AttrSpec,
2301 const DWARFFormValue &Val,
2302 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002303 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00002304 const char *String = *Val.getAsCString(&U);
Adrian Prantl3565af42015-09-14 16:46:10 +00002305 unsigned Offset = Linker.StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002306 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002307 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002308 return 4;
2309}
2310
Adrian Prantl3565af42015-09-14 16:46:10 +00002311unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
Frederic Riss9833de62015-03-06 23:22:53 +00002312 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2313 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002314 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002315 const DWARFUnit &U = Unit.getOrigUnit();
2316 uint32_t Ref = *Val.getAsReference(&U);
Frederic Riss9833de62015-03-06 23:22:53 +00002317 DIE *NewRefDie = nullptr;
2318 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002319 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002320
Frederic Riss1c650942015-07-21 22:41:43 +00002321 const DWARFDebugInfoEntryMinimal *RefDie =
Adrian Prantlfdd9a822015-09-22 18:50:58 +00002322 resolveDIEReference(Linker, CompileUnits, Val, U, InputDIE, RefUnit);
Frederic Riss1c650942015-07-21 22:41:43 +00002323
2324 // If the referenced DIE is not found, drop the attribute.
2325 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002326 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002327
2328 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2329 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002330
2331 // If we already have emitted an equivalent DeclContext, just point
2332 // at it.
2333 if (isODRAttribute(AttrSpec.Attr)) {
2334 Ctxt = RefInfo.Ctxt;
2335 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2336 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2337 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2338 dwarf::DW_FORM_ref_addr, Attr);
2339 return getRefAddrSize(U);
2340 }
2341 }
2342
Frederic Riss9833de62015-03-06 23:22:53 +00002343 if (!RefInfo.Clone) {
2344 assert(Ref > InputDIE.getOffset());
2345 // We haven't cloned this DIE yet. Just create an empty one and
2346 // store it. It'll get really cloned when we process it.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002347 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002348 }
2349 NewRefDie = RefInfo.Clone;
2350
Frederic Riss1c650942015-07-21 22:41:43 +00002351 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2352 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002353 // We cannot currently rely on a DIEEntry to emit ref_addr
2354 // references, because the implementation calls back to DwarfDebug
2355 // to find the unit offset. (We don't have a DwarfDebug)
2356 // FIXME: we should be able to design DIEEntry reliance on
2357 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002358 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002359 if (Ref < InputDIE.getOffset()) {
2360 // We must have already cloned that DIE.
2361 uint32_t NewRefOffset =
2362 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002363 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002364 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2365 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002366 } else {
2367 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002368 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002369 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002370 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002371 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2372 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002373 }
Frederic Riss1c650942015-07-21 22:41:43 +00002374 return getRefAddrSize(U);
Frederic Riss9833de62015-03-06 23:22:53 +00002375 }
2376
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002377 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2378 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002379 return AttrSize;
2380}
2381
Adrian Prantl3565af42015-09-14 16:46:10 +00002382unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2383 AttributeSpec AttrSpec,
2384 const DWARFFormValue &Val,
2385 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002386 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002387 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002388 DIELoc *Loc = nullptr;
2389 DIEBlock *Block = nullptr;
2390 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002391 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002392 Loc = new (DIEAlloc) DIELoc;
Adrian Prantl3565af42015-09-14 16:46:10 +00002393 Linker.DIELocs.push_back(Loc);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002394 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002395 Block = new (DIEAlloc) DIEBlock;
Adrian Prantl3565af42015-09-14 16:46:10 +00002396 Linker.DIEBlocks.push_back(Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002397 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002398 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2399 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002400
2401 if (Loc)
2402 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2403 dwarf::Form(AttrSpec.Form), Loc);
2404 else
2405 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2406 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002407 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2408 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002409 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2410 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002411 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2412 // the DIE class, this if could be replaced by
2413 // Attr->setSize(Bytes.size()).
Adrian Prantl3565af42015-09-14 16:46:10 +00002414 if (Linker.Streamer) {
2415 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002416 if (Loc)
Adrian Prantl3565af42015-09-14 16:46:10 +00002417 Loc->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002418 else
Adrian Prantl3565af42015-09-14 16:46:10 +00002419 Block->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002420 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002421 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002422 return AttrSize;
2423}
2424
Adrian Prantl3565af42015-09-14 16:46:10 +00002425unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2426 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2427 const CompileUnit &Unit, AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002428 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00002429 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2430 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2431 Die.getTag() == dwarf::DW_TAG_lexical_block)
Frederic Riss7b5563a2015-08-31 01:43:14 +00002432 // The low_pc of a block or inline subroutine might get
2433 // relocated because it happens to match the low_pc of the
2434 // enclosing subprogram. To prevent issues with that, always use
2435 // the low_pc from the input DIE if relocations have been applied.
2436 Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2437 Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002438 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2439 Addr = Unit.getLowPc();
2440 if (Addr == UINT64_MAX)
2441 return 0;
2442 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002443 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002444 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002445 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2446 if (uint64_t HighPc = Unit.getHighPc())
2447 Addr = HighPc;
2448 else
2449 return 0;
2450 } else
2451 // If we have a high_pc recorded for the input DIE, use
2452 // it. Otherwise (when no relocations where applied) just use the
2453 // one we just decoded.
2454 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002455 }
2456
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002457 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002458 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002459 return Unit.getOrigUnit().getAddressByteSize();
2460}
2461
Adrian Prantl3565af42015-09-14 16:46:10 +00002462unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00002463 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002464 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002465 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002466 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002467 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2468 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2469 if (Unit.getLowPc() == -1ULL)
2470 return 0;
2471 // Dwarf >= 4 high_pc is an size, not an address.
2472 Value = Unit.getHighPc() - Unit.getLowPc();
2473 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002474 Value = *Val.getAsSectionOffset();
2475 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2476 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002477 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2478 Value = *OptionalValue;
2479 else {
Adrian Prantl3565af42015-09-14 16:46:10 +00002480 Linker.reportWarning(
2481 "Unsupported scalar attribute form. Dropping attribute.",
2482 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002483 return 0;
2484 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002485 PatchLocation Patch =
2486 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2487 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002488 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002489 Unit.noteRangeAttribute(Die, Patch);
Frederic Riss29eedc72015-09-11 04:17:30 +00002490
Frederic Rissdfb97902015-03-14 15:49:07 +00002491 // A more generic way to check for location attributes would be
2492 // nice, but it's very unlikely that any other attribute needs a
2493 // location list.
2494 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2495 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002496 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002497 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2498 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002499
Frederic Rissb8b43d52015-03-04 22:07:44 +00002500 return AttrSize;
2501}
2502
2503/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2504/// value \p Val, and add it to \p Die.
2505/// \returns the size of the cloned attribute.
Adrian Prantl3565af42015-09-14 16:46:10 +00002506unsigned DwarfLinker::DIECloner::cloneAttribute(
2507 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2508 const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2509 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002510 const DWARFUnit &U = Unit.getOrigUnit();
2511
2512 switch (AttrSpec.Form) {
2513 case dwarf::DW_FORM_strp:
2514 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002515 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002516 case dwarf::DW_FORM_ref_addr:
2517 case dwarf::DW_FORM_ref1:
2518 case dwarf::DW_FORM_ref2:
2519 case dwarf::DW_FORM_ref4:
2520 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002521 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002522 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002523 case dwarf::DW_FORM_block:
2524 case dwarf::DW_FORM_block1:
2525 case dwarf::DW_FORM_block2:
2526 case dwarf::DW_FORM_block4:
2527 case dwarf::DW_FORM_exprloc:
2528 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2529 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002530 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002531 case dwarf::DW_FORM_data1:
2532 case dwarf::DW_FORM_data2:
2533 case dwarf::DW_FORM_data4:
2534 case dwarf::DW_FORM_data8:
2535 case dwarf::DW_FORM_udata:
2536 case dwarf::DW_FORM_sdata:
2537 case dwarf::DW_FORM_sec_offset:
2538 case dwarf::DW_FORM_flag:
2539 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002540 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2541 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002542 default:
Adrian Prantl3565af42015-09-14 16:46:10 +00002543 Linker.reportWarning(
2544 "Unsupported attribute form in cloneAttribute. Dropping.", &U,
2545 &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002546 }
2547
2548 return 0;
2549}
2550
Frederic Riss23e20e92015-03-07 01:25:09 +00002551/// \brief Apply the valid relocations found by findValidRelocs() to
2552/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2553/// in the debug_info section.
2554///
2555/// Like for findValidRelocs(), this function must be called with
2556/// monotonic \p BaseOffset values.
2557///
2558/// \returns wether any reloc has been applied.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002559bool DwarfLinker::RelocationManager::
2560applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2561 bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002562 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002563 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2564 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002565 if (NextValidReloc >= ValidRelocs.size())
2566 return false;
2567
2568 // Skip relocs that haven't been applied.
2569 while (NextValidReloc < ValidRelocs.size() &&
2570 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2571 ++NextValidReloc;
2572
2573 bool Applied = false;
2574 uint64_t EndOffset = BaseOffset + Data.size();
2575 while (NextValidReloc < ValidRelocs.size() &&
2576 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2577 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2578 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2579 assert(ValidReloc.Offset - BaseOffset < Data.size());
2580 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2581 char Buf[8];
2582 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2583 Value += ValidReloc.Addend;
2584 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2585 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2586 Buf[i] = uint8_t(Value >> (Index * 8));
2587 }
2588 assert(ValidReloc.Size <= sizeof(Buf));
2589 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2590 Applied = true;
2591 }
2592
2593 return Applied;
2594}
2595
Frederic Rissbce93ff2015-03-16 02:05:10 +00002596static bool isTypeTag(uint16_t Tag) {
2597 switch (Tag) {
2598 case dwarf::DW_TAG_array_type:
2599 case dwarf::DW_TAG_class_type:
2600 case dwarf::DW_TAG_enumeration_type:
2601 case dwarf::DW_TAG_pointer_type:
2602 case dwarf::DW_TAG_reference_type:
2603 case dwarf::DW_TAG_string_type:
2604 case dwarf::DW_TAG_structure_type:
2605 case dwarf::DW_TAG_subroutine_type:
2606 case dwarf::DW_TAG_typedef:
2607 case dwarf::DW_TAG_union_type:
2608 case dwarf::DW_TAG_ptr_to_member_type:
2609 case dwarf::DW_TAG_set_type:
2610 case dwarf::DW_TAG_subrange_type:
2611 case dwarf::DW_TAG_base_type:
2612 case dwarf::DW_TAG_const_type:
2613 case dwarf::DW_TAG_constant:
2614 case dwarf::DW_TAG_file_type:
2615 case dwarf::DW_TAG_namelist:
2616 case dwarf::DW_TAG_packed_type:
2617 case dwarf::DW_TAG_volatile_type:
2618 case dwarf::DW_TAG_restrict_type:
2619 case dwarf::DW_TAG_interface_type:
2620 case dwarf::DW_TAG_unspecified_type:
2621 case dwarf::DW_TAG_shared_type:
2622 return true;
2623 default:
2624 break;
2625 }
2626 return false;
2627}
2628
Frederic Riss29eedc72015-09-11 04:17:30 +00002629static bool
2630shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2631 uint16_t Tag, bool InDebugMap, bool SkipPC,
2632 bool InFunctionScope) {
2633 switch (AttrSpec.Attr) {
2634 default:
2635 return false;
2636 case dwarf::DW_AT_low_pc:
2637 case dwarf::DW_AT_high_pc:
2638 case dwarf::DW_AT_ranges:
2639 return SkipPC;
2640 case dwarf::DW_AT_location:
2641 case dwarf::DW_AT_frame_base:
2642 // FIXME: for some reason dsymutil-classic keeps the location
2643 // attributes when they are of block type (ie. not location
2644 // lists). This is totally wrong for globals where we will keep a
2645 // wrong address. It is mostly harmless for locals, but there is
2646 // no point in keeping these anyway when the function wasn't linked.
2647 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2648 !InDebugMap)) &&
2649 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2650 }
2651}
2652
Adrian Prantl3565af42015-09-14 16:46:10 +00002653DIE *DwarfLinker::DIECloner::cloneDIE(
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002654 const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2655 int64_t PCOffset, uint32_t OutOffset, unsigned Flags) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002656 DWARFUnit &U = Unit.getOrigUnit();
2657 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002658 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002659
2660 // Should the DIE appear in the output?
2661 if (!Unit.getInfo(Idx).Keep)
2662 return nullptr;
2663
2664 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002665 // The DIE might have been already created by a forward reference
2666 // (see cloneDieReferenceAttribute()).
2667 DIE *Die = Info.Clone;
2668 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002669 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002670 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002671 Die->setOffset(OutOffset);
Adrian Prantla112ef92015-09-23 17:35:52 +00002672 if ((Unit.hasODR() || Unit.isClangModule()) &&
2673 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
Frederic Riss1c650942015-07-21 22:41:43 +00002674 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2675 !Info.Ctxt->getCanonicalDIEOffset()) {
2676 // We are about to emit a DIE that is the root of its own valid
2677 // DeclContext tree. Make the current offset the canonical offset
2678 // for this context.
2679 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2680 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002681
2682 // Extract and clone every attribute.
2683 DataExtractor Data = U.getDebugInfoExtractor();
Adrian Prantle5162db2015-09-22 22:20:50 +00002684 // Point to the next DIE (generally there is always at least a NULL
2685 // entry after the current one). If this is a lone
2686 // DW_TAG_compile_unit without any children, point to the next unit.
2687 uint32_t NextOffset =
2688 (Idx + 1 < U.getNumDIEs())
2689 ? U.getDIEAtIndex(Idx + 1)->getOffset()
2690 : U.getNextUnitOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002691 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002692
2693 // We could copy the data only if we need to aply a relocation to
2694 // it. After testing, it seems there is no performance downside to
2695 // doing the copy unconditionally, and it makes the code simpler.
2696 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2697 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2698 // Modify the copy with relocated addresses.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002699 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
Frederic Riss31da3242015-03-11 18:45:52 +00002700 // If we applied relocations, we store the value of high_pc that was
2701 // potentially stored in the input DIE. If high_pc is an address
2702 // (Dwarf version == 2), then it might have been relocated to a
2703 // totally unrelated value (because the end address in the object
2704 // file might be start address of another function which got moved
2705 // independantly by the linker). The computation of the actual
2706 // high_pc value is done in cloneAddressAttribute().
2707 AttrInfo.OrigHighPc =
2708 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
Frederic Riss7b5563a2015-08-31 01:43:14 +00002709 // Also store the low_pc. It might get relocated in an
2710 // inline_subprogram that happens at the beginning of its
2711 // inlining function.
2712 AttrInfo.OrigLowPc =
2713 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_low_pc, UINT64_MAX);
Frederic Riss31da3242015-03-11 18:45:52 +00002714 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002715
2716 // Reset the Offset to 0 as we will be working on the local copy of
2717 // the data.
2718 Offset = 0;
2719
Frederic Rissb8b43d52015-03-04 22:07:44 +00002720 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2721 Offset += getULEB128Size(Abbrev->getCode());
2722
Frederic Riss31da3242015-03-11 18:45:52 +00002723 // We are entering a subprogram. Get and propagate the PCOffset.
2724 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2725 PCOffset = Info.AddrAdjust;
2726 AttrInfo.PCOffset = PCOffset;
2727
Frederic Riss29eedc72015-09-11 04:17:30 +00002728 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2729 Flags |= TF_InFunctionScope;
2730 if (!Info.InDebugMap)
2731 Flags |= TF_SkipPC;
2732 }
2733
2734 bool Copied = false;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002735 for (const auto &AttrSpec : Abbrev->attributes()) {
Frederic Riss29eedc72015-09-11 04:17:30 +00002736 if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2737 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2738 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2739 // FIXME: dsymutil-classic keeps the old abbreviation around
2740 // even if it's not used. We can remove this (and the copyAbbrev
2741 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2742 if (!Copied) {
2743 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2744 Copied = true;
2745 }
2746 continue;
2747 }
2748
Frederic Rissb8b43d52015-03-04 22:07:44 +00002749 DWARFFormValue Val(AttrSpec.Form);
2750 uint32_t AttrSize = Offset;
2751 Val.extractValue(Data, &Offset, &U);
2752 AttrSize = Offset - AttrSize;
2753
Frederic Riss31da3242015-03-11 18:45:52 +00002754 OutOffset +=
2755 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002756 }
2757
Frederic Rissbce93ff2015-03-16 02:05:10 +00002758 // Look for accelerator entries.
2759 uint16_t Tag = InputDIE.getTag();
2760 // FIXME: This is slightly wrong. An inline_subroutine without a
2761 // low_pc, but with AT_ranges might be interesting to get into the
2762 // accelerator tables too. For now stick with dsymutil's behavior.
2763 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2764 Tag != dwarf::DW_TAG_compile_unit &&
2765 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2766 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2767 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2768 AttrInfo.MangledNameOffset,
2769 Tag == dwarf::DW_TAG_inlined_subroutine);
2770 if (AttrInfo.Name)
2771 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2772 Tag == dwarf::DW_TAG_inlined_subroutine);
2773 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2774 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2775 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2776 }
2777
Adrian Prantle39475d2015-11-10 21:31:05 +00002778 // Determine whether there are any children that we want to keep.
2779 bool HasChildren = false;
2780 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2781 Child = Child->getSibling()) {
2782 unsigned Idx = U.getDIEIndex(Child);
2783 if (Unit.getInfo(Idx).Keep) {
2784 HasChildren = true;
2785 break;
2786 }
2787 }
2788
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002789 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Adrian Prantle39475d2015-11-10 21:31:05 +00002790 if (HasChildren)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002791 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2792 // Assign a permanent abbrev number
Adrian Prantl3565af42015-09-14 16:46:10 +00002793 Linker.AssignAbbrev(NewAbbrev);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002794 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002795
2796 // Add the size of the abbreviation number to the output offset.
2797 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2798
Adrian Prantle39475d2015-11-10 21:31:05 +00002799 if (!HasChildren) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002800 // Update our size.
2801 Die->setSize(OutOffset - Die->getOffset());
2802 return Die;
2803 }
2804
2805 // Recursively clone children.
2806 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2807 Child = Child->getSibling()) {
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002808 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset, Flags)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002809 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002810 OutOffset = Clone->getOffset() + Clone->getSize();
2811 }
2812 }
2813
2814 // Account for the end of children marker.
2815 OutOffset += sizeof(int8_t);
2816 // Update our size.
2817 Die->setSize(OutOffset - Die->getOffset());
2818 return Die;
2819}
2820
Frederic Riss25440872015-03-13 23:30:31 +00002821/// \brief Patch the input object file relevant debug_ranges entries
2822/// and emit them in the output file. Update the relevant attributes
2823/// to point at the new entries.
2824void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2825 DWARFContext &OrigDwarf) const {
2826 DWARFDebugRangeList RangeList;
2827 const auto &FunctionRanges = Unit.getFunctionRanges();
2828 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2829 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2830 OrigDwarf.isLittleEndian(), AddressSize);
2831 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2832 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002833 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002834 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2835 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2836 // Ranges addresses are based on the unit's low_pc. Compute the
Sanjay Patele4b9f502015-12-07 19:21:39 +00002837 // offset we need to apply to adapt to the new unit's low_pc.
Frederic Riss25440872015-03-13 23:30:31 +00002838 int64_t UnitPcOffset = 0;
2839 if (OrigLowPc != -1ULL)
2840 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2841
2842 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002843 uint32_t Offset = RangeAttribute.get();
2844 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002845 RangeList.extract(RangeExtractor, &Offset);
2846 const auto &Entries = RangeList.getEntries();
Frederic Riss94546202015-08-31 05:09:32 +00002847 if (!Entries.empty()) {
2848 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
Frederic Riss25440872015-03-13 23:30:31 +00002849
Frederic Riss25440872015-03-13 23:30:31 +00002850 if (CurrRange == InvalidRange ||
Frederic Riss94546202015-08-31 05:09:32 +00002851 First.StartAddress + OrigLowPc < CurrRange.start() ||
2852 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2853 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2854 if (CurrRange == InvalidRange ||
2855 CurrRange.start() > First.StartAddress + OrigLowPc) {
2856 reportWarning("no mapping for range.");
2857 continue;
2858 }
Frederic Riss25440872015-03-13 23:30:31 +00002859 }
2860 }
2861
2862 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2863 AddressSize);
2864 }
2865}
2866
Frederic Riss563b1b02015-03-14 03:46:51 +00002867/// \brief Generate the debug_aranges entries for \p Unit and if the
2868/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2869/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002870/// FIXME: this could actually be done right in patchRangesForUnit,
2871/// but for the sake of initial bit-for-bit compatibility with legacy
2872/// dsymutil, we have to do it in a delayed pass.
2873void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002874 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002875 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002876 Attr->set(Streamer->getRangesSectionSize());
2877 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002878}
2879
Frederic Riss63786b02015-03-15 20:45:43 +00002880/// \brief Insert the new line info sequence \p Seq into the current
2881/// set of already linked line info \p Rows.
2882static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2883 std::vector<DWARFDebugLine::Row> &Rows) {
2884 if (Seq.empty())
2885 return;
2886
2887 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2888 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2889 Seq.clear();
2890 return;
2891 }
2892
2893 auto InsertPoint = std::lower_bound(
2894 Rows.begin(), Rows.end(), Seq.front(),
2895 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2896 return LHS.Address < RHS.Address;
2897 });
2898
2899 // FIXME: this only removes the unneeded end_sequence if the
2900 // sequences have been inserted in order. using a global sort like
2901 // described in patchLineTableForUnit() and delaying the end_sequene
2902 // elimination to emitLineTableForUnit() we can get rid of all of them.
2903 if (InsertPoint != Rows.end() &&
2904 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2905 *InsertPoint = Seq.front();
2906 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2907 } else {
2908 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2909 }
2910
2911 Seq.clear();
2912}
2913
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002914static void patchStmtList(DIE &Die, DIEInteger Offset) {
2915 for (auto &V : Die.values())
2916 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002917 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002918 return;
2919 }
2920
2921 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2922}
2923
Frederic Riss63786b02015-03-15 20:45:43 +00002924/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2925/// recreate a relocated version of these for the address ranges that
2926/// are present in the binary.
2927void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2928 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002929 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002930 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2931 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2932 if (StmtList == -1ULL)
2933 return;
2934
2935 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002936 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2937 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002938
2939 // Parse the original line info for the unit.
2940 DWARFDebugLine::LineTable LineTable;
2941 uint32_t StmtOffset = StmtList;
2942 StringRef LineData = OrigDwarf.getLineSection().Data;
2943 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2944 Unit.getOrigUnit().getAddressByteSize());
2945 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2946 &StmtOffset);
2947
2948 // This vector is the output line table.
2949 std::vector<DWARFDebugLine::Row> NewRows;
2950 NewRows.reserve(LineTable.Rows.size());
2951
2952 // Current sequence of rows being extracted, before being inserted
2953 // in NewRows.
2954 std::vector<DWARFDebugLine::Row> Seq;
2955 const auto &FunctionRanges = Unit.getFunctionRanges();
2956 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2957
2958 // FIXME: This logic is meant to generate exactly the same output as
2959 // Darwin's classic dsynutil. There is a nicer way to implement this
2960 // by simply putting all the relocated line info in NewRows and simply
2961 // sorting NewRows before passing it to emitLineTableForUnit. This
2962 // should be correct as sequences for a function should stay
2963 // together in the sorted output. There are a few corner cases that
2964 // look suspicious though, and that required to implement the logic
2965 // this way. Revisit that once initial validation is finished.
2966
2967 // Iterate over the object file line info and extract the sequences
2968 // that correspond to linked functions.
2969 for (auto &Row : LineTable.Rows) {
2970 // Check wether we stepped out of the range. The range is
2971 // half-open, but consider accept the end address of the range if
2972 // it is marked as end_sequence in the input (because in that
2973 // case, the relocation offset is accurate and that entry won't
2974 // serve as the start of another function).
2975 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2976 Row.Address > CurrRange.stop() ||
2977 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2978 // We just stepped out of a known range. Insert a end_sequence
2979 // corresponding to the end of the range.
2980 uint64_t StopAddress = CurrRange != InvalidRange
2981 ? CurrRange.stop() + CurrRange.value()
2982 : -1ULL;
2983 CurrRange = FunctionRanges.find(Row.Address);
2984 bool CurrRangeValid =
2985 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2986 if (!CurrRangeValid) {
2987 CurrRange = InvalidRange;
2988 if (StopAddress != -1ULL) {
2989 // Try harder by looking in the DebugMapObject function
2990 // ranges map. There are corner cases where this finds a
2991 // valid entry. It's unclear if this is right or wrong, but
2992 // for now do as dsymutil.
2993 // FIXME: Understand exactly what cases this addresses and
2994 // potentially remove it along with the Ranges map.
2995 auto Range = Ranges.lower_bound(Row.Address);
2996 if (Range != Ranges.begin() && Range != Ranges.end())
2997 --Range;
2998
2999 if (Range != Ranges.end() && Range->first <= Row.Address &&
3000 Range->second.first >= Row.Address) {
3001 StopAddress = Row.Address + Range->second.second;
3002 }
3003 }
3004 }
3005 if (StopAddress != -1ULL && !Seq.empty()) {
3006 // Insert end sequence row with the computed end address, but
3007 // the same line as the previous one.
Yaron Kerene3c07062015-08-10 16:15:51 +00003008 auto NextLine = Seq.back();
Yaron Keren2ad3b332015-08-10 18:27:51 +00003009 NextLine.Address = StopAddress;
3010 NextLine.EndSequence = 1;
3011 NextLine.PrologueEnd = 0;
3012 NextLine.BasicBlock = 0;
3013 NextLine.EpilogueBegin = 0;
Yaron Kerenf850d982015-08-10 18:03:35 +00003014 Seq.push_back(NextLine);
Frederic Riss63786b02015-03-15 20:45:43 +00003015 insertLineSequence(Seq, NewRows);
3016 }
3017
3018 if (!CurrRangeValid)
3019 continue;
3020 }
3021
3022 // Ignore empty sequences.
3023 if (Row.EndSequence && Seq.empty())
3024 continue;
3025
3026 // Relocate row address and add it to the current sequence.
3027 Row.Address += CurrRange.value();
3028 Seq.emplace_back(Row);
3029
3030 if (Row.EndSequence)
3031 insertLineSequence(Seq, NewRows);
3032 }
3033
3034 // Finished extracting, now emit the line tables.
3035 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
3036 // FIXME: LLVM hardcodes it's prologue values. We just copy the
3037 // prologue over and that works because we act as both producer and
3038 // consumer. It would be nicer to have a real configurable line
3039 // table emitter.
3040 if (LineTable.Prologue.Version != 2 ||
3041 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00003042 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00003043 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00003044 else {
3045 MCDwarfLineTableParams Params;
3046 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
3047 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
3048 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
3049 Streamer->emitLineTableForUnit(Params,
3050 LineData.slice(StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00003051 LineTable.Prologue.MinInstLength, NewRows,
3052 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00003053 }
Frederic Riss63786b02015-03-15 20:45:43 +00003054}
3055
Frederic Rissbce93ff2015-03-16 02:05:10 +00003056void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
3057 Streamer->emitPubNamesForUnit(Unit);
3058 Streamer->emitPubTypesForUnit(Unit);
3059}
3060
Frederic Riss5a642072015-06-05 23:06:11 +00003061/// \brief Read the frame info stored in the object, and emit the
3062/// patched frame descriptions for the linked binary.
3063///
3064/// This is actually pretty easy as the data of the CIEs and FDEs can
3065/// be considered as black boxes and moved as is. The only thing to do
3066/// is to patch the addresses in the headers.
3067void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
3068 DWARFContext &OrigDwarf,
3069 unsigned AddrSize) {
3070 StringRef FrameData = OrigDwarf.getDebugFrameSection();
3071 if (FrameData.empty())
3072 return;
3073
3074 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
3075 uint32_t InputOffset = 0;
3076
3077 // Store the data of the CIEs defined in this object, keyed by their
3078 // offsets.
3079 DenseMap<uint32_t, StringRef> LocalCIES;
3080
3081 while (Data.isValidOffset(InputOffset)) {
3082 uint32_t EntryOffset = InputOffset;
3083 uint32_t InitialLength = Data.getU32(&InputOffset);
3084 if (InitialLength == 0xFFFFFFFF)
3085 return reportWarning("Dwarf64 bits no supported");
3086
3087 uint32_t CIEId = Data.getU32(&InputOffset);
3088 if (CIEId == 0xFFFFFFFF) {
3089 // This is a CIE, store it.
3090 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
3091 LocalCIES[EntryOffset] = CIEData;
3092 // The -4 is to account for the CIEId we just read.
3093 InputOffset += InitialLength - 4;
3094 continue;
3095 }
3096
3097 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
3098
3099 // Some compilers seem to emit frame info that doesn't start at
3100 // the function entry point, thus we can't just lookup the address
3101 // in the debug map. Use the linker's range map to see if the FDE
3102 // describes something that we can relocate.
3103 auto Range = Ranges.upper_bound(Loc);
3104 if (Range != Ranges.begin())
3105 --Range;
3106 if (Range == Ranges.end() || Range->first > Loc ||
3107 Range->second.first <= Loc) {
3108 // The +4 is to account for the size of the InitialLength field itself.
3109 InputOffset = EntryOffset + InitialLength + 4;
3110 continue;
3111 }
3112
3113 // This is an FDE, and we have a mapping.
3114 // Have we already emitted a corresponding CIE?
3115 StringRef CIEData = LocalCIES[CIEId];
3116 if (CIEData.empty())
3117 return reportWarning("Inconsistent debug_frame content. Dropping.");
3118
3119 // Look if we already emitted a CIE that corresponds to the
3120 // referenced one (the CIE data is the key of that lookup).
3121 auto IteratorInserted = EmittedCIEs.insert(
3122 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3123 // If there is no CIE yet for this ID, emit it.
3124 if (IteratorInserted.second ||
3125 // FIXME: dsymutil-classic only caches the last used CIE for
3126 // reuse. Mimic that behavior for now. Just removing that
3127 // second half of the condition and the LastCIEOffset variable
3128 // makes the code DTRT.
3129 LastCIEOffset != IteratorInserted.first->getValue()) {
3130 LastCIEOffset = Streamer->getFrameSectionSize();
3131 IteratorInserted.first->getValue() = LastCIEOffset;
3132 Streamer->emitCIE(CIEData);
3133 }
3134
3135 // Emit the FDE with updated address and CIE pointer.
3136 // (4 + AddrSize) is the size of the CIEId + initial_location
3137 // fields that will get reconstructed by emitFDE().
3138 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3139 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3140 Loc + Range->second.second,
3141 FrameData.substr(InputOffset, FDERemainingBytes));
3142 InputOffset += FDERemainingBytes;
3143 }
3144}
3145
Adrian Prantl3565af42015-09-14 16:46:10 +00003146void DwarfLinker::DIECloner::copyAbbrev(
3147 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
Frederic Riss29eedc72015-09-11 04:17:30 +00003148 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3149 dwarf::Form(Abbrev.hasChildren()));
3150
3151 for (const auto &Attr : Abbrev.attributes()) {
3152 uint16_t Form = Attr.Form;
3153 if (hasODR && isODRAttribute(Attr.Attr))
3154 Form = dwarf::DW_FORM_ref_addr;
3155 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3156 }
3157
Adrian Prantl3565af42015-09-14 16:46:10 +00003158 Linker.AssignAbbrev(Copy);
Frederic Riss29eedc72015-09-11 04:17:30 +00003159}
3160
Adrian Prantl20937022015-09-23 17:11:10 +00003161static uint64_t getDwoId(const DWARFDebugInfoEntryMinimal &CUDie,
3162 const DWARFUnit &Unit) {
3163 uint64_t DwoId =
3164 CUDie.getAttributeValueAsUnsignedConstant(&Unit, dwarf::DW_AT_dwo_id, 0);
3165 if (!DwoId)
3166 DwoId = CUDie.getAttributeValueAsUnsignedConstant(&Unit,
3167 dwarf::DW_AT_GNU_dwo_id, 0);
3168 return DwoId;
3169}
3170
Adrian Prantle5162db2015-09-22 22:20:50 +00003171bool DwarfLinker::registerModuleReference(
3172 const DWARFDebugInfoEntryMinimal &CUDie, const DWARFUnit &Unit,
3173 DebugMap &ModuleMap, unsigned Indent) {
3174 std::string PCMfile =
Adrian Prantl20937022015-09-23 17:11:10 +00003175 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_dwo_name, "");
3176 if (PCMfile.empty())
3177 PCMfile =
3178 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_GNU_dwo_name, "");
Adrian Prantle5162db2015-09-22 22:20:50 +00003179 if (PCMfile.empty())
3180 return false;
3181
3182 // Clang module DWARF skeleton CUs abuse this for the path to the module.
3183 std::string PCMpath =
3184 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_comp_dir, "");
Adrian Prantl20937022015-09-23 17:11:10 +00003185 uint64_t DwoId = getDwoId(CUDie, Unit);
Adrian Prantle5162db2015-09-22 22:20:50 +00003186
Adrian Prantla112ef92015-09-23 17:35:52 +00003187 std::string Name =
3188 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_name, "");
3189 if (Name.empty()) {
3190 reportWarning("Anonymous module skeleton CU for " + PCMfile);
3191 return true;
3192 }
3193
Adrian Prantle5162db2015-09-22 22:20:50 +00003194 if (Options.Verbose) {
3195 outs().indent(Indent);
3196 outs() << "Found clang module reference " << PCMfile;
3197 }
3198
Adrian Prantl20937022015-09-23 17:11:10 +00003199 auto Cached = ClangModules.find(PCMfile);
3200 if (Cached != ClangModules.end()) {
3201 if (Cached->second != DwoId)
3202 reportWarning(Twine("hash mismatch: this object file was built against a "
3203 "different version of the module ") + PCMfile);
Adrian Prantle5162db2015-09-22 22:20:50 +00003204 if (Options.Verbose)
3205 outs() << " [cached].\n";
3206 return true;
3207 }
3208 if (Options.Verbose)
3209 outs() << " ...\n";
3210
3211 // Cyclic dependencies are disallowed by Clang, but we still
3212 // shouldn't run into an infinite loop, so mark it as processed now.
Adrian Prantl20937022015-09-23 17:11:10 +00003213 ClangModules.insert({PCMfile, DwoId});
Adrian Prantla112ef92015-09-23 17:35:52 +00003214 loadClangModule(PCMfile, PCMpath, Name, DwoId, ModuleMap, Indent + 2);
Adrian Prantle5162db2015-09-22 22:20:50 +00003215 return true;
3216}
3217
Frederic Risseb85c8f2015-07-24 06:41:11 +00003218ErrorOr<const object::ObjectFile &>
3219DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3220 const DebugMap &Map) {
3221 auto ErrOrObjs =
3222 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
Frederic Rissafeac302015-08-31 05:16:35 +00003223 if (std::error_code EC = ErrOrObjs.getError()) {
Frederic Risseb85c8f2015-07-24 06:41:11 +00003224 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
Frederic Rissafeac302015-08-31 05:16:35 +00003225 return EC;
3226 }
Frederic Risseb85c8f2015-07-24 06:41:11 +00003227 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3228 if (std::error_code EC = ErrOrObj.getError())
3229 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3230 return ErrOrObj;
3231}
3232
Adrian Prantle5162db2015-09-22 22:20:50 +00003233void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
Adrian Prantla112ef92015-09-23 17:35:52 +00003234 StringRef ModuleName, uint64_t DwoId,
3235 DebugMap &ModuleMap, unsigned Indent) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003236 SmallString<80> Path(Options.PrependPath);
3237 if (sys::path::is_relative(Filename))
3238 sys::path::append(Path, ModulePath, Filename);
3239 else
3240 sys::path::append(Path, Filename);
3241 BinaryHolder ObjHolder(Options.Verbose);
3242 auto &Obj =
3243 ModuleMap.addDebugMapObject(Path, sys::TimeValue::PosixZeroTime());
3244 auto ErrOrObj = loadObject(ObjHolder, Obj, ModuleMap);
Adrian Prantla9e23832016-01-14 18:31:07 +00003245 if (!ErrOrObj) {
3246 // Try and emit more helpful warnings by applying some heuristics.
3247 StringRef ObjFile = CurrentDebugObject->getObjectFilename();
3248 bool isClangModule = sys::path::extension(Filename).equals(".pcm");
3249 bool isArchive = ObjFile.endswith(")");
3250 if (isClangModule) {
3251 sys::path::remove_filename(Path);
3252 StringRef ModuleCacheDir = sys::path::parent_path(Path);
3253 if (sys::fs::exists(ModuleCacheDir)) {
3254 // If the module's parent directory exists, we assume that the module
3255 // cache has expired and was pruned by clang. A more adventurous
3256 // dsymutil would invoke clang to rebuild the module now.
3257 if (!ModuleCacheHintDisplayed) {
3258 errs() << "note: The clang module cache may have expired since this "
3259 "object file was built. Rebuilding the object file will "
3260 "rebuild the module cache.\n";
3261 ModuleCacheHintDisplayed = true;
3262 }
3263 } else if (isArchive) {
3264 // If the module cache directory doesn't exist at all and the object
3265 // file is inside a static library, we assume that the static library
3266 // was built on a different machine. We don't want to discourage module
3267 // debugging for convenience libraries within a project though.
3268 if (!ArchiveHintDisplayed) {
3269 errs() << "note: Module debugging should be disabled when shipping "
3270 "static libraries.\n";
3271 ArchiveHintDisplayed = true;
3272 }
3273 }
3274 }
Adrian Prantle5162db2015-09-22 22:20:50 +00003275 return;
Adrian Prantla9e23832016-01-14 18:31:07 +00003276 }
Adrian Prantle5162db2015-09-22 22:20:50 +00003277
Benjamin Kramer008f4be2015-09-23 10:38:59 +00003278 std::unique_ptr<CompileUnit> Unit;
Adrian Prantle5162db2015-09-22 22:20:50 +00003279
3280 // Setup access to the debug info.
3281 DWARFContextInMemory DwarfContext(*ErrOrObj);
3282 RelocationManager RelocMgr(*this);
3283 for (const auto &CU : DwarfContext.compile_units()) {
3284 auto *CUDie = CU->getUnitDIE(false);
3285 // Recursively get all modules imported by this one.
3286 if (!registerModuleReference(*CUDie, *CU, ModuleMap, Indent)) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003287 if (Unit) {
3288 errs() << Filename << ": Clang modules are expected to have exactly"
3289 << " 1 compile unit.\n";
3290 exitDsymutil(1);
3291 }
Adrian Prantl20937022015-09-23 17:11:10 +00003292 if (getDwoId(*CUDie, *CU) != DwoId)
3293 reportWarning(
3294 Twine("hash mismatch: this object file was built against a "
3295 "different version of the module ") + Filename);
3296
3297 // Add this module.
Adrian Prantla112ef92015-09-23 17:35:52 +00003298 Unit = llvm::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
3299 ModuleName);
Adrian Prantle5162db2015-09-22 22:20:50 +00003300 Unit->setHasInterestingContent();
Adrian Prantla112ef92015-09-23 17:35:52 +00003301 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), StringPool,
3302 ODRContexts);
Adrian Prantle5162db2015-09-22 22:20:50 +00003303 // Keep everything.
3304 Unit->markEverythingAsKept();
3305 }
3306 }
3307 if (Options.Verbose) {
3308 outs().indent(Indent);
3309 outs() << "cloning .debug_info from " << Filename << "\n";
3310 }
3311
3312 DIECloner(*this, RelocMgr, DIEAlloc, MutableArrayRef<CompileUnit>(*Unit),
3313 Options)
3314 .cloneAllCompileUnits(DwarfContext);
3315}
3316
Adrian Prantl3565af42015-09-14 16:46:10 +00003317void DwarfLinker::DIECloner::cloneAllCompileUnits(
3318 DWARFContextInMemory &DwarfContext) {
3319 if (!Linker.Streamer)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003320 return;
3321
3322 for (auto &CurrentUnit : CompileUnits) {
3323 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Adrian Prantl3565af42015-09-14 16:46:10 +00003324 CurrentUnit.setStartOffset(Linker.OutputDebugInfoSize);
Adrian Prantl3abe18d2015-09-14 23:27:26 +00003325 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PC offset */,
3326 11 /* Unit Header size */, 0);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003327 CurrentUnit.setOutputUnitDIE(OutputDIE);
Adrian Prantl3565af42015-09-14 16:46:10 +00003328 Linker.OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3329 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003330 continue;
3331 // FIXME: for compatibility with the classic dsymutil, we emit
3332 // an empty line table for the unit, even if the unit doesn't
3333 // actually exist in the DIE tree.
Adrian Prantl3565af42015-09-14 16:46:10 +00003334 Linker.patchLineTableForUnit(CurrentUnit, DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003335 if (!OutputDIE)
3336 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003337 Linker.patchRangesForUnit(CurrentUnit, DwarfContext);
3338 Linker.Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3339 Linker.emitAcceleratorEntriesForUnit(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003340 }
3341
Adrian Prantl3565af42015-09-14 16:46:10 +00003342 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003343 return;
3344
3345 // Emit all the compile unit's debug information.
3346 for (auto &CurrentUnit : CompileUnits) {
Adrian Prantl3565af42015-09-14 16:46:10 +00003347 Linker.generateUnitRanges(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003348 CurrentUnit.fixupForwardReferences();
Adrian Prantl3565af42015-09-14 16:46:10 +00003349 Linker.Streamer->emitCompileUnitHeader(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003350 if (!CurrentUnit.getOutputUnitDIE())
3351 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003352 Linker.Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003353 }
3354}
3355
Frederic Rissd3455182015-01-28 18:27:01 +00003356bool DwarfLinker::link(const DebugMap &Map) {
3357
Frederic Rissc99ea202015-02-28 00:29:11 +00003358 if (!createStreamer(Map.getTriple(), OutputFilename))
3359 return false;
3360
Frederic Rissb8b43d52015-03-04 22:07:44 +00003361 // Size of the DIEs (and headers) generated for the linked output.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003362 OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00003363 // A unique ID that identifies each compile unit.
Adrian Prantle5162db2015-09-22 22:20:50 +00003364 UnitID = 0;
3365 DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
3366
Frederic Rissd3455182015-01-28 18:27:01 +00003367 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00003368 CurrentDebugObject = Obj.get();
3369
Frederic Rissb9818322015-02-28 00:29:07 +00003370 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00003371 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00003372 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3373 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00003374 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00003375
Frederic Riss1036e642015-02-13 23:18:22 +00003376 // Look for relocations that correspond to debug map entries.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003377 RelocationManager RelocMgr(*this);
3378 if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00003379 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00003380 outs() << "No valid relocations found. Skipping.\n";
3381 continue;
3382 }
3383
Frederic Riss563cba62015-01-28 22:15:14 +00003384 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00003385 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00003386 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00003387
Adrian Prantld2793a02015-10-05 23:11:20 +00003388 // In a first phase, just read in the debug info and load all clang modules.
Frederic Rissd3455182015-01-28 18:27:01 +00003389 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003390 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00003391 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00003392 outs() << "Input compilation unit:";
3393 CUDie->dump(outs(), CU.get(), 0);
3394 }
Adrian Prantld2793a02015-10-05 23:11:20 +00003395
3396 if (!registerModuleReference(*CUDie, *CU, ModuleMap))
Adrian Prantla112ef92015-09-23 17:35:52 +00003397 Units.emplace_back(*CU, UnitID++, !Options.NoODR, "");
Frederic Rissd3455182015-01-28 18:27:01 +00003398 }
Frederic Riss563cba62015-01-28 22:15:14 +00003399
Adrian Prantld2793a02015-10-05 23:11:20 +00003400 // Now build the DIE parent links that we will use during the next phase.
3401 for (auto &CurrentUnit : Units)
3402 analyzeContextInfo(CurrentUnit.getOrigUnit().getUnitDIE(), 0, CurrentUnit,
3403 &ODRContexts.getRoot(), StringPool, ODRContexts);
3404
Frederic Riss84c09a52015-02-13 23:18:34 +00003405 // Then mark all the DIEs that need to be present in the linked
3406 // output and collect some information about them. Note that this
3407 // loop can not be merged with the previous one becaue cross-cu
3408 // references require the ParentIdx to be setup for every CU in
3409 // the object file before calling this.
3410 for (auto &CurrentUnit : Units)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003411 lookForDIEsToKeep(RelocMgr, *CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00003412 CurrentUnit, 0);
3413
Frederic Riss23e20e92015-03-07 01:25:09 +00003414 // The calls to applyValidRelocs inside cloneDIE will walk the
3415 // reloc array again (in the same way findValidRelocsInDebugInfo()
3416 // did). We need to reset the NextValidReloc index to the beginning.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003417 RelocMgr.resetValidRelocs();
3418 if (RelocMgr.hasValidRelocs())
Adrian Prantl3565af42015-09-14 16:46:10 +00003419 DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3420 .cloneAllCompileUnits(DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003421 if (!Options.NoOutput && !Units.empty())
Frederic Riss5a642072015-06-05 23:06:11 +00003422 patchFrameInfoForObject(*Obj, DwarfContext,
3423 Units[0].getOrigUnit().getAddressByteSize());
3424
Frederic Riss563cba62015-01-28 22:15:14 +00003425 // Clean-up before starting working on the next object.
3426 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003427 }
3428
Frederic Rissb8b43d52015-03-04 22:07:44 +00003429 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003430 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003431 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003432 Streamer->emitStrings(StringPool);
3433 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003434
Frederic Riss24faade2015-09-02 16:49:13 +00003435 return Options.NoOutput ? true : Streamer->finish(Map);
Frederic Riss231f7142014-12-12 17:31:24 +00003436}
3437}
Frederic Rissd3455182015-01-28 18:27:01 +00003438
Frederic Riss30711fb2015-08-26 05:09:52 +00003439/// \brief Get the offset of string \p S in the string table. This
3440/// can insert a new element or return the offset of a preexisitng
3441/// one.
3442uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3443 if (S.empty() && !Strings.empty())
3444 return 0;
3445
3446 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3447 MapTy::iterator It;
3448 bool Inserted;
3449
3450 // A non-empty string can't be at offset 0, so if we have an entry
3451 // with a 0 offset, it must be a previously interned string.
3452 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3453 if (Inserted || It->getValue().first == 0) {
3454 // Set offset and chain at the end of the entries list.
3455 It->getValue().first = CurrentEndOffset;
3456 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3457 Last->getValue().second = &*It;
3458 Last = &*It;
3459 }
3460 return It->getValue().first;
3461}
3462
3463/// \brief Put \p S into the StringMap so that it gets permanent
3464/// storage, but do not actually link it in the chain of elements
3465/// that go into the output section. A latter call to
3466/// getStringOffset() with the same string will chain it though.
3467StringRef NonRelocatableStringpool::internString(StringRef S) {
3468 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3469 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3470 return InsertResult.first->getKey();
3471}
3472
Frederic Riss65e145c2015-08-26 05:09:55 +00003473void warn(const Twine &Warning, const Twine &Context) {
3474 errs() << Twine("while processing ") + Context + ":\n";
3475 errs() << Twine("warning: ") + Warning + "\n";
3476}
3477
3478bool error(const Twine &Error, const Twine &Context) {
3479 errs() << Twine("while processing ") + Context + ":\n";
3480 errs() << Twine("error: ") + Error + "\n";
3481 return false;
3482}
3483
Frederic Rissb9818322015-02-28 00:29:07 +00003484bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3485 const LinkOptions &Options) {
3486 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003487 return Linker.link(DM);
3488}
3489}
Frederic Riss231f7142014-12-12 17:31:24 +00003490}