blob: 67bf82bfe970383d9f667a933d59036e6916752e [file] [log] [blame]
Frederic Riss231f7142014-12-12 17:31:24 +00001//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "DebugMap.h"
Frederic Rissd3455182015-01-28 18:27:01 +000010#include "BinaryHolder.h"
11#include "DebugMap.h"
Frederic Riss231f7142014-12-12 17:31:24 +000012#include "dsymutil.h"
Frederic Riss24faade2015-09-02 16:49:13 +000013#include "MachOUtils.h"
Frederic Riss30711fb2015-08-26 05:09:52 +000014#include "NonRelocatableStringpool.h"
Frederic Riss1af75f72015-03-12 18:45:10 +000015#include "llvm/ADT/IntervalMap.h"
Adrian Prantl20937022015-09-23 17:11:10 +000016#include "llvm/ADT/StringMap.h"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000017#include "llvm/ADT/STLExtras.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000018#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000019#include "llvm/CodeGen/DIE.h"
Frederic Riss1c650942015-07-21 22:41:43 +000020#include "llvm/Config/config.h"
Zachary Turner82af9432015-01-30 18:07:45 +000021#include "llvm/DebugInfo/DWARF/DWARFContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000023#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000024#include "llvm/MC/MCAsmBackend.h"
25#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCContext.h"
27#include "llvm/MC/MCCodeEmitter.h"
Frederic Riss63786b02015-03-15 20:45:43 +000028#include "llvm/MC/MCDwarf.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000029#include "llvm/MC/MCInstrInfo.h"
30#include "llvm/MC/MCObjectFileInfo.h"
31#include "llvm/MC/MCRegisterInfo.h"
32#include "llvm/MC/MCStreamer.h"
Pete Cooper81902a32015-05-15 22:19:42 +000033#include "llvm/MC/MCSubtargetInfo.h"
David Majnemer03e2cc32015-12-21 22:09:27 +000034#include "llvm/MC/MCTargetOptionsCommandFlags.h"
Frederic Riss1036e642015-02-13 23:18:22 +000035#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000036#include "llvm/Support/Dwarf.h"
37#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000038#include "llvm/Support/TargetRegistry.h"
39#include "llvm/Target/TargetMachine.h"
40#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000041#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000042#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000043
44namespace llvm {
45namespace dsymutil {
46
Frederic Rissd3455182015-01-28 18:27:01 +000047namespace {
48
Frederic Riss1af75f72015-03-12 18:45:10 +000049template <typename KeyT, typename ValT>
50using HalfOpenIntervalMap =
51 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
52 IntervalMapHalfOpenInfo<KeyT>>;
53
Frederic Riss25440872015-03-13 23:30:31 +000054typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
55
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000056// FIXME: Delete this structure.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000057struct PatchLocation {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000058 DIE::value_iterator I;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000059
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000060 PatchLocation() = default;
61 PatchLocation(DIE::value_iterator I) : I(I) {}
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000062
63 void set(uint64_t New) const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000064 assert(I);
65 const auto &Old = *I;
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000066 assert(Old.getType() == DIEValue::isInteger);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000067 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000068 }
69
70 uint64_t get() const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000071 assert(I);
72 return I->getDIEInteger().getValue();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000073 }
74};
75
Frederic Riss1c650942015-07-21 22:41:43 +000076class CompileUnit;
77struct DeclMapInfo;
Frederic Riss1c650942015-07-21 22:41:43 +000078
79/// A DeclContext is a named program scope that is used for ODR
80/// uniquing of types.
81/// The set of DeclContext for the ODR-subject parts of a Dwarf link
82/// is expanded (and uniqued) with each new object file processed. We
83/// need to determine the context of each DIE in an linked object file
84/// to see if the corresponding type has already been emitted.
85///
86/// The contexts are conceptually organised as a tree (eg. a function
87/// scope is contained in a namespace scope that contains other
88/// scopes), but storing/accessing them in an actual tree is too
89/// inefficient: we need to be able to very quickly query a context
90/// for a given child context by name. Storing a StringMap in each
91/// DeclContext would be too space inefficient.
92/// The solution here is to give each DeclContext a link to its parent
93/// (this allows to walk up the tree), but to query the existance of a
94/// specific DeclContext using a separate DenseMap keyed on the hash
95/// of the fully qualified name of the context.
96class DeclContext {
97 unsigned QualifiedNameHash;
98 uint32_t Line;
99 uint32_t ByteSize;
100 uint16_t Tag;
101 StringRef Name;
102 StringRef File;
103 const DeclContext &Parent;
104 const DWARFDebugInfoEntryMinimal *LastSeenDIE;
105 uint32_t LastSeenCompileUnitID;
106 uint32_t CanonicalDIEOffset;
107
108 friend DeclMapInfo;
109
110public:
111 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
112
113 DeclContext()
114 : QualifiedNameHash(0), Line(0), ByteSize(0),
115 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
116 LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
117
118 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
119 StringRef Name, StringRef File, const DeclContext &Parent,
120 const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
121 unsigned CUId = 0)
122 : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
123 Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
124 LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
125
126 uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
127
128 bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
129
130 uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
131 void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
132
133 uint16_t getTag() const { return Tag; }
134 StringRef getName() const { return Name; }
135};
136
137/// Info type for the DenseMap storing the DeclContext pointers.
138struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
139 using DenseMapInfo<DeclContext *>::getEmptyKey;
140 using DenseMapInfo<DeclContext *>::getTombstoneKey;
141
142 static unsigned getHashValue(const DeclContext *Ctxt) {
143 return Ctxt->QualifiedNameHash;
144 }
145
146 static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
147 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
148 return RHS == LHS;
149 return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
150 LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
151 LHS->Name.data() == RHS->Name.data() &&
152 LHS->File.data() == RHS->File.data() &&
153 LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
154 }
155};
156
157/// This class gives a tree-like API to the DenseMap that stores the
158/// DeclContext objects. It also holds the BumpPtrAllocator where
159/// these objects will be allocated.
160class DeclContextTree {
161 BumpPtrAllocator Allocator;
162 DeclContext Root;
163 DeclContext::Map Contexts;
164
165public:
166 /// Get the child of \a Context described by \a DIE in \a Unit. The
167 /// required strings will be interned in \a StringPool.
168 /// \returns The child DeclContext along with one bit that is set if
169 /// this context is invalid.
Adrian Prantl42562c32015-10-02 00:27:08 +0000170 /// An invalid context means it shouldn't be considered for uniquing, but its
171 /// not returning null, because some children of that context might be
172 /// uniquing candidates. FIXME: The invalid bit along the return value is to
173 /// emulate some dsymutil-classic functionality.
Frederic Riss1c650942015-07-21 22:41:43 +0000174 PointerIntPair<DeclContext *, 1>
175 getChildDeclContext(DeclContext &Context,
176 const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
Adrian Prantl42562c32015-10-02 00:27:08 +0000177 NonRelocatableStringpool &StringPool, bool InClangModule);
Frederic Riss1c650942015-07-21 22:41:43 +0000178
179 DeclContext &getRoot() { return Root; }
180};
181
Frederic Riss563cba62015-01-28 22:15:14 +0000182/// \brief Stores all information relating to a compile unit, be it in
183/// its original instance in the object file to its brand new cloned
184/// and linked DIE tree.
185class CompileUnit {
186public:
187 /// \brief Information gathered about a DIE in the object file.
188 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +0000189 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss1c650942015-07-21 22:41:43 +0000190 DeclContext *Ctxt; ///< ODR Declaration context.
Frederic Riss9833de62015-03-06 23:22:53 +0000191 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +0000192 uint32_t ParentIdx; ///< The index of this DIE's parent.
Adrian Prantla112ef92015-09-23 17:35:52 +0000193 bool Keep : 1; ///< Is the DIE part of the linked output?
194 bool InDebugMap : 1;///< Was this DIE's entity found in the map?
195 bool Prune : 1; ///< Is this a pure forward declaration we can strip?
Frederic Riss563cba62015-01-28 22:15:14 +0000196 };
197
Adrian Prantla112ef92015-09-23 17:35:52 +0000198 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR,
199 StringRef ClangModuleName)
Frederic Riss3cced052015-03-14 03:46:40 +0000200 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Adrian Prantla112ef92015-09-23 17:35:52 +0000201 Ranges(RangeAlloc), ClangModuleName(ClangModuleName) {
Frederic Riss563cba62015-01-28 22:15:14 +0000202 Info.resize(OrigUnit.getNumDIEs());
Frederic Riss1c650942015-07-21 22:41:43 +0000203
204 const auto *CUDie = OrigUnit.getUnitDIE(false);
205 unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
206 &OrigUnit, dwarf::DW_AT_language, 0);
207 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
208 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
209 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
210 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
211 Lang == dwarf::DW_LANG_ObjC_plus_plus);
Frederic Riss563cba62015-01-28 22:15:14 +0000212 }
213
Frederic Riss2838f9e2015-03-05 05:29:05 +0000214 CompileUnit(CompileUnit &&RHS)
215 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
216 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +0000217 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
218 // The CompileUnit container has been 'reserve()'d with the right
219 // size. We cannot move the IntervalMap anyway.
220 llvm_unreachable("CompileUnits should not be moved.");
221 }
David Blaikiea8adc132015-03-04 22:20:52 +0000222
Frederic Rissc3349d42015-02-13 23:18:27 +0000223 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000224
Frederic Riss3cced052015-03-14 03:46:40 +0000225 unsigned getUniqueID() const { return ID; }
226
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +0000227 DIE *getOutputUnitDIE() const { return CUDie; }
228 void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000229
Frederic Riss1c650942015-07-21 22:41:43 +0000230 bool hasODR() const { return HasODR; }
Adrian Prantla112ef92015-09-23 17:35:52 +0000231 bool isClangModule() const { return !ClangModuleName.empty(); }
232 const std::string &getClangModuleName() const { return ClangModuleName; }
Frederic Riss1c650942015-07-21 22:41:43 +0000233
Frederic Riss563cba62015-01-28 22:15:14 +0000234 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
235 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
236
Frederic Rissb8b43d52015-03-04 22:07:44 +0000237 uint64_t getStartOffset() const { return StartOffset; }
238 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000239 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000240
Frederic Riss5a62dc32015-03-13 18:35:54 +0000241 uint64_t getLowPc() const { return LowPc; }
242 uint64_t getHighPc() const { return HighPc; }
243
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000244 Optional<PatchLocation> getUnitRangesAttribute() const {
245 return UnitRangeAttribute;
246 }
Frederic Riss25440872015-03-13 23:30:31 +0000247 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000248 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000249 return RangeAttributes;
250 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000251
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000252 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000253 getLocationAttributes() const {
254 return LocationAttributes;
255 }
256
Adrian Prantle5162db2015-09-22 22:20:50 +0000257 void setHasInterestingContent() { HasInterestingContent = true; }
258 bool hasInterestingContent() { return HasInterestingContent; }
259
260 /// Mark every DIE in this unit as kept. This function also
261 /// marks variables as InDebugMap so that they appear in the
262 /// reconstructed accelerator tables.
263 void markEverythingAsKept();
264
Frederic Riss9d441b62015-03-06 23:22:50 +0000265 /// \brief Compute the end offset for this unit. Must be
266 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000267 /// \returns the next unit offset (which is also the current
268 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000269 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000270
Frederic Riss6afcfce2015-03-13 18:35:57 +0000271 /// \brief Keep track of a forward reference to DIE \p Die in \p
272 /// RefUnit by \p Attr. The attribute should be fixed up later to
Frederic Riss1c650942015-07-21 22:41:43 +0000273 /// point to the absolute offset of \p Die in the debug_info section
274 /// or to the canonical offset of \p Ctxt if it is non-null.
Frederic Riss6afcfce2015-03-13 18:35:57 +0000275 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000276 DeclContext *Ctxt, PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000277
278 /// \brief Apply all fixups recored by noteForwardReference().
279 void fixupForwardReferences();
280
Frederic Riss1af75f72015-03-12 18:45:10 +0000281 /// \brief Add a function range [\p LowPC, \p HighPC) that is
282 /// relocatad by applying offset \p PCOffset.
283 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
284
Frederic Riss5c9c7062015-03-13 23:55:29 +0000285 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000286 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000287 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000288
Frederic Rissdfb97902015-03-14 15:49:07 +0000289 /// \brief Keep track of a location attribute pointing to a location
290 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000291 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000292
Frederic Rissbce93ff2015-03-16 02:05:10 +0000293 /// \brief Add a name accelerator entry for \p Die with \p Name
294 /// which is stored in the string table at \p Offset.
295 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
296 bool SkipPubnamesSection = false);
297
298 /// \brief Add a type accelerator entry for \p Die with \p Name
299 /// which is stored in the string table at \p Offset.
300 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
301
302 struct AccelInfo {
Frederic Rissf37964c2015-06-05 20:27:07 +0000303 StringRef Name; ///< Name of the entry.
304 const DIE *Die; ///< DIE this entry describes.
Frederic Rissbce93ff2015-03-16 02:05:10 +0000305 uint32_t NameOffset; ///< Offset of Name in the string pool.
306 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
307
308 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
309 bool SkipPubSection = false)
310 : Name(Name), Die(Die), NameOffset(NameOffset),
311 SkipPubSection(SkipPubSection) {}
312 };
313
314 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
315 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
316
Frederic Riss1c650942015-07-21 22:41:43 +0000317 /// Get the full path for file \a FileNum in the line table
Pete Cooperef4e36a2016-03-18 03:48:09 +0000318 StringRef getResolvedPath(unsigned FileNum) {
Frederic Riss1c650942015-07-21 22:41:43 +0000319 if (FileNum >= ResolvedPaths.size())
Pete Cooperef4e36a2016-03-18 03:48:09 +0000320 return StringRef();
321 return ResolvedPaths[FileNum];
Frederic Riss1c650942015-07-21 22:41:43 +0000322 }
323
324 /// Set the fully resolved path for the line-table's file \a FileNum
325 /// to \a Path.
Pete Cooperef4e36a2016-03-18 03:48:09 +0000326 void setResolvedPath(unsigned FileNum, StringRef Path) {
Frederic Riss1c650942015-07-21 22:41:43 +0000327 if (ResolvedPaths.size() <= FileNum)
328 ResolvedPaths.resize(FileNum + 1);
329 ResolvedPaths[FileNum] = Path;
330 }
331
Frederic Riss563cba62015-01-28 22:15:14 +0000332private:
333 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000334 unsigned ID;
Frederic Riss1c650942015-07-21 22:41:43 +0000335 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
336 DIE *CUDie; ///< Root of the linked DIE tree.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000337
338 uint64_t StartOffset;
339 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000340
Frederic Riss5a62dc32015-03-13 18:35:54 +0000341 uint64_t LowPc;
342 uint64_t HighPc;
343
Frederic Riss9833de62015-03-06 23:22:53 +0000344 /// \brief A list of attributes to fixup with the absolute offset of
345 /// a DIE in the debug_info section.
346 ///
347 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000348 /// cloning because for cross-cu forward refences the target DIE's
349 /// offset isn't known you emit the reference attribute.
Frederic Riss1c650942015-07-21 22:41:43 +0000350 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
351 PatchLocation>> ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000352
Frederic Riss25440872015-03-13 23:30:31 +0000353 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000354 /// \brief The ranges in that interval map are the PC ranges for
355 /// functions in this unit, associated with the PC offset to apply
356 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000357 FunctionIntervals Ranges;
358
359 /// \brief DW_AT_ranges attributes to patch after we have gathered
360 /// all the unit's function addresses.
361 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000362 std::vector<PatchLocation> RangeAttributes;
363 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000364 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000365
366 /// \brief Location attributes that need to be transfered from th
367 /// original debug_loc section to the liked one. They are stored
368 /// along with the PC offset that is to be applied to their
369 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000370 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000371
372 /// \brief Accelerator entries for the unit, both for the pub*
373 /// sections and the apple* ones.
374 /// @{
375 std::vector<AccelInfo> Pubnames;
376 std::vector<AccelInfo> Pubtypes;
377 /// @}
Frederic Riss1c650942015-07-21 22:41:43 +0000378
379 /// Cached resolved paths from the line table.
Pete Cooperef4e36a2016-03-18 03:48:09 +0000380 /// Note, the StringRefs here point in to the intern (uniquing) string pool.
381 /// This means that a StringRef returned here doesn't need to then be uniqued
382 /// for the purposes of getting a unique address for each string.
383 std::vector<StringRef> ResolvedPaths;
Frederic Riss1c650942015-07-21 22:41:43 +0000384
385 /// Is this unit subject to the ODR rule?
386 bool HasODR;
Adrian Prantle5162db2015-09-22 22:20:50 +0000387 /// Did a DIE actually contain a valid reloc?
388 bool HasInterestingContent;
Adrian Prantla112ef92015-09-23 17:35:52 +0000389 /// If this is a Clang module, this holds the module's name.
390 std::string ClangModuleName;
Frederic Riss563cba62015-01-28 22:15:14 +0000391};
392
Adrian Prantle5162db2015-09-22 22:20:50 +0000393void CompileUnit::markEverythingAsKept() {
394 for (auto &I : Info)
Adrian Prantla112ef92015-09-23 17:35:52 +0000395 // Mark everything that wasn't explicity marked for pruning.
396 I.Keep = !I.Prune;
Adrian Prantle5162db2015-09-22 22:20:50 +0000397}
398
Frederic Riss9d441b62015-03-06 23:22:50 +0000399uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000400 NextUnitOffset = StartOffset + 11 /* Header size */;
401 // The root DIE might be null, meaning that the Unit had nothing to
402 // contribute to the linked output. In that case, we will emit the
403 // unit header without any actual DIE.
404 if (CUDie)
405 NextUnitOffset += CUDie->getSize();
406 return NextUnitOffset;
407}
408
Frederic Riss6afcfce2015-03-13 18:35:57 +0000409/// \brief Keep track of a forward cross-cu reference from this unit
410/// to \p Die that lives in \p RefUnit.
411void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000412 DeclContext *Ctxt, PatchLocation Attr) {
413 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000414}
415
416/// \brief Apply all fixups recorded by noteForwardReference().
417void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000418 for (const auto &Ref : ForwardDIEReferences) {
419 DIE *RefDie;
420 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000421 PatchLocation Attr;
Frederic Riss1c650942015-07-21 22:41:43 +0000422 DeclContext *Ctxt;
423 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
424 if (Ctxt && Ctxt->getCanonicalDIEOffset())
425 Attr.set(Ctxt->getCanonicalDIEOffset());
426 else
427 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000428 }
Frederic Riss9833de62015-03-06 23:22:53 +0000429}
430
Frederic Riss5a62dc32015-03-13 18:35:54 +0000431void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
432 int64_t PcOffset) {
433 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
434 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
435 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000436}
437
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000438void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000439 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
440 RangeAttributes.push_back(Attr);
441 else
442 UnitRangeAttribute = Attr;
443}
444
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000445void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000446 LocationAttributes.emplace_back(Attr, PcOffset);
447}
448
Frederic Rissbce93ff2015-03-16 02:05:10 +0000449/// \brief Add a name accelerator entry for \p Die with \p Name
450/// which is stored in the string table at \p Offset.
451void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
452 uint32_t Offset, bool SkipPubSection) {
453 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
454}
455
456/// \brief Add a type accelerator entry for \p Die with \p Name
457/// which is stored in the string table at \p Offset.
458void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
459 uint32_t Offset) {
460 Pubtypes.emplace_back(Name, Die, Offset, false);
461}
462
Frederic Rissc99ea202015-02-28 00:29:11 +0000463/// \brief The Dwarf streaming logic
464///
465/// All interactions with the MC layer that is used to build the debug
466/// information binary representation are handled in this class.
467class DwarfStreamer {
468 /// \defgroup MCObjects MC layer objects constructed by the streamer
469 /// @{
470 std::unique_ptr<MCRegisterInfo> MRI;
471 std::unique_ptr<MCAsmInfo> MAI;
472 std::unique_ptr<MCObjectFileInfo> MOFI;
473 std::unique_ptr<MCContext> MC;
474 MCAsmBackend *MAB; // Owned by MCStreamer
475 std::unique_ptr<MCInstrInfo> MII;
476 std::unique_ptr<MCSubtargetInfo> MSTI;
477 MCCodeEmitter *MCE; // Owned by MCStreamer
478 MCStreamer *MS; // Owned by AsmPrinter
479 std::unique_ptr<TargetMachine> TM;
480 std::unique_ptr<AsmPrinter> Asm;
481 /// @}
482
483 /// \brief the file we stream the linked Dwarf to.
484 std::unique_ptr<raw_fd_ostream> OutFile;
485
Frederic Riss25440872015-03-13 23:30:31 +0000486 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000487 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000488 uint32_t LineSectionSize;
Frederic Riss5a642072015-06-05 23:06:11 +0000489 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000490
Frederic Rissbce93ff2015-03-16 02:05:10 +0000491 /// \brief Emit the pubnames or pubtypes section contribution for \p
492 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000493 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000494 const CompileUnit &Unit,
495 const std::vector<CompileUnit::AccelInfo> &Names);
496
Frederic Rissc99ea202015-02-28 00:29:11 +0000497public:
498 /// \brief Actually create the streamer and the ouptut file.
499 ///
500 /// This could be done directly in the constructor, but it feels
501 /// more natural to handle errors through return value.
502 bool init(Triple TheTriple, StringRef OutputFilename);
503
Frederic Rissb8b43d52015-03-04 22:07:44 +0000504 /// \brief Dump the file to the disk.
Frederic Riss24faade2015-09-02 16:49:13 +0000505 bool finish(const DebugMap &);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000506
507 AsmPrinter &getAsmPrinter() const { return *Asm; }
508
509 /// \brief Set the current output section to debug_info and change
510 /// the MC Dwarf version to \p DwarfVersion.
511 void switchToDebugInfoSection(unsigned DwarfVersion);
512
513 /// \brief Emit the compilation unit header for \p Unit in the
514 /// debug_info section.
515 ///
516 /// As a side effect, this also switches the current Dwarf version
517 /// of the MC layer to the one of U.getOrigUnit().
518 void emitCompileUnitHeader(CompileUnit &Unit);
519
520 /// \brief Recursively emit the DIE tree rooted at \p Die.
521 void emitDIE(DIE &Die);
522
523 /// \brief Emit the abbreviation table \p Abbrevs to the
524 /// debug_abbrev section.
David Blaikie6196aa02015-11-18 00:34:10 +0000525 void emitAbbrevs(const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000526
527 /// \brief Emit the string table described by \p Pool.
528 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000529
530 /// \brief Emit debug_ranges for \p FuncRange by translating the
531 /// original \p Entries.
532 void emitRangesEntries(
533 int64_t UnitPcOffset, uint64_t OrigLowPc,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000534 const FunctionIntervals::const_iterator &FuncRange,
Frederic Riss25440872015-03-13 23:30:31 +0000535 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
536 unsigned AddressSize);
537
Frederic Riss563b1b02015-03-14 03:46:51 +0000538 /// \brief Emit debug_aranges entries for \p Unit and if \p
539 /// DoRangesSection is true, also emit the debug_ranges entries for
540 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
541 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000542
543 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000544
545 /// \brief Emit the debug_loc contribution for \p Unit by copying
546 /// the entries from \p Dwarf and offseting them. Update the
547 /// location attributes to point to the new entries.
548 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000549
550 /// \brief Emit the line table described in \p Rows into the
551 /// debug_line section.
Frederic Rissa5e14532015-08-07 15:14:13 +0000552 void emitLineTableForUnit(MCDwarfLineTableParams Params,
553 StringRef PrologueBytes, unsigned MinInstLength,
Frederic Riss63786b02015-03-15 20:45:43 +0000554 std::vector<DWARFDebugLine::Row> &Rows,
555 unsigned AdddressSize);
556
557 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000558
559 /// \brief Emit the .debug_pubnames contribution for \p Unit.
560 void emitPubNamesForUnit(const CompileUnit &Unit);
561
562 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
563 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000564
565 /// \brief Emit a CIE.
566 void emitCIE(StringRef CIEBytes);
567
568 /// \brief Emit an FDE with data \p Bytes.
569 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
570 StringRef Bytes);
571
572 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000573};
574
575bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
576 std::string ErrorStr;
577 std::string TripleName;
578 StringRef Context = "dwarf streamer init";
579
580 // Get the target.
581 const Target *TheTarget =
582 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
583 if (!TheTarget)
584 return error(ErrorStr, Context);
585 TripleName = TheTriple.getTriple();
586
587 // Create all the MC Objects.
588 MRI.reset(TheTarget->createMCRegInfo(TripleName));
589 if (!MRI)
590 return error(Twine("no register info for target ") + TripleName, Context);
591
592 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
593 if (!MAI)
594 return error("no asm info for target " + TripleName, Context);
595
596 MOFI.reset(new MCObjectFileInfo);
597 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Rafael Espindola699281c2016-05-18 11:58:50 +0000598 MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, CodeModel::Default, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000599
600 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
601 if (!MAB)
602 return error("no asm backend for target " + TripleName, Context);
603
604 MII.reset(TheTarget->createMCInstrInfo());
605 if (!MII)
606 return error("no instr info info for target " + TripleName, Context);
607
608 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
609 if (!MSTI)
610 return error("no subtarget info for target " + TripleName, Context);
611
Eric Christopher0169e422015-03-10 22:03:14 +0000612 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000613 if (!MCE)
614 return error("no code emitter for target " + TripleName, Context);
615
616 // Create the output file.
617 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000618 OutFile =
619 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000620 if (EC)
621 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
622
David Majnemer03e2cc32015-12-21 22:09:27 +0000623 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
624 MS = TheTarget->createMCObjectStreamer(
625 TheTriple, *MC, *MAB, *OutFile, MCE, *MSTI, MCOptions.MCRelaxAll,
626 MCOptions.MCIncrementalLinkerCompatible,
627 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000628 if (!MS)
629 return error("no object streamer for target " + TripleName, Context);
630
631 // Finally create the AsmPrinter we'll use to emit the DIEs.
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000632 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
633 None));
Frederic Rissc99ea202015-02-28 00:29:11 +0000634 if (!TM)
635 return error("no target machine for target " + TripleName, Context);
636
637 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
638 if (!Asm)
639 return error("no asm printer for target " + TripleName, Context);
640
Frederic Riss25440872015-03-13 23:30:31 +0000641 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000642 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000643 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000644 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000645
Frederic Rissc99ea202015-02-28 00:29:11 +0000646 return true;
647}
648
Frederic Riss24faade2015-09-02 16:49:13 +0000649bool DwarfStreamer::finish(const DebugMap &DM) {
650 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty())
651 return MachOUtils::generateDsymCompanion(DM, *MS, *OutFile);
652
Frederic Rissc99ea202015-02-28 00:29:11 +0000653 MS->Finish();
654 return true;
655}
656
Frederic Rissb8b43d52015-03-04 22:07:44 +0000657/// \brief Set the current output section to debug_info and change
658/// the MC Dwarf version to \p DwarfVersion.
659void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
660 MS->SwitchSection(MOFI->getDwarfInfoSection());
661 MC->setDwarfVersion(DwarfVersion);
662}
663
664/// \brief Emit the compilation unit header for \p Unit in the
665/// debug_info section.
666///
667/// A Dwarf scetion header is encoded as:
668/// uint32_t Unit length (omiting this field)
669/// uint16_t Version
670/// uint32_t Abbreviation table offset
671/// uint8_t Address size
672///
673/// Leading to a total of 11 bytes.
674void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
675 unsigned Version = Unit.getOrigUnit().getVersion();
676 switchToDebugInfoSection(Version);
677
678 // Emit size of content not including length itself. The size has
679 // already been computed in CompileUnit::computeOffsets(). Substract
680 // 4 to that size to account for the length field.
681 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
682 Asm->EmitInt16(Version);
683 // We share one abbreviations table across all units so it's always at the
684 // start of the section.
685 Asm->EmitInt32(0);
686 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
687}
688
689/// \brief Emit the \p Abbrevs array as the shared abbreviation table
690/// for the linked Dwarf file.
David Blaikie6196aa02015-11-18 00:34:10 +0000691void DwarfStreamer::emitAbbrevs(
692 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs) {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000693 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
694 Asm->emitDwarfAbbrevs(Abbrevs);
695}
696
697/// \brief Recursively emit the DIE tree rooted at \p Die.
698void DwarfStreamer::emitDIE(DIE &Die) {
699 MS->SwitchSection(MOFI->getDwarfInfoSection());
700 Asm->emitDwarfDIE(Die);
701}
702
Frederic Rissef648462015-03-06 17:56:30 +0000703/// \brief Emit the debug_str section stored in \p Pool.
704void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000705 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000706 for (auto *Entry = Pool.getFirstEntry(); Entry;
707 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000708 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000709 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
710}
711
Frederic Riss25440872015-03-13 23:30:31 +0000712/// \brief Emit the debug_range section contents for \p FuncRange by
713/// translating the original \p Entries. The debug_range section
714/// format is totally trivial, consisting just of pairs of address
715/// sized addresses describing the ranges.
716void DwarfStreamer::emitRangesEntries(
717 int64_t UnitPcOffset, uint64_t OrigLowPc,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000718 const FunctionIntervals::const_iterator &FuncRange,
Frederic Riss25440872015-03-13 23:30:31 +0000719 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
720 unsigned AddressSize) {
721 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
722
723 // Offset each range by the right amount.
Frederic Riss94546202015-08-31 05:09:32 +0000724 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
Frederic Riss25440872015-03-13 23:30:31 +0000725 for (const auto &Range : Entries) {
726 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
727 warn("unsupported base address selection operation",
728 "emitting debug_ranges");
729 break;
730 }
731 // Do not emit empty ranges.
732 if (Range.StartAddress == Range.EndAddress)
733 continue;
734
735 // All range entries should lie in the function range.
736 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
737 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
738 warn("inconsistent range data.", "emitting debug_ranges");
739 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
740 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
741 RangesSectionSize += 2 * AddressSize;
742 }
743
744 // Add the terminator entry.
745 MS->EmitIntValue(0, AddressSize);
746 MS->EmitIntValue(0, AddressSize);
747 RangesSectionSize += 2 * AddressSize;
748}
749
Frederic Riss563b1b02015-03-14 03:46:51 +0000750/// \brief Emit the debug_aranges contribution of a unit and
751/// if \p DoDebugRanges is true the debug_range contents for a
752/// compile_unit level DW_AT_ranges attribute (Which are basically the
753/// same thing with a different base address).
754/// Just aggregate all the ranges gathered inside that unit.
755void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
756 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000757 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
758 // Gather the ranges in a vector, so that we can simplify them. The
759 // IntervalMap will have coalesced the non-linked ranges, but here
760 // we want to coalesce the linked addresses.
761 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
762 const auto &FunctionRanges = Unit.getFunctionRanges();
763 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
764 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000765 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
766 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000767
768 // The object addresses where sorted, but again, the linked
769 // addresses might end up in a different order.
770 std::sort(Ranges.begin(), Ranges.end());
771
Frederic Riss563b1b02015-03-14 03:46:51 +0000772 if (!Ranges.empty()) {
773 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
774
Rafael Espindola9ab09232015-03-17 20:07:06 +0000775 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
776 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000777
778 unsigned HeaderSize =
779 sizeof(int32_t) + // Size of contents (w/o this field
780 sizeof(int16_t) + // DWARF ARange version number
781 sizeof(int32_t) + // Offset of CU in the .debug_info section
782 sizeof(int8_t) + // Pointer Size (in bytes)
783 sizeof(int8_t); // Segment Size (in bytes)
784
785 unsigned TupleSize = AddressSize * 2;
786 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
787
788 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000789 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000790 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
791 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
792 Asm->EmitInt8(AddressSize); // Address size
793 Asm->EmitInt8(0); // Segment size
794
Petr Hosekfaef3202016-06-01 01:59:58 +0000795 Asm->OutStreamer->emitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000796
797 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
798 ++Range) {
799 uint64_t RangeStart = Range->first;
800 MS->EmitIntValue(RangeStart, AddressSize);
801 while ((Range + 1) != End && Range->second == (Range + 1)->first)
802 ++Range;
803 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
804 }
805
806 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000807 Asm->OutStreamer->EmitIntValue(0, AddressSize);
808 Asm->OutStreamer->EmitIntValue(0, AddressSize);
809 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000810 }
811
812 if (!DoDebugRanges)
813 return;
814
815 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
816 // Offset each range by the right amount.
817 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000818 // Emit coalesced ranges.
819 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000820 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000821 while (Range + 1 != End && Range->second == (Range + 1)->first)
822 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000823 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000824 RangesSectionSize += 2 * AddressSize;
825 }
826
827 // Add the terminator entry.
828 MS->EmitIntValue(0, AddressSize);
829 MS->EmitIntValue(0, AddressSize);
830 RangesSectionSize += 2 * AddressSize;
831}
832
Frederic Rissdfb97902015-03-14 15:49:07 +0000833/// \brief Emit location lists for \p Unit and update attribtues to
834/// point to the new entries.
835void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
836 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000837 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000838
839 if (Attributes.empty())
840 return;
841
842 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
843
844 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
845 const DWARFSection &InputSec = Dwarf.getLocSection();
846 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
847 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000848 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000849 int64_t UnitPcOffset = 0;
850 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
851 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
852 if (OrigLowPc != -1ULL)
853 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
854
855 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000856 uint32_t Offset = Attr.first.get();
857 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000858 // This is the quantity to add to the old location address to get
859 // the correct address for the new one.
860 int64_t LocPcOffset = Attr.second + UnitPcOffset;
861 while (Data.isValidOffset(Offset)) {
862 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
863 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
864 LocSectionSize += 2 * AddressSize;
865 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000866 Asm->OutStreamer->EmitIntValue(0, AddressSize);
867 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000868 break;
869 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000870 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
871 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000872 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000873 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000874 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000875 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000876 StringRef(InputSec.Data.substr(Offset, Length)));
877 Offset += Length;
878 LocSectionSize += Length + 2;
879 }
880 }
881}
882
Frederic Rissa5e14532015-08-07 15:14:13 +0000883void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
884 StringRef PrologueBytes,
Frederic Riss63786b02015-03-15 20:45:43 +0000885 unsigned MinInstLength,
886 std::vector<DWARFDebugLine::Row> &Rows,
887 unsigned PointerSize) {
888 // Switch to the section where the table will be emitted into.
889 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000890 MCSymbol *LineStartSym = MC->createTempSymbol();
891 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000892
893 // The first 4 bytes is the total length of the information for this
894 // compilation unit (not including these 4 bytes for the length).
895 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000896 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000897 // Copy Prologue.
898 MS->EmitBytes(PrologueBytes);
899 LineSectionSize += PrologueBytes.size() + 4;
900
Frederic Rissc3820d02015-03-15 22:20:28 +0000901 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000902 raw_svector_ostream EncodingOS(EncodingBuffer);
903
904 if (Rows.empty()) {
905 // We only have the dummy entry, dsymutil emits an entry with a 0
906 // address in that case.
Frederic Rissa5e14532015-08-07 15:14:13 +0000907 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000908 MS->EmitBytes(EncodingOS.str());
909 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000910 MS->EmitLabel(LineEndSym);
911 return;
912 }
913
914 // Line table state machine fields
915 unsigned FileNum = 1;
916 unsigned LastLine = 1;
917 unsigned Column = 0;
918 unsigned IsStatement = 1;
919 unsigned Isa = 0;
920 uint64_t Address = -1ULL;
921
922 unsigned RowsSinceLastSequence = 0;
923
924 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
925 auto &Row = Rows[Idx];
926
927 int64_t AddressDelta;
928 if (Address == -1ULL) {
929 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
930 MS->EmitULEB128IntValue(PointerSize + 1);
931 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
932 MS->EmitIntValue(Row.Address, PointerSize);
933 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
934 AddressDelta = 0;
935 } else {
936 AddressDelta = (Row.Address - Address) / MinInstLength;
937 }
938
939 // FIXME: code copied and transfromed from
940 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
941 // this code, but the current compatibility requirement with
942 // classic dsymutil makes it hard. Revisit that once this
943 // requirement is dropped.
944
945 if (FileNum != Row.File) {
946 FileNum = Row.File;
947 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
948 MS->EmitULEB128IntValue(FileNum);
949 LineSectionSize += 1 + getULEB128Size(FileNum);
950 }
951 if (Column != Row.Column) {
952 Column = Row.Column;
953 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
954 MS->EmitULEB128IntValue(Column);
955 LineSectionSize += 1 + getULEB128Size(Column);
956 }
957
958 // FIXME: We should handle the discriminator here, but dsymutil
959 // doesn' consider it, thus ignore it for now.
960
961 if (Isa != Row.Isa) {
962 Isa = Row.Isa;
963 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
964 MS->EmitULEB128IntValue(Isa);
965 LineSectionSize += 1 + getULEB128Size(Isa);
966 }
967 if (IsStatement != Row.IsStmt) {
968 IsStatement = Row.IsStmt;
969 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
970 LineSectionSize += 1;
971 }
972 if (Row.BasicBlock) {
973 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
974 LineSectionSize += 1;
975 }
976
977 if (Row.PrologueEnd) {
978 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
979 LineSectionSize += 1;
980 }
981
982 if (Row.EpilogueBegin) {
983 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
984 LineSectionSize += 1;
985 }
986
987 int64_t LineDelta = int64_t(Row.Line) - LastLine;
988 if (!Row.EndSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000989 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000990 MS->EmitBytes(EncodingOS.str());
991 LineSectionSize += EncodingBuffer.size();
992 EncodingBuffer.resize(0);
993 Address = Row.Address;
994 LastLine = Row.Line;
995 RowsSinceLastSequence++;
996 } else {
997 if (LineDelta) {
998 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
999 MS->EmitSLEB128IntValue(LineDelta);
1000 LineSectionSize += 1 + getSLEB128Size(LineDelta);
1001 }
1002 if (AddressDelta) {
1003 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
1004 MS->EmitULEB128IntValue(AddressDelta);
1005 LineSectionSize += 1 + getULEB128Size(AddressDelta);
1006 }
Frederic Rissa5e14532015-08-07 15:14:13 +00001007 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001008 MS->EmitBytes(EncodingOS.str());
1009 LineSectionSize += EncodingBuffer.size();
1010 EncodingBuffer.resize(0);
Frederic Riss63786b02015-03-15 20:45:43 +00001011 Address = -1ULL;
1012 LastLine = FileNum = IsStatement = 1;
1013 RowsSinceLastSequence = Column = Isa = 0;
1014 }
1015 }
1016
1017 if (RowsSinceLastSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +00001018 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001019 MS->EmitBytes(EncodingOS.str());
1020 LineSectionSize += EncodingBuffer.size();
1021 EncodingBuffer.resize(0);
1022 }
1023
1024 MS->EmitLabel(LineEndSym);
1025}
1026
Frederic Rissbce93ff2015-03-16 02:05:10 +00001027/// \brief Emit the pubnames or pubtypes section contribution for \p
1028/// Unit into \p Sec. The data is provided in \p Names.
1029void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001030 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001031 const std::vector<CompileUnit::AccelInfo> &Names) {
1032 if (Names.empty())
1033 return;
1034
1035 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001036 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001037 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1038 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001039
1040 bool HeaderEmitted = false;
1041 // Emit the pubnames for this compilation unit.
1042 for (const auto &Name : Names) {
1043 if (Name.SkipPubSection)
1044 continue;
1045
1046 if (!HeaderEmitted) {
1047 // Emit the header.
1048 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001049 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001050 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001051 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001052 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1053 HeaderEmitted = true;
1054 }
1055 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001056 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001057 StringRef(Name.Name.data(), Name.Name.size() + 1));
1058 }
1059
1060 if (!HeaderEmitted)
1061 return;
1062 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001063 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001064}
1065
1066/// \brief Emit .debug_pubnames for \p Unit.
1067void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1068 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1069 "names", Unit, Unit.getPubnames());
1070}
1071
1072/// \brief Emit .debug_pubtypes for \p Unit.
1073void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1074 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1075 "types", Unit, Unit.getPubtypes());
1076}
1077
Frederic Riss5a642072015-06-05 23:06:11 +00001078/// \brief Emit a CIE into the debug_frame section.
1079void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1080 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1081
1082 MS->EmitBytes(CIEBytes);
1083 FrameSectionSize += CIEBytes.size();
1084}
1085
1086/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1087/// contains the FDE data without the length, CIE offset and address
1088/// which will be replaced with the paramter values.
1089void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1090 uint32_t Address, StringRef FDEBytes) {
1091 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1092
1093 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1094 MS->EmitIntValue(CIEOffset, 4);
1095 MS->EmitIntValue(Address, AddrSize);
1096 MS->EmitBytes(FDEBytes);
1097 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1098}
1099
Frederic Rissd3455182015-01-28 18:27:01 +00001100/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001101///
1102/// The link of the dwarf information from the object files will be
1103/// driven by the selection of 'root DIEs', which are DIEs that
1104/// describe variables or functions that are present in the linked
1105/// binary (and thus have entries in the debug map). All the debug
1106/// information that will be linked (the DIEs, but also the line
1107/// tables, ranges, ...) is derived from that set of root DIEs.
1108///
1109/// The root DIEs are identified because they contain relocations that
1110/// correspond to a debug map entry at specific places (the low_pc for
1111/// a function, the location for a variable). These relocations are
1112/// called ValidRelocs in the DwarfLinker and are gathered as a very
1113/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001114class DwarfLinker {
1115public:
Frederic Rissb9818322015-02-28 00:29:07 +00001116 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1117 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001118 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001119
1120 /// \brief Link the contents of the DebugMap.
1121 bool link(const DebugMap &);
1122
Adrian Prantlc3021ee2015-09-22 18:50:51 +00001123 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1124 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1125
Frederic Rissd3455182015-01-28 18:27:01 +00001126private:
Frederic Riss563cba62015-01-28 22:15:14 +00001127 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001128 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001129
1130 /// \brief Called at the end of a debug object link.
1131 void endDebugObject();
1132
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001133 /// Keeps track of relocations.
1134 class RelocationManager {
1135 struct ValidReloc {
1136 uint32_t Offset;
1137 uint32_t Size;
1138 uint64_t Addend;
1139 const DebugMapObject::DebugMapEntry *Mapping;
Frederic Riss1036e642015-02-13 23:18:22 +00001140
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001141 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1142 const DebugMapObject::DebugMapEntry *Mapping)
1143 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
Frederic Riss1036e642015-02-13 23:18:22 +00001144
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001145 bool operator<(const ValidReloc &RHS) const {
1146 return Offset < RHS.Offset;
1147 }
1148 };
1149
1150 DwarfLinker &Linker;
1151
1152 /// \brief The valid relocations for the current DebugMapObject.
1153 /// This vector is sorted by relocation offset.
1154 std::vector<ValidReloc> ValidRelocs;
1155
1156 /// \brief Index into ValidRelocs of the next relocation to
1157 /// consider. As we walk the DIEs in acsending file offset and as
1158 /// ValidRelocs is sorted by file offset, keeping this index
1159 /// uptodate is all we have to do to have a cheap lookup during the
1160 /// root DIE selection and during DIE cloning.
1161 unsigned NextValidReloc;
1162
1163 public:
1164 RelocationManager(DwarfLinker &Linker)
1165 : Linker(Linker), NextValidReloc(0) {}
1166
1167 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1168 /// \brief Reset the NextValidReloc counter.
1169 void resetValidRelocs() { NextValidReloc = 0; }
1170
1171 /// \defgroup FindValidRelocations Translate debug map into a list
1172 /// of relevant relocations
1173 ///
1174 /// @{
1175 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1176 const DebugMapObject &DMO);
1177
1178 bool findValidRelocs(const object::SectionRef &Section,
1179 const object::ObjectFile &Obj,
1180 const DebugMapObject &DMO);
1181
1182 void findValidRelocsMachO(const object::SectionRef &Section,
1183 const object::MachOObjectFile &Obj,
1184 const DebugMapObject &DMO);
1185 /// @}
1186
1187 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1188 CompileUnit::DIEInfo &Info);
1189
1190 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1191 bool isLittleEndian);
Frederic Riss1036e642015-02-13 23:18:22 +00001192 };
1193
Frederic Riss84c09a52015-02-13 23:18:34 +00001194 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1195 ///
1196 /// @{
1197 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1198 /// keep. Store that information in \p CU's DIEInfo.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001199 void lookForDIEsToKeep(RelocationManager &RelocMgr,
1200 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001201 const DebugMapObject &DMO, CompileUnit &CU,
1202 unsigned Flags);
1203
Adrian Prantle5162db2015-09-22 22:20:50 +00001204 /// If this compile unit is really a skeleton CU that points to a
1205 /// clang module, register it in ClangModules and return true.
1206 ///
1207 /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
1208 /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
1209 /// hash.
1210 bool registerModuleReference(const DWARFDebugInfoEntryMinimal &CUDie,
1211 const DWARFUnit &Unit, DebugMap &ModuleMap,
1212 unsigned Indent = 0);
1213
1214 /// Recursively add the debug info in this clang module .pcm
1215 /// file (and all the modules imported by it in a bottom-up fashion)
1216 /// to Units.
Adrian Prantla112ef92015-09-23 17:35:52 +00001217 void loadClangModule(StringRef Filename, StringRef ModulePath,
1218 StringRef ModuleName, uint64_t DwoId,
Adrian Prantle5162db2015-09-22 22:20:50 +00001219 DebugMap &ModuleMap, unsigned Indent = 0);
1220
Frederic Riss84c09a52015-02-13 23:18:34 +00001221 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1222 enum TravesalFlags {
1223 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1224 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1225 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1226 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001227 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss29eedc72015-09-11 04:17:30 +00001228 TF_SkipPC = 1 << 5, ///< Skip all location attributes.
Frederic Riss84c09a52015-02-13 23:18:34 +00001229 };
1230
1231 /// \brief Mark the passed DIE as well as all the ones it depends on
1232 /// as kept.
Adrian Prantl6ec47122015-09-22 15:31:14 +00001233 void keepDIEAndDependencies(RelocationManager &RelocMgr,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001234 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001235 CompileUnit::DIEInfo &MyInfo,
1236 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001237 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001238
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001239 unsigned shouldKeepDIE(RelocationManager &RelocMgr,
1240 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001241 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1242 unsigned Flags);
1243
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001244 unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
1245 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001246 CompileUnit &Unit,
1247 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1248
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001249 unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
1250 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00001251 CompileUnit &Unit,
1252 CompileUnit::DIEInfo &MyInfo,
1253 unsigned Flags);
1254
1255 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1256 CompileUnit::DIEInfo &Info);
1257 /// @}
1258
Frederic Rissb8b43d52015-03-04 22:07:44 +00001259 /// \defgroup Linking Methods used to link the debug information
1260 ///
1261 /// @{
Frederic Rissb8b43d52015-03-04 22:07:44 +00001262
Adrian Prantl3565af42015-09-14 16:46:10 +00001263 class DIECloner {
1264 DwarfLinker &Linker;
1265 RelocationManager &RelocMgr;
1266 /// Allocator used for all the DIEValue objects.
1267 BumpPtrAllocator &DIEAlloc;
1268 MutableArrayRef<CompileUnit> CompileUnits;
1269 LinkOptions Options;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001270
Adrian Prantl3565af42015-09-14 16:46:10 +00001271 public:
1272 DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
1273 BumpPtrAllocator &DIEAlloc,
1274 MutableArrayRef<CompileUnit> CompileUnits, LinkOptions &Options)
1275 : Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
1276 CompileUnits(CompileUnits), Options(Options) {}
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001277
Adrian Prantl3565af42015-09-14 16:46:10 +00001278 /// Recursively clone \p InputDIE into an tree of DIE objects
1279 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1280 /// stripped out and addresses have been rewritten according to the
1281 /// debug map.
1282 ///
1283 /// \param OutOffset is the offset the cloned DIE in the output
1284 /// compile unit.
1285 /// \param PCOffset (while cloning a function scope) is the offset
1286 /// applied to the entry point of the function to get the linked address.
1287 ///
1288 /// \returns the root of the cloned tree or null if nothing was selected.
Adrian Prantl3abe18d2015-09-14 23:27:26 +00001289 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Adrian Prantl3565af42015-09-14 16:46:10 +00001290 int64_t PCOffset, uint32_t OutOffset, unsigned Flags);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001291
Adrian Prantl3565af42015-09-14 16:46:10 +00001292 /// Construct the output DIE tree by cloning the DIEs we
1293 /// chose to keep above. If there are no valid relocs, then there's
1294 /// nothing to clone/emit.
1295 void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001296
Adrian Prantl3565af42015-09-14 16:46:10 +00001297 private:
1298 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
Frederic Rissbce93ff2015-03-16 02:05:10 +00001299
Adrian Prantl3565af42015-09-14 16:46:10 +00001300 /// Information gathered and exchanged between the various
1301 /// clone*Attributes helpers about the attributes of a particular DIE.
1302 struct AttributesInfo {
1303 const char *Name, *MangledName; ///< Names.
1304 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
Frederic Riss31da3242015-03-11 18:45:52 +00001305
Adrian Prantl3565af42015-09-14 16:46:10 +00001306 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1307 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1308 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
Frederic Rissbce93ff2015-03-16 02:05:10 +00001309
Adrian Prantl3565af42015-09-14 16:46:10 +00001310 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1311 bool IsDeclaration; ///< Is this DIE only a declaration?
1312
1313 AttributesInfo()
1314 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1315 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1316 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1317 };
1318
1319 /// Helper for cloneDIE.
1320 unsigned cloneAttribute(DIE &Die,
1321 const DWARFDebugInfoEntryMinimal &InputDIE,
1322 CompileUnit &U, const DWARFFormValue &Val,
1323 const AttributeSpec AttrSpec, unsigned AttrSize,
1324 AttributesInfo &AttrInfo);
1325
1326 /// Clone a string attribute described by \p AttrSpec and add
1327 /// it to \p Die.
1328 /// \returns the size of the new attribute.
1329 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1330 const DWARFFormValue &Val,
1331 const DWARFUnit &U);
1332
1333 /// Clone an attribute referencing another DIE and add
1334 /// it to \p Die.
1335 /// \returns the size of the new attribute.
1336 unsigned
1337 cloneDieReferenceAttribute(DIE &Die,
1338 const DWARFDebugInfoEntryMinimal &InputDIE,
1339 AttributeSpec AttrSpec, unsigned AttrSize,
1340 const DWARFFormValue &Val, CompileUnit &Unit);
1341
1342 /// Clone an attribute referencing another DIE and add
1343 /// it to \p Die.
1344 /// \returns the size of the new attribute.
1345 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1346 const DWARFFormValue &Val, unsigned AttrSize);
1347
1348 /// Clone an attribute referencing another DIE and add
1349 /// it to \p Die.
1350 /// \returns the size of the new attribute.
1351 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1352 const DWARFFormValue &Val,
1353 const CompileUnit &Unit,
1354 AttributesInfo &Info);
1355
1356 /// Clone a scalar attribute and add it to \p Die.
1357 /// \returns the size of the new attribute.
1358 unsigned cloneScalarAttribute(DIE &Die,
1359 const DWARFDebugInfoEntryMinimal &InputDIE,
1360 CompileUnit &U, AttributeSpec AttrSpec,
1361 const DWARFFormValue &Val, unsigned AttrSize,
1362 AttributesInfo &Info);
1363
1364 /// Get the potential name and mangled name for the entity
1365 /// described by \p Die and store them in \Info if they are not
1366 /// already there.
1367 /// \returns is a name was found.
1368 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1369 AttributesInfo &Info);
1370
1371 /// Create a copy of abbreviation Abbrev.
1372 void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
Frederic Riss31da3242015-03-11 18:45:52 +00001373 };
1374
Frederic Rissb8b43d52015-03-04 22:07:44 +00001375 /// \brief Assign an abbreviation number to \p Abbrev
1376 void AssignAbbrev(DIEAbbrev &Abbrev);
1377
1378 /// \brief FoldingSet that uniques the abbreviations.
1379 FoldingSet<DIEAbbrev> AbbreviationsSet;
1380 /// \brief Storage for the unique Abbreviations.
1381 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1382 /// be changed to a vecot of unique_ptrs.
David Blaikie6196aa02015-11-18 00:34:10 +00001383 std::vector<std::unique_ptr<DIEAbbrev>> Abbreviations;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001384
Frederic Riss25440872015-03-13 23:30:31 +00001385 /// \brief Compute and emit debug_ranges section for \p Unit, and
1386 /// patch the attributes referencing it.
1387 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1388
1389 /// \brief Generate and emit the DW_AT_ranges attribute for a
1390 /// compile_unit if it had one.
1391 void generateUnitRanges(CompileUnit &Unit) const;
1392
Frederic Riss63786b02015-03-15 20:45:43 +00001393 /// \brief Extract the line tables fromt he original dwarf, extract
1394 /// the relevant parts according to the linked function ranges and
1395 /// emit the result in the debug_line section.
1396 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1397
Frederic Rissbce93ff2015-03-16 02:05:10 +00001398 /// \brief Emit the accelerator entries for \p Unit.
1399 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1400
Frederic Riss5a642072015-06-05 23:06:11 +00001401 /// \brief Patch the frame info for an object file and emit it.
1402 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1403 unsigned AddressSize);
1404
Frederic Rissb8b43d52015-03-04 22:07:44 +00001405 /// \brief DIELoc objects that need to be destructed (but not freed!).
1406 std::vector<DIELoc *> DIELocs;
1407 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1408 std::vector<DIEBlock *> DIEBlocks;
1409 /// \brief Allocator used for all the DIEValue objects.
1410 BumpPtrAllocator DIEAlloc;
1411 /// @}
1412
Frederic Riss1c650942015-07-21 22:41:43 +00001413 /// ODR Contexts for that link.
1414 DeclContextTree ODRContexts;
1415
Frederic Riss1b9da422015-02-13 23:18:29 +00001416 /// \defgroup Helpers Various helper methods.
1417 ///
1418 /// @{
Benjamin Kramerc321e532016-06-08 19:09:22 +00001419 bool createStreamer(const Triple &TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001420
1421 /// \brief Attempt to load a debug object from disk.
1422 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1423 DebugMapObject &Obj,
1424 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001425 /// @}
1426
Frederic Rissd3455182015-01-28 18:27:01 +00001427 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001428 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001429 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001430 std::unique_ptr<DwarfStreamer> Streamer;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001431 uint64_t OutputDebugInfoSize;
Adrian Prantle5162db2015-09-22 22:20:50 +00001432 unsigned UnitID; ///< A unique ID that identifies each compile unit.
Frederic Riss563cba62015-01-28 22:15:14 +00001433
1434 /// The units of the current debug map object.
1435 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001436
Oleg Ranevskyy5f78c5c2015-10-23 17:10:44 +00001437 /// The debug map object currently under consideration.
Frederic Riss1b9da422015-02-13 23:18:29 +00001438 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001439
1440 /// \brief The Dwarf string pool
1441 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001442
1443 /// \brief This map is keyed by the entry PC of functions in that
1444 /// debug object and the associated value is a pair storing the
1445 /// corresponding end PC and the offset to apply to get the linked
1446 /// address.
1447 ///
1448 /// See startDebugObject() for a more complete description of its use.
1449 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001450
1451 /// \brief The CIEs that have been emitted in the output
1452 /// section. The actual CIE data serves a the key to this StringMap,
1453 /// this takes care of comparing the semantics of CIEs defined in
1454 /// different object files.
1455 StringMap<uint32_t> EmittedCIEs;
1456
1457 /// Offset of the last CIE that has been emitted in the output
1458 /// debug_frame section.
1459 uint32_t LastCIEOffset;
Adrian Prantle5162db2015-09-22 22:20:50 +00001460
Adrian Prantl20937022015-09-23 17:11:10 +00001461 /// Mapping the PCM filename to the DwoId.
1462 StringMap<uint64_t> ClangModules;
Adrian Prantla9e23832016-01-14 18:31:07 +00001463
1464 bool ModuleCacheHintDisplayed = false;
1465 bool ArchiveHintDisplayed = false;
Frederic Rissd3455182015-01-28 18:27:01 +00001466};
1467
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001468/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
1469/// CompileUnit object instead.
1470static CompileUnit *getUnitForOffset(MutableArrayRef<CompileUnit> Units,
1471 unsigned Offset) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001472 auto CU =
1473 std::upper_bound(Units.begin(), Units.end(), Offset,
1474 [](uint32_t LHS, const CompileUnit &RHS) {
1475 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1476 });
1477 return CU != Units.end() ? &*CU : nullptr;
1478}
1479
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001480/// Resolve the DIE attribute reference that has been
Frederic Riss1b9da422015-02-13 23:18:29 +00001481/// extracted in \p RefValue. The resulting DIE migh be in another
1482/// CompileUnit which is stored into \p ReferencedCU.
1483/// \returns null if resolving fails for any reason.
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001484static const DWARFDebugInfoEntryMinimal *resolveDIEReference(
1485 const DwarfLinker &Linker, MutableArrayRef<CompileUnit> Units,
Frederic Riss1c650942015-07-21 22:41:43 +00001486 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001487 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1488 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1489 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1490
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001491 if ((RefCU = getUnitForOffset(Units, RefOffset)))
Frederic Riss1b9da422015-02-13 23:18:29 +00001492 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1493 return RefDie;
1494
Adrian Prantlfdd9a822015-09-22 18:50:58 +00001495 Linker.reportWarning("could not find referenced DIE", &Unit, &DIE);
Frederic Riss1b9da422015-02-13 23:18:29 +00001496 return nullptr;
1497}
1498
Frederic Riss1c650942015-07-21 22:41:43 +00001499/// \returns whether the passed \a Attr type might contain a DIE
1500/// reference suitable for ODR uniquing.
1501static bool isODRAttribute(uint16_t Attr) {
1502 switch (Attr) {
1503 default:
1504 return false;
1505 case dwarf::DW_AT_type:
1506 case dwarf::DW_AT_containing_type:
1507 case dwarf::DW_AT_specification:
1508 case dwarf::DW_AT_abstract_origin:
1509 case dwarf::DW_AT_import:
1510 return true;
1511 }
1512 llvm_unreachable("Improper attribute.");
1513}
1514
1515/// Set the last DIE/CU a context was seen in and, possibly invalidate
1516/// the context if it is ambiguous.
1517///
1518/// In the current implementation, we don't handle overloaded
1519/// functions well, because the argument types are not taken into
1520/// account when computing the DeclContext tree.
1521///
1522/// Some of this is mitigated byt using mangled names that do contain
1523/// the arguments types, but sometimes (eg. with function templates)
1524/// we don't have that. In that case, just do not unique anything that
1525/// refers to the contexts we are not able to distinguish.
1526///
1527/// If a context that is not a namespace appears twice in the same CU,
1528/// we know it is ambiguous. Make it invalid.
1529bool DeclContext::setLastSeenDIE(CompileUnit &U,
1530 const DWARFDebugInfoEntryMinimal *Die) {
1531 if (LastSeenCompileUnitID == U.getUniqueID()) {
1532 DWARFUnit &OrigUnit = U.getOrigUnit();
1533 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1534 U.getInfo(FirstIdx).Ctxt = nullptr;
1535 return false;
1536 }
1537
1538 LastSeenCompileUnitID = U.getUniqueID();
1539 LastSeenDIE = Die;
1540 return true;
1541}
1542
Frederic Riss1c650942015-07-21 22:41:43 +00001543PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1544 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
Adrian Prantl42562c32015-10-02 00:27:08 +00001545 NonRelocatableStringpool &StringPool, bool InClangModule) {
Frederic Riss1c650942015-07-21 22:41:43 +00001546 unsigned Tag = DIE->getTag();
1547
1548 // FIXME: dsymutil-classic compat: We should bail out here if we
1549 // have a specification or an abstract_origin. We will get the
1550 // parent context wrong here.
1551
1552 switch (Tag) {
1553 default:
1554 // By default stop gathering child contexts.
1555 return PointerIntPair<DeclContext *, 1>(nullptr);
Adrian Prantla112ef92015-09-23 17:35:52 +00001556 case dwarf::DW_TAG_module:
1557 break;
Frederic Riss1c650942015-07-21 22:41:43 +00001558 case dwarf::DW_TAG_compile_unit:
Frederic Riss1c650942015-07-21 22:41:43 +00001559 return PointerIntPair<DeclContext *, 1>(&Context);
1560 case dwarf::DW_TAG_subprogram:
1561 // Do not unique anything inside CU local functions.
1562 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1563 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1564 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1565 dwarf::DW_AT_external, 0))
1566 return PointerIntPair<DeclContext *, 1>(nullptr);
1567 // Fallthrough
1568 case dwarf::DW_TAG_member:
1569 case dwarf::DW_TAG_namespace:
1570 case dwarf::DW_TAG_structure_type:
1571 case dwarf::DW_TAG_class_type:
1572 case dwarf::DW_TAG_union_type:
1573 case dwarf::DW_TAG_enumeration_type:
1574 case dwarf::DW_TAG_typedef:
1575 // Artificial things might be ambiguous, because they might be
1576 // created on demand. For example implicitely defined constructors
1577 // are ambiguous because of the way we identify contexts, and they
1578 // won't be generated everytime everywhere.
1579 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1580 dwarf::DW_AT_artificial, 0))
1581 return PointerIntPair<DeclContext *, 1>(nullptr);
1582 break;
1583 }
1584
1585 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1586 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1587 StringRef NameRef;
1588 StringRef ShortNameRef;
1589 StringRef FileRef;
1590
1591 if (Name)
1592 NameRef = StringPool.internString(Name);
1593 else if (Tag == dwarf::DW_TAG_namespace)
1594 // FIXME: For dsymutil-classic compatibility. I think uniquing
1595 // within anonymous namespaces is wrong. There is no ODR guarantee
1596 // there.
1597 NameRef = StringPool.internString("(anonymous namespace)");
1598
1599 if (ShortName && ShortName != Name)
1600 ShortNameRef = StringPool.internString(ShortName);
1601 else
1602 ShortNameRef = NameRef;
1603
1604 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1605 Tag != dwarf::DW_TAG_union_type &&
1606 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1607 return PointerIntPair<DeclContext *, 1>(nullptr);
1608
Frederic Riss1c650942015-07-21 22:41:43 +00001609 unsigned Line = 0;
Adrian Prantl42562c32015-10-02 00:27:08 +00001610 unsigned ByteSize = UINT32_MAX;
Frederic Riss1c650942015-07-21 22:41:43 +00001611
Adrian Prantl42562c32015-10-02 00:27:08 +00001612 if (!InClangModule) {
1613 // Gather some discriminating data about the DeclContext we will be
1614 // creating: File, line number and byte size. This shouldn't be
1615 // necessary, because the ODR is just about names, but given that we
1616 // do some approximations with overloaded functions and anonymous
1617 // namespaces, use these additional data points to make the process
1618 // safer. This is disabled for clang modules, because forward
1619 // declarations of module-defined types do not have a file and line.
1620 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1621 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1622 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1623 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1624 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1625 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1626 &U.getOrigUnit())) {
1627 // FIXME: dsymutil-classic compatibility. I'd rather not
1628 // unique anything in anonymous namespaces, but if we do, then
1629 // verify that the file and line correspond.
1630 if (!Name && Tag == dwarf::DW_TAG_namespace)
1631 FileNum = 1;
Frederic Riss1c650942015-07-21 22:41:43 +00001632
Adrian Prantl42562c32015-10-02 00:27:08 +00001633 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1634 // instead of "" would allow more uniquing, but for now, do
1635 // it this way to match dsymutil-classic.
Pete Cooperb2ba7762016-07-22 01:41:32 +00001636 if (LT->hasFileAtIndex(FileNum)) {
Adrian Prantl42562c32015-10-02 00:27:08 +00001637 Line = DIE->getAttributeValueAsUnsignedConstant(
1638 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
Adrian Prantl42562c32015-10-02 00:27:08 +00001639 // Cache the resolved paths, because calling realpath is expansive.
Pete Cooperef4e36a2016-03-18 03:48:09 +00001640 StringRef ResolvedPath = U.getResolvedPath(FileNum);
1641 if (!ResolvedPath.empty()) {
1642 FileRef = ResolvedPath;
Adrian Prantl42562c32015-10-02 00:27:08 +00001643 } else {
Pete Cooperb2ba7762016-07-22 01:41:32 +00001644 std::string File;
1645 bool gotFileName =
1646 LT->getFileNameByIndex(FileNum, "",
1647 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1648 File);
1649 (void)gotFileName;
1650 assert(gotFileName && "Must get file name from line table");
Pete Coopercadadaa2016-07-22 01:52:58 +00001651#ifdef HAVE_REALPATH
Adrian Prantl42562c32015-10-02 00:27:08 +00001652 char RealPath[PATH_MAX + 1];
1653 RealPath[PATH_MAX] = 0;
1654 if (::realpath(File.c_str(), RealPath))
1655 File = RealPath;
Pete Cooper64d075e2016-03-18 05:04:04 +00001656#endif
Pete Cooperef4e36a2016-03-18 03:48:09 +00001657 FileRef = StringPool.internString(File);
1658 U.setResolvedPath(FileNum, FileRef);
Adrian Prantl42562c32015-10-02 00:27:08 +00001659 }
Adrian Prantl42562c32015-10-02 00:27:08 +00001660 }
Frederic Riss1c650942015-07-21 22:41:43 +00001661 }
1662 }
1663 }
1664 }
1665
1666 if (!Line && NameRef.empty())
1667 return PointerIntPair<DeclContext *, 1>(nullptr);
1668
Frederic Riss1c650942015-07-21 22:41:43 +00001669 // We hash NameRef, which is the mangled name, in order to get most
Adrian Prantla112ef92015-09-23 17:35:52 +00001670 // overloaded functions resolve correctly.
1671 //
1672 // Strictly speaking, hashing the Tag is only necessary for a
1673 // DW_TAG_module, to prevent uniquing of a module and a namespace
1674 // with the same name.
1675 //
1676 // FIXME: dsymutil-classic won't unique the same type presented
1677 // once as a struct and once as a class. Using the Tag in the fully
1678 // qualified name hash to get the same effect.
Frederic Riss1c650942015-07-21 22:41:43 +00001679 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1680
1681 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1682 // use the filename.
1683 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1684 Hash = hash_combine(Hash, FileRef);
1685
1686 // Now look if this context already exists.
1687 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1688 auto ContextIter = Contexts.find(&Key);
1689
1690 if (ContextIter == Contexts.end()) {
1691 // The context wasn't found.
1692 bool Inserted;
1693 DeclContext *NewContext =
1694 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1695 Context, DIE, U.getUniqueID());
1696 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1697 assert(Inserted && "Failed to insert DeclContext");
1698 (void)Inserted;
1699 } else if (Tag != dwarf::DW_TAG_namespace &&
1700 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1701 // The context was found, but it is ambiguous with another context
1702 // in the same file. Mark it invalid.
1703 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1704 }
1705
1706 assert(ContextIter != Contexts.end());
1707 // FIXME: dsymutil-classic compatibility. Union types aren't
1708 // uniques, but their children might be.
1709 if ((Tag == dwarf::DW_TAG_subprogram &&
1710 Context.getTag() != dwarf::DW_TAG_structure_type &&
1711 Context.getTag() != dwarf::DW_TAG_class_type) ||
1712 (Tag == dwarf::DW_TAG_union_type))
1713 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1714
1715 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1716}
1717
Adrian Prantl3565af42015-09-14 16:46:10 +00001718bool DwarfLinker::DIECloner::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1719 DWARFUnit &U, AttributesInfo &Info) {
1720 // FIXME: a bit wasteful as the first getName might return the
Frederic Rissbce93ff2015-03-16 02:05:10 +00001721 // short name.
1722 if (!Info.MangledName &&
1723 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001724 Info.MangledNameOffset =
1725 Linker.StringPool.getStringOffset(Info.MangledName);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001726
1727 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
Adrian Prantl3565af42015-09-14 16:46:10 +00001728 Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001729
1730 return Info.Name || Info.MangledName;
1731}
1732
Frederic Riss1b9da422015-02-13 23:18:29 +00001733/// \brief Report a warning to the user, optionaly including
1734/// information about a specific \p DIE related to the warning.
1735void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001736 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001737 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001738 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001739 Context = CurrentDebugObject->getObjectFilename();
1740 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001741
Frederic Rissb9818322015-02-28 00:29:07 +00001742 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001743 return;
1744
1745 errs() << " in DIE:\n";
1746 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1747 6 /* Indent */);
1748}
1749
Benjamin Kramerc321e532016-06-08 19:09:22 +00001750bool DwarfLinker::createStreamer(const Triple &TheTriple,
1751 StringRef OutputFilename) {
Frederic Rissc99ea202015-02-28 00:29:11 +00001752 if (Options.NoOutput)
1753 return true;
1754
Frederic Rissb52cf522015-02-28 00:42:37 +00001755 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001756 return Streamer->init(TheTriple, OutputFilename);
1757}
1758
Adrian Prantla112ef92015-09-23 17:35:52 +00001759/// Recursive helper to build the global DeclContext information and
1760/// gather the child->parent relationships in the original compile unit.
1761///
1762/// \return true when this DIE and all of its children are only
1763/// forward declarations to types defined in external clang modules
1764/// (i.e., forward declarations that are children of a DW_TAG_module).
1765static bool analyzeContextInfo(const DWARFDebugInfoEntryMinimal *DIE,
1766 unsigned ParentIdx, CompileUnit &CU,
1767 DeclContext *CurrentDeclContext,
1768 NonRelocatableStringpool &StringPool,
1769 DeclContextTree &Contexts,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001770 bool InImportedModule = false) {
Frederic Riss563cba62015-01-28 22:15:14 +00001771 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001772 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1773
Adrian Prantla112ef92015-09-23 17:35:52 +00001774 // Clang imposes an ODR on modules(!) regardless of the language:
1775 // "The module-id should consist of only a single identifier,
1776 // which provides the name of the module being defined. Each
1777 // module shall have a single definition."
1778 //
1779 // This does not extend to the types inside the modules:
1780 // "[I]n C, this implies that if two structs are defined in
1781 // different submodules with the same name, those two types are
1782 // distinct types (but may be compatible types if their
1783 // definitions match)."
1784 //
1785 // We treat non-C++ modules like namespaces for this reason.
Adrian Prantlf3e634b2015-09-24 16:10:14 +00001786 if (DIE->getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
Adrian Prantlea8a7242015-09-23 20:44:37 +00001787 DIE->getAttributeValueAsString(&CU.getOrigUnit(), dwarf::DW_AT_name,
1788 "") != CU.getClangModuleName()) {
1789 InImportedModule = true;
1790 }
Adrian Prantla112ef92015-09-23 17:35:52 +00001791
Frederic Riss1c650942015-07-21 22:41:43 +00001792 Info.ParentIdx = ParentIdx;
Adrian Prantl42562c32015-10-02 00:27:08 +00001793 bool InClangModule = CU.isClangModule() || InImportedModule;
1794 if (CU.hasODR() || InClangModule) {
Frederic Riss1c650942015-07-21 22:41:43 +00001795 if (CurrentDeclContext) {
Adrian Prantl42562c32015-10-02 00:27:08 +00001796 auto PtrInvalidPair = Contexts.getChildDeclContext(
1797 *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
Frederic Riss1c650942015-07-21 22:41:43 +00001798 CurrentDeclContext = PtrInvalidPair.getPointer();
1799 Info.Ctxt =
1800 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1801 } else
1802 Info.Ctxt = CurrentDeclContext = nullptr;
1803 }
Frederic Riss563cba62015-01-28 22:15:14 +00001804
Adrian Prantlea8a7242015-09-23 20:44:37 +00001805 Info.Prune = InImportedModule;
Frederic Riss563cba62015-01-28 22:15:14 +00001806 if (DIE->hasChildren())
1807 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1808 Child = Child->getSibling())
Adrian Prantla112ef92015-09-23 17:35:52 +00001809 Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
Adrian Prantlea8a7242015-09-23 20:44:37 +00001810 StringPool, Contexts, InImportedModule);
Adrian Prantla112ef92015-09-23 17:35:52 +00001811
1812 // Prune this DIE if it is either a forward declaration inside a
1813 // DW_TAG_module or a DW_TAG_module that contains nothing but
1814 // forward declarations.
1815 Info.Prune &= (DIE->getTag() == dwarf::DW_TAG_module) ||
1816 DIE->getAttributeValueAsUnsignedConstant(
1817 &CU.getOrigUnit(), dwarf::DW_AT_declaration, 0);
1818
Adrian Prantld2793a02015-10-05 23:11:20 +00001819 // Don't prune it if there is no definition for the DIE.
1820 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
1821
Adrian Prantla112ef92015-09-23 17:35:52 +00001822 return Info.Prune;
Frederic Riss563cba62015-01-28 22:15:14 +00001823}
1824
Frederic Riss84c09a52015-02-13 23:18:34 +00001825static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1826 switch (Tag) {
1827 default:
1828 return false;
1829 case dwarf::DW_TAG_subprogram:
1830 case dwarf::DW_TAG_lexical_block:
1831 case dwarf::DW_TAG_subroutine_type:
1832 case dwarf::DW_TAG_structure_type:
1833 case dwarf::DW_TAG_class_type:
1834 case dwarf::DW_TAG_union_type:
1835 return true;
1836 }
1837 llvm_unreachable("Invalid Tag");
1838}
1839
Frederic Riss1c650942015-07-21 22:41:43 +00001840static unsigned getRefAddrSize(const DWARFUnit &U) {
1841 if (U.getVersion() == 2)
1842 return U.getAddressByteSize();
1843 return 4;
1844}
1845
Frederic Riss63786b02015-03-15 20:45:43 +00001846void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001847 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss63786b02015-03-15 20:45:43 +00001848 // Iterate over the debug map entries and put all the ones that are
1849 // functions (because they have a size) into the Ranges map. This
1850 // map is very similar to the FunctionRanges that are stored in each
1851 // unit, with 2 notable differences:
1852 // - obviously this one is global, while the other ones are per-unit.
1853 // - this one contains not only the functions described in the DIE
1854 // tree, but also the ones that are only in the debug map.
1855 // The latter information is required to reproduce dsymutil's logic
1856 // while linking line tables. The cases where this information
1857 // matters look like bugs that need to be investigated, but for now
1858 // we need to reproduce dsymutil's behavior.
1859 // FIXME: Once we understood exactly if that information is needed,
1860 // maybe totally remove this (or try to use it to do a real
1861 // -gline-tables-only on Darwin.
1862 for (const auto &Entry : Obj.symbols()) {
1863 const auto &Mapping = Entry.getValue();
Frederic Rissd8c33dc2016-01-31 04:29:22 +00001864 if (Mapping.Size && Mapping.ObjectAddress)
1865 Ranges[*Mapping.ObjectAddress] = std::make_pair(
1866 *Mapping.ObjectAddress + Mapping.Size,
1867 int64_t(Mapping.BinaryAddress) - *Mapping.ObjectAddress);
Frederic Riss63786b02015-03-15 20:45:43 +00001868 }
Frederic Riss563cba62015-01-28 22:15:14 +00001869}
1870
Frederic Riss1036e642015-02-13 23:18:22 +00001871void DwarfLinker::endDebugObject() {
1872 Units.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001873 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001874
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001875 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1876 (*I)->~DIEBlock();
1877 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1878 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001879
1880 DIEBlocks.clear();
1881 DIELocs.clear();
1882 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001883}
1884
Frederic Riss1d536582016-02-01 04:43:14 +00001885static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
1886 switch (Arch) {
1887 case Triple::x86:
1888 return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
1889 RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
1890 case Triple::x86_64:
1891 return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
1892 case Triple::arm:
1893 case Triple::thumb:
1894 return RelocType == MachO::ARM_RELOC_SECTDIFF ||
1895 RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1896 RelocType == MachO::ARM_RELOC_HALF ||
1897 RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
1898 case Triple::aarch64:
1899 return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
1900 default:
1901 return false;
1902 }
1903}
1904
Frederic Riss1036e642015-02-13 23:18:22 +00001905/// \brief Iterate over the relocations of the given \p Section and
1906/// store the ones that correspond to debug map entries into the
1907/// ValidRelocs array.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001908void DwarfLinker::RelocationManager::
1909findValidRelocsMachO(const object::SectionRef &Section,
1910 const object::MachOObjectFile &Obj,
1911 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001912 StringRef Contents;
1913 Section.getContents(Contents);
1914 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
Frederic Riss1d536582016-02-01 04:43:14 +00001915 bool SkipNext = false;
Frederic Riss1036e642015-02-13 23:18:22 +00001916
1917 for (const object::RelocationRef &Reloc : Section.relocations()) {
Frederic Riss1d536582016-02-01 04:43:14 +00001918 if (SkipNext) {
1919 SkipNext = false;
1920 continue;
1921 }
1922
Frederic Riss1036e642015-02-13 23:18:22 +00001923 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1924 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
Frederic Riss1d536582016-02-01 04:43:14 +00001925
1926 if (isMachOPairedReloc(Obj.getAnyRelocationType(MachOReloc),
1927 Obj.getArch())) {
1928 SkipNext = true;
1929 Linker.reportWarning(" unsupported relocation in debug_info section.");
1930 continue;
1931 }
1932
Frederic Riss1036e642015-02-13 23:18:22 +00001933 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001934 uint64_t Offset64 = Reloc.getOffset();
1935 if ((RelocSize != 4 && RelocSize != 8)) {
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001936 Linker.reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001937 continue;
1938 }
1939 uint32_t Offset = Offset64;
1940 // Mach-o uses REL relocations, the addend is at the relocation offset.
1941 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
Frederic Riss0314e1e2016-02-01 03:44:22 +00001942 uint64_t SymAddress;
1943 int64_t SymOffset;
1944
1945 if (Obj.isRelocationScattered(MachOReloc)) {
1946 // The address of the base symbol for scattered relocations is
1947 // stored in the reloc itself. The actual addend will store the
1948 // base address plus the offset.
1949 SymAddress = Obj.getScatteredRelocationValue(MachOReloc);
1950 SymOffset = int64_t(Addend) - SymAddress;
1951 } else {
1952 SymAddress = Addend;
1953 SymOffset = 0;
1954 }
Frederic Riss1036e642015-02-13 23:18:22 +00001955
1956 auto Sym = Reloc.getSymbol();
1957 if (Sym != Obj.symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001958 Expected<StringRef> SymbolName = Sym->getName();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001959 if (!SymbolName) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001960 consumeError(SymbolName.takeError());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001961 Linker.reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001962 continue;
1963 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001964 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001965 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
Frederic Riss0314e1e2016-02-01 03:44:22 +00001966 } else if (const auto *Mapping = DMO.lookupObjectAddress(SymAddress)) {
Frederic Riss1036e642015-02-13 23:18:22 +00001967 // Do not store the addend. The addend was the address of the
1968 // symbol in the object file, the address in the binary that is
1969 // stored in the debug map doesn't need to be offseted.
Frederic Riss0314e1e2016-02-01 03:44:22 +00001970 ValidRelocs.emplace_back(Offset64, RelocSize, SymOffset, Mapping);
Frederic Riss1036e642015-02-13 23:18:22 +00001971 }
1972 }
1973}
1974
1975/// \brief Dispatch the valid relocation finding logic to the
1976/// appropriate handler depending on the object file format.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001977bool DwarfLinker::RelocationManager::findValidRelocs(
1978 const object::SectionRef &Section, const object::ObjectFile &Obj,
1979 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00001980 // Dispatch to the right handler depending on the file type.
1981 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1982 findValidRelocsMachO(Section, *MachOObj, DMO);
1983 else
Adrian Prantl67a4fc72015-09-11 23:45:30 +00001984 Linker.reportWarning(Twine("unsupported object file type: ") +
1985 Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001986
1987 if (ValidRelocs.empty())
1988 return false;
1989
1990 // Sort the relocations by offset. We will walk the DIEs linearly in
1991 // the file, this allows us to just keep an index in the relocation
1992 // array that we advance during our walk, rather than resorting to
1993 // some associative container. See DwarfLinker::NextValidReloc.
1994 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1995 return true;
1996}
1997
1998/// \brief Look for relocations in the debug_info section that match
1999/// entries in the debug map. These relocations will drive the Dwarf
2000/// link by indicating which DIEs refer to symbols present in the
2001/// linked binary.
2002/// \returns wether there are any valid relocations in the debug info.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002003bool DwarfLinker::RelocationManager::
2004findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
2005 const DebugMapObject &DMO) {
Frederic Riss1036e642015-02-13 23:18:22 +00002006 // Find the debug_info section.
2007 for (const object::SectionRef &Section : Obj.sections()) {
2008 StringRef SectionName;
2009 Section.getName(SectionName);
2010 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
2011 if (SectionName != "debug_info")
2012 continue;
2013 return findValidRelocs(Section, Obj, DMO);
2014 }
2015 return false;
2016}
Frederic Riss563cba62015-01-28 22:15:14 +00002017
Frederic Riss84c09a52015-02-13 23:18:34 +00002018/// \brief Checks that there is a relocation against an actual debug
2019/// map entry between \p StartOffset and \p NextOffset.
2020///
2021/// This function must be called with offsets in strictly ascending
2022/// order because it never looks back at relocations it already 'went past'.
2023/// \returns true and sets Info.InDebugMap if it is the case.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002024bool DwarfLinker::RelocationManager::
2025hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
2026 CompileUnit::DIEInfo &Info) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002027 assert(NextValidReloc == 0 ||
2028 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
2029 if (NextValidReloc >= ValidRelocs.size())
2030 return false;
2031
2032 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
2033
2034 // We might need to skip some relocs that we didn't consider. For
2035 // example the high_pc of a discarded DIE might contain a reloc that
2036 // is in the list because it actually corresponds to the start of a
2037 // function that is in the debug map.
2038 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
2039 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
2040
2041 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
2042 return false;
2043
2044 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00002045 const auto &Mapping = ValidReloc.Mapping->getValue();
Frederic Rissd8c33dc2016-01-31 04:29:22 +00002046 uint64_t ObjectAddress =
2047 Mapping.ObjectAddress ? uint64_t(*Mapping.ObjectAddress) : UINT64_MAX;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002048 if (Linker.Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002049 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
Frederic Rissd8c33dc2016-01-31 04:29:22 +00002050 << " " << format("\t%016" PRIx64 " => %016" PRIx64, ObjectAddress,
Frederic Riss08462f72015-06-01 21:12:45 +00002051 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00002052
Frederic Rissd8c33dc2016-01-31 04:29:22 +00002053 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend;
2054 if (Mapping.ObjectAddress)
2055 Info.AddrAdjust -= ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00002056 Info.InDebugMap = true;
2057 return true;
2058}
2059
2060/// \brief Get the starting and ending (exclusive) offset for the
2061/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
2062/// supposed to point to the position of the first attribute described
2063/// by \p Abbrev.
2064/// \return [StartOffset, EndOffset) as a pair.
2065static std::pair<uint32_t, uint32_t>
2066getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
2067 unsigned Offset, const DWARFUnit &Unit) {
2068 DataExtractor Data = Unit.getDebugInfoExtractor();
2069
2070 for (unsigned i = 0; i < Idx; ++i)
2071 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
2072
2073 uint32_t End = Offset;
2074 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
2075
2076 return std::make_pair(Offset, End);
2077}
2078
2079/// \brief Check if a variable describing DIE should be kept.
2080/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002081unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
2082 const DWARFDebugInfoEntryMinimal &DIE,
2083 CompileUnit &Unit,
2084 CompileUnit::DIEInfo &MyInfo,
2085 unsigned Flags) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002086 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2087
2088 // Global variables with constant value can always be kept.
2089 if (!(Flags & TF_InFunctionScope) &&
2090 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
2091 MyInfo.InDebugMap = true;
2092 return Flags | TF_Keep;
2093 }
2094
2095 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
2096 if (LocationIdx == -1U)
2097 return Flags;
2098
2099 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2100 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2101 uint32_t LocationOffset, LocationEndOffset;
2102 std::tie(LocationOffset, LocationEndOffset) =
2103 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
2104
2105 // See if there is a relocation to a valid debug map entry inside
2106 // this variable's location. The order is important here. We want to
2107 // always check in the variable has a valid relocation, so that the
2108 // DIEInfo is filled. However, we don't want a static variable in a
2109 // function to force us to keep the enclosing function.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002110 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
Frederic Riss84c09a52015-02-13 23:18:34 +00002111 (Flags & TF_InFunctionScope))
2112 return Flags;
2113
Frederic Rissb9818322015-02-28 00:29:07 +00002114 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002115 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2116
2117 return Flags | TF_Keep;
2118}
2119
2120/// \brief Check if a function describing DIE should be kept.
2121/// \returns updated TraversalFlags.
2122unsigned DwarfLinker::shouldKeepSubprogramDIE(
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002123 RelocationManager &RelocMgr,
Frederic Riss84c09a52015-02-13 23:18:34 +00002124 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2125 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2126 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2127
2128 Flags |= TF_InFunctionScope;
2129
2130 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2131 if (LowPcIdx == -1U)
2132 return Flags;
2133
2134 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2135 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2136 uint32_t LowPcOffset, LowPcEndOffset;
2137 std::tie(LowPcOffset, LowPcEndOffset) =
2138 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2139
2140 uint64_t LowPc =
2141 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2142 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2143 if (LowPc == -1ULL ||
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002144 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
Frederic Riss84c09a52015-02-13 23:18:34 +00002145 return Flags;
2146
Frederic Rissb9818322015-02-28 00:29:07 +00002147 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002148 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2149
Frederic Riss1af75f72015-03-12 18:45:10 +00002150 Flags |= TF_Keep;
2151
2152 DWARFFormValue HighPcValue;
2153 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2154 reportWarning("Function without high_pc. Range will be discarded.\n",
2155 &OrigUnit, &DIE);
2156 return Flags;
2157 }
2158
2159 uint64_t HighPc;
2160 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2161 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2162 } else {
2163 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2164 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2165 }
2166
Frederic Riss63786b02015-03-15 20:45:43 +00002167 // Replace the debug map range with a more accurate one.
2168 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00002169 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2170 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00002171}
2172
2173/// \brief Check if a DIE should be kept.
2174/// \returns updated TraversalFlags.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002175unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
2176 const DWARFDebugInfoEntryMinimal &DIE,
Frederic Riss84c09a52015-02-13 23:18:34 +00002177 CompileUnit &Unit,
2178 CompileUnit::DIEInfo &MyInfo,
2179 unsigned Flags) {
2180 switch (DIE.getTag()) {
2181 case dwarf::DW_TAG_constant:
2182 case dwarf::DW_TAG_variable:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002183 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002184 case dwarf::DW_TAG_subprogram:
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002185 return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002186 case dwarf::DW_TAG_module:
2187 case dwarf::DW_TAG_imported_module:
2188 case dwarf::DW_TAG_imported_declaration:
2189 case dwarf::DW_TAG_imported_unit:
2190 // We always want to keep these.
2191 return Flags | TF_Keep;
2192 }
2193
2194 return Flags;
2195}
2196
Frederic Riss84c09a52015-02-13 23:18:34 +00002197/// \brief Mark the passed DIE as well as all the ones it depends on
2198/// as kept.
2199///
2200/// This function is called by lookForDIEsToKeep on DIEs that are
2201/// newly discovered to be needed in the link. It recursively calls
2202/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2203/// TraversalFlags to inform it that it's not doing the primary DIE
2204/// tree walk.
Adrian Prantl6ec47122015-09-22 15:31:14 +00002205void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002206 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002207 CompileUnit::DIEInfo &MyInfo,
2208 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002209 CompileUnit &CU, bool UseODR) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002210 const DWARFUnit &Unit = CU.getOrigUnit();
2211 MyInfo.Keep = true;
2212
2213 // First mark all the parent chain as kept.
2214 unsigned AncestorIdx = MyInfo.ParentIdx;
2215 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002216 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002217 lookForDIEsToKeep(RelocMgr, *Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002218 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002219 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2220 }
2221
2222 // Then we need to mark all the DIEs referenced by this DIE's
2223 // attributes as kept.
2224 DataExtractor Data = Unit.getDebugInfoExtractor();
Frederic Riss36c3cb82015-09-11 04:17:25 +00002225 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
2226 uint32_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
Frederic Riss84c09a52015-02-13 23:18:34 +00002227
2228 // Mark all DIEs referenced through atttributes as kept.
2229 for (const auto &AttrSpec : Abbrev->attributes()) {
2230 DWARFFormValue Val(AttrSpec.Form);
2231
2232 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2233 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2234 continue;
2235 }
2236
2237 Val.extractValue(Data, &Offset, &Unit);
2238 CompileUnit *ReferencedCU;
Frederic Riss1c650942015-07-21 22:41:43 +00002239 if (const auto *RefDIE =
Adrian Prantlfdd9a822015-09-22 18:50:58 +00002240 resolveDIEReference(*this, MutableArrayRef<CompileUnit>(Units), Val,
2241 Unit, Die, ReferencedCU)) {
Frederic Riss1c650942015-07-21 22:41:43 +00002242 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2243 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2244 // If the referenced DIE has a DeclContext that has already been
2245 // emitted, then do not keep the one in this CU. We'll link to
2246 // the canonical DIE in cloneDieReferenceAttribute.
2247 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2248 // be necessary and could be advantageously replaced by
2249 // ReferencedCU->hasODR() && CU.hasODR().
2250 // FIXME: compatibility with dsymutil-classic. There is no
2251 // reason not to unique ref_addr references.
2252 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2253 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2254 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2255 continue;
2256
Adrian Prantle39475d2015-11-10 21:31:05 +00002257 // Keep a module forward declaration if there is no definition.
2258 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
2259 Info.Ctxt->getCanonicalDIEOffset()))
2260 Info.Prune = false;
2261
Frederic Riss1c650942015-07-21 22:41:43 +00002262 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002263 lookForDIEsToKeep(RelocMgr, *RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002264 TF_Keep | TF_DependencyWalk | ODRFlag);
2265 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002266 }
2267}
2268
2269/// \brief Recursively walk the \p DIE tree and look for DIEs to
2270/// keep. Store that information in \p CU's DIEInfo.
2271///
2272/// This function is the entry point of the DIE selection
2273/// algorithm. It is expected to walk the DIE tree in file order and
2274/// (though the mediation of its helper) call hasValidRelocation() on
2275/// each DIE that might be a 'root DIE' (See DwarfLinker class
2276/// comment).
2277/// While walking the dependencies of root DIEs, this function is
2278/// also called, but during these dependency walks the file order is
2279/// not respected. The TF_DependencyWalk flag tells us which kind of
2280/// traversal we are currently doing.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002281void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
2282 const DWARFDebugInfoEntryMinimal &Die,
Frederic Riss84c09a52015-02-13 23:18:34 +00002283 const DebugMapObject &DMO, CompileUnit &CU,
2284 unsigned Flags) {
Frederic Riss36c3cb82015-09-11 04:17:25 +00002285 unsigned Idx = CU.getOrigUnit().getDIEIndex(&Die);
Frederic Riss84c09a52015-02-13 23:18:34 +00002286 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2287 bool AlreadyKept = MyInfo.Keep;
Adrian Prantla112ef92015-09-23 17:35:52 +00002288 if (MyInfo.Prune)
2289 return;
Frederic Riss84c09a52015-02-13 23:18:34 +00002290
2291 // If the Keep flag is set, we are marking a required DIE's
2292 // dependencies. If our target is already marked as kept, we're all
2293 // set.
2294 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2295 return;
2296
Adrian Prantl6ec47122015-09-22 15:31:14 +00002297 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
Frederic Riss84c09a52015-02-13 23:18:34 +00002298 // because it would screw up the relocation finding logic.
2299 if (!(Flags & TF_DependencyWalk))
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002300 Flags = shouldKeepDIE(RelocMgr, Die, CU, MyInfo, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002301
2302 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002303 if (!AlreadyKept && (Flags & TF_Keep)) {
2304 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
Adrian Prantl6ec47122015-09-22 15:31:14 +00002305 keepDIEAndDependencies(RelocMgr, Die, MyInfo, DMO, CU, UseOdr);
Frederic Riss1c650942015-07-21 22:41:43 +00002306 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002307 // The TF_ParentWalk flag tells us that we are currently walking up
2308 // the parent chain of a required DIE, and we don't want to mark all
2309 // the children of the parents as kept (consider for example a
2310 // DW_TAG_namespace node in the parent chain). There are however a
2311 // set of DIE types for which we want to ignore that directive and still
2312 // walk their children.
Frederic Riss36c3cb82015-09-11 04:17:25 +00002313 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
Frederic Riss84c09a52015-02-13 23:18:34 +00002314 Flags &= ~TF_ParentWalk;
2315
Frederic Riss36c3cb82015-09-11 04:17:25 +00002316 if (!Die.hasChildren() || (Flags & TF_ParentWalk))
Frederic Riss84c09a52015-02-13 23:18:34 +00002317 return;
2318
Frederic Riss36c3cb82015-09-11 04:17:25 +00002319 for (auto *Child = Die.getFirstChild(); Child && !Child->isNULL();
Frederic Riss84c09a52015-02-13 23:18:34 +00002320 Child = Child->getSibling())
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002321 lookForDIEsToKeep(RelocMgr, *Child, DMO, CU, Flags);
Frederic Riss84c09a52015-02-13 23:18:34 +00002322}
2323
Frederic Rissb8b43d52015-03-04 22:07:44 +00002324/// \brief Assign an abbreviation numer to \p Abbrev.
2325///
2326/// Our DIEs get freed after every DebugMapObject has been processed,
2327/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2328/// the instances hold by the DIEs. When we encounter an abbreviation
2329/// that we don't know, we create a permanent copy of it.
2330void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2331 // Check the set for priors.
2332 FoldingSetNodeID ID;
2333 Abbrev.Profile(ID);
2334 void *InsertToken;
2335 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2336
2337 // If it's newly added.
2338 if (InSet) {
2339 // Assign existing abbreviation number.
2340 Abbrev.setNumber(InSet->getNumber());
2341 } else {
2342 // Add to abbreviation list.
2343 Abbreviations.push_back(
David Blaikie6196aa02015-11-18 00:34:10 +00002344 llvm::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002345 for (const auto &Attr : Abbrev.getData())
2346 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
David Blaikie6196aa02015-11-18 00:34:10 +00002347 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002348 // Assign the unique abbreviation number.
2349 Abbrev.setNumber(Abbreviations.size());
2350 Abbreviations.back()->setNumber(Abbreviations.size());
2351 }
2352}
2353
Adrian Prantl3565af42015-09-14 16:46:10 +00002354unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
2355 AttributeSpec AttrSpec,
2356 const DWARFFormValue &Val,
2357 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002358 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00002359 const char *String = *Val.getAsCString(&U);
Adrian Prantl3565af42015-09-14 16:46:10 +00002360 unsigned Offset = Linker.StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002361 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002362 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002363 return 4;
2364}
2365
Adrian Prantl3565af42015-09-14 16:46:10 +00002366unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
Frederic Riss9833de62015-03-06 23:22:53 +00002367 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2368 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002369 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002370 const DWARFUnit &U = Unit.getOrigUnit();
2371 uint32_t Ref = *Val.getAsReference(&U);
Frederic Riss9833de62015-03-06 23:22:53 +00002372 DIE *NewRefDie = nullptr;
2373 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002374 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002375
Frederic Riss1c650942015-07-21 22:41:43 +00002376 const DWARFDebugInfoEntryMinimal *RefDie =
Adrian Prantlfdd9a822015-09-22 18:50:58 +00002377 resolveDIEReference(Linker, CompileUnits, Val, U, InputDIE, RefUnit);
Frederic Riss1c650942015-07-21 22:41:43 +00002378
2379 // If the referenced DIE is not found, drop the attribute.
2380 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002381 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002382
2383 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2384 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002385
2386 // If we already have emitted an equivalent DeclContext, just point
2387 // at it.
2388 if (isODRAttribute(AttrSpec.Attr)) {
2389 Ctxt = RefInfo.Ctxt;
2390 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2391 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2392 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2393 dwarf::DW_FORM_ref_addr, Attr);
2394 return getRefAddrSize(U);
2395 }
2396 }
2397
Frederic Riss9833de62015-03-06 23:22:53 +00002398 if (!RefInfo.Clone) {
2399 assert(Ref > InputDIE.getOffset());
2400 // We haven't cloned this DIE yet. Just create an empty one and
2401 // store it. It'll get really cloned when we process it.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002402 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002403 }
2404 NewRefDie = RefInfo.Clone;
2405
Frederic Riss1c650942015-07-21 22:41:43 +00002406 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2407 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002408 // We cannot currently rely on a DIEEntry to emit ref_addr
2409 // references, because the implementation calls back to DwarfDebug
2410 // to find the unit offset. (We don't have a DwarfDebug)
2411 // FIXME: we should be able to design DIEEntry reliance on
2412 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002413 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002414 if (Ref < InputDIE.getOffset()) {
2415 // We must have already cloned that DIE.
2416 uint32_t NewRefOffset =
2417 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002418 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002419 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2420 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002421 } else {
2422 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002423 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002424 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002425 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002426 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2427 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002428 }
Frederic Riss1c650942015-07-21 22:41:43 +00002429 return getRefAddrSize(U);
Frederic Riss9833de62015-03-06 23:22:53 +00002430 }
2431
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002432 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2433 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002434 return AttrSize;
2435}
2436
Adrian Prantl3565af42015-09-14 16:46:10 +00002437unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
2438 AttributeSpec AttrSpec,
2439 const DWARFFormValue &Val,
2440 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002441 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002442 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002443 DIELoc *Loc = nullptr;
2444 DIEBlock *Block = nullptr;
2445 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002446 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002447 Loc = new (DIEAlloc) DIELoc;
Adrian Prantl3565af42015-09-14 16:46:10 +00002448 Linker.DIELocs.push_back(Loc);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002449 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002450 Block = new (DIEAlloc) DIEBlock;
Adrian Prantl3565af42015-09-14 16:46:10 +00002451 Linker.DIEBlocks.push_back(Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002452 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002453 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2454 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002455
2456 if (Loc)
2457 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2458 dwarf::Form(AttrSpec.Form), Loc);
2459 else
2460 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2461 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002462 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2463 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002464 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2465 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002466 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2467 // the DIE class, this if could be replaced by
2468 // Attr->setSize(Bytes.size()).
Adrian Prantl3565af42015-09-14 16:46:10 +00002469 if (Linker.Streamer) {
2470 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002471 if (Loc)
Adrian Prantl3565af42015-09-14 16:46:10 +00002472 Loc->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002473 else
Adrian Prantl3565af42015-09-14 16:46:10 +00002474 Block->ComputeSize(AsmPrinter);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002475 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002476 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002477 return AttrSize;
2478}
2479
Adrian Prantl3565af42015-09-14 16:46:10 +00002480unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
2481 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
2482 const CompileUnit &Unit, AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002483 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00002484 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2485 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2486 Die.getTag() == dwarf::DW_TAG_lexical_block)
Frederic Riss7b5563a2015-08-31 01:43:14 +00002487 // The low_pc of a block or inline subroutine might get
2488 // relocated because it happens to match the low_pc of the
2489 // enclosing subprogram. To prevent issues with that, always use
2490 // the low_pc from the input DIE if relocations have been applied.
2491 Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2492 Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002493 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2494 Addr = Unit.getLowPc();
2495 if (Addr == UINT64_MAX)
2496 return 0;
2497 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002498 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002499 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002500 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2501 if (uint64_t HighPc = Unit.getHighPc())
2502 Addr = HighPc;
2503 else
2504 return 0;
2505 } else
2506 // If we have a high_pc recorded for the input DIE, use
2507 // it. Otherwise (when no relocations where applied) just use the
2508 // one we just decoded.
2509 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002510 }
2511
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002512 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002513 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002514 return Unit.getOrigUnit().getAddressByteSize();
2515}
2516
Adrian Prantl3565af42015-09-14 16:46:10 +00002517unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00002518 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002519 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002520 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002521 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002522 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2523 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2524 if (Unit.getLowPc() == -1ULL)
2525 return 0;
2526 // Dwarf >= 4 high_pc is an size, not an address.
2527 Value = Unit.getHighPc() - Unit.getLowPc();
2528 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002529 Value = *Val.getAsSectionOffset();
2530 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2531 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002532 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2533 Value = *OptionalValue;
2534 else {
Adrian Prantl3565af42015-09-14 16:46:10 +00002535 Linker.reportWarning(
2536 "Unsupported scalar attribute form. Dropping attribute.",
2537 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002538 return 0;
2539 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002540 PatchLocation Patch =
2541 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2542 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002543 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002544 Unit.noteRangeAttribute(Die, Patch);
Frederic Riss29eedc72015-09-11 04:17:30 +00002545
Frederic Rissdfb97902015-03-14 15:49:07 +00002546 // A more generic way to check for location attributes would be
2547 // nice, but it's very unlikely that any other attribute needs a
2548 // location list.
2549 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2550 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002551 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002552 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2553 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002554
Frederic Rissb8b43d52015-03-04 22:07:44 +00002555 return AttrSize;
2556}
2557
2558/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2559/// value \p Val, and add it to \p Die.
2560/// \returns the size of the cloned attribute.
Adrian Prantl3565af42015-09-14 16:46:10 +00002561unsigned DwarfLinker::DIECloner::cloneAttribute(
2562 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2563 const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
2564 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002565 const DWARFUnit &U = Unit.getOrigUnit();
2566
2567 switch (AttrSpec.Form) {
2568 case dwarf::DW_FORM_strp:
2569 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002570 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002571 case dwarf::DW_FORM_ref_addr:
2572 case dwarf::DW_FORM_ref1:
2573 case dwarf::DW_FORM_ref2:
2574 case dwarf::DW_FORM_ref4:
2575 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002576 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002577 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002578 case dwarf::DW_FORM_block:
2579 case dwarf::DW_FORM_block1:
2580 case dwarf::DW_FORM_block2:
2581 case dwarf::DW_FORM_block4:
2582 case dwarf::DW_FORM_exprloc:
2583 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2584 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002585 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002586 case dwarf::DW_FORM_data1:
2587 case dwarf::DW_FORM_data2:
2588 case dwarf::DW_FORM_data4:
2589 case dwarf::DW_FORM_data8:
2590 case dwarf::DW_FORM_udata:
2591 case dwarf::DW_FORM_sdata:
2592 case dwarf::DW_FORM_sec_offset:
2593 case dwarf::DW_FORM_flag:
2594 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002595 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2596 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002597 default:
Adrian Prantl3565af42015-09-14 16:46:10 +00002598 Linker.reportWarning(
2599 "Unsupported attribute form in cloneAttribute. Dropping.", &U,
2600 &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002601 }
2602
2603 return 0;
2604}
2605
Frederic Riss23e20e92015-03-07 01:25:09 +00002606/// \brief Apply the valid relocations found by findValidRelocs() to
2607/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2608/// in the debug_info section.
2609///
2610/// Like for findValidRelocs(), this function must be called with
2611/// monotonic \p BaseOffset values.
2612///
2613/// \returns wether any reloc has been applied.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002614bool DwarfLinker::RelocationManager::
2615applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
2616 bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002617 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002618 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2619 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002620 if (NextValidReloc >= ValidRelocs.size())
2621 return false;
2622
2623 // Skip relocs that haven't been applied.
2624 while (NextValidReloc < ValidRelocs.size() &&
2625 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2626 ++NextValidReloc;
2627
2628 bool Applied = false;
2629 uint64_t EndOffset = BaseOffset + Data.size();
2630 while (NextValidReloc < ValidRelocs.size() &&
2631 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2632 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2633 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2634 assert(ValidReloc.Offset - BaseOffset < Data.size());
2635 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2636 char Buf[8];
2637 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2638 Value += ValidReloc.Addend;
2639 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2640 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2641 Buf[i] = uint8_t(Value >> (Index * 8));
2642 }
2643 assert(ValidReloc.Size <= sizeof(Buf));
2644 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2645 Applied = true;
2646 }
2647
2648 return Applied;
2649}
2650
Frederic Rissbce93ff2015-03-16 02:05:10 +00002651static bool isTypeTag(uint16_t Tag) {
2652 switch (Tag) {
2653 case dwarf::DW_TAG_array_type:
2654 case dwarf::DW_TAG_class_type:
2655 case dwarf::DW_TAG_enumeration_type:
2656 case dwarf::DW_TAG_pointer_type:
2657 case dwarf::DW_TAG_reference_type:
2658 case dwarf::DW_TAG_string_type:
2659 case dwarf::DW_TAG_structure_type:
2660 case dwarf::DW_TAG_subroutine_type:
2661 case dwarf::DW_TAG_typedef:
2662 case dwarf::DW_TAG_union_type:
2663 case dwarf::DW_TAG_ptr_to_member_type:
2664 case dwarf::DW_TAG_set_type:
2665 case dwarf::DW_TAG_subrange_type:
2666 case dwarf::DW_TAG_base_type:
2667 case dwarf::DW_TAG_const_type:
2668 case dwarf::DW_TAG_constant:
2669 case dwarf::DW_TAG_file_type:
2670 case dwarf::DW_TAG_namelist:
2671 case dwarf::DW_TAG_packed_type:
2672 case dwarf::DW_TAG_volatile_type:
2673 case dwarf::DW_TAG_restrict_type:
2674 case dwarf::DW_TAG_interface_type:
2675 case dwarf::DW_TAG_unspecified_type:
2676 case dwarf::DW_TAG_shared_type:
2677 return true;
2678 default:
2679 break;
2680 }
2681 return false;
2682}
2683
Frederic Riss29eedc72015-09-11 04:17:30 +00002684static bool
2685shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
2686 uint16_t Tag, bool InDebugMap, bool SkipPC,
2687 bool InFunctionScope) {
2688 switch (AttrSpec.Attr) {
2689 default:
2690 return false;
2691 case dwarf::DW_AT_low_pc:
2692 case dwarf::DW_AT_high_pc:
2693 case dwarf::DW_AT_ranges:
2694 return SkipPC;
2695 case dwarf::DW_AT_location:
2696 case dwarf::DW_AT_frame_base:
2697 // FIXME: for some reason dsymutil-classic keeps the location
2698 // attributes when they are of block type (ie. not location
2699 // lists). This is totally wrong for globals where we will keep a
2700 // wrong address. It is mostly harmless for locals, but there is
2701 // no point in keeping these anyway when the function wasn't linked.
2702 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
2703 !InDebugMap)) &&
2704 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
2705 }
2706}
2707
Adrian Prantl3565af42015-09-14 16:46:10 +00002708DIE *DwarfLinker::DIECloner::cloneDIE(
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002709 const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2710 int64_t PCOffset, uint32_t OutOffset, unsigned Flags) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002711 DWARFUnit &U = Unit.getOrigUnit();
2712 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002713 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002714
2715 // Should the DIE appear in the output?
2716 if (!Unit.getInfo(Idx).Keep)
2717 return nullptr;
2718
2719 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002720 // The DIE might have been already created by a forward reference
2721 // (see cloneDieReferenceAttribute()).
2722 DIE *Die = Info.Clone;
2723 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002724 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002725 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002726 Die->setOffset(OutOffset);
Adrian Prantla112ef92015-09-23 17:35:52 +00002727 if ((Unit.hasODR() || Unit.isClangModule()) &&
2728 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
Frederic Riss1c650942015-07-21 22:41:43 +00002729 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2730 !Info.Ctxt->getCanonicalDIEOffset()) {
2731 // We are about to emit a DIE that is the root of its own valid
2732 // DeclContext tree. Make the current offset the canonical offset
2733 // for this context.
2734 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2735 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002736
2737 // Extract and clone every attribute.
2738 DataExtractor Data = U.getDebugInfoExtractor();
Adrian Prantle5162db2015-09-22 22:20:50 +00002739 // Point to the next DIE (generally there is always at least a NULL
2740 // entry after the current one). If this is a lone
2741 // DW_TAG_compile_unit without any children, point to the next unit.
2742 uint32_t NextOffset =
2743 (Idx + 1 < U.getNumDIEs())
2744 ? U.getDIEAtIndex(Idx + 1)->getOffset()
2745 : U.getNextUnitOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002746 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002747
2748 // We could copy the data only if we need to aply a relocation to
2749 // it. After testing, it seems there is no performance downside to
2750 // doing the copy unconditionally, and it makes the code simpler.
2751 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2752 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2753 // Modify the copy with relocated addresses.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00002754 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
Frederic Riss31da3242015-03-11 18:45:52 +00002755 // If we applied relocations, we store the value of high_pc that was
2756 // potentially stored in the input DIE. If high_pc is an address
2757 // (Dwarf version == 2), then it might have been relocated to a
2758 // totally unrelated value (because the end address in the object
2759 // file might be start address of another function which got moved
2760 // independantly by the linker). The computation of the actual
2761 // high_pc value is done in cloneAddressAttribute().
2762 AttrInfo.OrigHighPc =
2763 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
Frederic Riss7b5563a2015-08-31 01:43:14 +00002764 // Also store the low_pc. It might get relocated in an
2765 // inline_subprogram that happens at the beginning of its
2766 // inlining function.
2767 AttrInfo.OrigLowPc =
2768 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_low_pc, UINT64_MAX);
Frederic Riss31da3242015-03-11 18:45:52 +00002769 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002770
2771 // Reset the Offset to 0 as we will be working on the local copy of
2772 // the data.
2773 Offset = 0;
2774
Frederic Rissb8b43d52015-03-04 22:07:44 +00002775 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2776 Offset += getULEB128Size(Abbrev->getCode());
2777
Frederic Riss31da3242015-03-11 18:45:52 +00002778 // We are entering a subprogram. Get and propagate the PCOffset.
2779 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2780 PCOffset = Info.AddrAdjust;
2781 AttrInfo.PCOffset = PCOffset;
2782
Frederic Riss29eedc72015-09-11 04:17:30 +00002783 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
2784 Flags |= TF_InFunctionScope;
2785 if (!Info.InDebugMap)
2786 Flags |= TF_SkipPC;
2787 }
2788
2789 bool Copied = false;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002790 for (const auto &AttrSpec : Abbrev->attributes()) {
Frederic Riss29eedc72015-09-11 04:17:30 +00002791 if (shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
2792 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
2793 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
2794 // FIXME: dsymutil-classic keeps the old abbreviation around
2795 // even if it's not used. We can remove this (and the copyAbbrev
2796 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
2797 if (!Copied) {
2798 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
2799 Copied = true;
2800 }
2801 continue;
2802 }
2803
Frederic Rissb8b43d52015-03-04 22:07:44 +00002804 DWARFFormValue Val(AttrSpec.Form);
2805 uint32_t AttrSize = Offset;
2806 Val.extractValue(Data, &Offset, &U);
2807 AttrSize = Offset - AttrSize;
2808
Frederic Riss31da3242015-03-11 18:45:52 +00002809 OutOffset +=
2810 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002811 }
2812
Frederic Rissbce93ff2015-03-16 02:05:10 +00002813 // Look for accelerator entries.
2814 uint16_t Tag = InputDIE.getTag();
2815 // FIXME: This is slightly wrong. An inline_subroutine without a
2816 // low_pc, but with AT_ranges might be interesting to get into the
2817 // accelerator tables too. For now stick with dsymutil's behavior.
2818 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2819 Tag != dwarf::DW_TAG_compile_unit &&
2820 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2821 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2822 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2823 AttrInfo.MangledNameOffset,
2824 Tag == dwarf::DW_TAG_inlined_subroutine);
2825 if (AttrInfo.Name)
2826 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2827 Tag == dwarf::DW_TAG_inlined_subroutine);
2828 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2829 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2830 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2831 }
2832
Adrian Prantle39475d2015-11-10 21:31:05 +00002833 // Determine whether there are any children that we want to keep.
2834 bool HasChildren = false;
2835 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2836 Child = Child->getSibling()) {
2837 unsigned Idx = U.getDIEIndex(Child);
2838 if (Unit.getInfo(Idx).Keep) {
2839 HasChildren = true;
2840 break;
2841 }
2842 }
2843
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002844 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Adrian Prantle39475d2015-11-10 21:31:05 +00002845 if (HasChildren)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002846 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2847 // Assign a permanent abbrev number
Adrian Prantl3565af42015-09-14 16:46:10 +00002848 Linker.AssignAbbrev(NewAbbrev);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002849 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002850
2851 // Add the size of the abbreviation number to the output offset.
2852 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2853
Adrian Prantle39475d2015-11-10 21:31:05 +00002854 if (!HasChildren) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002855 // Update our size.
2856 Die->setSize(OutOffset - Die->getOffset());
2857 return Die;
2858 }
2859
2860 // Recursively clone children.
2861 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2862 Child = Child->getSibling()) {
Adrian Prantl3abe18d2015-09-14 23:27:26 +00002863 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset, Flags)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002864 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002865 OutOffset = Clone->getOffset() + Clone->getSize();
2866 }
2867 }
2868
2869 // Account for the end of children marker.
2870 OutOffset += sizeof(int8_t);
2871 // Update our size.
2872 Die->setSize(OutOffset - Die->getOffset());
2873 return Die;
2874}
2875
Frederic Riss25440872015-03-13 23:30:31 +00002876/// \brief Patch the input object file relevant debug_ranges entries
2877/// and emit them in the output file. Update the relevant attributes
2878/// to point at the new entries.
2879void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2880 DWARFContext &OrigDwarf) const {
2881 DWARFDebugRangeList RangeList;
2882 const auto &FunctionRanges = Unit.getFunctionRanges();
2883 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2884 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2885 OrigDwarf.isLittleEndian(), AddressSize);
2886 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2887 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002888 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002889 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2890 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2891 // Ranges addresses are based on the unit's low_pc. Compute the
Sanjay Patele4b9f502015-12-07 19:21:39 +00002892 // offset we need to apply to adapt to the new unit's low_pc.
Frederic Riss25440872015-03-13 23:30:31 +00002893 int64_t UnitPcOffset = 0;
2894 if (OrigLowPc != -1ULL)
2895 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2896
2897 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002898 uint32_t Offset = RangeAttribute.get();
2899 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002900 RangeList.extract(RangeExtractor, &Offset);
2901 const auto &Entries = RangeList.getEntries();
Frederic Riss94546202015-08-31 05:09:32 +00002902 if (!Entries.empty()) {
2903 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
Frederic Riss25440872015-03-13 23:30:31 +00002904
Frederic Riss25440872015-03-13 23:30:31 +00002905 if (CurrRange == InvalidRange ||
Frederic Riss94546202015-08-31 05:09:32 +00002906 First.StartAddress + OrigLowPc < CurrRange.start() ||
2907 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
2908 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2909 if (CurrRange == InvalidRange ||
2910 CurrRange.start() > First.StartAddress + OrigLowPc) {
2911 reportWarning("no mapping for range.");
2912 continue;
2913 }
Frederic Riss25440872015-03-13 23:30:31 +00002914 }
2915 }
2916
2917 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2918 AddressSize);
2919 }
2920}
2921
Frederic Riss563b1b02015-03-14 03:46:51 +00002922/// \brief Generate the debug_aranges entries for \p Unit and if the
2923/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2924/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002925/// FIXME: this could actually be done right in patchRangesForUnit,
2926/// but for the sake of initial bit-for-bit compatibility with legacy
2927/// dsymutil, we have to do it in a delayed pass.
2928void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002929 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002930 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002931 Attr->set(Streamer->getRangesSectionSize());
2932 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002933}
2934
Frederic Riss63786b02015-03-15 20:45:43 +00002935/// \brief Insert the new line info sequence \p Seq into the current
2936/// set of already linked line info \p Rows.
2937static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2938 std::vector<DWARFDebugLine::Row> &Rows) {
2939 if (Seq.empty())
2940 return;
2941
2942 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2943 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2944 Seq.clear();
2945 return;
2946 }
2947
2948 auto InsertPoint = std::lower_bound(
2949 Rows.begin(), Rows.end(), Seq.front(),
2950 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2951 return LHS.Address < RHS.Address;
2952 });
2953
2954 // FIXME: this only removes the unneeded end_sequence if the
2955 // sequences have been inserted in order. using a global sort like
2956 // described in patchLineTableForUnit() and delaying the end_sequene
2957 // elimination to emitLineTableForUnit() we can get rid of all of them.
2958 if (InsertPoint != Rows.end() &&
2959 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2960 *InsertPoint = Seq.front();
2961 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2962 } else {
2963 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2964 }
2965
2966 Seq.clear();
2967}
2968
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002969static void patchStmtList(DIE &Die, DIEInteger Offset) {
2970 for (auto &V : Die.values())
2971 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002972 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002973 return;
2974 }
2975
2976 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2977}
2978
Frederic Riss63786b02015-03-15 20:45:43 +00002979/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2980/// recreate a relocated version of these for the address ranges that
2981/// are present in the binary.
2982void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2983 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002984 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002985 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2986 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2987 if (StmtList == -1ULL)
2988 return;
2989
2990 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002991 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2992 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002993
2994 // Parse the original line info for the unit.
2995 DWARFDebugLine::LineTable LineTable;
2996 uint32_t StmtOffset = StmtList;
2997 StringRef LineData = OrigDwarf.getLineSection().Data;
2998 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2999 Unit.getOrigUnit().getAddressByteSize());
3000 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
3001 &StmtOffset);
3002
3003 // This vector is the output line table.
3004 std::vector<DWARFDebugLine::Row> NewRows;
3005 NewRows.reserve(LineTable.Rows.size());
3006
3007 // Current sequence of rows being extracted, before being inserted
3008 // in NewRows.
3009 std::vector<DWARFDebugLine::Row> Seq;
3010 const auto &FunctionRanges = Unit.getFunctionRanges();
3011 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
3012
3013 // FIXME: This logic is meant to generate exactly the same output as
3014 // Darwin's classic dsynutil. There is a nicer way to implement this
3015 // by simply putting all the relocated line info in NewRows and simply
3016 // sorting NewRows before passing it to emitLineTableForUnit. This
3017 // should be correct as sequences for a function should stay
3018 // together in the sorted output. There are a few corner cases that
3019 // look suspicious though, and that required to implement the logic
3020 // this way. Revisit that once initial validation is finished.
3021
3022 // Iterate over the object file line info and extract the sequences
3023 // that correspond to linked functions.
3024 for (auto &Row : LineTable.Rows) {
3025 // Check wether we stepped out of the range. The range is
3026 // half-open, but consider accept the end address of the range if
3027 // it is marked as end_sequence in the input (because in that
3028 // case, the relocation offset is accurate and that entry won't
3029 // serve as the start of another function).
3030 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
3031 Row.Address > CurrRange.stop() ||
3032 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
3033 // We just stepped out of a known range. Insert a end_sequence
3034 // corresponding to the end of the range.
3035 uint64_t StopAddress = CurrRange != InvalidRange
3036 ? CurrRange.stop() + CurrRange.value()
3037 : -1ULL;
3038 CurrRange = FunctionRanges.find(Row.Address);
3039 bool CurrRangeValid =
3040 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
3041 if (!CurrRangeValid) {
3042 CurrRange = InvalidRange;
3043 if (StopAddress != -1ULL) {
3044 // Try harder by looking in the DebugMapObject function
3045 // ranges map. There are corner cases where this finds a
3046 // valid entry. It's unclear if this is right or wrong, but
3047 // for now do as dsymutil.
3048 // FIXME: Understand exactly what cases this addresses and
3049 // potentially remove it along with the Ranges map.
3050 auto Range = Ranges.lower_bound(Row.Address);
3051 if (Range != Ranges.begin() && Range != Ranges.end())
3052 --Range;
3053
3054 if (Range != Ranges.end() && Range->first <= Row.Address &&
3055 Range->second.first >= Row.Address) {
3056 StopAddress = Row.Address + Range->second.second;
3057 }
3058 }
3059 }
3060 if (StopAddress != -1ULL && !Seq.empty()) {
3061 // Insert end sequence row with the computed end address, but
3062 // the same line as the previous one.
Yaron Kerene3c07062015-08-10 16:15:51 +00003063 auto NextLine = Seq.back();
Yaron Keren2ad3b332015-08-10 18:27:51 +00003064 NextLine.Address = StopAddress;
3065 NextLine.EndSequence = 1;
3066 NextLine.PrologueEnd = 0;
3067 NextLine.BasicBlock = 0;
3068 NextLine.EpilogueBegin = 0;
Yaron Kerenf850d982015-08-10 18:03:35 +00003069 Seq.push_back(NextLine);
Frederic Riss63786b02015-03-15 20:45:43 +00003070 insertLineSequence(Seq, NewRows);
3071 }
3072
3073 if (!CurrRangeValid)
3074 continue;
3075 }
3076
3077 // Ignore empty sequences.
3078 if (Row.EndSequence && Seq.empty())
3079 continue;
3080
3081 // Relocate row address and add it to the current sequence.
3082 Row.Address += CurrRange.value();
3083 Seq.emplace_back(Row);
3084
3085 if (Row.EndSequence)
3086 insertLineSequence(Seq, NewRows);
3087 }
3088
3089 // Finished extracting, now emit the line tables.
3090 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
3091 // FIXME: LLVM hardcodes it's prologue values. We just copy the
3092 // prologue over and that works because we act as both producer and
3093 // consumer. It would be nicer to have a real configurable line
3094 // table emitter.
3095 if (LineTable.Prologue.Version != 2 ||
3096 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00003097 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00003098 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00003099 else {
3100 MCDwarfLineTableParams Params;
3101 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
3102 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
3103 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
3104 Streamer->emitLineTableForUnit(Params,
3105 LineData.slice(StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00003106 LineTable.Prologue.MinInstLength, NewRows,
3107 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00003108 }
Frederic Riss63786b02015-03-15 20:45:43 +00003109}
3110
Frederic Rissbce93ff2015-03-16 02:05:10 +00003111void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
3112 Streamer->emitPubNamesForUnit(Unit);
3113 Streamer->emitPubTypesForUnit(Unit);
3114}
3115
Frederic Riss5a642072015-06-05 23:06:11 +00003116/// \brief Read the frame info stored in the object, and emit the
3117/// patched frame descriptions for the linked binary.
3118///
3119/// This is actually pretty easy as the data of the CIEs and FDEs can
3120/// be considered as black boxes and moved as is. The only thing to do
3121/// is to patch the addresses in the headers.
3122void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
3123 DWARFContext &OrigDwarf,
3124 unsigned AddrSize) {
3125 StringRef FrameData = OrigDwarf.getDebugFrameSection();
3126 if (FrameData.empty())
3127 return;
3128
3129 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
3130 uint32_t InputOffset = 0;
3131
3132 // Store the data of the CIEs defined in this object, keyed by their
3133 // offsets.
3134 DenseMap<uint32_t, StringRef> LocalCIES;
3135
3136 while (Data.isValidOffset(InputOffset)) {
3137 uint32_t EntryOffset = InputOffset;
3138 uint32_t InitialLength = Data.getU32(&InputOffset);
3139 if (InitialLength == 0xFFFFFFFF)
3140 return reportWarning("Dwarf64 bits no supported");
3141
3142 uint32_t CIEId = Data.getU32(&InputOffset);
3143 if (CIEId == 0xFFFFFFFF) {
3144 // This is a CIE, store it.
3145 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
3146 LocalCIES[EntryOffset] = CIEData;
3147 // The -4 is to account for the CIEId we just read.
3148 InputOffset += InitialLength - 4;
3149 continue;
3150 }
3151
3152 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
3153
3154 // Some compilers seem to emit frame info that doesn't start at
3155 // the function entry point, thus we can't just lookup the address
3156 // in the debug map. Use the linker's range map to see if the FDE
3157 // describes something that we can relocate.
3158 auto Range = Ranges.upper_bound(Loc);
3159 if (Range != Ranges.begin())
3160 --Range;
3161 if (Range == Ranges.end() || Range->first > Loc ||
3162 Range->second.first <= Loc) {
3163 // The +4 is to account for the size of the InitialLength field itself.
3164 InputOffset = EntryOffset + InitialLength + 4;
3165 continue;
3166 }
3167
3168 // This is an FDE, and we have a mapping.
3169 // Have we already emitted a corresponding CIE?
3170 StringRef CIEData = LocalCIES[CIEId];
3171 if (CIEData.empty())
3172 return reportWarning("Inconsistent debug_frame content. Dropping.");
3173
3174 // Look if we already emitted a CIE that corresponds to the
3175 // referenced one (the CIE data is the key of that lookup).
3176 auto IteratorInserted = EmittedCIEs.insert(
3177 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3178 // If there is no CIE yet for this ID, emit it.
3179 if (IteratorInserted.second ||
3180 // FIXME: dsymutil-classic only caches the last used CIE for
3181 // reuse. Mimic that behavior for now. Just removing that
3182 // second half of the condition and the LastCIEOffset variable
3183 // makes the code DTRT.
3184 LastCIEOffset != IteratorInserted.first->getValue()) {
3185 LastCIEOffset = Streamer->getFrameSectionSize();
3186 IteratorInserted.first->getValue() = LastCIEOffset;
3187 Streamer->emitCIE(CIEData);
3188 }
3189
3190 // Emit the FDE with updated address and CIE pointer.
3191 // (4 + AddrSize) is the size of the CIEId + initial_location
3192 // fields that will get reconstructed by emitFDE().
3193 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3194 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3195 Loc + Range->second.second,
3196 FrameData.substr(InputOffset, FDERemainingBytes));
3197 InputOffset += FDERemainingBytes;
3198 }
3199}
3200
Adrian Prantl3565af42015-09-14 16:46:10 +00003201void DwarfLinker::DIECloner::copyAbbrev(
3202 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
Frederic Riss29eedc72015-09-11 04:17:30 +00003203 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
3204 dwarf::Form(Abbrev.hasChildren()));
3205
3206 for (const auto &Attr : Abbrev.attributes()) {
3207 uint16_t Form = Attr.Form;
3208 if (hasODR && isODRAttribute(Attr.Attr))
3209 Form = dwarf::DW_FORM_ref_addr;
3210 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
3211 }
3212
Adrian Prantl3565af42015-09-14 16:46:10 +00003213 Linker.AssignAbbrev(Copy);
Frederic Riss29eedc72015-09-11 04:17:30 +00003214}
3215
Adrian Prantl20937022015-09-23 17:11:10 +00003216static uint64_t getDwoId(const DWARFDebugInfoEntryMinimal &CUDie,
3217 const DWARFUnit &Unit) {
3218 uint64_t DwoId =
3219 CUDie.getAttributeValueAsUnsignedConstant(&Unit, dwarf::DW_AT_dwo_id, 0);
3220 if (!DwoId)
3221 DwoId = CUDie.getAttributeValueAsUnsignedConstant(&Unit,
3222 dwarf::DW_AT_GNU_dwo_id, 0);
3223 return DwoId;
3224}
3225
Adrian Prantle5162db2015-09-22 22:20:50 +00003226bool DwarfLinker::registerModuleReference(
3227 const DWARFDebugInfoEntryMinimal &CUDie, const DWARFUnit &Unit,
3228 DebugMap &ModuleMap, unsigned Indent) {
3229 std::string PCMfile =
Adrian Prantl20937022015-09-23 17:11:10 +00003230 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_dwo_name, "");
3231 if (PCMfile.empty())
3232 PCMfile =
3233 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_GNU_dwo_name, "");
Adrian Prantle5162db2015-09-22 22:20:50 +00003234 if (PCMfile.empty())
3235 return false;
3236
3237 // Clang module DWARF skeleton CUs abuse this for the path to the module.
3238 std::string PCMpath =
3239 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_comp_dir, "");
Adrian Prantl20937022015-09-23 17:11:10 +00003240 uint64_t DwoId = getDwoId(CUDie, Unit);
Adrian Prantle5162db2015-09-22 22:20:50 +00003241
Adrian Prantla112ef92015-09-23 17:35:52 +00003242 std::string Name =
3243 CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_name, "");
3244 if (Name.empty()) {
3245 reportWarning("Anonymous module skeleton CU for " + PCMfile);
3246 return true;
3247 }
3248
Adrian Prantle5162db2015-09-22 22:20:50 +00003249 if (Options.Verbose) {
3250 outs().indent(Indent);
3251 outs() << "Found clang module reference " << PCMfile;
3252 }
3253
Adrian Prantl20937022015-09-23 17:11:10 +00003254 auto Cached = ClangModules.find(PCMfile);
3255 if (Cached != ClangModules.end()) {
Adrian Prantle1bc3e22016-05-13 00:17:58 +00003256 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
3257 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
3258 // ASTFileSignatures will change randomly when a module is rebuilt.
3259 if (Options.Verbose && (Cached->second != DwoId))
Adrian Prantl20937022015-09-23 17:11:10 +00003260 reportWarning(Twine("hash mismatch: this object file was built against a "
3261 "different version of the module ") + PCMfile);
Adrian Prantle5162db2015-09-22 22:20:50 +00003262 if (Options.Verbose)
3263 outs() << " [cached].\n";
3264 return true;
3265 }
3266 if (Options.Verbose)
3267 outs() << " ...\n";
3268
3269 // Cyclic dependencies are disallowed by Clang, but we still
3270 // shouldn't run into an infinite loop, so mark it as processed now.
Adrian Prantl20937022015-09-23 17:11:10 +00003271 ClangModules.insert({PCMfile, DwoId});
Adrian Prantla112ef92015-09-23 17:35:52 +00003272 loadClangModule(PCMfile, PCMpath, Name, DwoId, ModuleMap, Indent + 2);
Adrian Prantle5162db2015-09-22 22:20:50 +00003273 return true;
3274}
3275
Frederic Risseb85c8f2015-07-24 06:41:11 +00003276ErrorOr<const object::ObjectFile &>
3277DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3278 const DebugMap &Map) {
3279 auto ErrOrObjs =
3280 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
Frederic Rissafeac302015-08-31 05:16:35 +00003281 if (std::error_code EC = ErrOrObjs.getError()) {
Frederic Risseb85c8f2015-07-24 06:41:11 +00003282 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
Frederic Rissafeac302015-08-31 05:16:35 +00003283 return EC;
3284 }
Frederic Risseb85c8f2015-07-24 06:41:11 +00003285 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3286 if (std::error_code EC = ErrOrObj.getError())
3287 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3288 return ErrOrObj;
3289}
3290
Adrian Prantle5162db2015-09-22 22:20:50 +00003291void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
Adrian Prantla112ef92015-09-23 17:35:52 +00003292 StringRef ModuleName, uint64_t DwoId,
3293 DebugMap &ModuleMap, unsigned Indent) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003294 SmallString<80> Path(Options.PrependPath);
3295 if (sys::path::is_relative(Filename))
3296 sys::path::append(Path, ModulePath, Filename);
3297 else
3298 sys::path::append(Path, Filename);
3299 BinaryHolder ObjHolder(Options.Verbose);
3300 auto &Obj =
3301 ModuleMap.addDebugMapObject(Path, sys::TimeValue::PosixZeroTime());
3302 auto ErrOrObj = loadObject(ObjHolder, Obj, ModuleMap);
Adrian Prantla9e23832016-01-14 18:31:07 +00003303 if (!ErrOrObj) {
3304 // Try and emit more helpful warnings by applying some heuristics.
3305 StringRef ObjFile = CurrentDebugObject->getObjectFilename();
3306 bool isClangModule = sys::path::extension(Filename).equals(".pcm");
3307 bool isArchive = ObjFile.endswith(")");
3308 if (isClangModule) {
Adrian Prantla9e23832016-01-14 18:31:07 +00003309 StringRef ModuleCacheDir = sys::path::parent_path(Path);
3310 if (sys::fs::exists(ModuleCacheDir)) {
3311 // If the module's parent directory exists, we assume that the module
3312 // cache has expired and was pruned by clang. A more adventurous
3313 // dsymutil would invoke clang to rebuild the module now.
3314 if (!ModuleCacheHintDisplayed) {
3315 errs() << "note: The clang module cache may have expired since this "
3316 "object file was built. Rebuilding the object file will "
3317 "rebuild the module cache.\n";
3318 ModuleCacheHintDisplayed = true;
3319 }
3320 } else if (isArchive) {
3321 // If the module cache directory doesn't exist at all and the object
3322 // file is inside a static library, we assume that the static library
3323 // was built on a different machine. We don't want to discourage module
3324 // debugging for convenience libraries within a project though.
3325 if (!ArchiveHintDisplayed) {
Adrian Prantl9e7e8832016-05-20 20:36:06 +00003326 errs() << "note: Linking a static library that was built with "
3327 "-gmodules, but the module cache was not found. "
3328 "Redistributable static libraries should never be built "
3329 "with module debugging enabled. The debug experience will "
3330 "be degraded due to incomplete debug information.\n";
Adrian Prantla9e23832016-01-14 18:31:07 +00003331 ArchiveHintDisplayed = true;
3332 }
3333 }
3334 }
Adrian Prantle5162db2015-09-22 22:20:50 +00003335 return;
Adrian Prantla9e23832016-01-14 18:31:07 +00003336 }
Adrian Prantle5162db2015-09-22 22:20:50 +00003337
Benjamin Kramer008f4be2015-09-23 10:38:59 +00003338 std::unique_ptr<CompileUnit> Unit;
Adrian Prantle5162db2015-09-22 22:20:50 +00003339
3340 // Setup access to the debug info.
3341 DWARFContextInMemory DwarfContext(*ErrOrObj);
3342 RelocationManager RelocMgr(*this);
3343 for (const auto &CU : DwarfContext.compile_units()) {
3344 auto *CUDie = CU->getUnitDIE(false);
3345 // Recursively get all modules imported by this one.
3346 if (!registerModuleReference(*CUDie, *CU, ModuleMap, Indent)) {
Adrian Prantle5162db2015-09-22 22:20:50 +00003347 if (Unit) {
3348 errs() << Filename << ": Clang modules are expected to have exactly"
3349 << " 1 compile unit.\n";
3350 exitDsymutil(1);
3351 }
Adrian Prantl2c0b0ab2016-04-25 17:04:32 +00003352 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
3353 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
3354 // ASTFileSignatures will change randomly when a module is rebuilt.
Adrian Prantle1bc3e22016-05-13 00:17:58 +00003355 uint64_t PCMDwoId = getDwoId(*CUDie, *CU);
3356 if (PCMDwoId != DwoId) {
3357 if (Options.Verbose)
3358 reportWarning(
3359 Twine("hash mismatch: this object file was built against a "
3360 "different version of the module ") + Filename);
3361 // Update the cache entry with the DwoId of the module loaded from disk.
3362 ClangModules[Filename] = PCMDwoId;
3363 }
Adrian Prantl20937022015-09-23 17:11:10 +00003364
3365 // Add this module.
Adrian Prantla112ef92015-09-23 17:35:52 +00003366 Unit = llvm::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
3367 ModuleName);
Adrian Prantle5162db2015-09-22 22:20:50 +00003368 Unit->setHasInterestingContent();
Adrian Prantla112ef92015-09-23 17:35:52 +00003369 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), StringPool,
3370 ODRContexts);
Adrian Prantle5162db2015-09-22 22:20:50 +00003371 // Keep everything.
3372 Unit->markEverythingAsKept();
3373 }
3374 }
3375 if (Options.Verbose) {
3376 outs().indent(Indent);
3377 outs() << "cloning .debug_info from " << Filename << "\n";
3378 }
3379
3380 DIECloner(*this, RelocMgr, DIEAlloc, MutableArrayRef<CompileUnit>(*Unit),
3381 Options)
3382 .cloneAllCompileUnits(DwarfContext);
3383}
3384
Adrian Prantl3565af42015-09-14 16:46:10 +00003385void DwarfLinker::DIECloner::cloneAllCompileUnits(
3386 DWARFContextInMemory &DwarfContext) {
3387 if (!Linker.Streamer)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003388 return;
3389
3390 for (auto &CurrentUnit : CompileUnits) {
3391 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Adrian Prantl3565af42015-09-14 16:46:10 +00003392 CurrentUnit.setStartOffset(Linker.OutputDebugInfoSize);
Adrian Prantl3abe18d2015-09-14 23:27:26 +00003393 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PC offset */,
3394 11 /* Unit Header size */, 0);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003395 CurrentUnit.setOutputUnitDIE(OutputDIE);
Adrian Prantl3565af42015-09-14 16:46:10 +00003396 Linker.OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3397 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003398 continue;
3399 // FIXME: for compatibility with the classic dsymutil, we emit
3400 // an empty line table for the unit, even if the unit doesn't
3401 // actually exist in the DIE tree.
Adrian Prantl3565af42015-09-14 16:46:10 +00003402 Linker.patchLineTableForUnit(CurrentUnit, DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003403 if (!OutputDIE)
3404 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003405 Linker.patchRangesForUnit(CurrentUnit, DwarfContext);
3406 Linker.Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3407 Linker.emitAcceleratorEntriesForUnit(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003408 }
3409
Adrian Prantl3565af42015-09-14 16:46:10 +00003410 if (Linker.Options.NoOutput)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003411 return;
3412
3413 // Emit all the compile unit's debug information.
3414 for (auto &CurrentUnit : CompileUnits) {
Adrian Prantl3565af42015-09-14 16:46:10 +00003415 Linker.generateUnitRanges(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003416 CurrentUnit.fixupForwardReferences();
Adrian Prantl3565af42015-09-14 16:46:10 +00003417 Linker.Streamer->emitCompileUnitHeader(CurrentUnit);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003418 if (!CurrentUnit.getOutputUnitDIE())
3419 continue;
Adrian Prantl3565af42015-09-14 16:46:10 +00003420 Linker.Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003421 }
3422}
3423
Frederic Rissd3455182015-01-28 18:27:01 +00003424bool DwarfLinker::link(const DebugMap &Map) {
3425
Frederic Rissc99ea202015-02-28 00:29:11 +00003426 if (!createStreamer(Map.getTriple(), OutputFilename))
3427 return false;
3428
Frederic Rissb8b43d52015-03-04 22:07:44 +00003429 // Size of the DIEs (and headers) generated for the linked output.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003430 OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00003431 // A unique ID that identifies each compile unit.
Adrian Prantle5162db2015-09-22 22:20:50 +00003432 UnitID = 0;
3433 DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
3434
Frederic Rissd3455182015-01-28 18:27:01 +00003435 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00003436 CurrentDebugObject = Obj.get();
3437
Frederic Rissb9818322015-02-28 00:29:07 +00003438 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00003439 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00003440 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3441 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00003442 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00003443
Frederic Riss1036e642015-02-13 23:18:22 +00003444 // Look for relocations that correspond to debug map entries.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003445 RelocationManager RelocMgr(*this);
3446 if (!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00003447 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00003448 outs() << "No valid relocations found. Skipping.\n";
3449 continue;
3450 }
3451
Frederic Riss563cba62015-01-28 22:15:14 +00003452 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00003453 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00003454 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00003455
Adrian Prantld2793a02015-10-05 23:11:20 +00003456 // In a first phase, just read in the debug info and load all clang modules.
Frederic Rissd3455182015-01-28 18:27:01 +00003457 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003458 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00003459 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00003460 outs() << "Input compilation unit:";
3461 CUDie->dump(outs(), CU.get(), 0);
3462 }
Adrian Prantld2793a02015-10-05 23:11:20 +00003463
3464 if (!registerModuleReference(*CUDie, *CU, ModuleMap))
Adrian Prantla112ef92015-09-23 17:35:52 +00003465 Units.emplace_back(*CU, UnitID++, !Options.NoODR, "");
Frederic Rissd3455182015-01-28 18:27:01 +00003466 }
Frederic Riss563cba62015-01-28 22:15:14 +00003467
Adrian Prantld2793a02015-10-05 23:11:20 +00003468 // Now build the DIE parent links that we will use during the next phase.
3469 for (auto &CurrentUnit : Units)
3470 analyzeContextInfo(CurrentUnit.getOrigUnit().getUnitDIE(), 0, CurrentUnit,
3471 &ODRContexts.getRoot(), StringPool, ODRContexts);
3472
Frederic Riss84c09a52015-02-13 23:18:34 +00003473 // Then mark all the DIEs that need to be present in the linked
3474 // output and collect some information about them. Note that this
3475 // loop can not be merged with the previous one becaue cross-cu
3476 // references require the ParentIdx to be setup for every CU in
3477 // the object file before calling this.
3478 for (auto &CurrentUnit : Units)
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003479 lookForDIEsToKeep(RelocMgr, *CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00003480 CurrentUnit, 0);
3481
Frederic Riss23e20e92015-03-07 01:25:09 +00003482 // The calls to applyValidRelocs inside cloneDIE will walk the
3483 // reloc array again (in the same way findValidRelocsInDebugInfo()
3484 // did). We need to reset the NextValidReloc index to the beginning.
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003485 RelocMgr.resetValidRelocs();
3486 if (RelocMgr.hasValidRelocs())
Adrian Prantl3565af42015-09-14 16:46:10 +00003487 DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
3488 .cloneAllCompileUnits(DwarfContext);
Adrian Prantl67a4fc72015-09-11 23:45:30 +00003489 if (!Options.NoOutput && !Units.empty())
Frederic Riss5a642072015-06-05 23:06:11 +00003490 patchFrameInfoForObject(*Obj, DwarfContext,
3491 Units[0].getOrigUnit().getAddressByteSize());
3492
Frederic Riss563cba62015-01-28 22:15:14 +00003493 // Clean-up before starting working on the next object.
3494 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003495 }
3496
Frederic Rissb8b43d52015-03-04 22:07:44 +00003497 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003498 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003499 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003500 Streamer->emitStrings(StringPool);
3501 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003502
Frederic Riss24faade2015-09-02 16:49:13 +00003503 return Options.NoOutput ? true : Streamer->finish(Map);
Frederic Riss231f7142014-12-12 17:31:24 +00003504}
3505}
Frederic Rissd3455182015-01-28 18:27:01 +00003506
Frederic Riss30711fb2015-08-26 05:09:52 +00003507/// \brief Get the offset of string \p S in the string table. This
3508/// can insert a new element or return the offset of a preexisitng
3509/// one.
3510uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3511 if (S.empty() && !Strings.empty())
3512 return 0;
3513
3514 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3515 MapTy::iterator It;
3516 bool Inserted;
3517
3518 // A non-empty string can't be at offset 0, so if we have an entry
3519 // with a 0 offset, it must be a previously interned string.
3520 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3521 if (Inserted || It->getValue().first == 0) {
3522 // Set offset and chain at the end of the entries list.
3523 It->getValue().first = CurrentEndOffset;
3524 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3525 Last->getValue().second = &*It;
3526 Last = &*It;
3527 }
3528 return It->getValue().first;
3529}
3530
3531/// \brief Put \p S into the StringMap so that it gets permanent
3532/// storage, but do not actually link it in the chain of elements
3533/// that go into the output section. A latter call to
3534/// getStringOffset() with the same string will chain it though.
3535StringRef NonRelocatableStringpool::internString(StringRef S) {
3536 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3537 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3538 return InsertResult.first->getKey();
3539}
3540
Frederic Riss65e145c2015-08-26 05:09:55 +00003541void warn(const Twine &Warning, const Twine &Context) {
3542 errs() << Twine("while processing ") + Context + ":\n";
3543 errs() << Twine("warning: ") + Warning + "\n";
3544}
3545
3546bool error(const Twine &Error, const Twine &Context) {
3547 errs() << Twine("while processing ") + Context + ":\n";
3548 errs() << Twine("error: ") + Error + "\n";
3549 return false;
3550}
3551
Frederic Rissb9818322015-02-28 00:29:07 +00003552bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3553 const LinkOptions &Options) {
3554 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003555 return Linker.link(DM);
3556}
3557}
Frederic Riss231f7142014-12-12 17:31:24 +00003558}