blob: 5d9a4f86329a9e28b076d3bb3bceaaa0bc65a200 [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 Riss30711fb2015-08-26 05:09:52 +000013#include "NonRelocatableStringpool.h"
Frederic Riss1af75f72015-03-12 18:45:10 +000014#include "llvm/ADT/IntervalMap.h"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000015#include "llvm/ADT/StringMap.h"
16#include "llvm/ADT/STLExtras.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000017#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000018#include "llvm/CodeGen/DIE.h"
Frederic Riss1c650942015-07-21 22:41:43 +000019#include "llvm/Config/config.h"
Zachary Turner82af9432015-01-30 18:07:45 +000020#include "llvm/DebugInfo/DWARF/DWARFContext.h"
21#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000022#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000023#include "llvm/MC/MCAsmBackend.h"
24#include "llvm/MC/MCAsmInfo.h"
25#include "llvm/MC/MCContext.h"
26#include "llvm/MC/MCCodeEmitter.h"
Frederic Riss63786b02015-03-15 20:45:43 +000027#include "llvm/MC/MCDwarf.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000028#include "llvm/MC/MCInstrInfo.h"
29#include "llvm/MC/MCObjectFileInfo.h"
30#include "llvm/MC/MCRegisterInfo.h"
31#include "llvm/MC/MCStreamer.h"
Pete Cooper81902a32015-05-15 22:19:42 +000032#include "llvm/MC/MCSubtargetInfo.h"
Frederic Riss1036e642015-02-13 23:18:22 +000033#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000034#include "llvm/Support/Dwarf.h"
35#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000036#include "llvm/Support/TargetRegistry.h"
37#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000039#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000040#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000041
42namespace llvm {
43namespace dsymutil {
44
Frederic Rissd3455182015-01-28 18:27:01 +000045namespace {
46
Frederic Rissdef4fb72015-02-28 00:29:01 +000047void warn(const Twine &Warning, const Twine &Context) {
48 errs() << Twine("while processing ") + Context + ":\n";
49 errs() << Twine("warning: ") + Warning + "\n";
50}
51
Frederic Rissc99ea202015-02-28 00:29:11 +000052bool error(const Twine &Error, const Twine &Context) {
53 errs() << Twine("while processing ") + Context + ":\n";
54 errs() << Twine("error: ") + Error + "\n";
55 return false;
56}
57
Frederic Riss1af75f72015-03-12 18:45:10 +000058template <typename KeyT, typename ValT>
59using HalfOpenIntervalMap =
60 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
61 IntervalMapHalfOpenInfo<KeyT>>;
62
Frederic Riss25440872015-03-13 23:30:31 +000063typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
64
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000065// FIXME: Delete this structure.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000066struct PatchLocation {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000067 DIE::value_iterator I;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000068
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000069 PatchLocation() = default;
70 PatchLocation(DIE::value_iterator I) : I(I) {}
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000071
72 void set(uint64_t New) const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000073 assert(I);
74 const auto &Old = *I;
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000075 assert(Old.getType() == DIEValue::isInteger);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000076 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000077 }
78
79 uint64_t get() const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000080 assert(I);
81 return I->getDIEInteger().getValue();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000082 }
83};
84
Frederic Riss1c650942015-07-21 22:41:43 +000085class CompileUnit;
86struct DeclMapInfo;
Frederic Riss1c650942015-07-21 22:41:43 +000087
88/// A DeclContext is a named program scope that is used for ODR
89/// uniquing of types.
90/// The set of DeclContext for the ODR-subject parts of a Dwarf link
91/// is expanded (and uniqued) with each new object file processed. We
92/// need to determine the context of each DIE in an linked object file
93/// to see if the corresponding type has already been emitted.
94///
95/// The contexts are conceptually organised as a tree (eg. a function
96/// scope is contained in a namespace scope that contains other
97/// scopes), but storing/accessing them in an actual tree is too
98/// inefficient: we need to be able to very quickly query a context
99/// for a given child context by name. Storing a StringMap in each
100/// DeclContext would be too space inefficient.
101/// The solution here is to give each DeclContext a link to its parent
102/// (this allows to walk up the tree), but to query the existance of a
103/// specific DeclContext using a separate DenseMap keyed on the hash
104/// of the fully qualified name of the context.
105class DeclContext {
106 unsigned QualifiedNameHash;
107 uint32_t Line;
108 uint32_t ByteSize;
109 uint16_t Tag;
110 StringRef Name;
111 StringRef File;
112 const DeclContext &Parent;
113 const DWARFDebugInfoEntryMinimal *LastSeenDIE;
114 uint32_t LastSeenCompileUnitID;
115 uint32_t CanonicalDIEOffset;
116
117 friend DeclMapInfo;
118
119public:
120 typedef DenseSet<DeclContext *, DeclMapInfo> Map;
121
122 DeclContext()
123 : QualifiedNameHash(0), Line(0), ByteSize(0),
124 Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
125 LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
126
127 DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
128 StringRef Name, StringRef File, const DeclContext &Parent,
129 const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
130 unsigned CUId = 0)
131 : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
132 Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
133 LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
134
135 uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
136
137 bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
138
139 uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
140 void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
141
142 uint16_t getTag() const { return Tag; }
143 StringRef getName() const { return Name; }
144};
145
146/// Info type for the DenseMap storing the DeclContext pointers.
147struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
148 using DenseMapInfo<DeclContext *>::getEmptyKey;
149 using DenseMapInfo<DeclContext *>::getTombstoneKey;
150
151 static unsigned getHashValue(const DeclContext *Ctxt) {
152 return Ctxt->QualifiedNameHash;
153 }
154
155 static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
156 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
157 return RHS == LHS;
158 return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
159 LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
160 LHS->Name.data() == RHS->Name.data() &&
161 LHS->File.data() == RHS->File.data() &&
162 LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
163 }
164};
165
166/// This class gives a tree-like API to the DenseMap that stores the
167/// DeclContext objects. It also holds the BumpPtrAllocator where
168/// these objects will be allocated.
169class DeclContextTree {
170 BumpPtrAllocator Allocator;
171 DeclContext Root;
172 DeclContext::Map Contexts;
173
174public:
175 /// Get the child of \a Context described by \a DIE in \a Unit. The
176 /// required strings will be interned in \a StringPool.
177 /// \returns The child DeclContext along with one bit that is set if
178 /// this context is invalid.
179 /// FIXME: the invalid bit along the return value is to emulate some
180 /// dsymutil-classic functionality. See the fucntion definition for
181 /// a more thorough discussion of its use.
182 PointerIntPair<DeclContext *, 1>
183 getChildDeclContext(DeclContext &Context,
184 const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
185 NonRelocatableStringpool &StringPool);
186
187 DeclContext &getRoot() { return Root; }
188};
189
Frederic Riss563cba62015-01-28 22:15:14 +0000190/// \brief Stores all information relating to a compile unit, be it in
191/// its original instance in the object file to its brand new cloned
192/// and linked DIE tree.
193class CompileUnit {
194public:
195 /// \brief Information gathered about a DIE in the object file.
196 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +0000197 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss1c650942015-07-21 22:41:43 +0000198 DeclContext *Ctxt; ///< ODR Declaration context.
Frederic Riss9833de62015-03-06 23:22:53 +0000199 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +0000200 uint32_t ParentIdx; ///< The index of this DIE's parent.
201 bool Keep; ///< Is the DIE part of the linked output?
202 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +0000203 };
204
Frederic Riss1c650942015-07-21 22:41:43 +0000205 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR)
Frederic Riss3cced052015-03-14 03:46:40 +0000206 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000207 Ranges(RangeAlloc) {
Frederic Riss563cba62015-01-28 22:15:14 +0000208 Info.resize(OrigUnit.getNumDIEs());
Frederic Riss1c650942015-07-21 22:41:43 +0000209
210 const auto *CUDie = OrigUnit.getUnitDIE(false);
211 unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
212 &OrigUnit, dwarf::DW_AT_language, 0);
213 HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
214 Lang == dwarf::DW_LANG_C_plus_plus_03 ||
215 Lang == dwarf::DW_LANG_C_plus_plus_11 ||
216 Lang == dwarf::DW_LANG_C_plus_plus_14 ||
217 Lang == dwarf::DW_LANG_ObjC_plus_plus);
Frederic Riss563cba62015-01-28 22:15:14 +0000218 }
219
Frederic Riss2838f9e2015-03-05 05:29:05 +0000220 CompileUnit(CompileUnit &&RHS)
221 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
222 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +0000223 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
224 // The CompileUnit container has been 'reserve()'d with the right
225 // size. We cannot move the IntervalMap anyway.
226 llvm_unreachable("CompileUnits should not be moved.");
227 }
David Blaikiea8adc132015-03-04 22:20:52 +0000228
Frederic Rissc3349d42015-02-13 23:18:27 +0000229 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000230
Frederic Riss3cced052015-03-14 03:46:40 +0000231 unsigned getUniqueID() const { return ID; }
232
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +0000233 DIE *getOutputUnitDIE() const { return CUDie; }
234 void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000235
Frederic Riss1c650942015-07-21 22:41:43 +0000236 bool hasODR() const { return HasODR; }
237
Frederic Riss563cba62015-01-28 22:15:14 +0000238 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
239 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
240
Frederic Rissb8b43d52015-03-04 22:07:44 +0000241 uint64_t getStartOffset() const { return StartOffset; }
242 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000243 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000244
Frederic Riss5a62dc32015-03-13 18:35:54 +0000245 uint64_t getLowPc() const { return LowPc; }
246 uint64_t getHighPc() const { return HighPc; }
247
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000248 Optional<PatchLocation> getUnitRangesAttribute() const {
249 return UnitRangeAttribute;
250 }
Frederic Riss25440872015-03-13 23:30:31 +0000251 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000252 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000253 return RangeAttributes;
254 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000255
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000256 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000257 getLocationAttributes() const {
258 return LocationAttributes;
259 }
260
Frederic Riss9d441b62015-03-06 23:22:50 +0000261 /// \brief Compute the end offset for this unit. Must be
262 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000263 /// \returns the next unit offset (which is also the current
264 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000265 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000266
Frederic Riss6afcfce2015-03-13 18:35:57 +0000267 /// \brief Keep track of a forward reference to DIE \p Die in \p
268 /// RefUnit by \p Attr. The attribute should be fixed up later to
Frederic Riss1c650942015-07-21 22:41:43 +0000269 /// point to the absolute offset of \p Die in the debug_info section
270 /// or to the canonical offset of \p Ctxt if it is non-null.
Frederic Riss6afcfce2015-03-13 18:35:57 +0000271 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000272 DeclContext *Ctxt, PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000273
274 /// \brief Apply all fixups recored by noteForwardReference().
275 void fixupForwardReferences();
276
Frederic Riss1af75f72015-03-12 18:45:10 +0000277 /// \brief Add a function range [\p LowPC, \p HighPC) that is
278 /// relocatad by applying offset \p PCOffset.
279 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
280
Frederic Riss5c9c7062015-03-13 23:55:29 +0000281 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000282 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000283 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000284
Frederic Rissdfb97902015-03-14 15:49:07 +0000285 /// \brief Keep track of a location attribute pointing to a location
286 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000287 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000288
Frederic Rissbce93ff2015-03-16 02:05:10 +0000289 /// \brief Add a name accelerator entry for \p Die with \p Name
290 /// which is stored in the string table at \p Offset.
291 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
292 bool SkipPubnamesSection = false);
293
294 /// \brief Add a type accelerator entry for \p Die with \p Name
295 /// which is stored in the string table at \p Offset.
296 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
297
298 struct AccelInfo {
Frederic Rissf37964c2015-06-05 20:27:07 +0000299 StringRef Name; ///< Name of the entry.
300 const DIE *Die; ///< DIE this entry describes.
Frederic Rissbce93ff2015-03-16 02:05:10 +0000301 uint32_t NameOffset; ///< Offset of Name in the string pool.
302 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
303
304 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
305 bool SkipPubSection = false)
306 : Name(Name), Die(Die), NameOffset(NameOffset),
307 SkipPubSection(SkipPubSection) {}
308 };
309
310 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
311 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
312
Frederic Riss1c650942015-07-21 22:41:43 +0000313 /// Get the full path for file \a FileNum in the line table
314 const char *getResolvedPath(unsigned FileNum) {
315 if (FileNum >= ResolvedPaths.size())
316 return nullptr;
317 return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
318 : nullptr;
319 }
320
321 /// Set the fully resolved path for the line-table's file \a FileNum
322 /// to \a Path.
323 void setResolvedPath(unsigned FileNum, const std::string &Path) {
324 if (ResolvedPaths.size() <= FileNum)
325 ResolvedPaths.resize(FileNum + 1);
326 ResolvedPaths[FileNum] = Path;
327 }
328
Frederic Riss563cba62015-01-28 22:15:14 +0000329private:
330 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000331 unsigned ID;
Frederic Riss1c650942015-07-21 22:41:43 +0000332 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
333 DIE *CUDie; ///< Root of the linked DIE tree.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000334
335 uint64_t StartOffset;
336 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000337
Frederic Riss5a62dc32015-03-13 18:35:54 +0000338 uint64_t LowPc;
339 uint64_t HighPc;
340
Frederic Riss9833de62015-03-06 23:22:53 +0000341 /// \brief A list of attributes to fixup with the absolute offset of
342 /// a DIE in the debug_info section.
343 ///
344 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000345 /// cloning because for cross-cu forward refences the target DIE's
346 /// offset isn't known you emit the reference attribute.
Frederic Riss1c650942015-07-21 22:41:43 +0000347 std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
348 PatchLocation>> ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000349
Frederic Riss25440872015-03-13 23:30:31 +0000350 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000351 /// \brief The ranges in that interval map are the PC ranges for
352 /// functions in this unit, associated with the PC offset to apply
353 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000354 FunctionIntervals Ranges;
355
356 /// \brief DW_AT_ranges attributes to patch after we have gathered
357 /// all the unit's function addresses.
358 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000359 std::vector<PatchLocation> RangeAttributes;
360 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000361 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000362
363 /// \brief Location attributes that need to be transfered from th
364 /// original debug_loc section to the liked one. They are stored
365 /// along with the PC offset that is to be applied to their
366 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000367 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000368
369 /// \brief Accelerator entries for the unit, both for the pub*
370 /// sections and the apple* ones.
371 /// @{
372 std::vector<AccelInfo> Pubnames;
373 std::vector<AccelInfo> Pubtypes;
374 /// @}
Frederic Riss1c650942015-07-21 22:41:43 +0000375
376 /// Cached resolved paths from the line table.
377 std::vector<std::string> ResolvedPaths;
378
379 /// Is this unit subject to the ODR rule?
380 bool HasODR;
Frederic Riss563cba62015-01-28 22:15:14 +0000381};
382
Frederic Riss9d441b62015-03-06 23:22:50 +0000383uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000384 NextUnitOffset = StartOffset + 11 /* Header size */;
385 // The root DIE might be null, meaning that the Unit had nothing to
386 // contribute to the linked output. In that case, we will emit the
387 // unit header without any actual DIE.
388 if (CUDie)
389 NextUnitOffset += CUDie->getSize();
390 return NextUnitOffset;
391}
392
Frederic Riss6afcfce2015-03-13 18:35:57 +0000393/// \brief Keep track of a forward cross-cu reference from this unit
394/// to \p Die that lives in \p RefUnit.
395void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Frederic Riss1c650942015-07-21 22:41:43 +0000396 DeclContext *Ctxt, PatchLocation Attr) {
397 ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000398}
399
400/// \brief Apply all fixups recorded by noteForwardReference().
401void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000402 for (const auto &Ref : ForwardDIEReferences) {
403 DIE *RefDie;
404 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000405 PatchLocation Attr;
Frederic Riss1c650942015-07-21 22:41:43 +0000406 DeclContext *Ctxt;
407 std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
408 if (Ctxt && Ctxt->getCanonicalDIEOffset())
409 Attr.set(Ctxt->getCanonicalDIEOffset());
410 else
411 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000412 }
Frederic Riss9833de62015-03-06 23:22:53 +0000413}
414
Frederic Riss5a62dc32015-03-13 18:35:54 +0000415void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
416 int64_t PcOffset) {
417 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
418 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
419 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000420}
421
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000422void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000423 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
424 RangeAttributes.push_back(Attr);
425 else
426 UnitRangeAttribute = Attr;
427}
428
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000429void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000430 LocationAttributes.emplace_back(Attr, PcOffset);
431}
432
Frederic Rissbce93ff2015-03-16 02:05:10 +0000433/// \brief Add a name accelerator entry for \p Die with \p Name
434/// which is stored in the string table at \p Offset.
435void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
436 uint32_t Offset, bool SkipPubSection) {
437 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
438}
439
440/// \brief Add a type accelerator entry for \p Die with \p Name
441/// which is stored in the string table at \p Offset.
442void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
443 uint32_t Offset) {
444 Pubtypes.emplace_back(Name, Die, Offset, false);
445}
446
Frederic Rissc99ea202015-02-28 00:29:11 +0000447/// \brief The Dwarf streaming logic
448///
449/// All interactions with the MC layer that is used to build the debug
450/// information binary representation are handled in this class.
451class DwarfStreamer {
452 /// \defgroup MCObjects MC layer objects constructed by the streamer
453 /// @{
454 std::unique_ptr<MCRegisterInfo> MRI;
455 std::unique_ptr<MCAsmInfo> MAI;
456 std::unique_ptr<MCObjectFileInfo> MOFI;
457 std::unique_ptr<MCContext> MC;
458 MCAsmBackend *MAB; // Owned by MCStreamer
459 std::unique_ptr<MCInstrInfo> MII;
460 std::unique_ptr<MCSubtargetInfo> MSTI;
461 MCCodeEmitter *MCE; // Owned by MCStreamer
462 MCStreamer *MS; // Owned by AsmPrinter
463 std::unique_ptr<TargetMachine> TM;
464 std::unique_ptr<AsmPrinter> Asm;
465 /// @}
466
467 /// \brief the file we stream the linked Dwarf to.
468 std::unique_ptr<raw_fd_ostream> OutFile;
469
Frederic Riss25440872015-03-13 23:30:31 +0000470 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000471 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000472 uint32_t LineSectionSize;
Frederic Riss5a642072015-06-05 23:06:11 +0000473 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000474
Frederic Rissbce93ff2015-03-16 02:05:10 +0000475 /// \brief Emit the pubnames or pubtypes section contribution for \p
476 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000477 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000478 const CompileUnit &Unit,
479 const std::vector<CompileUnit::AccelInfo> &Names);
480
Frederic Rissc99ea202015-02-28 00:29:11 +0000481public:
482 /// \brief Actually create the streamer and the ouptut file.
483 ///
484 /// This could be done directly in the constructor, but it feels
485 /// more natural to handle errors through return value.
486 bool init(Triple TheTriple, StringRef OutputFilename);
487
Frederic Rissb8b43d52015-03-04 22:07:44 +0000488 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000489 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000490
491 AsmPrinter &getAsmPrinter() const { return *Asm; }
492
493 /// \brief Set the current output section to debug_info and change
494 /// the MC Dwarf version to \p DwarfVersion.
495 void switchToDebugInfoSection(unsigned DwarfVersion);
496
497 /// \brief Emit the compilation unit header for \p Unit in the
498 /// debug_info section.
499 ///
500 /// As a side effect, this also switches the current Dwarf version
501 /// of the MC layer to the one of U.getOrigUnit().
502 void emitCompileUnitHeader(CompileUnit &Unit);
503
504 /// \brief Recursively emit the DIE tree rooted at \p Die.
505 void emitDIE(DIE &Die);
506
507 /// \brief Emit the abbreviation table \p Abbrevs to the
508 /// debug_abbrev section.
509 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000510
511 /// \brief Emit the string table described by \p Pool.
512 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000513
514 /// \brief Emit debug_ranges for \p FuncRange by translating the
515 /// original \p Entries.
516 void emitRangesEntries(
517 int64_t UnitPcOffset, uint64_t OrigLowPc,
518 FunctionIntervals::const_iterator FuncRange,
519 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
520 unsigned AddressSize);
521
Frederic Riss563b1b02015-03-14 03:46:51 +0000522 /// \brief Emit debug_aranges entries for \p Unit and if \p
523 /// DoRangesSection is true, also emit the debug_ranges entries for
524 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
525 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000526
527 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000528
529 /// \brief Emit the debug_loc contribution for \p Unit by copying
530 /// the entries from \p Dwarf and offseting them. Update the
531 /// location attributes to point to the new entries.
532 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000533
534 /// \brief Emit the line table described in \p Rows into the
535 /// debug_line section.
Frederic Rissa5e14532015-08-07 15:14:13 +0000536 void emitLineTableForUnit(MCDwarfLineTableParams Params,
537 StringRef PrologueBytes, unsigned MinInstLength,
Frederic Riss63786b02015-03-15 20:45:43 +0000538 std::vector<DWARFDebugLine::Row> &Rows,
539 unsigned AdddressSize);
540
541 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000542
543 /// \brief Emit the .debug_pubnames contribution for \p Unit.
544 void emitPubNamesForUnit(const CompileUnit &Unit);
545
546 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
547 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000548
549 /// \brief Emit a CIE.
550 void emitCIE(StringRef CIEBytes);
551
552 /// \brief Emit an FDE with data \p Bytes.
553 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
554 StringRef Bytes);
555
556 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000557};
558
559bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
560 std::string ErrorStr;
561 std::string TripleName;
562 StringRef Context = "dwarf streamer init";
563
564 // Get the target.
565 const Target *TheTarget =
566 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
567 if (!TheTarget)
568 return error(ErrorStr, Context);
569 TripleName = TheTriple.getTriple();
570
571 // Create all the MC Objects.
572 MRI.reset(TheTarget->createMCRegInfo(TripleName));
573 if (!MRI)
574 return error(Twine("no register info for target ") + TripleName, Context);
575
576 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
577 if (!MAI)
578 return error("no asm info for target " + TripleName, Context);
579
580 MOFI.reset(new MCObjectFileInfo);
581 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000582 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
Frederic Rissc99ea202015-02-28 00:29:11 +0000583 *MC);
584
585 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
586 if (!MAB)
587 return error("no asm backend for target " + TripleName, Context);
588
589 MII.reset(TheTarget->createMCInstrInfo());
590 if (!MII)
591 return error("no instr info info for target " + TripleName, Context);
592
593 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
594 if (!MSTI)
595 return error("no subtarget info for target " + TripleName, Context);
596
Eric Christopher0169e422015-03-10 22:03:14 +0000597 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000598 if (!MCE)
599 return error("no code emitter for target " + TripleName, Context);
600
601 // Create the output file.
602 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000603 OutFile =
604 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000605 if (EC)
606 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
607
Rafael Espindolaf696df12015-03-16 22:29:29 +0000608 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000609 *MSTI, false,
610 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000611 if (!MS)
612 return error("no object streamer for target " + TripleName, Context);
613
614 // Finally create the AsmPrinter we'll use to emit the DIEs.
615 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
616 if (!TM)
617 return error("no target machine for target " + TripleName, Context);
618
619 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
620 if (!Asm)
621 return error("no asm printer for target " + TripleName, Context);
622
Frederic Riss25440872015-03-13 23:30:31 +0000623 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000624 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000625 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000626 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000627
Frederic Rissc99ea202015-02-28 00:29:11 +0000628 return true;
629}
630
631bool DwarfStreamer::finish() {
632 MS->Finish();
633 return true;
634}
635
Frederic Rissb8b43d52015-03-04 22:07:44 +0000636/// \brief Set the current output section to debug_info and change
637/// the MC Dwarf version to \p DwarfVersion.
638void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
639 MS->SwitchSection(MOFI->getDwarfInfoSection());
640 MC->setDwarfVersion(DwarfVersion);
641}
642
643/// \brief Emit the compilation unit header for \p Unit in the
644/// debug_info section.
645///
646/// A Dwarf scetion header is encoded as:
647/// uint32_t Unit length (omiting this field)
648/// uint16_t Version
649/// uint32_t Abbreviation table offset
650/// uint8_t Address size
651///
652/// Leading to a total of 11 bytes.
653void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
654 unsigned Version = Unit.getOrigUnit().getVersion();
655 switchToDebugInfoSection(Version);
656
657 // Emit size of content not including length itself. The size has
658 // already been computed in CompileUnit::computeOffsets(). Substract
659 // 4 to that size to account for the length field.
660 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
661 Asm->EmitInt16(Version);
662 // We share one abbreviations table across all units so it's always at the
663 // start of the section.
664 Asm->EmitInt32(0);
665 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
666}
667
668/// \brief Emit the \p Abbrevs array as the shared abbreviation table
669/// for the linked Dwarf file.
670void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
671 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
672 Asm->emitDwarfAbbrevs(Abbrevs);
673}
674
675/// \brief Recursively emit the DIE tree rooted at \p Die.
676void DwarfStreamer::emitDIE(DIE &Die) {
677 MS->SwitchSection(MOFI->getDwarfInfoSection());
678 Asm->emitDwarfDIE(Die);
679}
680
Frederic Rissef648462015-03-06 17:56:30 +0000681/// \brief Emit the debug_str section stored in \p Pool.
682void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000683 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000684 for (auto *Entry = Pool.getFirstEntry(); Entry;
685 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000686 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000687 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
688}
689
Frederic Riss25440872015-03-13 23:30:31 +0000690/// \brief Emit the debug_range section contents for \p FuncRange by
691/// translating the original \p Entries. The debug_range section
692/// format is totally trivial, consisting just of pairs of address
693/// sized addresses describing the ranges.
694void DwarfStreamer::emitRangesEntries(
695 int64_t UnitPcOffset, uint64_t OrigLowPc,
696 FunctionIntervals::const_iterator FuncRange,
697 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
698 unsigned AddressSize) {
699 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
700
701 // Offset each range by the right amount.
702 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
703 for (const auto &Range : Entries) {
704 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
705 warn("unsupported base address selection operation",
706 "emitting debug_ranges");
707 break;
708 }
709 // Do not emit empty ranges.
710 if (Range.StartAddress == Range.EndAddress)
711 continue;
712
713 // All range entries should lie in the function range.
714 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
715 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
716 warn("inconsistent range data.", "emitting debug_ranges");
717 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
718 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
719 RangesSectionSize += 2 * AddressSize;
720 }
721
722 // Add the terminator entry.
723 MS->EmitIntValue(0, AddressSize);
724 MS->EmitIntValue(0, AddressSize);
725 RangesSectionSize += 2 * AddressSize;
726}
727
Frederic Riss563b1b02015-03-14 03:46:51 +0000728/// \brief Emit the debug_aranges contribution of a unit and
729/// if \p DoDebugRanges is true the debug_range contents for a
730/// compile_unit level DW_AT_ranges attribute (Which are basically the
731/// same thing with a different base address).
732/// Just aggregate all the ranges gathered inside that unit.
733void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
734 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000735 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
736 // Gather the ranges in a vector, so that we can simplify them. The
737 // IntervalMap will have coalesced the non-linked ranges, but here
738 // we want to coalesce the linked addresses.
739 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
740 const auto &FunctionRanges = Unit.getFunctionRanges();
741 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
742 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000743 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
744 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000745
746 // The object addresses where sorted, but again, the linked
747 // addresses might end up in a different order.
748 std::sort(Ranges.begin(), Ranges.end());
749
Frederic Riss563b1b02015-03-14 03:46:51 +0000750 if (!Ranges.empty()) {
751 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
752
Rafael Espindola9ab09232015-03-17 20:07:06 +0000753 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
754 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000755
756 unsigned HeaderSize =
757 sizeof(int32_t) + // Size of contents (w/o this field
758 sizeof(int16_t) + // DWARF ARange version number
759 sizeof(int32_t) + // Offset of CU in the .debug_info section
760 sizeof(int8_t) + // Pointer Size (in bytes)
761 sizeof(int8_t); // Segment Size (in bytes)
762
763 unsigned TupleSize = AddressSize * 2;
764 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
765
766 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000767 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000768 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
769 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
770 Asm->EmitInt8(AddressSize); // Address size
771 Asm->EmitInt8(0); // Segment size
772
Lang Hames9ff69c82015-04-24 19:11:51 +0000773 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000774
775 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
776 ++Range) {
777 uint64_t RangeStart = Range->first;
778 MS->EmitIntValue(RangeStart, AddressSize);
779 while ((Range + 1) != End && Range->second == (Range + 1)->first)
780 ++Range;
781 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
782 }
783
784 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000785 Asm->OutStreamer->EmitIntValue(0, AddressSize);
786 Asm->OutStreamer->EmitIntValue(0, AddressSize);
787 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000788 }
789
790 if (!DoDebugRanges)
791 return;
792
793 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
794 // Offset each range by the right amount.
795 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000796 // Emit coalesced ranges.
797 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000798 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000799 while (Range + 1 != End && Range->second == (Range + 1)->first)
800 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000801 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000802 RangesSectionSize += 2 * AddressSize;
803 }
804
805 // Add the terminator entry.
806 MS->EmitIntValue(0, AddressSize);
807 MS->EmitIntValue(0, AddressSize);
808 RangesSectionSize += 2 * AddressSize;
809}
810
Frederic Rissdfb97902015-03-14 15:49:07 +0000811/// \brief Emit location lists for \p Unit and update attribtues to
812/// point to the new entries.
813void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
814 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000815 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000816
817 if (Attributes.empty())
818 return;
819
820 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
821
822 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
823 const DWARFSection &InputSec = Dwarf.getLocSection();
824 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
825 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000826 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000827 int64_t UnitPcOffset = 0;
828 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
829 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
830 if (OrigLowPc != -1ULL)
831 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
832
833 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000834 uint32_t Offset = Attr.first.get();
835 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000836 // This is the quantity to add to the old location address to get
837 // the correct address for the new one.
838 int64_t LocPcOffset = Attr.second + UnitPcOffset;
839 while (Data.isValidOffset(Offset)) {
840 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
841 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
842 LocSectionSize += 2 * AddressSize;
843 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000844 Asm->OutStreamer->EmitIntValue(0, AddressSize);
845 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000846 break;
847 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000848 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
849 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000850 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000851 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000852 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000853 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000854 StringRef(InputSec.Data.substr(Offset, Length)));
855 Offset += Length;
856 LocSectionSize += Length + 2;
857 }
858 }
859}
860
Frederic Rissa5e14532015-08-07 15:14:13 +0000861void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
862 StringRef PrologueBytes,
Frederic Riss63786b02015-03-15 20:45:43 +0000863 unsigned MinInstLength,
864 std::vector<DWARFDebugLine::Row> &Rows,
865 unsigned PointerSize) {
866 // Switch to the section where the table will be emitted into.
867 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000868 MCSymbol *LineStartSym = MC->createTempSymbol();
869 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000870
871 // The first 4 bytes is the total length of the information for this
872 // compilation unit (not including these 4 bytes for the length).
873 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000874 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000875 // Copy Prologue.
876 MS->EmitBytes(PrologueBytes);
877 LineSectionSize += PrologueBytes.size() + 4;
878
Frederic Rissc3820d02015-03-15 22:20:28 +0000879 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000880 raw_svector_ostream EncodingOS(EncodingBuffer);
881
882 if (Rows.empty()) {
883 // We only have the dummy entry, dsymutil emits an entry with a 0
884 // address in that case.
Frederic Rissa5e14532015-08-07 15:14:13 +0000885 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000886 MS->EmitBytes(EncodingOS.str());
887 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000888 MS->EmitLabel(LineEndSym);
889 return;
890 }
891
892 // Line table state machine fields
893 unsigned FileNum = 1;
894 unsigned LastLine = 1;
895 unsigned Column = 0;
896 unsigned IsStatement = 1;
897 unsigned Isa = 0;
898 uint64_t Address = -1ULL;
899
900 unsigned RowsSinceLastSequence = 0;
901
902 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
903 auto &Row = Rows[Idx];
904
905 int64_t AddressDelta;
906 if (Address == -1ULL) {
907 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
908 MS->EmitULEB128IntValue(PointerSize + 1);
909 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
910 MS->EmitIntValue(Row.Address, PointerSize);
911 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
912 AddressDelta = 0;
913 } else {
914 AddressDelta = (Row.Address - Address) / MinInstLength;
915 }
916
917 // FIXME: code copied and transfromed from
918 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
919 // this code, but the current compatibility requirement with
920 // classic dsymutil makes it hard. Revisit that once this
921 // requirement is dropped.
922
923 if (FileNum != Row.File) {
924 FileNum = Row.File;
925 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
926 MS->EmitULEB128IntValue(FileNum);
927 LineSectionSize += 1 + getULEB128Size(FileNum);
928 }
929 if (Column != Row.Column) {
930 Column = Row.Column;
931 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
932 MS->EmitULEB128IntValue(Column);
933 LineSectionSize += 1 + getULEB128Size(Column);
934 }
935
936 // FIXME: We should handle the discriminator here, but dsymutil
937 // doesn' consider it, thus ignore it for now.
938
939 if (Isa != Row.Isa) {
940 Isa = Row.Isa;
941 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
942 MS->EmitULEB128IntValue(Isa);
943 LineSectionSize += 1 + getULEB128Size(Isa);
944 }
945 if (IsStatement != Row.IsStmt) {
946 IsStatement = Row.IsStmt;
947 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
948 LineSectionSize += 1;
949 }
950 if (Row.BasicBlock) {
951 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
952 LineSectionSize += 1;
953 }
954
955 if (Row.PrologueEnd) {
956 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
957 LineSectionSize += 1;
958 }
959
960 if (Row.EpilogueBegin) {
961 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
962 LineSectionSize += 1;
963 }
964
965 int64_t LineDelta = int64_t(Row.Line) - LastLine;
966 if (!Row.EndSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000967 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000968 MS->EmitBytes(EncodingOS.str());
969 LineSectionSize += EncodingBuffer.size();
970 EncodingBuffer.resize(0);
971 Address = Row.Address;
972 LastLine = Row.Line;
973 RowsSinceLastSequence++;
974 } else {
975 if (LineDelta) {
976 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
977 MS->EmitSLEB128IntValue(LineDelta);
978 LineSectionSize += 1 + getSLEB128Size(LineDelta);
979 }
980 if (AddressDelta) {
981 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
982 MS->EmitULEB128IntValue(AddressDelta);
983 LineSectionSize += 1 + getULEB128Size(AddressDelta);
984 }
Frederic Rissa5e14532015-08-07 15:14:13 +0000985 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000986 MS->EmitBytes(EncodingOS.str());
987 LineSectionSize += EncodingBuffer.size();
988 EncodingBuffer.resize(0);
Frederic Riss63786b02015-03-15 20:45:43 +0000989 Address = -1ULL;
990 LastLine = FileNum = IsStatement = 1;
991 RowsSinceLastSequence = Column = Isa = 0;
992 }
993 }
994
995 if (RowsSinceLastSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +0000996 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000997 MS->EmitBytes(EncodingOS.str());
998 LineSectionSize += EncodingBuffer.size();
999 EncodingBuffer.resize(0);
1000 }
1001
1002 MS->EmitLabel(LineEndSym);
1003}
1004
Frederic Rissbce93ff2015-03-16 02:05:10 +00001005/// \brief Emit the pubnames or pubtypes section contribution for \p
1006/// Unit into \p Sec. The data is provided in \p Names.
1007void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001008 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001009 const std::vector<CompileUnit::AccelInfo> &Names) {
1010 if (Names.empty())
1011 return;
1012
1013 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001014 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001015 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1016 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001017
1018 bool HeaderEmitted = false;
1019 // Emit the pubnames for this compilation unit.
1020 for (const auto &Name : Names) {
1021 if (Name.SkipPubSection)
1022 continue;
1023
1024 if (!HeaderEmitted) {
1025 // Emit the header.
1026 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001027 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001028 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001029 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001030 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1031 HeaderEmitted = true;
1032 }
1033 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001034 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001035 StringRef(Name.Name.data(), Name.Name.size() + 1));
1036 }
1037
1038 if (!HeaderEmitted)
1039 return;
1040 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001041 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001042}
1043
1044/// \brief Emit .debug_pubnames for \p Unit.
1045void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1046 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1047 "names", Unit, Unit.getPubnames());
1048}
1049
1050/// \brief Emit .debug_pubtypes for \p Unit.
1051void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1052 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1053 "types", Unit, Unit.getPubtypes());
1054}
1055
Frederic Riss5a642072015-06-05 23:06:11 +00001056/// \brief Emit a CIE into the debug_frame section.
1057void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1058 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1059
1060 MS->EmitBytes(CIEBytes);
1061 FrameSectionSize += CIEBytes.size();
1062}
1063
1064/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1065/// contains the FDE data without the length, CIE offset and address
1066/// which will be replaced with the paramter values.
1067void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1068 uint32_t Address, StringRef FDEBytes) {
1069 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1070
1071 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1072 MS->EmitIntValue(CIEOffset, 4);
1073 MS->EmitIntValue(Address, AddrSize);
1074 MS->EmitBytes(FDEBytes);
1075 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1076}
1077
Frederic Rissd3455182015-01-28 18:27:01 +00001078/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001079///
1080/// The link of the dwarf information from the object files will be
1081/// driven by the selection of 'root DIEs', which are DIEs that
1082/// describe variables or functions that are present in the linked
1083/// binary (and thus have entries in the debug map). All the debug
1084/// information that will be linked (the DIEs, but also the line
1085/// tables, ranges, ...) is derived from that set of root DIEs.
1086///
1087/// The root DIEs are identified because they contain relocations that
1088/// correspond to a debug map entry at specific places (the low_pc for
1089/// a function, the location for a variable). These relocations are
1090/// called ValidRelocs in the DwarfLinker and are gathered as a very
1091/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001092class DwarfLinker {
1093public:
Frederic Rissb9818322015-02-28 00:29:07 +00001094 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1095 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001096 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001097
Frederic Rissb8b43d52015-03-04 22:07:44 +00001098 ~DwarfLinker() {
1099 for (auto *Abbrev : Abbreviations)
1100 delete Abbrev;
1101 }
1102
Frederic Rissd3455182015-01-28 18:27:01 +00001103 /// \brief Link the contents of the DebugMap.
1104 bool link(const DebugMap &);
1105
1106private:
Frederic Riss563cba62015-01-28 22:15:14 +00001107 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001108 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001109
1110 /// \brief Called at the end of a debug object link.
1111 void endDebugObject();
1112
Frederic Riss1036e642015-02-13 23:18:22 +00001113 /// \defgroup FindValidRelocations Translate debug map into a list
1114 /// of relevant relocations
1115 ///
1116 /// @{
1117 struct ValidReloc {
1118 uint32_t Offset;
1119 uint32_t Size;
1120 uint64_t Addend;
1121 const DebugMapObject::DebugMapEntry *Mapping;
1122
1123 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1124 const DebugMapObject::DebugMapEntry *Mapping)
1125 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1126
1127 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1128 };
1129
1130 /// \brief The valid relocations for the current DebugMapObject.
1131 /// This vector is sorted by relocation offset.
1132 std::vector<ValidReloc> ValidRelocs;
1133
1134 /// \brief Index into ValidRelocs of the next relocation to
1135 /// consider. As we walk the DIEs in acsending file offset and as
1136 /// ValidRelocs is sorted by file offset, keeping this index
1137 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +00001138 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +00001139 unsigned NextValidReloc;
1140
1141 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1142 const DebugMapObject &DMO);
1143
1144 bool findValidRelocs(const object::SectionRef &Section,
1145 const object::ObjectFile &Obj,
1146 const DebugMapObject &DMO);
1147
1148 void findValidRelocsMachO(const object::SectionRef &Section,
1149 const object::MachOObjectFile &Obj,
1150 const DebugMapObject &DMO);
1151 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +00001152
Frederic Riss84c09a52015-02-13 23:18:34 +00001153 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1154 ///
1155 /// @{
1156 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1157 /// keep. Store that information in \p CU's DIEInfo.
1158 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1159 const DebugMapObject &DMO, CompileUnit &CU,
1160 unsigned Flags);
1161
1162 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1163 enum TravesalFlags {
1164 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1165 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1166 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1167 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001168 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss84c09a52015-02-13 23:18:34 +00001169 };
1170
1171 /// \brief Mark the passed DIE as well as all the ones it depends on
1172 /// as kept.
1173 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1174 CompileUnit::DIEInfo &MyInfo,
1175 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001176 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001177
1178 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1179 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1180 unsigned Flags);
1181
1182 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1183 CompileUnit &Unit,
1184 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1185
1186 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1187 CompileUnit &Unit,
1188 CompileUnit::DIEInfo &MyInfo,
1189 unsigned Flags);
1190
1191 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1192 CompileUnit::DIEInfo &Info);
1193 /// @}
1194
Frederic Rissb8b43d52015-03-04 22:07:44 +00001195 /// \defgroup Linking Methods used to link the debug information
1196 ///
1197 /// @{
1198 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1199 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1200 /// stripped out and addresses have been rewritten according to the
1201 /// debug map.
1202 ///
1203 /// \param OutOffset is the offset the cloned DIE in the output
1204 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +00001205 /// \param PCOffset (while cloning a function scope) is the offset
1206 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001207 ///
1208 /// \returns the root of the cloned tree.
1209 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +00001210 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001211
1212 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1213
Frederic Riss31da3242015-03-11 18:45:52 +00001214 /// \brief Information gathered and exchanged between the various
1215 /// clone*Attributes helpers about the attributes of a particular DIE.
1216 struct AttributesInfo {
Frederic Rissbce93ff2015-03-16 02:05:10 +00001217 const char *Name, *MangledName; ///< Names.
1218 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1219
Frederic Riss31da3242015-03-11 18:45:52 +00001220 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1221 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1222
Frederic Rissbce93ff2015-03-16 02:05:10 +00001223 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1224 bool IsDeclaration; ///< Is this DIE only a declaration?
1225
1226 AttributesInfo()
1227 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1228 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1229 IsDeclaration(false) {}
Frederic Riss31da3242015-03-11 18:45:52 +00001230 };
1231
Frederic Rissb8b43d52015-03-04 22:07:44 +00001232 /// \brief Helper for cloneDIE.
1233 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1234 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001235 const AttributeSpec AttrSpec, unsigned AttrSize,
1236 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001237
1238 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001239 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1240 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001241
1242 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001243 unsigned
1244 cloneDieReferenceAttribute(DIE &Die,
1245 const DWARFDebugInfoEntryMinimal &InputDIE,
1246 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001247 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001248
1249 /// \brief Helper for cloneDIE.
1250 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1251 const DWARFFormValue &Val, unsigned AttrSize);
1252
1253 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001254 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1255 const DWARFFormValue &Val,
1256 const CompileUnit &Unit, AttributesInfo &Info);
1257
1258 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001259 unsigned cloneScalarAttribute(DIE &Die,
1260 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001261 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001262 const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001263 AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001264
Frederic Riss23e20e92015-03-07 01:25:09 +00001265 /// \brief Helper for cloneDIE.
1266 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1267 bool isLittleEndian);
1268
Frederic Rissb8b43d52015-03-04 22:07:44 +00001269 /// \brief Assign an abbreviation number to \p Abbrev
1270 void AssignAbbrev(DIEAbbrev &Abbrev);
1271
1272 /// \brief FoldingSet that uniques the abbreviations.
1273 FoldingSet<DIEAbbrev> AbbreviationsSet;
1274 /// \brief Storage for the unique Abbreviations.
1275 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1276 /// be changed to a vecot of unique_ptrs.
1277 std::vector<DIEAbbrev *> Abbreviations;
1278
Frederic Riss25440872015-03-13 23:30:31 +00001279 /// \brief Compute and emit debug_ranges section for \p Unit, and
1280 /// patch the attributes referencing it.
1281 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1282
1283 /// \brief Generate and emit the DW_AT_ranges attribute for a
1284 /// compile_unit if it had one.
1285 void generateUnitRanges(CompileUnit &Unit) const;
1286
Frederic Riss63786b02015-03-15 20:45:43 +00001287 /// \brief Extract the line tables fromt he original dwarf, extract
1288 /// the relevant parts according to the linked function ranges and
1289 /// emit the result in the debug_line section.
1290 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1291
Frederic Rissbce93ff2015-03-16 02:05:10 +00001292 /// \brief Emit the accelerator entries for \p Unit.
1293 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1294
Frederic Riss5a642072015-06-05 23:06:11 +00001295 /// \brief Patch the frame info for an object file and emit it.
1296 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1297 unsigned AddressSize);
1298
Frederic Rissb8b43d52015-03-04 22:07:44 +00001299 /// \brief DIELoc objects that need to be destructed (but not freed!).
1300 std::vector<DIELoc *> DIELocs;
1301 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1302 std::vector<DIEBlock *> DIEBlocks;
1303 /// \brief Allocator used for all the DIEValue objects.
1304 BumpPtrAllocator DIEAlloc;
1305 /// @}
1306
Frederic Riss1c650942015-07-21 22:41:43 +00001307 /// ODR Contexts for that link.
1308 DeclContextTree ODRContexts;
1309
Frederic Riss1b9da422015-02-13 23:18:29 +00001310 /// \defgroup Helpers Various helper methods.
1311 ///
1312 /// @{
1313 const DWARFDebugInfoEntryMinimal *
Frederic Riss1c650942015-07-21 22:41:43 +00001314 resolveDIEReference(const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001315 const DWARFDebugInfoEntryMinimal &DIE,
1316 CompileUnit *&ReferencedCU);
1317
1318 CompileUnit *getUnitForOffset(unsigned Offset);
1319
Frederic Rissbce93ff2015-03-16 02:05:10 +00001320 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1321 AttributesInfo &Info);
1322
Frederic Riss1b9da422015-02-13 23:18:29 +00001323 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001324 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001325
1326 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001327
1328 /// \brief Attempt to load a debug object from disk.
1329 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1330 DebugMapObject &Obj,
1331 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001332 /// @}
1333
Frederic Riss563cba62015-01-28 22:15:14 +00001334private:
Frederic Rissd3455182015-01-28 18:27:01 +00001335 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001336 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001337 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001338 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001339
1340 /// The units of the current debug map object.
1341 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001342
1343 /// The debug map object curently under consideration.
1344 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001345
1346 /// \brief The Dwarf string pool
1347 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001348
1349 /// \brief This map is keyed by the entry PC of functions in that
1350 /// debug object and the associated value is a pair storing the
1351 /// corresponding end PC and the offset to apply to get the linked
1352 /// address.
1353 ///
1354 /// See startDebugObject() for a more complete description of its use.
1355 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001356
1357 /// \brief The CIEs that have been emitted in the output
1358 /// section. The actual CIE data serves a the key to this StringMap,
1359 /// this takes care of comparing the semantics of CIEs defined in
1360 /// different object files.
1361 StringMap<uint32_t> EmittedCIEs;
1362
1363 /// Offset of the last CIE that has been emitted in the output
1364 /// debug_frame section.
1365 uint32_t LastCIEOffset;
Frederic Rissd3455182015-01-28 18:27:01 +00001366};
1367
Frederic Riss1b9da422015-02-13 23:18:29 +00001368/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1369/// returning our CompileUnit object instead.
1370CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1371 auto CU =
1372 std::upper_bound(Units.begin(), Units.end(), Offset,
1373 [](uint32_t LHS, const CompileUnit &RHS) {
1374 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1375 });
1376 return CU != Units.end() ? &*CU : nullptr;
1377}
1378
1379/// \brief Resolve the DIE attribute reference that has been
1380/// extracted in \p RefValue. The resulting DIE migh be in another
1381/// CompileUnit which is stored into \p ReferencedCU.
1382/// \returns null if resolving fails for any reason.
1383const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
Frederic Riss1c650942015-07-21 22:41:43 +00001384 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001385 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1386 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1387 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1388
1389 if ((RefCU = getUnitForOffset(RefOffset)))
1390 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1391 return RefDie;
1392
1393 reportWarning("could not find referenced DIE", &Unit, &DIE);
1394 return nullptr;
1395}
1396
Frederic Riss1c650942015-07-21 22:41:43 +00001397/// \returns whether the passed \a Attr type might contain a DIE
1398/// reference suitable for ODR uniquing.
1399static bool isODRAttribute(uint16_t Attr) {
1400 switch (Attr) {
1401 default:
1402 return false;
1403 case dwarf::DW_AT_type:
1404 case dwarf::DW_AT_containing_type:
1405 case dwarf::DW_AT_specification:
1406 case dwarf::DW_AT_abstract_origin:
1407 case dwarf::DW_AT_import:
1408 return true;
1409 }
1410 llvm_unreachable("Improper attribute.");
1411}
1412
1413/// Set the last DIE/CU a context was seen in and, possibly invalidate
1414/// the context if it is ambiguous.
1415///
1416/// In the current implementation, we don't handle overloaded
1417/// functions well, because the argument types are not taken into
1418/// account when computing the DeclContext tree.
1419///
1420/// Some of this is mitigated byt using mangled names that do contain
1421/// the arguments types, but sometimes (eg. with function templates)
1422/// we don't have that. In that case, just do not unique anything that
1423/// refers to the contexts we are not able to distinguish.
1424///
1425/// If a context that is not a namespace appears twice in the same CU,
1426/// we know it is ambiguous. Make it invalid.
1427bool DeclContext::setLastSeenDIE(CompileUnit &U,
1428 const DWARFDebugInfoEntryMinimal *Die) {
1429 if (LastSeenCompileUnitID == U.getUniqueID()) {
1430 DWARFUnit &OrigUnit = U.getOrigUnit();
1431 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1432 U.getInfo(FirstIdx).Ctxt = nullptr;
1433 return false;
1434 }
1435
1436 LastSeenCompileUnitID = U.getUniqueID();
1437 LastSeenDIE = Die;
1438 return true;
1439}
1440
1441/// Get the child context of \a Context corresponding to \a DIE.
1442///
1443/// \returns the child context or null if we shouldn't track children
1444/// contexts. It also returns an additional bit meaning 'invalid'. An
1445/// invalid context means it shouldn't be considered for uniquing, but
1446/// its not returning null, because some children of that context
1447/// might be uniquing candidates.
1448/// FIXME: this is for dsymutil-classic compatibility, I don't think
1449/// it buys us much.
1450PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1451 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1452 NonRelocatableStringpool &StringPool) {
1453 unsigned Tag = DIE->getTag();
1454
1455 // FIXME: dsymutil-classic compat: We should bail out here if we
1456 // have a specification or an abstract_origin. We will get the
1457 // parent context wrong here.
1458
1459 switch (Tag) {
1460 default:
1461 // By default stop gathering child contexts.
1462 return PointerIntPair<DeclContext *, 1>(nullptr);
1463 case dwarf::DW_TAG_compile_unit:
1464 // FIXME: Add support for DW_TAG_module.
1465 return PointerIntPair<DeclContext *, 1>(&Context);
1466 case dwarf::DW_TAG_subprogram:
1467 // Do not unique anything inside CU local functions.
1468 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1469 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1470 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1471 dwarf::DW_AT_external, 0))
1472 return PointerIntPair<DeclContext *, 1>(nullptr);
1473 // Fallthrough
1474 case dwarf::DW_TAG_member:
1475 case dwarf::DW_TAG_namespace:
1476 case dwarf::DW_TAG_structure_type:
1477 case dwarf::DW_TAG_class_type:
1478 case dwarf::DW_TAG_union_type:
1479 case dwarf::DW_TAG_enumeration_type:
1480 case dwarf::DW_TAG_typedef:
1481 // Artificial things might be ambiguous, because they might be
1482 // created on demand. For example implicitely defined constructors
1483 // are ambiguous because of the way we identify contexts, and they
1484 // won't be generated everytime everywhere.
1485 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1486 dwarf::DW_AT_artificial, 0))
1487 return PointerIntPair<DeclContext *, 1>(nullptr);
1488 break;
1489 }
1490
1491 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1492 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1493 StringRef NameRef;
1494 StringRef ShortNameRef;
1495 StringRef FileRef;
1496
1497 if (Name)
1498 NameRef = StringPool.internString(Name);
1499 else if (Tag == dwarf::DW_TAG_namespace)
1500 // FIXME: For dsymutil-classic compatibility. I think uniquing
1501 // within anonymous namespaces is wrong. There is no ODR guarantee
1502 // there.
1503 NameRef = StringPool.internString("(anonymous namespace)");
1504
1505 if (ShortName && ShortName != Name)
1506 ShortNameRef = StringPool.internString(ShortName);
1507 else
1508 ShortNameRef = NameRef;
1509
1510 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1511 Tag != dwarf::DW_TAG_union_type &&
1512 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1513 return PointerIntPair<DeclContext *, 1>(nullptr);
1514
1515 std::string File;
1516 unsigned Line = 0;
1517 unsigned ByteSize = 0;
1518
1519 // Gather some discriminating data about the DeclContext we will be
1520 // creating: File, line number and byte size. This shouldn't be
1521 // necessary, because the ODR is just about names, but given that we
1522 // do some approximations with overloaded functions and anonymous
1523 // namespaces, use these additional data points to make the process safer.
1524 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1525 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1526 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1527 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1528 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1529 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1530 &U.getOrigUnit())) {
1531 // FIXME: dsymutil-classic compatibility. I'd rather not
1532 // unique anything in anonymous namespaces, but if we do, then
1533 // verify that the file and line correspond.
1534 if (!Name && Tag == dwarf::DW_TAG_namespace)
1535 FileNum = 1;
1536
1537 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1538 // instead of "" would allow more uniquing, but for now, do
1539 // it this way to match dsymutil-classic.
1540 if (LT->getFileNameByIndex(
1541 FileNum, "",
1542 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1543 File)) {
1544 Line = DIE->getAttributeValueAsUnsignedConstant(
1545 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1546#ifdef HAVE_REALPATH
1547 // Cache the resolved paths, because calling realpath is expansive.
1548 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1549 File = ResolvedPath;
1550 } else {
1551 char RealPath[PATH_MAX + 1];
1552 RealPath[PATH_MAX] = 0;
1553 if (::realpath(File.c_str(), RealPath))
1554 File = RealPath;
1555 U.setResolvedPath(FileNum, File);
1556 }
1557#endif
1558 FileRef = StringPool.internString(File);
1559 }
1560 }
1561 }
1562 }
1563
1564 if (!Line && NameRef.empty())
1565 return PointerIntPair<DeclContext *, 1>(nullptr);
1566
1567 // FIXME: dsymutil-classic compat won't unique the same type
1568 // presented once as a struct and once as a class. Use the Tag in
1569 // the fully qualified name hash to get the same effect.
1570 // We hash NameRef, which is the mangled name, in order to get most
1571 // overloaded functions resolvec correctly.
1572 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1573
1574 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1575 // use the filename.
1576 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1577 Hash = hash_combine(Hash, FileRef);
1578
1579 // Now look if this context already exists.
1580 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1581 auto ContextIter = Contexts.find(&Key);
1582
1583 if (ContextIter == Contexts.end()) {
1584 // The context wasn't found.
1585 bool Inserted;
1586 DeclContext *NewContext =
1587 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1588 Context, DIE, U.getUniqueID());
1589 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1590 assert(Inserted && "Failed to insert DeclContext");
1591 (void)Inserted;
1592 } else if (Tag != dwarf::DW_TAG_namespace &&
1593 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1594 // The context was found, but it is ambiguous with another context
1595 // in the same file. Mark it invalid.
1596 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1597 }
1598
1599 assert(ContextIter != Contexts.end());
1600 // FIXME: dsymutil-classic compatibility. Union types aren't
1601 // uniques, but their children might be.
1602 if ((Tag == dwarf::DW_TAG_subprogram &&
1603 Context.getTag() != dwarf::DW_TAG_structure_type &&
1604 Context.getTag() != dwarf::DW_TAG_class_type) ||
1605 (Tag == dwarf::DW_TAG_union_type))
1606 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1607
1608 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1609}
1610
Frederic Rissbce93ff2015-03-16 02:05:10 +00001611/// \brief Get the potential name and mangled name for the entity
1612/// described by \p Die and store them in \Info if they are not
1613/// already there.
1614/// \returns is a name was found.
1615bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1616 DWARFUnit &U, AttributesInfo &Info) {
1617 // FIXME: a bit wastefull as the first getName might return the
1618 // short name.
1619 if (!Info.MangledName &&
1620 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1621 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1622
1623 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1624 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1625
1626 return Info.Name || Info.MangledName;
1627}
1628
Frederic Riss1b9da422015-02-13 23:18:29 +00001629/// \brief Report a warning to the user, optionaly including
1630/// information about a specific \p DIE related to the warning.
1631void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001632 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001633 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001634 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001635 Context = CurrentDebugObject->getObjectFilename();
1636 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001637
Frederic Rissb9818322015-02-28 00:29:07 +00001638 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001639 return;
1640
1641 errs() << " in DIE:\n";
1642 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1643 6 /* Indent */);
1644}
1645
Frederic Rissc99ea202015-02-28 00:29:11 +00001646bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1647 if (Options.NoOutput)
1648 return true;
1649
Frederic Rissb52cf522015-02-28 00:42:37 +00001650 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001651 return Streamer->init(TheTriple, OutputFilename);
1652}
1653
Frederic Riss563cba62015-01-28 22:15:14 +00001654/// \brief Recursive helper to gather the child->parent relationships in the
1655/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001656static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
Frederic Riss1c650942015-07-21 22:41:43 +00001657 unsigned ParentIdx, CompileUnit &CU,
1658 DeclContext *CurrentDeclContext,
1659 NonRelocatableStringpool &StringPool,
1660 DeclContextTree &Contexts) {
Frederic Riss563cba62015-01-28 22:15:14 +00001661 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001662 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1663
1664 Info.ParentIdx = ParentIdx;
1665 if (CU.hasODR()) {
1666 if (CurrentDeclContext) {
1667 auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1668 DIE, CU, StringPool);
1669 CurrentDeclContext = PtrInvalidPair.getPointer();
1670 Info.Ctxt =
1671 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1672 } else
1673 Info.Ctxt = CurrentDeclContext = nullptr;
1674 }
Frederic Riss563cba62015-01-28 22:15:14 +00001675
1676 if (DIE->hasChildren())
1677 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1678 Child = Child->getSibling())
Frederic Riss1c650942015-07-21 22:41:43 +00001679 gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1680 Contexts);
Frederic Riss563cba62015-01-28 22:15:14 +00001681}
1682
Frederic Riss84c09a52015-02-13 23:18:34 +00001683static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1684 switch (Tag) {
1685 default:
1686 return false;
1687 case dwarf::DW_TAG_subprogram:
1688 case dwarf::DW_TAG_lexical_block:
1689 case dwarf::DW_TAG_subroutine_type:
1690 case dwarf::DW_TAG_structure_type:
1691 case dwarf::DW_TAG_class_type:
1692 case dwarf::DW_TAG_union_type:
1693 return true;
1694 }
1695 llvm_unreachable("Invalid Tag");
1696}
1697
Frederic Riss1c650942015-07-21 22:41:43 +00001698static unsigned getRefAddrSize(const DWARFUnit &U) {
1699 if (U.getVersion() == 2)
1700 return U.getAddressByteSize();
1701 return 4;
1702}
1703
Frederic Riss63786b02015-03-15 20:45:43 +00001704void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001705 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001706 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001707 // Iterate over the debug map entries and put all the ones that are
1708 // functions (because they have a size) into the Ranges map. This
1709 // map is very similar to the FunctionRanges that are stored in each
1710 // unit, with 2 notable differences:
1711 // - obviously this one is global, while the other ones are per-unit.
1712 // - this one contains not only the functions described in the DIE
1713 // tree, but also the ones that are only in the debug map.
1714 // The latter information is required to reproduce dsymutil's logic
1715 // while linking line tables. The cases where this information
1716 // matters look like bugs that need to be investigated, but for now
1717 // we need to reproduce dsymutil's behavior.
1718 // FIXME: Once we understood exactly if that information is needed,
1719 // maybe totally remove this (or try to use it to do a real
1720 // -gline-tables-only on Darwin.
1721 for (const auto &Entry : Obj.symbols()) {
1722 const auto &Mapping = Entry.getValue();
1723 if (Mapping.Size)
1724 Ranges[Mapping.ObjectAddress] = std::make_pair(
1725 Mapping.ObjectAddress + Mapping.Size,
1726 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1727 }
Frederic Riss563cba62015-01-28 22:15:14 +00001728}
1729
Frederic Riss1036e642015-02-13 23:18:22 +00001730void DwarfLinker::endDebugObject() {
1731 Units.clear();
1732 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001733 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001734
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001735 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1736 (*I)->~DIEBlock();
1737 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1738 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001739
1740 DIEBlocks.clear();
1741 DIELocs.clear();
1742 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001743}
1744
1745/// \brief Iterate over the relocations of the given \p Section and
1746/// store the ones that correspond to debug map entries into the
1747/// ValidRelocs array.
1748void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1749 const object::MachOObjectFile &Obj,
1750 const DebugMapObject &DMO) {
1751 StringRef Contents;
1752 Section.getContents(Contents);
1753 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1754
1755 for (const object::RelocationRef &Reloc : Section.relocations()) {
1756 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1757 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1758 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001759 uint64_t Offset64 = Reloc.getOffset();
1760 if ((RelocSize != 4 && RelocSize != 8)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001761 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001762 continue;
1763 }
1764 uint32_t Offset = Offset64;
1765 // Mach-o uses REL relocations, the addend is at the relocation offset.
1766 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1767
1768 auto Sym = Reloc.getSymbol();
1769 if (Sym != Obj.symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001770 ErrorOr<StringRef> SymbolName = Sym->getName();
1771 if (!SymbolName) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001772 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001773 continue;
1774 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001775 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001776 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1777 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1778 // Do not store the addend. The addend was the address of the
1779 // symbol in the object file, the address in the binary that is
1780 // stored in the debug map doesn't need to be offseted.
1781 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1782 }
1783 }
1784}
1785
1786/// \brief Dispatch the valid relocation finding logic to the
1787/// appropriate handler depending on the object file format.
1788bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1789 const object::ObjectFile &Obj,
1790 const DebugMapObject &DMO) {
1791 // Dispatch to the right handler depending on the file type.
1792 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1793 findValidRelocsMachO(Section, *MachOObj, DMO);
1794 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001795 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001796
1797 if (ValidRelocs.empty())
1798 return false;
1799
1800 // Sort the relocations by offset. We will walk the DIEs linearly in
1801 // the file, this allows us to just keep an index in the relocation
1802 // array that we advance during our walk, rather than resorting to
1803 // some associative container. See DwarfLinker::NextValidReloc.
1804 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1805 return true;
1806}
1807
1808/// \brief Look for relocations in the debug_info section that match
1809/// entries in the debug map. These relocations will drive the Dwarf
1810/// link by indicating which DIEs refer to symbols present in the
1811/// linked binary.
1812/// \returns wether there are any valid relocations in the debug info.
1813bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1814 const DebugMapObject &DMO) {
1815 // Find the debug_info section.
1816 for (const object::SectionRef &Section : Obj.sections()) {
1817 StringRef SectionName;
1818 Section.getName(SectionName);
1819 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1820 if (SectionName != "debug_info")
1821 continue;
1822 return findValidRelocs(Section, Obj, DMO);
1823 }
1824 return false;
1825}
Frederic Riss563cba62015-01-28 22:15:14 +00001826
Frederic Riss84c09a52015-02-13 23:18:34 +00001827/// \brief Checks that there is a relocation against an actual debug
1828/// map entry between \p StartOffset and \p NextOffset.
1829///
1830/// This function must be called with offsets in strictly ascending
1831/// order because it never looks back at relocations it already 'went past'.
1832/// \returns true and sets Info.InDebugMap if it is the case.
1833bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1834 CompileUnit::DIEInfo &Info) {
1835 assert(NextValidReloc == 0 ||
1836 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1837 if (NextValidReloc >= ValidRelocs.size())
1838 return false;
1839
1840 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1841
1842 // We might need to skip some relocs that we didn't consider. For
1843 // example the high_pc of a discarded DIE might contain a reloc that
1844 // is in the list because it actually corresponds to the start of a
1845 // function that is in the debug map.
1846 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1847 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1848
1849 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1850 return false;
1851
1852 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00001853 const auto &Mapping = ValidReloc.Mapping->getValue();
Frederic Rissb9818322015-02-28 00:29:07 +00001854 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001855 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1856 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
Frederic Riss08462f72015-06-01 21:12:45 +00001857 uint64_t(Mapping.ObjectAddress),
1858 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00001859
Frederic Rissf37964c2015-06-05 20:27:07 +00001860 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1861 Mapping.ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001862 Info.InDebugMap = true;
1863 return true;
1864}
1865
1866/// \brief Get the starting and ending (exclusive) offset for the
1867/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1868/// supposed to point to the position of the first attribute described
1869/// by \p Abbrev.
1870/// \return [StartOffset, EndOffset) as a pair.
1871static std::pair<uint32_t, uint32_t>
1872getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1873 unsigned Offset, const DWARFUnit &Unit) {
1874 DataExtractor Data = Unit.getDebugInfoExtractor();
1875
1876 for (unsigned i = 0; i < Idx; ++i)
1877 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1878
1879 uint32_t End = Offset;
1880 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1881
1882 return std::make_pair(Offset, End);
1883}
1884
1885/// \brief Check if a variable describing DIE should be kept.
1886/// \returns updated TraversalFlags.
1887unsigned DwarfLinker::shouldKeepVariableDIE(
1888 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1889 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1890 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1891
1892 // Global variables with constant value can always be kept.
1893 if (!(Flags & TF_InFunctionScope) &&
1894 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1895 MyInfo.InDebugMap = true;
1896 return Flags | TF_Keep;
1897 }
1898
1899 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1900 if (LocationIdx == -1U)
1901 return Flags;
1902
1903 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1904 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1905 uint32_t LocationOffset, LocationEndOffset;
1906 std::tie(LocationOffset, LocationEndOffset) =
1907 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1908
1909 // See if there is a relocation to a valid debug map entry inside
1910 // this variable's location. The order is important here. We want to
1911 // always check in the variable has a valid relocation, so that the
1912 // DIEInfo is filled. However, we don't want a static variable in a
1913 // function to force us to keep the enclosing function.
1914 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1915 (Flags & TF_InFunctionScope))
1916 return Flags;
1917
Frederic Rissb9818322015-02-28 00:29:07 +00001918 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001919 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1920
1921 return Flags | TF_Keep;
1922}
1923
1924/// \brief Check if a function describing DIE should be kept.
1925/// \returns updated TraversalFlags.
1926unsigned DwarfLinker::shouldKeepSubprogramDIE(
1927 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1928 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1929 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1930
1931 Flags |= TF_InFunctionScope;
1932
1933 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1934 if (LowPcIdx == -1U)
1935 return Flags;
1936
1937 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1938 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1939 uint32_t LowPcOffset, LowPcEndOffset;
1940 std::tie(LowPcOffset, LowPcEndOffset) =
1941 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1942
1943 uint64_t LowPc =
1944 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1945 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1946 if (LowPc == -1ULL ||
1947 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1948 return Flags;
1949
Frederic Rissb9818322015-02-28 00:29:07 +00001950 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001951 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1952
Frederic Riss1af75f72015-03-12 18:45:10 +00001953 Flags |= TF_Keep;
1954
1955 DWARFFormValue HighPcValue;
1956 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1957 reportWarning("Function without high_pc. Range will be discarded.\n",
1958 &OrigUnit, &DIE);
1959 return Flags;
1960 }
1961
1962 uint64_t HighPc;
1963 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1964 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1965 } else {
1966 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1967 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1968 }
1969
Frederic Riss63786b02015-03-15 20:45:43 +00001970 // Replace the debug map range with a more accurate one.
1971 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00001972 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1973 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001974}
1975
1976/// \brief Check if a DIE should be kept.
1977/// \returns updated TraversalFlags.
1978unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1979 CompileUnit &Unit,
1980 CompileUnit::DIEInfo &MyInfo,
1981 unsigned Flags) {
1982 switch (DIE.getTag()) {
1983 case dwarf::DW_TAG_constant:
1984 case dwarf::DW_TAG_variable:
1985 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1986 case dwarf::DW_TAG_subprogram:
1987 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1988 case dwarf::DW_TAG_module:
1989 case dwarf::DW_TAG_imported_module:
1990 case dwarf::DW_TAG_imported_declaration:
1991 case dwarf::DW_TAG_imported_unit:
1992 // We always want to keep these.
1993 return Flags | TF_Keep;
1994 }
1995
1996 return Flags;
1997}
1998
Frederic Riss84c09a52015-02-13 23:18:34 +00001999/// \brief Mark the passed DIE as well as all the ones it depends on
2000/// as kept.
2001///
2002/// This function is called by lookForDIEsToKeep on DIEs that are
2003/// newly discovered to be needed in the link. It recursively calls
2004/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2005/// TraversalFlags to inform it that it's not doing the primary DIE
2006/// tree walk.
2007void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
2008 CompileUnit::DIEInfo &MyInfo,
2009 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002010 CompileUnit &CU, bool UseODR) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002011 const DWARFUnit &Unit = CU.getOrigUnit();
2012 MyInfo.Keep = true;
2013
2014 // First mark all the parent chain as kept.
2015 unsigned AncestorIdx = MyInfo.ParentIdx;
2016 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002017 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Frederic Riss84c09a52015-02-13 23:18:34 +00002018 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002019 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002020 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2021 }
2022
2023 // Then we need to mark all the DIEs referenced by this DIE's
2024 // attributes as kept.
2025 DataExtractor Data = Unit.getDebugInfoExtractor();
2026 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2027 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2028
2029 // Mark all DIEs referenced through atttributes as kept.
2030 for (const auto &AttrSpec : Abbrev->attributes()) {
2031 DWARFFormValue Val(AttrSpec.Form);
2032
2033 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2034 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2035 continue;
2036 }
2037
2038 Val.extractValue(Data, &Offset, &Unit);
2039 CompileUnit *ReferencedCU;
Frederic Riss1c650942015-07-21 22:41:43 +00002040 if (const auto *RefDIE =
2041 resolveDIEReference(Val, Unit, DIE, ReferencedCU)) {
2042 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2043 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2044 // If the referenced DIE has a DeclContext that has already been
2045 // emitted, then do not keep the one in this CU. We'll link to
2046 // the canonical DIE in cloneDieReferenceAttribute.
2047 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2048 // be necessary and could be advantageously replaced by
2049 // ReferencedCU->hasODR() && CU.hasODR().
2050 // FIXME: compatibility with dsymutil-classic. There is no
2051 // reason not to unique ref_addr references.
2052 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2053 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2054 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2055 continue;
2056
2057 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Frederic Riss84c09a52015-02-13 23:18:34 +00002058 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002059 TF_Keep | TF_DependencyWalk | ODRFlag);
2060 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002061 }
2062}
2063
2064/// \brief Recursively walk the \p DIE tree and look for DIEs to
2065/// keep. Store that information in \p CU's DIEInfo.
2066///
2067/// This function is the entry point of the DIE selection
2068/// algorithm. It is expected to walk the DIE tree in file order and
2069/// (though the mediation of its helper) call hasValidRelocation() on
2070/// each DIE that might be a 'root DIE' (See DwarfLinker class
2071/// comment).
2072/// While walking the dependencies of root DIEs, this function is
2073/// also called, but during these dependency walks the file order is
2074/// not respected. The TF_DependencyWalk flag tells us which kind of
2075/// traversal we are currently doing.
2076void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
2077 const DebugMapObject &DMO, CompileUnit &CU,
2078 unsigned Flags) {
2079 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
2080 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2081 bool AlreadyKept = MyInfo.Keep;
2082
2083 // If the Keep flag is set, we are marking a required DIE's
2084 // dependencies. If our target is already marked as kept, we're all
2085 // set.
2086 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2087 return;
2088
2089 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
2090 // because it would screw up the relocation finding logic.
2091 if (!(Flags & TF_DependencyWalk))
2092 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
2093
2094 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002095 if (!AlreadyKept && (Flags & TF_Keep)) {
2096 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2097 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, UseOdr);
2098 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002099 // The TF_ParentWalk flag tells us that we are currently walking up
2100 // the parent chain of a required DIE, and we don't want to mark all
2101 // the children of the parents as kept (consider for example a
2102 // DW_TAG_namespace node in the parent chain). There are however a
2103 // set of DIE types for which we want to ignore that directive and still
2104 // walk their children.
2105 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
2106 Flags &= ~TF_ParentWalk;
2107
2108 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
2109 return;
2110
2111 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
2112 Child = Child->getSibling())
2113 lookForDIEsToKeep(*Child, DMO, CU, Flags);
2114}
2115
Frederic Rissb8b43d52015-03-04 22:07:44 +00002116/// \brief Assign an abbreviation numer to \p Abbrev.
2117///
2118/// Our DIEs get freed after every DebugMapObject has been processed,
2119/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2120/// the instances hold by the DIEs. When we encounter an abbreviation
2121/// that we don't know, we create a permanent copy of it.
2122void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2123 // Check the set for priors.
2124 FoldingSetNodeID ID;
2125 Abbrev.Profile(ID);
2126 void *InsertToken;
2127 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2128
2129 // If it's newly added.
2130 if (InSet) {
2131 // Assign existing abbreviation number.
2132 Abbrev.setNumber(InSet->getNumber());
2133 } else {
2134 // Add to abbreviation list.
2135 Abbreviations.push_back(
2136 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2137 for (const auto &Attr : Abbrev.getData())
2138 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2139 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2140 // Assign the unique abbreviation number.
2141 Abbrev.setNumber(Abbreviations.size());
2142 Abbreviations.back()->setNumber(Abbreviations.size());
2143 }
2144}
2145
2146/// \brief Clone a string attribute described by \p AttrSpec and add
2147/// it to \p Die.
2148/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00002149unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
2150 const DWARFFormValue &Val,
2151 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002152 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00002153 const char *String = *Val.getAsCString(&U);
2154 unsigned Offset = StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002155 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002156 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002157 return 4;
2158}
2159
2160/// \brief Clone an attribute referencing another DIE and add
2161/// it to \p Die.
2162/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00002163unsigned DwarfLinker::cloneDieReferenceAttribute(
2164 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2165 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002166 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002167 const DWARFUnit &U = Unit.getOrigUnit();
2168 uint32_t Ref = *Val.getAsReference(&U);
Frederic Riss9833de62015-03-06 23:22:53 +00002169 DIE *NewRefDie = nullptr;
2170 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002171 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002172
Frederic Riss1c650942015-07-21 22:41:43 +00002173 const DWARFDebugInfoEntryMinimal *RefDie =
2174 resolveDIEReference(Val, U, InputDIE, RefUnit);
2175
2176 // If the referenced DIE is not found, drop the attribute.
2177 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002178 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002179
2180 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2181 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002182
2183 // If we already have emitted an equivalent DeclContext, just point
2184 // at it.
2185 if (isODRAttribute(AttrSpec.Attr)) {
2186 Ctxt = RefInfo.Ctxt;
2187 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2188 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2189 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2190 dwarf::DW_FORM_ref_addr, Attr);
2191 return getRefAddrSize(U);
2192 }
2193 }
2194
Frederic Riss9833de62015-03-06 23:22:53 +00002195 if (!RefInfo.Clone) {
2196 assert(Ref > InputDIE.getOffset());
2197 // We haven't cloned this DIE yet. Just create an empty one and
2198 // store it. It'll get really cloned when we process it.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002199 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002200 }
2201 NewRefDie = RefInfo.Clone;
2202
Frederic Riss1c650942015-07-21 22:41:43 +00002203 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2204 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002205 // We cannot currently rely on a DIEEntry to emit ref_addr
2206 // references, because the implementation calls back to DwarfDebug
2207 // to find the unit offset. (We don't have a DwarfDebug)
2208 // FIXME: we should be able to design DIEEntry reliance on
2209 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002210 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002211 if (Ref < InputDIE.getOffset()) {
2212 // We must have already cloned that DIE.
2213 uint32_t NewRefOffset =
2214 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002215 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002216 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2217 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002218 } else {
2219 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002220 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002221 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002222 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002223 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2224 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002225 }
Frederic Riss1c650942015-07-21 22:41:43 +00002226 return getRefAddrSize(U);
Frederic Riss9833de62015-03-06 23:22:53 +00002227 }
2228
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002229 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2230 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002231 return AttrSize;
2232}
2233
2234/// \brief Clone an attribute of block form (locations, constants) and add
2235/// it to \p Die.
2236/// \returns the size of the new attribute.
2237unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
2238 const DWARFFormValue &Val,
2239 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002240 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002241 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002242 DIELoc *Loc = nullptr;
2243 DIEBlock *Block = nullptr;
2244 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002245 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002246 Loc = new (DIEAlloc) DIELoc;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002247 DIELocs.push_back(Loc);
2248 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002249 Block = new (DIEAlloc) DIEBlock;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002250 DIEBlocks.push_back(Block);
2251 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002252 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2253 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002254
2255 if (Loc)
2256 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2257 dwarf::Form(AttrSpec.Form), Loc);
2258 else
2259 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2260 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002261 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2262 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002263 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2264 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002265 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2266 // the DIE class, this if could be replaced by
2267 // Attr->setSize(Bytes.size()).
2268 if (Streamer) {
2269 if (Loc)
2270 Loc->ComputeSize(&Streamer->getAsmPrinter());
2271 else
2272 Block->ComputeSize(&Streamer->getAsmPrinter());
2273 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002274 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002275 return AttrSize;
2276}
2277
Frederic Riss31da3242015-03-11 18:45:52 +00002278/// \brief Clone an address attribute and add it to \p Die.
2279/// \returns the size of the new attribute.
2280unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
2281 const DWARFFormValue &Val,
2282 const CompileUnit &Unit,
2283 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002284 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00002285 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2286 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2287 Die.getTag() == dwarf::DW_TAG_lexical_block)
2288 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002289 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2290 Addr = Unit.getLowPc();
2291 if (Addr == UINT64_MAX)
2292 return 0;
2293 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002294 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002295 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002296 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2297 if (uint64_t HighPc = Unit.getHighPc())
2298 Addr = HighPc;
2299 else
2300 return 0;
2301 } else
2302 // If we have a high_pc recorded for the input DIE, use
2303 // it. Otherwise (when no relocations where applied) just use the
2304 // one we just decoded.
2305 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002306 }
2307
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002308 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002309 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002310 return Unit.getOrigUnit().getAddressByteSize();
2311}
2312
Frederic Rissb8b43d52015-03-04 22:07:44 +00002313/// \brief Clone a scalar attribute and add it to \p Die.
2314/// \returns the size of the new attribute.
2315unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00002316 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002317 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002318 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002319 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002320 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2321 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2322 if (Unit.getLowPc() == -1ULL)
2323 return 0;
2324 // Dwarf >= 4 high_pc is an size, not an address.
2325 Value = Unit.getHighPc() - Unit.getLowPc();
2326 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002327 Value = *Val.getAsSectionOffset();
2328 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2329 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002330 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2331 Value = *OptionalValue;
2332 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002333 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
2334 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002335 return 0;
2336 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002337 PatchLocation Patch =
2338 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2339 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002340 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002341 Unit.noteRangeAttribute(Die, Patch);
Frederic Rissdfb97902015-03-14 15:49:07 +00002342 // A more generic way to check for location attributes would be
2343 // nice, but it's very unlikely that any other attribute needs a
2344 // location list.
2345 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2346 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002347 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002348 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2349 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002350
Frederic Rissb8b43d52015-03-04 22:07:44 +00002351 return AttrSize;
2352}
2353
2354/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2355/// value \p Val, and add it to \p Die.
2356/// \returns the size of the cloned attribute.
2357unsigned DwarfLinker::cloneAttribute(DIE &Die,
2358 const DWARFDebugInfoEntryMinimal &InputDIE,
2359 CompileUnit &Unit,
2360 const DWARFFormValue &Val,
2361 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00002362 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002363 const DWARFUnit &U = Unit.getOrigUnit();
2364
2365 switch (AttrSpec.Form) {
2366 case dwarf::DW_FORM_strp:
2367 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002368 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002369 case dwarf::DW_FORM_ref_addr:
2370 case dwarf::DW_FORM_ref1:
2371 case dwarf::DW_FORM_ref2:
2372 case dwarf::DW_FORM_ref4:
2373 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002374 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002375 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002376 case dwarf::DW_FORM_block:
2377 case dwarf::DW_FORM_block1:
2378 case dwarf::DW_FORM_block2:
2379 case dwarf::DW_FORM_block4:
2380 case dwarf::DW_FORM_exprloc:
2381 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2382 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002383 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002384 case dwarf::DW_FORM_data1:
2385 case dwarf::DW_FORM_data2:
2386 case dwarf::DW_FORM_data4:
2387 case dwarf::DW_FORM_data8:
2388 case dwarf::DW_FORM_udata:
2389 case dwarf::DW_FORM_sdata:
2390 case dwarf::DW_FORM_sec_offset:
2391 case dwarf::DW_FORM_flag:
2392 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002393 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2394 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002395 default:
2396 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2397 &InputDIE);
2398 }
2399
2400 return 0;
2401}
2402
Frederic Riss23e20e92015-03-07 01:25:09 +00002403/// \brief Apply the valid relocations found by findValidRelocs() to
2404/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2405/// in the debug_info section.
2406///
2407/// Like for findValidRelocs(), this function must be called with
2408/// monotonic \p BaseOffset values.
2409///
2410/// \returns wether any reloc has been applied.
2411bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2412 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002413 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002414 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2415 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002416 if (NextValidReloc >= ValidRelocs.size())
2417 return false;
2418
2419 // Skip relocs that haven't been applied.
2420 while (NextValidReloc < ValidRelocs.size() &&
2421 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2422 ++NextValidReloc;
2423
2424 bool Applied = false;
2425 uint64_t EndOffset = BaseOffset + Data.size();
2426 while (NextValidReloc < ValidRelocs.size() &&
2427 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2428 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2429 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2430 assert(ValidReloc.Offset - BaseOffset < Data.size());
2431 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2432 char Buf[8];
2433 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2434 Value += ValidReloc.Addend;
2435 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2436 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2437 Buf[i] = uint8_t(Value >> (Index * 8));
2438 }
2439 assert(ValidReloc.Size <= sizeof(Buf));
2440 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2441 Applied = true;
2442 }
2443
2444 return Applied;
2445}
2446
Frederic Rissbce93ff2015-03-16 02:05:10 +00002447static bool isTypeTag(uint16_t Tag) {
2448 switch (Tag) {
2449 case dwarf::DW_TAG_array_type:
2450 case dwarf::DW_TAG_class_type:
2451 case dwarf::DW_TAG_enumeration_type:
2452 case dwarf::DW_TAG_pointer_type:
2453 case dwarf::DW_TAG_reference_type:
2454 case dwarf::DW_TAG_string_type:
2455 case dwarf::DW_TAG_structure_type:
2456 case dwarf::DW_TAG_subroutine_type:
2457 case dwarf::DW_TAG_typedef:
2458 case dwarf::DW_TAG_union_type:
2459 case dwarf::DW_TAG_ptr_to_member_type:
2460 case dwarf::DW_TAG_set_type:
2461 case dwarf::DW_TAG_subrange_type:
2462 case dwarf::DW_TAG_base_type:
2463 case dwarf::DW_TAG_const_type:
2464 case dwarf::DW_TAG_constant:
2465 case dwarf::DW_TAG_file_type:
2466 case dwarf::DW_TAG_namelist:
2467 case dwarf::DW_TAG_packed_type:
2468 case dwarf::DW_TAG_volatile_type:
2469 case dwarf::DW_TAG_restrict_type:
2470 case dwarf::DW_TAG_interface_type:
2471 case dwarf::DW_TAG_unspecified_type:
2472 case dwarf::DW_TAG_shared_type:
2473 return true;
2474 default:
2475 break;
2476 }
2477 return false;
2478}
2479
Frederic Rissb8b43d52015-03-04 22:07:44 +00002480/// \brief Recursively clone \p InputDIE's subtrees that have been
2481/// selected to appear in the linked output.
2482///
2483/// \param OutOffset is the Offset where the newly created DIE will
2484/// lie in the linked compile unit.
2485///
2486/// \returns the cloned DIE object or null if nothing was selected.
2487DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00002488 CompileUnit &Unit, int64_t PCOffset,
2489 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002490 DWARFUnit &U = Unit.getOrigUnit();
2491 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002492 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002493
2494 // Should the DIE appear in the output?
2495 if (!Unit.getInfo(Idx).Keep)
2496 return nullptr;
2497
2498 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002499 // The DIE might have been already created by a forward reference
2500 // (see cloneDieReferenceAttribute()).
2501 DIE *Die = Info.Clone;
2502 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002503 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002504 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002505 Die->setOffset(OutOffset);
Frederic Riss1c650942015-07-21 22:41:43 +00002506 if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2507 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2508 !Info.Ctxt->getCanonicalDIEOffset()) {
2509 // We are about to emit a DIE that is the root of its own valid
2510 // DeclContext tree. Make the current offset the canonical offset
2511 // for this context.
2512 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2513 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002514
2515 // Extract and clone every attribute.
2516 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002517 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002518 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002519
2520 // We could copy the data only if we need to aply a relocation to
2521 // it. After testing, it seems there is no performance downside to
2522 // doing the copy unconditionally, and it makes the code simpler.
2523 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2524 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2525 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00002526 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2527 // If we applied relocations, we store the value of high_pc that was
2528 // potentially stored in the input DIE. If high_pc is an address
2529 // (Dwarf version == 2), then it might have been relocated to a
2530 // totally unrelated value (because the end address in the object
2531 // file might be start address of another function which got moved
2532 // independantly by the linker). The computation of the actual
2533 // high_pc value is done in cloneAddressAttribute().
2534 AttrInfo.OrigHighPc =
2535 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2536 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002537
2538 // Reset the Offset to 0 as we will be working on the local copy of
2539 // the data.
2540 Offset = 0;
2541
Frederic Rissb8b43d52015-03-04 22:07:44 +00002542 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2543 Offset += getULEB128Size(Abbrev->getCode());
2544
Frederic Riss31da3242015-03-11 18:45:52 +00002545 // We are entering a subprogram. Get and propagate the PCOffset.
2546 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2547 PCOffset = Info.AddrAdjust;
2548 AttrInfo.PCOffset = PCOffset;
2549
Frederic Rissb8b43d52015-03-04 22:07:44 +00002550 for (const auto &AttrSpec : Abbrev->attributes()) {
2551 DWARFFormValue Val(AttrSpec.Form);
2552 uint32_t AttrSize = Offset;
2553 Val.extractValue(Data, &Offset, &U);
2554 AttrSize = Offset - AttrSize;
2555
Frederic Riss31da3242015-03-11 18:45:52 +00002556 OutOffset +=
2557 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002558 }
2559
Frederic Rissbce93ff2015-03-16 02:05:10 +00002560 // Look for accelerator entries.
2561 uint16_t Tag = InputDIE.getTag();
2562 // FIXME: This is slightly wrong. An inline_subroutine without a
2563 // low_pc, but with AT_ranges might be interesting to get into the
2564 // accelerator tables too. For now stick with dsymutil's behavior.
2565 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2566 Tag != dwarf::DW_TAG_compile_unit &&
2567 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2568 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2569 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2570 AttrInfo.MangledNameOffset,
2571 Tag == dwarf::DW_TAG_inlined_subroutine);
2572 if (AttrInfo.Name)
2573 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2574 Tag == dwarf::DW_TAG_inlined_subroutine);
2575 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2576 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2577 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2578 }
2579
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002580 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002581 // If a scope DIE is kept, we must have kept at least one child. If
2582 // it's not the case, we'll just be emitting one wasteful end of
2583 // children marker, but things won't break.
2584 if (InputDIE.hasChildren())
2585 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2586 // Assign a permanent abbrev number
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002587 AssignAbbrev(NewAbbrev);
2588 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002589
2590 // Add the size of the abbreviation number to the output offset.
2591 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2592
2593 if (!Abbrev->hasChildren()) {
2594 // Update our size.
2595 Die->setSize(OutOffset - Die->getOffset());
2596 return Die;
2597 }
2598
2599 // Recursively clone children.
2600 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2601 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00002602 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002603 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002604 OutOffset = Clone->getOffset() + Clone->getSize();
2605 }
2606 }
2607
2608 // Account for the end of children marker.
2609 OutOffset += sizeof(int8_t);
2610 // Update our size.
2611 Die->setSize(OutOffset - Die->getOffset());
2612 return Die;
2613}
2614
Frederic Riss25440872015-03-13 23:30:31 +00002615/// \brief Patch the input object file relevant debug_ranges entries
2616/// and emit them in the output file. Update the relevant attributes
2617/// to point at the new entries.
2618void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2619 DWARFContext &OrigDwarf) const {
2620 DWARFDebugRangeList RangeList;
2621 const auto &FunctionRanges = Unit.getFunctionRanges();
2622 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2623 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2624 OrigDwarf.isLittleEndian(), AddressSize);
2625 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2626 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002627 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002628 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2629 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2630 // Ranges addresses are based on the unit's low_pc. Compute the
2631 // offset we need to apply to adapt to the the new unit's low_pc.
2632 int64_t UnitPcOffset = 0;
2633 if (OrigLowPc != -1ULL)
2634 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2635
2636 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002637 uint32_t Offset = RangeAttribute.get();
2638 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002639 RangeList.extract(RangeExtractor, &Offset);
2640 const auto &Entries = RangeList.getEntries();
2641 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2642
2643 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2644 First.StartAddress >= CurrRange.stop()) {
2645 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2646 if (CurrRange == InvalidRange ||
2647 CurrRange.start() > First.StartAddress + OrigLowPc) {
2648 reportWarning("no mapping for range.");
2649 continue;
2650 }
2651 }
2652
2653 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2654 AddressSize);
2655 }
2656}
2657
Frederic Riss563b1b02015-03-14 03:46:51 +00002658/// \brief Generate the debug_aranges entries for \p Unit and if the
2659/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2660/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002661/// FIXME: this could actually be done right in patchRangesForUnit,
2662/// but for the sake of initial bit-for-bit compatibility with legacy
2663/// dsymutil, we have to do it in a delayed pass.
2664void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002665 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002666 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002667 Attr->set(Streamer->getRangesSectionSize());
2668 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002669}
2670
Frederic Riss63786b02015-03-15 20:45:43 +00002671/// \brief Insert the new line info sequence \p Seq into the current
2672/// set of already linked line info \p Rows.
2673static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2674 std::vector<DWARFDebugLine::Row> &Rows) {
2675 if (Seq.empty())
2676 return;
2677
2678 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2679 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2680 Seq.clear();
2681 return;
2682 }
2683
2684 auto InsertPoint = std::lower_bound(
2685 Rows.begin(), Rows.end(), Seq.front(),
2686 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2687 return LHS.Address < RHS.Address;
2688 });
2689
2690 // FIXME: this only removes the unneeded end_sequence if the
2691 // sequences have been inserted in order. using a global sort like
2692 // described in patchLineTableForUnit() and delaying the end_sequene
2693 // elimination to emitLineTableForUnit() we can get rid of all of them.
2694 if (InsertPoint != Rows.end() &&
2695 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2696 *InsertPoint = Seq.front();
2697 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2698 } else {
2699 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2700 }
2701
2702 Seq.clear();
2703}
2704
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002705static void patchStmtList(DIE &Die, DIEInteger Offset) {
2706 for (auto &V : Die.values())
2707 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002708 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002709 return;
2710 }
2711
2712 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2713}
2714
Frederic Riss63786b02015-03-15 20:45:43 +00002715/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2716/// recreate a relocated version of these for the address ranges that
2717/// are present in the binary.
2718void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2719 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002720 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002721 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2722 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2723 if (StmtList == -1ULL)
2724 return;
2725
2726 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002727 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2728 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002729
2730 // Parse the original line info for the unit.
2731 DWARFDebugLine::LineTable LineTable;
2732 uint32_t StmtOffset = StmtList;
2733 StringRef LineData = OrigDwarf.getLineSection().Data;
2734 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2735 Unit.getOrigUnit().getAddressByteSize());
2736 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2737 &StmtOffset);
2738
2739 // This vector is the output line table.
2740 std::vector<DWARFDebugLine::Row> NewRows;
2741 NewRows.reserve(LineTable.Rows.size());
2742
2743 // Current sequence of rows being extracted, before being inserted
2744 // in NewRows.
2745 std::vector<DWARFDebugLine::Row> Seq;
2746 const auto &FunctionRanges = Unit.getFunctionRanges();
2747 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2748
2749 // FIXME: This logic is meant to generate exactly the same output as
2750 // Darwin's classic dsynutil. There is a nicer way to implement this
2751 // by simply putting all the relocated line info in NewRows and simply
2752 // sorting NewRows before passing it to emitLineTableForUnit. This
2753 // should be correct as sequences for a function should stay
2754 // together in the sorted output. There are a few corner cases that
2755 // look suspicious though, and that required to implement the logic
2756 // this way. Revisit that once initial validation is finished.
2757
2758 // Iterate over the object file line info and extract the sequences
2759 // that correspond to linked functions.
2760 for (auto &Row : LineTable.Rows) {
2761 // Check wether we stepped out of the range. The range is
2762 // half-open, but consider accept the end address of the range if
2763 // it is marked as end_sequence in the input (because in that
2764 // case, the relocation offset is accurate and that entry won't
2765 // serve as the start of another function).
2766 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2767 Row.Address > CurrRange.stop() ||
2768 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2769 // We just stepped out of a known range. Insert a end_sequence
2770 // corresponding to the end of the range.
2771 uint64_t StopAddress = CurrRange != InvalidRange
2772 ? CurrRange.stop() + CurrRange.value()
2773 : -1ULL;
2774 CurrRange = FunctionRanges.find(Row.Address);
2775 bool CurrRangeValid =
2776 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2777 if (!CurrRangeValid) {
2778 CurrRange = InvalidRange;
2779 if (StopAddress != -1ULL) {
2780 // Try harder by looking in the DebugMapObject function
2781 // ranges map. There are corner cases where this finds a
2782 // valid entry. It's unclear if this is right or wrong, but
2783 // for now do as dsymutil.
2784 // FIXME: Understand exactly what cases this addresses and
2785 // potentially remove it along with the Ranges map.
2786 auto Range = Ranges.lower_bound(Row.Address);
2787 if (Range != Ranges.begin() && Range != Ranges.end())
2788 --Range;
2789
2790 if (Range != Ranges.end() && Range->first <= Row.Address &&
2791 Range->second.first >= Row.Address) {
2792 StopAddress = Row.Address + Range->second.second;
2793 }
2794 }
2795 }
2796 if (StopAddress != -1ULL && !Seq.empty()) {
2797 // Insert end sequence row with the computed end address, but
2798 // the same line as the previous one.
Yaron Kerene3c07062015-08-10 16:15:51 +00002799 auto NextLine = Seq.back();
Yaron Keren2ad3b332015-08-10 18:27:51 +00002800 NextLine.Address = StopAddress;
2801 NextLine.EndSequence = 1;
2802 NextLine.PrologueEnd = 0;
2803 NextLine.BasicBlock = 0;
2804 NextLine.EpilogueBegin = 0;
Yaron Kerenf850d982015-08-10 18:03:35 +00002805 Seq.push_back(NextLine);
Frederic Riss63786b02015-03-15 20:45:43 +00002806 insertLineSequence(Seq, NewRows);
2807 }
2808
2809 if (!CurrRangeValid)
2810 continue;
2811 }
2812
2813 // Ignore empty sequences.
2814 if (Row.EndSequence && Seq.empty())
2815 continue;
2816
2817 // Relocate row address and add it to the current sequence.
2818 Row.Address += CurrRange.value();
2819 Seq.emplace_back(Row);
2820
2821 if (Row.EndSequence)
2822 insertLineSequence(Seq, NewRows);
2823 }
2824
2825 // Finished extracting, now emit the line tables.
2826 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2827 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2828 // prologue over and that works because we act as both producer and
2829 // consumer. It would be nicer to have a real configurable line
2830 // table emitter.
2831 if (LineTable.Prologue.Version != 2 ||
2832 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00002833 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00002834 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00002835 else {
2836 MCDwarfLineTableParams Params;
2837 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
2838 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
2839 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
2840 Streamer->emitLineTableForUnit(Params,
2841 LineData.slice(StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00002842 LineTable.Prologue.MinInstLength, NewRows,
2843 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00002844 }
Frederic Riss63786b02015-03-15 20:45:43 +00002845}
2846
Frederic Rissbce93ff2015-03-16 02:05:10 +00002847void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2848 Streamer->emitPubNamesForUnit(Unit);
2849 Streamer->emitPubTypesForUnit(Unit);
2850}
2851
Frederic Riss5a642072015-06-05 23:06:11 +00002852/// \brief Read the frame info stored in the object, and emit the
2853/// patched frame descriptions for the linked binary.
2854///
2855/// This is actually pretty easy as the data of the CIEs and FDEs can
2856/// be considered as black boxes and moved as is. The only thing to do
2857/// is to patch the addresses in the headers.
2858void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2859 DWARFContext &OrigDwarf,
2860 unsigned AddrSize) {
2861 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2862 if (FrameData.empty())
2863 return;
2864
2865 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2866 uint32_t InputOffset = 0;
2867
2868 // Store the data of the CIEs defined in this object, keyed by their
2869 // offsets.
2870 DenseMap<uint32_t, StringRef> LocalCIES;
2871
2872 while (Data.isValidOffset(InputOffset)) {
2873 uint32_t EntryOffset = InputOffset;
2874 uint32_t InitialLength = Data.getU32(&InputOffset);
2875 if (InitialLength == 0xFFFFFFFF)
2876 return reportWarning("Dwarf64 bits no supported");
2877
2878 uint32_t CIEId = Data.getU32(&InputOffset);
2879 if (CIEId == 0xFFFFFFFF) {
2880 // This is a CIE, store it.
2881 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2882 LocalCIES[EntryOffset] = CIEData;
2883 // The -4 is to account for the CIEId we just read.
2884 InputOffset += InitialLength - 4;
2885 continue;
2886 }
2887
2888 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2889
2890 // Some compilers seem to emit frame info that doesn't start at
2891 // the function entry point, thus we can't just lookup the address
2892 // in the debug map. Use the linker's range map to see if the FDE
2893 // describes something that we can relocate.
2894 auto Range = Ranges.upper_bound(Loc);
2895 if (Range != Ranges.begin())
2896 --Range;
2897 if (Range == Ranges.end() || Range->first > Loc ||
2898 Range->second.first <= Loc) {
2899 // The +4 is to account for the size of the InitialLength field itself.
2900 InputOffset = EntryOffset + InitialLength + 4;
2901 continue;
2902 }
2903
2904 // This is an FDE, and we have a mapping.
2905 // Have we already emitted a corresponding CIE?
2906 StringRef CIEData = LocalCIES[CIEId];
2907 if (CIEData.empty())
2908 return reportWarning("Inconsistent debug_frame content. Dropping.");
2909
2910 // Look if we already emitted a CIE that corresponds to the
2911 // referenced one (the CIE data is the key of that lookup).
2912 auto IteratorInserted = EmittedCIEs.insert(
2913 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2914 // If there is no CIE yet for this ID, emit it.
2915 if (IteratorInserted.second ||
2916 // FIXME: dsymutil-classic only caches the last used CIE for
2917 // reuse. Mimic that behavior for now. Just removing that
2918 // second half of the condition and the LastCIEOffset variable
2919 // makes the code DTRT.
2920 LastCIEOffset != IteratorInserted.first->getValue()) {
2921 LastCIEOffset = Streamer->getFrameSectionSize();
2922 IteratorInserted.first->getValue() = LastCIEOffset;
2923 Streamer->emitCIE(CIEData);
2924 }
2925
2926 // Emit the FDE with updated address and CIE pointer.
2927 // (4 + AddrSize) is the size of the CIEId + initial_location
2928 // fields that will get reconstructed by emitFDE().
2929 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
2930 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
2931 Loc + Range->second.second,
2932 FrameData.substr(InputOffset, FDERemainingBytes));
2933 InputOffset += FDERemainingBytes;
2934 }
2935}
2936
Frederic Risseb85c8f2015-07-24 06:41:11 +00002937ErrorOr<const object::ObjectFile &>
2938DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
2939 const DebugMap &Map) {
2940 auto ErrOrObjs =
2941 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
2942 if (std::error_code EC = ErrOrObjs.getError())
2943 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
2944 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
2945 if (std::error_code EC = ErrOrObj.getError())
2946 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
2947 return ErrOrObj;
2948}
2949
Frederic Rissd3455182015-01-28 18:27:01 +00002950bool DwarfLinker::link(const DebugMap &Map) {
2951
Frederic Rissc99ea202015-02-28 00:29:11 +00002952 if (!createStreamer(Map.getTriple(), OutputFilename))
2953 return false;
2954
Frederic Rissb8b43d52015-03-04 22:07:44 +00002955 // Size of the DIEs (and headers) generated for the linked output.
2956 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00002957 // A unique ID that identifies each compile unit.
2958 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00002959 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002960 CurrentDebugObject = Obj.get();
2961
Frederic Rissb9818322015-02-28 00:29:07 +00002962 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00002963 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00002964 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
2965 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00002966 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00002967
Frederic Riss1036e642015-02-13 23:18:22 +00002968 // Look for relocations that correspond to debug map entries.
2969 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00002970 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00002971 outs() << "No valid relocations found. Skipping.\n";
2972 continue;
2973 }
2974
Frederic Riss563cba62015-01-28 22:15:14 +00002975 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00002976 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00002977 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00002978
Frederic Riss563cba62015-01-28 22:15:14 +00002979 // In a first phase, just read in the debug info and store the DIE
2980 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00002981 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002982 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00002983 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00002984 outs() << "Input compilation unit:";
2985 CUDie->dump(outs(), CU.get(), 0);
2986 }
Frederic Riss1c650942015-07-21 22:41:43 +00002987 Units.emplace_back(*CU, UnitID++, !Options.NoODR);
2988 gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
2989 StringPool, ODRContexts);
Frederic Rissd3455182015-01-28 18:27:01 +00002990 }
Frederic Riss563cba62015-01-28 22:15:14 +00002991
Frederic Riss84c09a52015-02-13 23:18:34 +00002992 // Then mark all the DIEs that need to be present in the linked
2993 // output and collect some information about them. Note that this
2994 // loop can not be merged with the previous one becaue cross-cu
2995 // references require the ParentIdx to be setup for every CU in
2996 // the object file before calling this.
2997 for (auto &CurrentUnit : Units)
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002998 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00002999 CurrentUnit, 0);
3000
Frederic Riss23e20e92015-03-07 01:25:09 +00003001 // The calls to applyValidRelocs inside cloneDIE will walk the
3002 // reloc array again (in the same way findValidRelocsInDebugInfo()
3003 // did). We need to reset the NextValidReloc index to the beginning.
3004 NextValidReloc = 0;
3005
Frederic Rissb8b43d52015-03-04 22:07:44 +00003006 // Construct the output DIE tree by cloning the DIEs we chose to
3007 // keep above. If there are no valid relocs, then there's nothing
3008 // to clone/emit.
3009 if (!ValidRelocs.empty())
3010 for (auto &CurrentUnit : Units) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003011 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00003012 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00003013 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
3014 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00003015 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00003016 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00003017 if (Options.NoOutput)
3018 continue;
3019 // FIXME: for compatibility with the classic dsymutil, we emit
3020 // an empty line table for the unit, even if the unit doesn't
3021 // actually exist in the DIE tree.
3022 patchLineTableForUnit(CurrentUnit, DwarfContext);
3023 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00003024 continue;
3025 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00003026 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissbce93ff2015-03-16 02:05:10 +00003027 emitAcceleratorEntriesForUnit(CurrentUnit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00003028 }
3029
3030 // Emit all the compile unit's debug information.
3031 if (!ValidRelocs.empty() && !Options.NoOutput)
3032 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00003033 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00003034 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00003035 Streamer->emitCompileUnitHeader(CurrentUnit);
3036 if (!CurrentUnit.getOutputUnitDIE())
3037 continue;
3038 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
3039 }
3040
Frederic Riss5a642072015-06-05 23:06:11 +00003041 if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
3042 patchFrameInfoForObject(*Obj, DwarfContext,
3043 Units[0].getOrigUnit().getAddressByteSize());
3044
Frederic Riss563cba62015-01-28 22:15:14 +00003045 // Clean-up before starting working on the next object.
3046 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003047 }
3048
Frederic Rissb8b43d52015-03-04 22:07:44 +00003049 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003050 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003051 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003052 Streamer->emitStrings(StringPool);
3053 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003054
Frederic Rissc99ea202015-02-28 00:29:11 +00003055 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00003056}
3057}
Frederic Rissd3455182015-01-28 18:27:01 +00003058
Frederic Riss30711fb2015-08-26 05:09:52 +00003059/// \brief Get the offset of string \p S in the string table. This
3060/// can insert a new element or return the offset of a preexisitng
3061/// one.
3062uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
3063 if (S.empty() && !Strings.empty())
3064 return 0;
3065
3066 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3067 MapTy::iterator It;
3068 bool Inserted;
3069
3070 // A non-empty string can't be at offset 0, so if we have an entry
3071 // with a 0 offset, it must be a previously interned string.
3072 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
3073 if (Inserted || It->getValue().first == 0) {
3074 // Set offset and chain at the end of the entries list.
3075 It->getValue().first = CurrentEndOffset;
3076 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
3077 Last->getValue().second = &*It;
3078 Last = &*It;
3079 }
3080 return It->getValue().first;
3081}
3082
3083/// \brief Put \p S into the StringMap so that it gets permanent
3084/// storage, but do not actually link it in the chain of elements
3085/// that go into the output section. A latter call to
3086/// getStringOffset() with the same string will chain it though.
3087StringRef NonRelocatableStringpool::internString(StringRef S) {
3088 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
3089 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
3090 return InsertResult.first->getKey();
3091}
3092
Frederic Rissb9818322015-02-28 00:29:07 +00003093bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3094 const LinkOptions &Options) {
3095 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003096 return Linker.link(DM);
3097}
3098}
Frederic Riss231f7142014-12-12 17:31:24 +00003099}