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