blob: d839f07657baaf39890d693ffac511d966cfc674 [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 Riss1af75f72015-03-12 18:45:10 +000013#include "llvm/ADT/IntervalMap.h"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000014#include "llvm/ADT/StringMap.h"
15#include "llvm/ADT/STLExtras.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000016#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000017#include "llvm/CodeGen/DIE.h"
Frederic Riss1c650942015-07-21 22:41:43 +000018#include "llvm/Config/config.h"
Zachary Turner82af9432015-01-30 18:07:45 +000019#include "llvm/DebugInfo/DWARF/DWARFContext.h"
20#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000021#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000022#include "llvm/MC/MCAsmBackend.h"
23#include "llvm/MC/MCAsmInfo.h"
24#include "llvm/MC/MCContext.h"
25#include "llvm/MC/MCCodeEmitter.h"
Frederic Riss63786b02015-03-15 20:45:43 +000026#include "llvm/MC/MCDwarf.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000027#include "llvm/MC/MCInstrInfo.h"
28#include "llvm/MC/MCObjectFileInfo.h"
29#include "llvm/MC/MCRegisterInfo.h"
30#include "llvm/MC/MCStreamer.h"
Pete Cooper81902a32015-05-15 22:19:42 +000031#include "llvm/MC/MCSubtargetInfo.h"
Frederic Riss1036e642015-02-13 23:18:22 +000032#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000033#include "llvm/Support/Dwarf.h"
34#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000035#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000038#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000039#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000040
41namespace llvm {
42namespace dsymutil {
43
Frederic Rissd3455182015-01-28 18:27:01 +000044namespace {
45
Frederic Rissdef4fb72015-02-28 00:29:01 +000046void warn(const Twine &Warning, const Twine &Context) {
47 errs() << Twine("while processing ") + Context + ":\n";
48 errs() << Twine("warning: ") + Warning + "\n";
49}
50
Frederic Rissc99ea202015-02-28 00:29:11 +000051bool error(const Twine &Error, const Twine &Context) {
52 errs() << Twine("while processing ") + Context + ":\n";
53 errs() << Twine("error: ") + Error + "\n";
54 return false;
55}
56
Frederic Riss1af75f72015-03-12 18:45:10 +000057template <typename KeyT, typename ValT>
58using HalfOpenIntervalMap =
59 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
60 IntervalMapHalfOpenInfo<KeyT>>;
61
Frederic Riss25440872015-03-13 23:30:31 +000062typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
63
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000064// FIXME: Delete this structure.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000065struct PatchLocation {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000066 DIE::value_iterator I;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000067
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000068 PatchLocation() = default;
69 PatchLocation(DIE::value_iterator I) : I(I) {}
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000070
71 void set(uint64_t New) const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000072 assert(I);
73 const auto &Old = *I;
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000074 assert(Old.getType() == DIEValue::isInteger);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000075 *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000076 }
77
78 uint64_t get() const {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +000079 assert(I);
80 return I->getDIEInteger().getValue();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000081 }
82};
83
Frederic Riss1c650942015-07-21 22:41:43 +000084class CompileUnit;
85struct DeclMapInfo;
86class NonRelocatableStringpool;
87
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 Rissef648462015-03-06 17:56:30 +0000447/// \brief A string table that doesn't need relocations.
448///
449/// We are doing a final link, no need for a string table that
450/// has relocation entries for every reference to it. This class
451/// provides this ablitity by just associating offsets with
452/// strings.
453class NonRelocatableStringpool {
454public:
455 /// \brief Entries are stored into the StringMap and simply linked
456 /// together through the second element of this pair in order to
457 /// keep track of insertion order.
458 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
459 MapTy;
460
461 NonRelocatableStringpool()
462 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
463 // Legacy dsymutil puts an empty string at the start of the line
464 // table.
465 getStringOffset("");
466 }
467
468 /// \brief Get the offset of string \p S in the string table. This
469 /// can insert a new element or return the offset of a preexisitng
470 /// one.
471 uint32_t getStringOffset(StringRef S);
472
Frederic Riss1c650942015-07-21 22:41:43 +0000473 /// \brief Get permanent storage for \p S (but do not necessarily
474 /// emit \p S in the output section).
475 /// \returns The StringRef that points to permanent storage to use
476 /// in place of \p S.
477 StringRef internString(StringRef S);
478
Frederic Rissef648462015-03-06 17:56:30 +0000479 // \brief Return the first entry of the string table.
480 const MapTy::MapEntryTy *getFirstEntry() const {
481 return getNextEntry(&Sentinel);
482 }
483
484 // \brief Get the entry following \p E in the string table or null
485 // if \p E was the last entry.
486 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
487 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
488 }
489
490 uint64_t getSize() { return CurrentEndOffset; }
491
492private:
493 MapTy Strings;
494 uint32_t CurrentEndOffset;
495 MapTy::MapEntryTy Sentinel, *Last;
496};
497
498/// \brief Get the offset of string \p S in the string table. This
499/// can insert a new element or return the offset of a preexisitng
500/// one.
501uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
502 if (S.empty() && !Strings.empty())
503 return 0;
504
505 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
506 MapTy::iterator It;
507 bool Inserted;
508
509 // A non-empty string can't be at offset 0, so if we have an entry
510 // with a 0 offset, it must be a previously interned string.
511 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
512 if (Inserted || It->getValue().first == 0) {
513 // Set offset and chain at the end of the entries list.
514 It->getValue().first = CurrentEndOffset;
515 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
516 Last->getValue().second = &*It;
517 Last = &*It;
518 }
519 return It->getValue().first;
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000520}
Frederic Rissef648462015-03-06 17:56:30 +0000521
Frederic Riss1c650942015-07-21 22:41:43 +0000522/// \brief Put \p S into the StringMap so that it gets permanent
523/// storage, but do not actually link it in the chain of elements
524/// that go into the output section. A latter call to
525/// getStringOffset() with the same string will chain it though.
526StringRef NonRelocatableStringpool::internString(StringRef S) {
527 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
528 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
529 return InsertResult.first->getKey();
Benjamin Kramer55dd48c2015-07-22 11:54:19 +0000530}
Frederic Riss1c650942015-07-21 22:41:43 +0000531
Frederic Rissc99ea202015-02-28 00:29:11 +0000532/// \brief The Dwarf streaming logic
533///
534/// All interactions with the MC layer that is used to build the debug
535/// information binary representation are handled in this class.
536class DwarfStreamer {
537 /// \defgroup MCObjects MC layer objects constructed by the streamer
538 /// @{
539 std::unique_ptr<MCRegisterInfo> MRI;
540 std::unique_ptr<MCAsmInfo> MAI;
541 std::unique_ptr<MCObjectFileInfo> MOFI;
542 std::unique_ptr<MCContext> MC;
543 MCAsmBackend *MAB; // Owned by MCStreamer
544 std::unique_ptr<MCInstrInfo> MII;
545 std::unique_ptr<MCSubtargetInfo> MSTI;
546 MCCodeEmitter *MCE; // Owned by MCStreamer
547 MCStreamer *MS; // Owned by AsmPrinter
548 std::unique_ptr<TargetMachine> TM;
549 std::unique_ptr<AsmPrinter> Asm;
550 /// @}
551
552 /// \brief the file we stream the linked Dwarf to.
553 std::unique_ptr<raw_fd_ostream> OutFile;
554
Frederic Riss25440872015-03-13 23:30:31 +0000555 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000556 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000557 uint32_t LineSectionSize;
Frederic Riss5a642072015-06-05 23:06:11 +0000558 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000559
Frederic Rissbce93ff2015-03-16 02:05:10 +0000560 /// \brief Emit the pubnames or pubtypes section contribution for \p
561 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000562 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000563 const CompileUnit &Unit,
564 const std::vector<CompileUnit::AccelInfo> &Names);
565
Frederic Rissc99ea202015-02-28 00:29:11 +0000566public:
567 /// \brief Actually create the streamer and the ouptut file.
568 ///
569 /// This could be done directly in the constructor, but it feels
570 /// more natural to handle errors through return value.
571 bool init(Triple TheTriple, StringRef OutputFilename);
572
Frederic Rissb8b43d52015-03-04 22:07:44 +0000573 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000574 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000575
576 AsmPrinter &getAsmPrinter() const { return *Asm; }
577
578 /// \brief Set the current output section to debug_info and change
579 /// the MC Dwarf version to \p DwarfVersion.
580 void switchToDebugInfoSection(unsigned DwarfVersion);
581
582 /// \brief Emit the compilation unit header for \p Unit in the
583 /// debug_info section.
584 ///
585 /// As a side effect, this also switches the current Dwarf version
586 /// of the MC layer to the one of U.getOrigUnit().
587 void emitCompileUnitHeader(CompileUnit &Unit);
588
589 /// \brief Recursively emit the DIE tree rooted at \p Die.
590 void emitDIE(DIE &Die);
591
592 /// \brief Emit the abbreviation table \p Abbrevs to the
593 /// debug_abbrev section.
594 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000595
596 /// \brief Emit the string table described by \p Pool.
597 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000598
599 /// \brief Emit debug_ranges for \p FuncRange by translating the
600 /// original \p Entries.
601 void emitRangesEntries(
602 int64_t UnitPcOffset, uint64_t OrigLowPc,
603 FunctionIntervals::const_iterator FuncRange,
604 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
605 unsigned AddressSize);
606
Frederic Riss563b1b02015-03-14 03:46:51 +0000607 /// \brief Emit debug_aranges entries for \p Unit and if \p
608 /// DoRangesSection is true, also emit the debug_ranges entries for
609 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
610 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000611
612 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000613
614 /// \brief Emit the debug_loc contribution for \p Unit by copying
615 /// the entries from \p Dwarf and offseting them. Update the
616 /// location attributes to point to the new entries.
617 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000618
619 /// \brief Emit the line table described in \p Rows into the
620 /// debug_line section.
Frederic Rissa5e14532015-08-07 15:14:13 +0000621 void emitLineTableForUnit(MCDwarfLineTableParams Params,
622 StringRef PrologueBytes, unsigned MinInstLength,
Frederic Riss63786b02015-03-15 20:45:43 +0000623 std::vector<DWARFDebugLine::Row> &Rows,
624 unsigned AdddressSize);
625
626 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000627
628 /// \brief Emit the .debug_pubnames contribution for \p Unit.
629 void emitPubNamesForUnit(const CompileUnit &Unit);
630
631 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
632 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000633
634 /// \brief Emit a CIE.
635 void emitCIE(StringRef CIEBytes);
636
637 /// \brief Emit an FDE with data \p Bytes.
638 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
639 StringRef Bytes);
640
641 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000642};
643
644bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
645 std::string ErrorStr;
646 std::string TripleName;
647 StringRef Context = "dwarf streamer init";
648
649 // Get the target.
650 const Target *TheTarget =
651 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
652 if (!TheTarget)
653 return error(ErrorStr, Context);
654 TripleName = TheTriple.getTriple();
655
656 // Create all the MC Objects.
657 MRI.reset(TheTarget->createMCRegInfo(TripleName));
658 if (!MRI)
659 return error(Twine("no register info for target ") + TripleName, Context);
660
661 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
662 if (!MAI)
663 return error("no asm info for target " + TripleName, Context);
664
665 MOFI.reset(new MCObjectFileInfo);
666 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000667 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
Frederic Rissc99ea202015-02-28 00:29:11 +0000668 *MC);
669
670 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
671 if (!MAB)
672 return error("no asm backend for target " + TripleName, Context);
673
674 MII.reset(TheTarget->createMCInstrInfo());
675 if (!MII)
676 return error("no instr info info for target " + TripleName, Context);
677
678 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
679 if (!MSTI)
680 return error("no subtarget info for target " + TripleName, Context);
681
Eric Christopher0169e422015-03-10 22:03:14 +0000682 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000683 if (!MCE)
684 return error("no code emitter for target " + TripleName, Context);
685
686 // Create the output file.
687 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000688 OutFile =
689 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000690 if (EC)
691 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
692
Rafael Espindolaf696df12015-03-16 22:29:29 +0000693 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000694 *MSTI, false,
695 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000696 if (!MS)
697 return error("no object streamer for target " + TripleName, Context);
698
699 // Finally create the AsmPrinter we'll use to emit the DIEs.
700 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
701 if (!TM)
702 return error("no target machine for target " + TripleName, Context);
703
704 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
705 if (!Asm)
706 return error("no asm printer for target " + TripleName, Context);
707
Frederic Riss25440872015-03-13 23:30:31 +0000708 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000709 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000710 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000711 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000712
Frederic Rissc99ea202015-02-28 00:29:11 +0000713 return true;
714}
715
716bool DwarfStreamer::finish() {
717 MS->Finish();
718 return true;
719}
720
Frederic Rissb8b43d52015-03-04 22:07:44 +0000721/// \brief Set the current output section to debug_info and change
722/// the MC Dwarf version to \p DwarfVersion.
723void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
724 MS->SwitchSection(MOFI->getDwarfInfoSection());
725 MC->setDwarfVersion(DwarfVersion);
726}
727
728/// \brief Emit the compilation unit header for \p Unit in the
729/// debug_info section.
730///
731/// A Dwarf scetion header is encoded as:
732/// uint32_t Unit length (omiting this field)
733/// uint16_t Version
734/// uint32_t Abbreviation table offset
735/// uint8_t Address size
736///
737/// Leading to a total of 11 bytes.
738void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
739 unsigned Version = Unit.getOrigUnit().getVersion();
740 switchToDebugInfoSection(Version);
741
742 // Emit size of content not including length itself. The size has
743 // already been computed in CompileUnit::computeOffsets(). Substract
744 // 4 to that size to account for the length field.
745 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
746 Asm->EmitInt16(Version);
747 // We share one abbreviations table across all units so it's always at the
748 // start of the section.
749 Asm->EmitInt32(0);
750 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
751}
752
753/// \brief Emit the \p Abbrevs array as the shared abbreviation table
754/// for the linked Dwarf file.
755void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
756 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
757 Asm->emitDwarfAbbrevs(Abbrevs);
758}
759
760/// \brief Recursively emit the DIE tree rooted at \p Die.
761void DwarfStreamer::emitDIE(DIE &Die) {
762 MS->SwitchSection(MOFI->getDwarfInfoSection());
763 Asm->emitDwarfDIE(Die);
764}
765
Frederic Rissef648462015-03-06 17:56:30 +0000766/// \brief Emit the debug_str section stored in \p Pool.
767void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000768 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000769 for (auto *Entry = Pool.getFirstEntry(); Entry;
770 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000771 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000772 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
773}
774
Frederic Riss25440872015-03-13 23:30:31 +0000775/// \brief Emit the debug_range section contents for \p FuncRange by
776/// translating the original \p Entries. The debug_range section
777/// format is totally trivial, consisting just of pairs of address
778/// sized addresses describing the ranges.
779void DwarfStreamer::emitRangesEntries(
780 int64_t UnitPcOffset, uint64_t OrigLowPc,
781 FunctionIntervals::const_iterator FuncRange,
782 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
783 unsigned AddressSize) {
784 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
785
786 // Offset each range by the right amount.
787 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
788 for (const auto &Range : Entries) {
789 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
790 warn("unsupported base address selection operation",
791 "emitting debug_ranges");
792 break;
793 }
794 // Do not emit empty ranges.
795 if (Range.StartAddress == Range.EndAddress)
796 continue;
797
798 // All range entries should lie in the function range.
799 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
800 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
801 warn("inconsistent range data.", "emitting debug_ranges");
802 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
803 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
804 RangesSectionSize += 2 * AddressSize;
805 }
806
807 // Add the terminator entry.
808 MS->EmitIntValue(0, AddressSize);
809 MS->EmitIntValue(0, AddressSize);
810 RangesSectionSize += 2 * AddressSize;
811}
812
Frederic Riss563b1b02015-03-14 03:46:51 +0000813/// \brief Emit the debug_aranges contribution of a unit and
814/// if \p DoDebugRanges is true the debug_range contents for a
815/// compile_unit level DW_AT_ranges attribute (Which are basically the
816/// same thing with a different base address).
817/// Just aggregate all the ranges gathered inside that unit.
818void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
819 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000820 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
821 // Gather the ranges in a vector, so that we can simplify them. The
822 // IntervalMap will have coalesced the non-linked ranges, but here
823 // we want to coalesce the linked addresses.
824 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
825 const auto &FunctionRanges = Unit.getFunctionRanges();
826 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
827 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000828 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
829 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000830
831 // The object addresses where sorted, but again, the linked
832 // addresses might end up in a different order.
833 std::sort(Ranges.begin(), Ranges.end());
834
Frederic Riss563b1b02015-03-14 03:46:51 +0000835 if (!Ranges.empty()) {
836 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
837
Rafael Espindola9ab09232015-03-17 20:07:06 +0000838 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
839 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000840
841 unsigned HeaderSize =
842 sizeof(int32_t) + // Size of contents (w/o this field
843 sizeof(int16_t) + // DWARF ARange version number
844 sizeof(int32_t) + // Offset of CU in the .debug_info section
845 sizeof(int8_t) + // Pointer Size (in bytes)
846 sizeof(int8_t); // Segment Size (in bytes)
847
848 unsigned TupleSize = AddressSize * 2;
849 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
850
851 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000852 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000853 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
854 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
855 Asm->EmitInt8(AddressSize); // Address size
856 Asm->EmitInt8(0); // Segment size
857
Lang Hames9ff69c82015-04-24 19:11:51 +0000858 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000859
860 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
861 ++Range) {
862 uint64_t RangeStart = Range->first;
863 MS->EmitIntValue(RangeStart, AddressSize);
864 while ((Range + 1) != End && Range->second == (Range + 1)->first)
865 ++Range;
866 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
867 }
868
869 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000870 Asm->OutStreamer->EmitIntValue(0, AddressSize);
871 Asm->OutStreamer->EmitIntValue(0, AddressSize);
872 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000873 }
874
875 if (!DoDebugRanges)
876 return;
877
878 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
879 // Offset each range by the right amount.
880 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000881 // Emit coalesced ranges.
882 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000883 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000884 while (Range + 1 != End && Range->second == (Range + 1)->first)
885 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000886 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000887 RangesSectionSize += 2 * AddressSize;
888 }
889
890 // Add the terminator entry.
891 MS->EmitIntValue(0, AddressSize);
892 MS->EmitIntValue(0, AddressSize);
893 RangesSectionSize += 2 * AddressSize;
894}
895
Frederic Rissdfb97902015-03-14 15:49:07 +0000896/// \brief Emit location lists for \p Unit and update attribtues to
897/// point to the new entries.
898void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
899 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000900 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000901
902 if (Attributes.empty())
903 return;
904
905 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
906
907 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
908 const DWARFSection &InputSec = Dwarf.getLocSection();
909 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
910 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000911 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000912 int64_t UnitPcOffset = 0;
913 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
914 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
915 if (OrigLowPc != -1ULL)
916 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
917
918 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000919 uint32_t Offset = Attr.first.get();
920 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000921 // This is the quantity to add to the old location address to get
922 // the correct address for the new one.
923 int64_t LocPcOffset = Attr.second + UnitPcOffset;
924 while (Data.isValidOffset(Offset)) {
925 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
926 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
927 LocSectionSize += 2 * AddressSize;
928 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000929 Asm->OutStreamer->EmitIntValue(0, AddressSize);
930 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000931 break;
932 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000933 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
934 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000935 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000936 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000937 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000938 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000939 StringRef(InputSec.Data.substr(Offset, Length)));
940 Offset += Length;
941 LocSectionSize += Length + 2;
942 }
943 }
944}
945
Frederic Rissa5e14532015-08-07 15:14:13 +0000946void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
947 StringRef PrologueBytes,
Frederic Riss63786b02015-03-15 20:45:43 +0000948 unsigned MinInstLength,
949 std::vector<DWARFDebugLine::Row> &Rows,
950 unsigned PointerSize) {
951 // Switch to the section where the table will be emitted into.
952 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000953 MCSymbol *LineStartSym = MC->createTempSymbol();
954 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000955
956 // The first 4 bytes is the total length of the information for this
957 // compilation unit (not including these 4 bytes for the length).
958 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000959 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000960 // Copy Prologue.
961 MS->EmitBytes(PrologueBytes);
962 LineSectionSize += PrologueBytes.size() + 4;
963
Frederic Rissc3820d02015-03-15 22:20:28 +0000964 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000965 raw_svector_ostream EncodingOS(EncodingBuffer);
966
967 if (Rows.empty()) {
968 // We only have the dummy entry, dsymutil emits an entry with a 0
969 // address in that case.
Frederic Rissa5e14532015-08-07 15:14:13 +0000970 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +0000971 MS->EmitBytes(EncodingOS.str());
972 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000973 MS->EmitLabel(LineEndSym);
974 return;
975 }
976
977 // Line table state machine fields
978 unsigned FileNum = 1;
979 unsigned LastLine = 1;
980 unsigned Column = 0;
981 unsigned IsStatement = 1;
982 unsigned Isa = 0;
983 uint64_t Address = -1ULL;
984
985 unsigned RowsSinceLastSequence = 0;
986
987 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
988 auto &Row = Rows[Idx];
989
990 int64_t AddressDelta;
991 if (Address == -1ULL) {
992 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
993 MS->EmitULEB128IntValue(PointerSize + 1);
994 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
995 MS->EmitIntValue(Row.Address, PointerSize);
996 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
997 AddressDelta = 0;
998 } else {
999 AddressDelta = (Row.Address - Address) / MinInstLength;
1000 }
1001
1002 // FIXME: code copied and transfromed from
1003 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
1004 // this code, but the current compatibility requirement with
1005 // classic dsymutil makes it hard. Revisit that once this
1006 // requirement is dropped.
1007
1008 if (FileNum != Row.File) {
1009 FileNum = Row.File;
1010 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
1011 MS->EmitULEB128IntValue(FileNum);
1012 LineSectionSize += 1 + getULEB128Size(FileNum);
1013 }
1014 if (Column != Row.Column) {
1015 Column = Row.Column;
1016 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
1017 MS->EmitULEB128IntValue(Column);
1018 LineSectionSize += 1 + getULEB128Size(Column);
1019 }
1020
1021 // FIXME: We should handle the discriminator here, but dsymutil
1022 // doesn' consider it, thus ignore it for now.
1023
1024 if (Isa != Row.Isa) {
1025 Isa = Row.Isa;
1026 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
1027 MS->EmitULEB128IntValue(Isa);
1028 LineSectionSize += 1 + getULEB128Size(Isa);
1029 }
1030 if (IsStatement != Row.IsStmt) {
1031 IsStatement = Row.IsStmt;
1032 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
1033 LineSectionSize += 1;
1034 }
1035 if (Row.BasicBlock) {
1036 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
1037 LineSectionSize += 1;
1038 }
1039
1040 if (Row.PrologueEnd) {
1041 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
1042 LineSectionSize += 1;
1043 }
1044
1045 if (Row.EpilogueBegin) {
1046 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
1047 LineSectionSize += 1;
1048 }
1049
1050 int64_t LineDelta = int64_t(Row.Line) - LastLine;
1051 if (!Row.EndSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +00001052 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001053 MS->EmitBytes(EncodingOS.str());
1054 LineSectionSize += EncodingBuffer.size();
1055 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +00001056 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +00001057 Address = Row.Address;
1058 LastLine = Row.Line;
1059 RowsSinceLastSequence++;
1060 } else {
1061 if (LineDelta) {
1062 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
1063 MS->EmitSLEB128IntValue(LineDelta);
1064 LineSectionSize += 1 + getSLEB128Size(LineDelta);
1065 }
1066 if (AddressDelta) {
1067 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
1068 MS->EmitULEB128IntValue(AddressDelta);
1069 LineSectionSize += 1 + getULEB128Size(AddressDelta);
1070 }
Frederic Rissa5e14532015-08-07 15:14:13 +00001071 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001072 MS->EmitBytes(EncodingOS.str());
1073 LineSectionSize += EncodingBuffer.size();
1074 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +00001075 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +00001076 Address = -1ULL;
1077 LastLine = FileNum = IsStatement = 1;
1078 RowsSinceLastSequence = Column = Isa = 0;
1079 }
1080 }
1081
1082 if (RowsSinceLastSequence) {
Frederic Rissa5e14532015-08-07 15:14:13 +00001083 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
Frederic Riss63786b02015-03-15 20:45:43 +00001084 MS->EmitBytes(EncodingOS.str());
1085 LineSectionSize += EncodingBuffer.size();
1086 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +00001087 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +00001088 }
1089
1090 MS->EmitLabel(LineEndSym);
1091}
1092
Frederic Rissbce93ff2015-03-16 02:05:10 +00001093/// \brief Emit the pubnames or pubtypes section contribution for \p
1094/// Unit into \p Sec. The data is provided in \p Names.
1095void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001096 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001097 const std::vector<CompileUnit::AccelInfo> &Names) {
1098 if (Names.empty())
1099 return;
1100
1101 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001102 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +00001103 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1104 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +00001105
1106 bool HeaderEmitted = false;
1107 // Emit the pubnames for this compilation unit.
1108 for (const auto &Name : Names) {
1109 if (Name.SkipPubSection)
1110 continue;
1111
1112 if (!HeaderEmitted) {
1113 // Emit the header.
1114 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +00001115 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001116 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +00001117 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +00001118 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1119 HeaderEmitted = true;
1120 }
1121 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +00001122 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +00001123 StringRef(Name.Name.data(), Name.Name.size() + 1));
1124 }
1125
1126 if (!HeaderEmitted)
1127 return;
1128 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +00001129 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001130}
1131
1132/// \brief Emit .debug_pubnames for \p Unit.
1133void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1134 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1135 "names", Unit, Unit.getPubnames());
1136}
1137
1138/// \brief Emit .debug_pubtypes for \p Unit.
1139void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1140 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1141 "types", Unit, Unit.getPubtypes());
1142}
1143
Frederic Riss5a642072015-06-05 23:06:11 +00001144/// \brief Emit a CIE into the debug_frame section.
1145void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1146 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1147
1148 MS->EmitBytes(CIEBytes);
1149 FrameSectionSize += CIEBytes.size();
1150}
1151
1152/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1153/// contains the FDE data without the length, CIE offset and address
1154/// which will be replaced with the paramter values.
1155void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1156 uint32_t Address, StringRef FDEBytes) {
1157 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1158
1159 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1160 MS->EmitIntValue(CIEOffset, 4);
1161 MS->EmitIntValue(Address, AddrSize);
1162 MS->EmitBytes(FDEBytes);
1163 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1164}
1165
Frederic Rissd3455182015-01-28 18:27:01 +00001166/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001167///
1168/// The link of the dwarf information from the object files will be
1169/// driven by the selection of 'root DIEs', which are DIEs that
1170/// describe variables or functions that are present in the linked
1171/// binary (and thus have entries in the debug map). All the debug
1172/// information that will be linked (the DIEs, but also the line
1173/// tables, ranges, ...) is derived from that set of root DIEs.
1174///
1175/// The root DIEs are identified because they contain relocations that
1176/// correspond to a debug map entry at specific places (the low_pc for
1177/// a function, the location for a variable). These relocations are
1178/// called ValidRelocs in the DwarfLinker and are gathered as a very
1179/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001180class DwarfLinker {
1181public:
Frederic Rissb9818322015-02-28 00:29:07 +00001182 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1183 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001184 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001185
Frederic Rissb8b43d52015-03-04 22:07:44 +00001186 ~DwarfLinker() {
1187 for (auto *Abbrev : Abbreviations)
1188 delete Abbrev;
1189 }
1190
Frederic Rissd3455182015-01-28 18:27:01 +00001191 /// \brief Link the contents of the DebugMap.
1192 bool link(const DebugMap &);
1193
1194private:
Frederic Riss563cba62015-01-28 22:15:14 +00001195 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001196 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001197
1198 /// \brief Called at the end of a debug object link.
1199 void endDebugObject();
1200
Frederic Riss1036e642015-02-13 23:18:22 +00001201 /// \defgroup FindValidRelocations Translate debug map into a list
1202 /// of relevant relocations
1203 ///
1204 /// @{
1205 struct ValidReloc {
1206 uint32_t Offset;
1207 uint32_t Size;
1208 uint64_t Addend;
1209 const DebugMapObject::DebugMapEntry *Mapping;
1210
1211 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1212 const DebugMapObject::DebugMapEntry *Mapping)
1213 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1214
1215 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1216 };
1217
1218 /// \brief The valid relocations for the current DebugMapObject.
1219 /// This vector is sorted by relocation offset.
1220 std::vector<ValidReloc> ValidRelocs;
1221
1222 /// \brief Index into ValidRelocs of the next relocation to
1223 /// consider. As we walk the DIEs in acsending file offset and as
1224 /// ValidRelocs is sorted by file offset, keeping this index
1225 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +00001226 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +00001227 unsigned NextValidReloc;
1228
1229 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1230 const DebugMapObject &DMO);
1231
1232 bool findValidRelocs(const object::SectionRef &Section,
1233 const object::ObjectFile &Obj,
1234 const DebugMapObject &DMO);
1235
1236 void findValidRelocsMachO(const object::SectionRef &Section,
1237 const object::MachOObjectFile &Obj,
1238 const DebugMapObject &DMO);
1239 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +00001240
Frederic Riss84c09a52015-02-13 23:18:34 +00001241 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1242 ///
1243 /// @{
1244 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1245 /// keep. Store that information in \p CU's DIEInfo.
1246 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1247 const DebugMapObject &DMO, CompileUnit &CU,
1248 unsigned Flags);
1249
1250 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1251 enum TravesalFlags {
1252 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1253 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1254 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1255 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
Frederic Riss1c650942015-07-21 22:41:43 +00001256 TF_ODR = 1 << 4, ///< Use the ODR whhile keeping dependants.
Frederic Riss84c09a52015-02-13 23:18:34 +00001257 };
1258
1259 /// \brief Mark the passed DIE as well as all the ones it depends on
1260 /// as kept.
1261 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1262 CompileUnit::DIEInfo &MyInfo,
1263 const DebugMapObject &DMO, CompileUnit &CU,
Frederic Riss1c650942015-07-21 22:41:43 +00001264 bool UseODR);
Frederic Riss84c09a52015-02-13 23:18:34 +00001265
1266 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1267 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1268 unsigned Flags);
1269
1270 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1271 CompileUnit &Unit,
1272 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1273
1274 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1275 CompileUnit &Unit,
1276 CompileUnit::DIEInfo &MyInfo,
1277 unsigned Flags);
1278
1279 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1280 CompileUnit::DIEInfo &Info);
1281 /// @}
1282
Frederic Rissb8b43d52015-03-04 22:07:44 +00001283 /// \defgroup Linking Methods used to link the debug information
1284 ///
1285 /// @{
1286 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1287 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1288 /// stripped out and addresses have been rewritten according to the
1289 /// debug map.
1290 ///
1291 /// \param OutOffset is the offset the cloned DIE in the output
1292 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +00001293 /// \param PCOffset (while cloning a function scope) is the offset
1294 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001295 ///
1296 /// \returns the root of the cloned tree.
1297 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +00001298 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001299
1300 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1301
Frederic Riss31da3242015-03-11 18:45:52 +00001302 /// \brief Information gathered and exchanged between the various
1303 /// clone*Attributes helpers about the attributes of a particular DIE.
1304 struct AttributesInfo {
Frederic Rissbce93ff2015-03-16 02:05:10 +00001305 const char *Name, *MangledName; ///< Names.
1306 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1307
Frederic Riss31da3242015-03-11 18:45:52 +00001308 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1309 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1310
Frederic Rissbce93ff2015-03-16 02:05:10 +00001311 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1312 bool IsDeclaration; ///< Is this DIE only a declaration?
1313
1314 AttributesInfo()
1315 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1316 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1317 IsDeclaration(false) {}
Frederic Riss31da3242015-03-11 18:45:52 +00001318 };
1319
Frederic Rissb8b43d52015-03-04 22:07:44 +00001320 /// \brief Helper for cloneDIE.
1321 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1322 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001323 const AttributeSpec AttrSpec, unsigned AttrSize,
1324 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001325
1326 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001327 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1328 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001329
1330 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001331 unsigned
1332 cloneDieReferenceAttribute(DIE &Die,
1333 const DWARFDebugInfoEntryMinimal &InputDIE,
1334 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001335 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001336
1337 /// \brief Helper for cloneDIE.
1338 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1339 const DWARFFormValue &Val, unsigned AttrSize);
1340
1341 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001342 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1343 const DWARFFormValue &Val,
1344 const CompileUnit &Unit, AttributesInfo &Info);
1345
1346 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001347 unsigned cloneScalarAttribute(DIE &Die,
1348 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001349 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001350 const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001351 AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001352
Frederic Riss23e20e92015-03-07 01:25:09 +00001353 /// \brief Helper for cloneDIE.
1354 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1355 bool isLittleEndian);
1356
Frederic Rissb8b43d52015-03-04 22:07:44 +00001357 /// \brief Assign an abbreviation number to \p Abbrev
1358 void AssignAbbrev(DIEAbbrev &Abbrev);
1359
1360 /// \brief FoldingSet that uniques the abbreviations.
1361 FoldingSet<DIEAbbrev> AbbreviationsSet;
1362 /// \brief Storage for the unique Abbreviations.
1363 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1364 /// be changed to a vecot of unique_ptrs.
1365 std::vector<DIEAbbrev *> Abbreviations;
1366
Frederic Riss25440872015-03-13 23:30:31 +00001367 /// \brief Compute and emit debug_ranges section for \p Unit, and
1368 /// patch the attributes referencing it.
1369 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1370
1371 /// \brief Generate and emit the DW_AT_ranges attribute for a
1372 /// compile_unit if it had one.
1373 void generateUnitRanges(CompileUnit &Unit) const;
1374
Frederic Riss63786b02015-03-15 20:45:43 +00001375 /// \brief Extract the line tables fromt he original dwarf, extract
1376 /// the relevant parts according to the linked function ranges and
1377 /// emit the result in the debug_line section.
1378 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1379
Frederic Rissbce93ff2015-03-16 02:05:10 +00001380 /// \brief Emit the accelerator entries for \p Unit.
1381 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1382
Frederic Riss5a642072015-06-05 23:06:11 +00001383 /// \brief Patch the frame info for an object file and emit it.
1384 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1385 unsigned AddressSize);
1386
Frederic Rissb8b43d52015-03-04 22:07:44 +00001387 /// \brief DIELoc objects that need to be destructed (but not freed!).
1388 std::vector<DIELoc *> DIELocs;
1389 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1390 std::vector<DIEBlock *> DIEBlocks;
1391 /// \brief Allocator used for all the DIEValue objects.
1392 BumpPtrAllocator DIEAlloc;
1393 /// @}
1394
Frederic Riss1c650942015-07-21 22:41:43 +00001395 /// ODR Contexts for that link.
1396 DeclContextTree ODRContexts;
1397
Frederic Riss1b9da422015-02-13 23:18:29 +00001398 /// \defgroup Helpers Various helper methods.
1399 ///
1400 /// @{
1401 const DWARFDebugInfoEntryMinimal *
Frederic Riss1c650942015-07-21 22:41:43 +00001402 resolveDIEReference(const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001403 const DWARFDebugInfoEntryMinimal &DIE,
1404 CompileUnit *&ReferencedCU);
1405
1406 CompileUnit *getUnitForOffset(unsigned Offset);
1407
Frederic Rissbce93ff2015-03-16 02:05:10 +00001408 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1409 AttributesInfo &Info);
1410
Frederic Riss1b9da422015-02-13 23:18:29 +00001411 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001412 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001413
1414 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Risseb85c8f2015-07-24 06:41:11 +00001415
1416 /// \brief Attempt to load a debug object from disk.
1417 ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1418 DebugMapObject &Obj,
1419 const DebugMap &Map);
Frederic Riss1b9da422015-02-13 23:18:29 +00001420 /// @}
1421
Frederic Riss563cba62015-01-28 22:15:14 +00001422private:
Frederic Rissd3455182015-01-28 18:27:01 +00001423 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001424 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001425 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001426 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001427
1428 /// The units of the current debug map object.
1429 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001430
1431 /// The debug map object curently under consideration.
1432 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001433
1434 /// \brief The Dwarf string pool
1435 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001436
1437 /// \brief This map is keyed by the entry PC of functions in that
1438 /// debug object and the associated value is a pair storing the
1439 /// corresponding end PC and the offset to apply to get the linked
1440 /// address.
1441 ///
1442 /// See startDebugObject() for a more complete description of its use.
1443 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001444
1445 /// \brief The CIEs that have been emitted in the output
1446 /// section. The actual CIE data serves a the key to this StringMap,
1447 /// this takes care of comparing the semantics of CIEs defined in
1448 /// different object files.
1449 StringMap<uint32_t> EmittedCIEs;
1450
1451 /// Offset of the last CIE that has been emitted in the output
1452 /// debug_frame section.
1453 uint32_t LastCIEOffset;
Frederic Rissd3455182015-01-28 18:27:01 +00001454};
1455
Frederic Riss1b9da422015-02-13 23:18:29 +00001456/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1457/// returning our CompileUnit object instead.
1458CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1459 auto CU =
1460 std::upper_bound(Units.begin(), Units.end(), Offset,
1461 [](uint32_t LHS, const CompileUnit &RHS) {
1462 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1463 });
1464 return CU != Units.end() ? &*CU : nullptr;
1465}
1466
1467/// \brief Resolve the DIE attribute reference that has been
1468/// extracted in \p RefValue. The resulting DIE migh be in another
1469/// CompileUnit which is stored into \p ReferencedCU.
1470/// \returns null if resolving fails for any reason.
1471const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
Frederic Riss1c650942015-07-21 22:41:43 +00001472 const DWARFFormValue &RefValue, const DWARFUnit &Unit,
Frederic Riss1b9da422015-02-13 23:18:29 +00001473 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1474 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1475 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1476
1477 if ((RefCU = getUnitForOffset(RefOffset)))
1478 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1479 return RefDie;
1480
1481 reportWarning("could not find referenced DIE", &Unit, &DIE);
1482 return nullptr;
1483}
1484
Frederic Riss1c650942015-07-21 22:41:43 +00001485/// \returns whether the passed \a Attr type might contain a DIE
1486/// reference suitable for ODR uniquing.
1487static bool isODRAttribute(uint16_t Attr) {
1488 switch (Attr) {
1489 default:
1490 return false;
1491 case dwarf::DW_AT_type:
1492 case dwarf::DW_AT_containing_type:
1493 case dwarf::DW_AT_specification:
1494 case dwarf::DW_AT_abstract_origin:
1495 case dwarf::DW_AT_import:
1496 return true;
1497 }
1498 llvm_unreachable("Improper attribute.");
1499}
1500
1501/// Set the last DIE/CU a context was seen in and, possibly invalidate
1502/// the context if it is ambiguous.
1503///
1504/// In the current implementation, we don't handle overloaded
1505/// functions well, because the argument types are not taken into
1506/// account when computing the DeclContext tree.
1507///
1508/// Some of this is mitigated byt using mangled names that do contain
1509/// the arguments types, but sometimes (eg. with function templates)
1510/// we don't have that. In that case, just do not unique anything that
1511/// refers to the contexts we are not able to distinguish.
1512///
1513/// If a context that is not a namespace appears twice in the same CU,
1514/// we know it is ambiguous. Make it invalid.
1515bool DeclContext::setLastSeenDIE(CompileUnit &U,
1516 const DWARFDebugInfoEntryMinimal *Die) {
1517 if (LastSeenCompileUnitID == U.getUniqueID()) {
1518 DWARFUnit &OrigUnit = U.getOrigUnit();
1519 uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1520 U.getInfo(FirstIdx).Ctxt = nullptr;
1521 return false;
1522 }
1523
1524 LastSeenCompileUnitID = U.getUniqueID();
1525 LastSeenDIE = Die;
1526 return true;
1527}
1528
1529/// Get the child context of \a Context corresponding to \a DIE.
1530///
1531/// \returns the child context or null if we shouldn't track children
1532/// contexts. It also returns an additional bit meaning 'invalid'. An
1533/// invalid context means it shouldn't be considered for uniquing, but
1534/// its not returning null, because some children of that context
1535/// might be uniquing candidates.
1536/// FIXME: this is for dsymutil-classic compatibility, I don't think
1537/// it buys us much.
1538PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1539 DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1540 NonRelocatableStringpool &StringPool) {
1541 unsigned Tag = DIE->getTag();
1542
1543 // FIXME: dsymutil-classic compat: We should bail out here if we
1544 // have a specification or an abstract_origin. We will get the
1545 // parent context wrong here.
1546
1547 switch (Tag) {
1548 default:
1549 // By default stop gathering child contexts.
1550 return PointerIntPair<DeclContext *, 1>(nullptr);
1551 case dwarf::DW_TAG_compile_unit:
1552 // FIXME: Add support for DW_TAG_module.
1553 return PointerIntPair<DeclContext *, 1>(&Context);
1554 case dwarf::DW_TAG_subprogram:
1555 // Do not unique anything inside CU local functions.
1556 if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1557 Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1558 !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1559 dwarf::DW_AT_external, 0))
1560 return PointerIntPair<DeclContext *, 1>(nullptr);
1561 // Fallthrough
1562 case dwarf::DW_TAG_member:
1563 case dwarf::DW_TAG_namespace:
1564 case dwarf::DW_TAG_structure_type:
1565 case dwarf::DW_TAG_class_type:
1566 case dwarf::DW_TAG_union_type:
1567 case dwarf::DW_TAG_enumeration_type:
1568 case dwarf::DW_TAG_typedef:
1569 // Artificial things might be ambiguous, because they might be
1570 // created on demand. For example implicitely defined constructors
1571 // are ambiguous because of the way we identify contexts, and they
1572 // won't be generated everytime everywhere.
1573 if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1574 dwarf::DW_AT_artificial, 0))
1575 return PointerIntPair<DeclContext *, 1>(nullptr);
1576 break;
1577 }
1578
1579 const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1580 const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1581 StringRef NameRef;
1582 StringRef ShortNameRef;
1583 StringRef FileRef;
1584
1585 if (Name)
1586 NameRef = StringPool.internString(Name);
1587 else if (Tag == dwarf::DW_TAG_namespace)
1588 // FIXME: For dsymutil-classic compatibility. I think uniquing
1589 // within anonymous namespaces is wrong. There is no ODR guarantee
1590 // there.
1591 NameRef = StringPool.internString("(anonymous namespace)");
1592
1593 if (ShortName && ShortName != Name)
1594 ShortNameRef = StringPool.internString(ShortName);
1595 else
1596 ShortNameRef = NameRef;
1597
1598 if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1599 Tag != dwarf::DW_TAG_union_type &&
1600 Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1601 return PointerIntPair<DeclContext *, 1>(nullptr);
1602
1603 std::string File;
1604 unsigned Line = 0;
1605 unsigned ByteSize = 0;
1606
1607 // Gather some discriminating data about the DeclContext we will be
1608 // creating: File, line number and byte size. This shouldn't be
1609 // necessary, because the ODR is just about names, but given that we
1610 // do some approximations with overloaded functions and anonymous
1611 // namespaces, use these additional data points to make the process safer.
1612 ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1613 &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1614 if (Tag != dwarf::DW_TAG_namespace || !Name) {
1615 if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1616 &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1617 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1618 &U.getOrigUnit())) {
1619 // FIXME: dsymutil-classic compatibility. I'd rather not
1620 // unique anything in anonymous namespaces, but if we do, then
1621 // verify that the file and line correspond.
1622 if (!Name && Tag == dwarf::DW_TAG_namespace)
1623 FileNum = 1;
1624
1625 // FIXME: Passing U.getOrigUnit().getCompilationDir()
1626 // instead of "" would allow more uniquing, but for now, do
1627 // it this way to match dsymutil-classic.
1628 if (LT->getFileNameByIndex(
1629 FileNum, "",
1630 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1631 File)) {
1632 Line = DIE->getAttributeValueAsUnsignedConstant(
1633 &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1634#ifdef HAVE_REALPATH
1635 // Cache the resolved paths, because calling realpath is expansive.
1636 if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1637 File = ResolvedPath;
1638 } else {
1639 char RealPath[PATH_MAX + 1];
1640 RealPath[PATH_MAX] = 0;
1641 if (::realpath(File.c_str(), RealPath))
1642 File = RealPath;
1643 U.setResolvedPath(FileNum, File);
1644 }
1645#endif
1646 FileRef = StringPool.internString(File);
1647 }
1648 }
1649 }
1650 }
1651
1652 if (!Line && NameRef.empty())
1653 return PointerIntPair<DeclContext *, 1>(nullptr);
1654
1655 // FIXME: dsymutil-classic compat won't unique the same type
1656 // presented once as a struct and once as a class. Use the Tag in
1657 // the fully qualified name hash to get the same effect.
1658 // We hash NameRef, which is the mangled name, in order to get most
1659 // overloaded functions resolvec correctly.
1660 unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1661
1662 // FIXME: dsymutil-classic compatibility: when we don't have a name,
1663 // use the filename.
1664 if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1665 Hash = hash_combine(Hash, FileRef);
1666
1667 // Now look if this context already exists.
1668 DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1669 auto ContextIter = Contexts.find(&Key);
1670
1671 if (ContextIter == Contexts.end()) {
1672 // The context wasn't found.
1673 bool Inserted;
1674 DeclContext *NewContext =
1675 new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1676 Context, DIE, U.getUniqueID());
1677 std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1678 assert(Inserted && "Failed to insert DeclContext");
1679 (void)Inserted;
1680 } else if (Tag != dwarf::DW_TAG_namespace &&
1681 !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1682 // The context was found, but it is ambiguous with another context
1683 // in the same file. Mark it invalid.
1684 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1685 }
1686
1687 assert(ContextIter != Contexts.end());
1688 // FIXME: dsymutil-classic compatibility. Union types aren't
1689 // uniques, but their children might be.
1690 if ((Tag == dwarf::DW_TAG_subprogram &&
1691 Context.getTag() != dwarf::DW_TAG_structure_type &&
1692 Context.getTag() != dwarf::DW_TAG_class_type) ||
1693 (Tag == dwarf::DW_TAG_union_type))
1694 return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1695
1696 return PointerIntPair<DeclContext *, 1>(*ContextIter);
1697}
1698
Frederic Rissbce93ff2015-03-16 02:05:10 +00001699/// \brief Get the potential name and mangled name for the entity
1700/// described by \p Die and store them in \Info if they are not
1701/// already there.
1702/// \returns is a name was found.
1703bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1704 DWARFUnit &U, AttributesInfo &Info) {
1705 // FIXME: a bit wastefull as the first getName might return the
1706 // short name.
1707 if (!Info.MangledName &&
1708 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1709 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1710
1711 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1712 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1713
1714 return Info.Name || Info.MangledName;
1715}
1716
Frederic Riss1b9da422015-02-13 23:18:29 +00001717/// \brief Report a warning to the user, optionaly including
1718/// information about a specific \p DIE related to the warning.
1719void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001720 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001721 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001722 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001723 Context = CurrentDebugObject->getObjectFilename();
1724 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001725
Frederic Rissb9818322015-02-28 00:29:07 +00001726 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001727 return;
1728
1729 errs() << " in DIE:\n";
1730 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1731 6 /* Indent */);
1732}
1733
Frederic Rissc99ea202015-02-28 00:29:11 +00001734bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1735 if (Options.NoOutput)
1736 return true;
1737
Frederic Rissb52cf522015-02-28 00:42:37 +00001738 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001739 return Streamer->init(TheTriple, OutputFilename);
1740}
1741
Frederic Riss563cba62015-01-28 22:15:14 +00001742/// \brief Recursive helper to gather the child->parent relationships in the
1743/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001744static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
Frederic Riss1c650942015-07-21 22:41:43 +00001745 unsigned ParentIdx, CompileUnit &CU,
1746 DeclContext *CurrentDeclContext,
1747 NonRelocatableStringpool &StringPool,
1748 DeclContextTree &Contexts) {
Frederic Riss563cba62015-01-28 22:15:14 +00001749 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
Frederic Riss1c650942015-07-21 22:41:43 +00001750 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1751
1752 Info.ParentIdx = ParentIdx;
1753 if (CU.hasODR()) {
1754 if (CurrentDeclContext) {
1755 auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1756 DIE, CU, StringPool);
1757 CurrentDeclContext = PtrInvalidPair.getPointer();
1758 Info.Ctxt =
1759 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1760 } else
1761 Info.Ctxt = CurrentDeclContext = nullptr;
1762 }
Frederic Riss563cba62015-01-28 22:15:14 +00001763
1764 if (DIE->hasChildren())
1765 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1766 Child = Child->getSibling())
Frederic Riss1c650942015-07-21 22:41:43 +00001767 gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1768 Contexts);
Frederic Riss563cba62015-01-28 22:15:14 +00001769}
1770
Frederic Riss84c09a52015-02-13 23:18:34 +00001771static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1772 switch (Tag) {
1773 default:
1774 return false;
1775 case dwarf::DW_TAG_subprogram:
1776 case dwarf::DW_TAG_lexical_block:
1777 case dwarf::DW_TAG_subroutine_type:
1778 case dwarf::DW_TAG_structure_type:
1779 case dwarf::DW_TAG_class_type:
1780 case dwarf::DW_TAG_union_type:
1781 return true;
1782 }
1783 llvm_unreachable("Invalid Tag");
1784}
1785
Frederic Riss1c650942015-07-21 22:41:43 +00001786static unsigned getRefAddrSize(const DWARFUnit &U) {
1787 if (U.getVersion() == 2)
1788 return U.getAddressByteSize();
1789 return 4;
1790}
1791
Frederic Riss63786b02015-03-15 20:45:43 +00001792void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001793 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001794 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001795 // Iterate over the debug map entries and put all the ones that are
1796 // functions (because they have a size) into the Ranges map. This
1797 // map is very similar to the FunctionRanges that are stored in each
1798 // unit, with 2 notable differences:
1799 // - obviously this one is global, while the other ones are per-unit.
1800 // - this one contains not only the functions described in the DIE
1801 // tree, but also the ones that are only in the debug map.
1802 // The latter information is required to reproduce dsymutil's logic
1803 // while linking line tables. The cases where this information
1804 // matters look like bugs that need to be investigated, but for now
1805 // we need to reproduce dsymutil's behavior.
1806 // FIXME: Once we understood exactly if that information is needed,
1807 // maybe totally remove this (or try to use it to do a real
1808 // -gline-tables-only on Darwin.
1809 for (const auto &Entry : Obj.symbols()) {
1810 const auto &Mapping = Entry.getValue();
1811 if (Mapping.Size)
1812 Ranges[Mapping.ObjectAddress] = std::make_pair(
1813 Mapping.ObjectAddress + Mapping.Size,
1814 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1815 }
Frederic Riss563cba62015-01-28 22:15:14 +00001816}
1817
Frederic Riss1036e642015-02-13 23:18:22 +00001818void DwarfLinker::endDebugObject() {
1819 Units.clear();
1820 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001821 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001822
Aaron Ballmana17cbff2015-06-26 14:51:22 +00001823 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1824 (*I)->~DIEBlock();
1825 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1826 (*I)->~DIELoc();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001827
1828 DIEBlocks.clear();
1829 DIELocs.clear();
1830 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001831}
1832
1833/// \brief Iterate over the relocations of the given \p Section and
1834/// store the ones that correspond to debug map entries into the
1835/// ValidRelocs array.
1836void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1837 const object::MachOObjectFile &Obj,
1838 const DebugMapObject &DMO) {
1839 StringRef Contents;
1840 Section.getContents(Contents);
1841 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1842
1843 for (const object::RelocationRef &Reloc : Section.relocations()) {
1844 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1845 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1846 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001847 uint64_t Offset64 = Reloc.getOffset();
1848 if ((RelocSize != 4 && RelocSize != 8)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001849 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001850 continue;
1851 }
1852 uint32_t Offset = Offset64;
1853 // Mach-o uses REL relocations, the addend is at the relocation offset.
1854 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1855
1856 auto Sym = Reloc.getSymbol();
1857 if (Sym != Obj.symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001858 ErrorOr<StringRef> SymbolName = Sym->getName();
1859 if (!SymbolName) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001860 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001861 continue;
1862 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001863 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
Frederic Riss1036e642015-02-13 23:18:22 +00001864 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1865 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1866 // Do not store the addend. The addend was the address of the
1867 // symbol in the object file, the address in the binary that is
1868 // stored in the debug map doesn't need to be offseted.
1869 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1870 }
1871 }
1872}
1873
1874/// \brief Dispatch the valid relocation finding logic to the
1875/// appropriate handler depending on the object file format.
1876bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1877 const object::ObjectFile &Obj,
1878 const DebugMapObject &DMO) {
1879 // Dispatch to the right handler depending on the file type.
1880 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1881 findValidRelocsMachO(Section, *MachOObj, DMO);
1882 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001883 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001884
1885 if (ValidRelocs.empty())
1886 return false;
1887
1888 // Sort the relocations by offset. We will walk the DIEs linearly in
1889 // the file, this allows us to just keep an index in the relocation
1890 // array that we advance during our walk, rather than resorting to
1891 // some associative container. See DwarfLinker::NextValidReloc.
1892 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1893 return true;
1894}
1895
1896/// \brief Look for relocations in the debug_info section that match
1897/// entries in the debug map. These relocations will drive the Dwarf
1898/// link by indicating which DIEs refer to symbols present in the
1899/// linked binary.
1900/// \returns wether there are any valid relocations in the debug info.
1901bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1902 const DebugMapObject &DMO) {
1903 // Find the debug_info section.
1904 for (const object::SectionRef &Section : Obj.sections()) {
1905 StringRef SectionName;
1906 Section.getName(SectionName);
1907 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1908 if (SectionName != "debug_info")
1909 continue;
1910 return findValidRelocs(Section, Obj, DMO);
1911 }
1912 return false;
1913}
Frederic Riss563cba62015-01-28 22:15:14 +00001914
Frederic Riss84c09a52015-02-13 23:18:34 +00001915/// \brief Checks that there is a relocation against an actual debug
1916/// map entry between \p StartOffset and \p NextOffset.
1917///
1918/// This function must be called with offsets in strictly ascending
1919/// order because it never looks back at relocations it already 'went past'.
1920/// \returns true and sets Info.InDebugMap if it is the case.
1921bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1922 CompileUnit::DIEInfo &Info) {
1923 assert(NextValidReloc == 0 ||
1924 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1925 if (NextValidReloc >= ValidRelocs.size())
1926 return false;
1927
1928 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1929
1930 // We might need to skip some relocs that we didn't consider. For
1931 // example the high_pc of a discarded DIE might contain a reloc that
1932 // is in the list because it actually corresponds to the start of a
1933 // function that is in the debug map.
1934 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1935 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1936
1937 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1938 return false;
1939
1940 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00001941 const auto &Mapping = ValidReloc.Mapping->getValue();
Frederic Rissb9818322015-02-28 00:29:07 +00001942 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001943 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1944 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
Frederic Riss08462f72015-06-01 21:12:45 +00001945 uint64_t(Mapping.ObjectAddress),
1946 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00001947
Frederic Rissf37964c2015-06-05 20:27:07 +00001948 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1949 Mapping.ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001950 Info.InDebugMap = true;
1951 return true;
1952}
1953
1954/// \brief Get the starting and ending (exclusive) offset for the
1955/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1956/// supposed to point to the position of the first attribute described
1957/// by \p Abbrev.
1958/// \return [StartOffset, EndOffset) as a pair.
1959static std::pair<uint32_t, uint32_t>
1960getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1961 unsigned Offset, const DWARFUnit &Unit) {
1962 DataExtractor Data = Unit.getDebugInfoExtractor();
1963
1964 for (unsigned i = 0; i < Idx; ++i)
1965 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1966
1967 uint32_t End = Offset;
1968 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1969
1970 return std::make_pair(Offset, End);
1971}
1972
1973/// \brief Check if a variable describing DIE should be kept.
1974/// \returns updated TraversalFlags.
1975unsigned DwarfLinker::shouldKeepVariableDIE(
1976 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1977 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1978 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1979
1980 // Global variables with constant value can always be kept.
1981 if (!(Flags & TF_InFunctionScope) &&
1982 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1983 MyInfo.InDebugMap = true;
1984 return Flags | TF_Keep;
1985 }
1986
1987 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1988 if (LocationIdx == -1U)
1989 return Flags;
1990
1991 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1992 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1993 uint32_t LocationOffset, LocationEndOffset;
1994 std::tie(LocationOffset, LocationEndOffset) =
1995 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1996
1997 // See if there is a relocation to a valid debug map entry inside
1998 // this variable's location. The order is important here. We want to
1999 // always check in the variable has a valid relocation, so that the
2000 // DIEInfo is filled. However, we don't want a static variable in a
2001 // function to force us to keep the enclosing function.
2002 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
2003 (Flags & TF_InFunctionScope))
2004 return Flags;
2005
Frederic Rissb9818322015-02-28 00:29:07 +00002006 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002007 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2008
2009 return Flags | TF_Keep;
2010}
2011
2012/// \brief Check if a function describing DIE should be kept.
2013/// \returns updated TraversalFlags.
2014unsigned DwarfLinker::shouldKeepSubprogramDIE(
2015 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2016 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2017 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2018
2019 Flags |= TF_InFunctionScope;
2020
2021 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2022 if (LowPcIdx == -1U)
2023 return Flags;
2024
2025 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2026 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2027 uint32_t LowPcOffset, LowPcEndOffset;
2028 std::tie(LowPcOffset, LowPcEndOffset) =
2029 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2030
2031 uint64_t LowPc =
2032 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2033 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2034 if (LowPc == -1ULL ||
2035 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
2036 return Flags;
2037
Frederic Rissb9818322015-02-28 00:29:07 +00002038 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00002039 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2040
Frederic Riss1af75f72015-03-12 18:45:10 +00002041 Flags |= TF_Keep;
2042
2043 DWARFFormValue HighPcValue;
2044 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2045 reportWarning("Function without high_pc. Range will be discarded.\n",
2046 &OrigUnit, &DIE);
2047 return Flags;
2048 }
2049
2050 uint64_t HighPc;
2051 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2052 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2053 } else {
2054 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2055 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2056 }
2057
Frederic Riss63786b02015-03-15 20:45:43 +00002058 // Replace the debug map range with a more accurate one.
2059 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00002060 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2061 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00002062}
2063
2064/// \brief Check if a DIE should be kept.
2065/// \returns updated TraversalFlags.
2066unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
2067 CompileUnit &Unit,
2068 CompileUnit::DIEInfo &MyInfo,
2069 unsigned Flags) {
2070 switch (DIE.getTag()) {
2071 case dwarf::DW_TAG_constant:
2072 case dwarf::DW_TAG_variable:
2073 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
2074 case dwarf::DW_TAG_subprogram:
2075 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
2076 case dwarf::DW_TAG_module:
2077 case dwarf::DW_TAG_imported_module:
2078 case dwarf::DW_TAG_imported_declaration:
2079 case dwarf::DW_TAG_imported_unit:
2080 // We always want to keep these.
2081 return Flags | TF_Keep;
2082 }
2083
2084 return Flags;
2085}
2086
Frederic Riss84c09a52015-02-13 23:18:34 +00002087/// \brief Mark the passed DIE as well as all the ones it depends on
2088/// as kept.
2089///
2090/// This function is called by lookForDIEsToKeep on DIEs that are
2091/// newly discovered to be needed in the link. It recursively calls
2092/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2093/// TraversalFlags to inform it that it's not doing the primary DIE
2094/// tree walk.
2095void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
2096 CompileUnit::DIEInfo &MyInfo,
2097 const DebugMapObject &DMO,
Frederic Riss1c650942015-07-21 22:41:43 +00002098 CompileUnit &CU, bool UseODR) {
Frederic Riss84c09a52015-02-13 23:18:34 +00002099 const DWARFUnit &Unit = CU.getOrigUnit();
2100 MyInfo.Keep = true;
2101
2102 // First mark all the parent chain as kept.
2103 unsigned AncestorIdx = MyInfo.ParentIdx;
2104 while (!CU.getInfo(AncestorIdx).Keep) {
Frederic Riss1c650942015-07-21 22:41:43 +00002105 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Frederic Riss84c09a52015-02-13 23:18:34 +00002106 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
Frederic Riss1c650942015-07-21 22:41:43 +00002107 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
Frederic Riss84c09a52015-02-13 23:18:34 +00002108 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2109 }
2110
2111 // Then we need to mark all the DIEs referenced by this DIE's
2112 // attributes as kept.
2113 DataExtractor Data = Unit.getDebugInfoExtractor();
2114 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2115 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2116
2117 // Mark all DIEs referenced through atttributes as kept.
2118 for (const auto &AttrSpec : Abbrev->attributes()) {
2119 DWARFFormValue Val(AttrSpec.Form);
2120
2121 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2122 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2123 continue;
2124 }
2125
2126 Val.extractValue(Data, &Offset, &Unit);
2127 CompileUnit *ReferencedCU;
Frederic Riss1c650942015-07-21 22:41:43 +00002128 if (const auto *RefDIE =
2129 resolveDIEReference(Val, Unit, DIE, ReferencedCU)) {
2130 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2131 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2132 // If the referenced DIE has a DeclContext that has already been
2133 // emitted, then do not keep the one in this CU. We'll link to
2134 // the canonical DIE in cloneDieReferenceAttribute.
2135 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2136 // be necessary and could be advantageously replaced by
2137 // ReferencedCU->hasODR() && CU.hasODR().
2138 // FIXME: compatibility with dsymutil-classic. There is no
2139 // reason not to unique ref_addr references.
2140 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2141 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2142 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2143 continue;
2144
2145 unsigned ODRFlag = UseODR ? TF_ODR : 0;
Frederic Riss84c09a52015-02-13 23:18:34 +00002146 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
Frederic Riss1c650942015-07-21 22:41:43 +00002147 TF_Keep | TF_DependencyWalk | ODRFlag);
2148 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002149 }
2150}
2151
2152/// \brief Recursively walk the \p DIE tree and look for DIEs to
2153/// keep. Store that information in \p CU's DIEInfo.
2154///
2155/// This function is the entry point of the DIE selection
2156/// algorithm. It is expected to walk the DIE tree in file order and
2157/// (though the mediation of its helper) call hasValidRelocation() on
2158/// each DIE that might be a 'root DIE' (See DwarfLinker class
2159/// comment).
2160/// While walking the dependencies of root DIEs, this function is
2161/// also called, but during these dependency walks the file order is
2162/// not respected. The TF_DependencyWalk flag tells us which kind of
2163/// traversal we are currently doing.
2164void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
2165 const DebugMapObject &DMO, CompileUnit &CU,
2166 unsigned Flags) {
2167 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
2168 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2169 bool AlreadyKept = MyInfo.Keep;
2170
2171 // If the Keep flag is set, we are marking a required DIE's
2172 // dependencies. If our target is already marked as kept, we're all
2173 // set.
2174 if ((Flags & TF_DependencyWalk) && AlreadyKept)
2175 return;
2176
2177 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
2178 // because it would screw up the relocation finding logic.
2179 if (!(Flags & TF_DependencyWalk))
2180 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
2181
2182 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
Frederic Riss1c650942015-07-21 22:41:43 +00002183 if (!AlreadyKept && (Flags & TF_Keep)) {
2184 bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2185 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, UseOdr);
2186 }
Frederic Riss84c09a52015-02-13 23:18:34 +00002187 // The TF_ParentWalk flag tells us that we are currently walking up
2188 // the parent chain of a required DIE, and we don't want to mark all
2189 // the children of the parents as kept (consider for example a
2190 // DW_TAG_namespace node in the parent chain). There are however a
2191 // set of DIE types for which we want to ignore that directive and still
2192 // walk their children.
2193 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
2194 Flags &= ~TF_ParentWalk;
2195
2196 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
2197 return;
2198
2199 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
2200 Child = Child->getSibling())
2201 lookForDIEsToKeep(*Child, DMO, CU, Flags);
2202}
2203
Frederic Rissb8b43d52015-03-04 22:07:44 +00002204/// \brief Assign an abbreviation numer to \p Abbrev.
2205///
2206/// Our DIEs get freed after every DebugMapObject has been processed,
2207/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2208/// the instances hold by the DIEs. When we encounter an abbreviation
2209/// that we don't know, we create a permanent copy of it.
2210void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2211 // Check the set for priors.
2212 FoldingSetNodeID ID;
2213 Abbrev.Profile(ID);
2214 void *InsertToken;
2215 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2216
2217 // If it's newly added.
2218 if (InSet) {
2219 // Assign existing abbreviation number.
2220 Abbrev.setNumber(InSet->getNumber());
2221 } else {
2222 // Add to abbreviation list.
2223 Abbreviations.push_back(
2224 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2225 for (const auto &Attr : Abbrev.getData())
2226 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2227 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2228 // Assign the unique abbreviation number.
2229 Abbrev.setNumber(Abbreviations.size());
2230 Abbreviations.back()->setNumber(Abbreviations.size());
2231 }
2232}
2233
2234/// \brief Clone a string attribute described by \p AttrSpec and add
2235/// it to \p Die.
2236/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00002237unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
2238 const DWARFFormValue &Val,
2239 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002240 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00002241 const char *String = *Val.getAsCString(&U);
2242 unsigned Offset = StringPool.getStringOffset(String);
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002243 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002244 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002245 return 4;
2246}
2247
2248/// \brief Clone an attribute referencing another DIE and add
2249/// it to \p Die.
2250/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00002251unsigned DwarfLinker::cloneDieReferenceAttribute(
2252 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2253 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002254 CompileUnit &Unit) {
Frederic Riss1c650942015-07-21 22:41:43 +00002255 const DWARFUnit &U = Unit.getOrigUnit();
2256 uint32_t Ref = *Val.getAsReference(&U);
Frederic Riss9833de62015-03-06 23:22:53 +00002257 DIE *NewRefDie = nullptr;
2258 CompileUnit *RefUnit = nullptr;
Frederic Riss1c650942015-07-21 22:41:43 +00002259 DeclContext *Ctxt = nullptr;
Frederic Riss9833de62015-03-06 23:22:53 +00002260
Frederic Riss1c650942015-07-21 22:41:43 +00002261 const DWARFDebugInfoEntryMinimal *RefDie =
2262 resolveDIEReference(Val, U, InputDIE, RefUnit);
2263
2264 // If the referenced DIE is not found, drop the attribute.
2265 if (!RefDie)
Frederic Riss9833de62015-03-06 23:22:53 +00002266 return 0;
Frederic Riss9833de62015-03-06 23:22:53 +00002267
2268 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2269 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
Frederic Riss1c650942015-07-21 22:41:43 +00002270
2271 // If we already have emitted an equivalent DeclContext, just point
2272 // at it.
2273 if (isODRAttribute(AttrSpec.Attr)) {
2274 Ctxt = RefInfo.Ctxt;
2275 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2276 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2277 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2278 dwarf::DW_FORM_ref_addr, Attr);
2279 return getRefAddrSize(U);
2280 }
2281 }
2282
Frederic Riss9833de62015-03-06 23:22:53 +00002283 if (!RefInfo.Clone) {
2284 assert(Ref > InputDIE.getOffset());
2285 // We haven't cloned this DIE yet. Just create an empty one and
2286 // store it. It'll get really cloned when we process it.
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002287 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002288 }
2289 NewRefDie = RefInfo.Clone;
2290
Frederic Riss1c650942015-07-21 22:41:43 +00002291 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2292 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
Frederic Riss9833de62015-03-06 23:22:53 +00002293 // We cannot currently rely on a DIEEntry to emit ref_addr
2294 // references, because the implementation calls back to DwarfDebug
2295 // to find the unit offset. (We don't have a DwarfDebug)
2296 // FIXME: we should be able to design DIEEntry reliance on
2297 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002298 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00002299 if (Ref < InputDIE.getOffset()) {
2300 // We must have already cloned that DIE.
2301 uint32_t NewRefOffset =
2302 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002303 Attr = NewRefOffset;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002304 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2305 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00002306 } else {
2307 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002308 Attr = 0xBADDEF;
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002309 Unit.noteForwardReference(
Frederic Riss1c650942015-07-21 22:41:43 +00002310 NewRefDie, RefUnit, Ctxt,
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002311 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2312 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
Frederic Riss9833de62015-03-06 23:22:53 +00002313 }
Frederic Riss1c650942015-07-21 22:41:43 +00002314 return getRefAddrSize(U);
Frederic Riss9833de62015-03-06 23:22:53 +00002315 }
2316
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002317 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2318 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002319 return AttrSize;
2320}
2321
2322/// \brief Clone an attribute of block form (locations, constants) and add
2323/// it to \p Die.
2324/// \returns the size of the new attribute.
2325unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
2326 const DWARFFormValue &Val,
2327 unsigned AttrSize) {
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002328 DIEValueList *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002329 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002330 DIELoc *Loc = nullptr;
2331 DIEBlock *Block = nullptr;
2332 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00002333 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002334 Loc = new (DIEAlloc) DIELoc;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002335 DIELocs.push_back(Loc);
2336 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002337 Block = new (DIEAlloc) DIEBlock;
Frederic Rissb8b43d52015-03-04 22:07:44 +00002338 DIEBlocks.push_back(Block);
2339 }
Duncan P. N. Exon Smithaf9bb0f2015-08-02 20:48:47 +00002340 Attr = Loc ? static_cast<DIEValueList *>(Loc)
2341 : static_cast<DIEValueList *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002342
2343 if (Loc)
2344 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2345 dwarf::Form(AttrSpec.Form), Loc);
2346 else
2347 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2348 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002349 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2350 for (auto Byte : Bytes)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002351 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2352 dwarf::DW_FORM_data1, DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00002353 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2354 // the DIE class, this if could be replaced by
2355 // Attr->setSize(Bytes.size()).
2356 if (Streamer) {
2357 if (Loc)
2358 Loc->ComputeSize(&Streamer->getAsmPrinter());
2359 else
2360 Block->ComputeSize(&Streamer->getAsmPrinter());
2361 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002362 Die.addValue(DIEAlloc, Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002363 return AttrSize;
2364}
2365
Frederic Riss31da3242015-03-11 18:45:52 +00002366/// \brief Clone an address attribute and add it to \p Die.
2367/// \returns the size of the new attribute.
2368unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
2369 const DWARFFormValue &Val,
2370 const CompileUnit &Unit,
2371 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002372 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00002373 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2374 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2375 Die.getTag() == dwarf::DW_TAG_lexical_block)
2376 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002377 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2378 Addr = Unit.getLowPc();
2379 if (Addr == UINT64_MAX)
2380 return 0;
2381 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00002382 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00002383 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002384 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2385 if (uint64_t HighPc = Unit.getHighPc())
2386 Addr = HighPc;
2387 else
2388 return 0;
2389 } else
2390 // If we have a high_pc recorded for the input DIE, use
2391 // it. Otherwise (when no relocations where applied) just use the
2392 // one we just decoded.
2393 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00002394 }
2395
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002396 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002397 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00002398 return Unit.getOrigUnit().getAddressByteSize();
2399}
2400
Frederic Rissb8b43d52015-03-04 22:07:44 +00002401/// \brief Clone a scalar attribute and add it to \p Die.
2402/// \returns the size of the new attribute.
2403unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00002404 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00002405 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00002406 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002407 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00002408 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2409 Die.getTag() == dwarf::DW_TAG_compile_unit) {
2410 if (Unit.getLowPc() == -1ULL)
2411 return 0;
2412 // Dwarf >= 4 high_pc is an size, not an address.
2413 Value = Unit.getHighPc() - Unit.getLowPc();
2414 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00002415 Value = *Val.getAsSectionOffset();
2416 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2417 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002418 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2419 Value = *OptionalValue;
2420 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002421 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
2422 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002423 return 0;
2424 }
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002425 PatchLocation Patch =
2426 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2427 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
Frederic Riss25440872015-03-13 23:30:31 +00002428 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002429 Unit.noteRangeAttribute(Die, Patch);
Frederic Rissdfb97902015-03-14 15:49:07 +00002430 // A more generic way to check for location attributes would be
2431 // nice, but it's very unlikely that any other attribute needs a
2432 // location list.
2433 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2434 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002435 Unit.noteLocationAttribute(Patch, Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002436 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2437 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002438
Frederic Rissb8b43d52015-03-04 22:07:44 +00002439 return AttrSize;
2440}
2441
2442/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2443/// value \p Val, and add it to \p Die.
2444/// \returns the size of the cloned attribute.
2445unsigned DwarfLinker::cloneAttribute(DIE &Die,
2446 const DWARFDebugInfoEntryMinimal &InputDIE,
2447 CompileUnit &Unit,
2448 const DWARFFormValue &Val,
2449 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00002450 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002451 const DWARFUnit &U = Unit.getOrigUnit();
2452
2453 switch (AttrSpec.Form) {
2454 case dwarf::DW_FORM_strp:
2455 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002456 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002457 case dwarf::DW_FORM_ref_addr:
2458 case dwarf::DW_FORM_ref1:
2459 case dwarf::DW_FORM_ref2:
2460 case dwarf::DW_FORM_ref4:
2461 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002462 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002463 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002464 case dwarf::DW_FORM_block:
2465 case dwarf::DW_FORM_block1:
2466 case dwarf::DW_FORM_block2:
2467 case dwarf::DW_FORM_block4:
2468 case dwarf::DW_FORM_exprloc:
2469 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2470 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002471 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002472 case dwarf::DW_FORM_data1:
2473 case dwarf::DW_FORM_data2:
2474 case dwarf::DW_FORM_data4:
2475 case dwarf::DW_FORM_data8:
2476 case dwarf::DW_FORM_udata:
2477 case dwarf::DW_FORM_sdata:
2478 case dwarf::DW_FORM_sec_offset:
2479 case dwarf::DW_FORM_flag:
2480 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002481 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2482 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002483 default:
2484 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2485 &InputDIE);
2486 }
2487
2488 return 0;
2489}
2490
Frederic Riss23e20e92015-03-07 01:25:09 +00002491/// \brief Apply the valid relocations found by findValidRelocs() to
2492/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2493/// in the debug_info section.
2494///
2495/// Like for findValidRelocs(), this function must be called with
2496/// monotonic \p BaseOffset values.
2497///
2498/// \returns wether any reloc has been applied.
2499bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2500 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002501 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002502 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2503 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002504 if (NextValidReloc >= ValidRelocs.size())
2505 return false;
2506
2507 // Skip relocs that haven't been applied.
2508 while (NextValidReloc < ValidRelocs.size() &&
2509 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2510 ++NextValidReloc;
2511
2512 bool Applied = false;
2513 uint64_t EndOffset = BaseOffset + Data.size();
2514 while (NextValidReloc < ValidRelocs.size() &&
2515 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2516 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2517 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2518 assert(ValidReloc.Offset - BaseOffset < Data.size());
2519 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2520 char Buf[8];
2521 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2522 Value += ValidReloc.Addend;
2523 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2524 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2525 Buf[i] = uint8_t(Value >> (Index * 8));
2526 }
2527 assert(ValidReloc.Size <= sizeof(Buf));
2528 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2529 Applied = true;
2530 }
2531
2532 return Applied;
2533}
2534
Frederic Rissbce93ff2015-03-16 02:05:10 +00002535static bool isTypeTag(uint16_t Tag) {
2536 switch (Tag) {
2537 case dwarf::DW_TAG_array_type:
2538 case dwarf::DW_TAG_class_type:
2539 case dwarf::DW_TAG_enumeration_type:
2540 case dwarf::DW_TAG_pointer_type:
2541 case dwarf::DW_TAG_reference_type:
2542 case dwarf::DW_TAG_string_type:
2543 case dwarf::DW_TAG_structure_type:
2544 case dwarf::DW_TAG_subroutine_type:
2545 case dwarf::DW_TAG_typedef:
2546 case dwarf::DW_TAG_union_type:
2547 case dwarf::DW_TAG_ptr_to_member_type:
2548 case dwarf::DW_TAG_set_type:
2549 case dwarf::DW_TAG_subrange_type:
2550 case dwarf::DW_TAG_base_type:
2551 case dwarf::DW_TAG_const_type:
2552 case dwarf::DW_TAG_constant:
2553 case dwarf::DW_TAG_file_type:
2554 case dwarf::DW_TAG_namelist:
2555 case dwarf::DW_TAG_packed_type:
2556 case dwarf::DW_TAG_volatile_type:
2557 case dwarf::DW_TAG_restrict_type:
2558 case dwarf::DW_TAG_interface_type:
2559 case dwarf::DW_TAG_unspecified_type:
2560 case dwarf::DW_TAG_shared_type:
2561 return true;
2562 default:
2563 break;
2564 }
2565 return false;
2566}
2567
Frederic Rissb8b43d52015-03-04 22:07:44 +00002568/// \brief Recursively clone \p InputDIE's subtrees that have been
2569/// selected to appear in the linked output.
2570///
2571/// \param OutOffset is the Offset where the newly created DIE will
2572/// lie in the linked compile unit.
2573///
2574/// \returns the cloned DIE object or null if nothing was selected.
2575DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00002576 CompileUnit &Unit, int64_t PCOffset,
2577 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002578 DWARFUnit &U = Unit.getOrigUnit();
2579 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002580 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002581
2582 // Should the DIE appear in the output?
2583 if (!Unit.getInfo(Idx).Keep)
2584 return nullptr;
2585
2586 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002587 // The DIE might have been already created by a forward reference
2588 // (see cloneDieReferenceAttribute()).
2589 DIE *Die = Info.Clone;
2590 if (!Die)
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002591 Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
Frederic Riss9833de62015-03-06 23:22:53 +00002592 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002593 Die->setOffset(OutOffset);
Frederic Riss1c650942015-07-21 22:41:43 +00002594 if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2595 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2596 !Info.Ctxt->getCanonicalDIEOffset()) {
2597 // We are about to emit a DIE that is the root of its own valid
2598 // DeclContext tree. Make the current offset the canonical offset
2599 // for this context.
2600 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2601 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002602
2603 // Extract and clone every attribute.
2604 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002605 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002606 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002607
2608 // We could copy the data only if we need to aply a relocation to
2609 // it. After testing, it seems there is no performance downside to
2610 // doing the copy unconditionally, and it makes the code simpler.
2611 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2612 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2613 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00002614 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2615 // If we applied relocations, we store the value of high_pc that was
2616 // potentially stored in the input DIE. If high_pc is an address
2617 // (Dwarf version == 2), then it might have been relocated to a
2618 // totally unrelated value (because the end address in the object
2619 // file might be start address of another function which got moved
2620 // independantly by the linker). The computation of the actual
2621 // high_pc value is done in cloneAddressAttribute().
2622 AttrInfo.OrigHighPc =
2623 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2624 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002625
2626 // Reset the Offset to 0 as we will be working on the local copy of
2627 // the data.
2628 Offset = 0;
2629
Frederic Rissb8b43d52015-03-04 22:07:44 +00002630 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2631 Offset += getULEB128Size(Abbrev->getCode());
2632
Frederic Riss31da3242015-03-11 18:45:52 +00002633 // We are entering a subprogram. Get and propagate the PCOffset.
2634 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2635 PCOffset = Info.AddrAdjust;
2636 AttrInfo.PCOffset = PCOffset;
2637
Frederic Rissb8b43d52015-03-04 22:07:44 +00002638 for (const auto &AttrSpec : Abbrev->attributes()) {
2639 DWARFFormValue Val(AttrSpec.Form);
2640 uint32_t AttrSize = Offset;
2641 Val.extractValue(Data, &Offset, &U);
2642 AttrSize = Offset - AttrSize;
2643
Frederic Riss31da3242015-03-11 18:45:52 +00002644 OutOffset +=
2645 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002646 }
2647
Frederic Rissbce93ff2015-03-16 02:05:10 +00002648 // Look for accelerator entries.
2649 uint16_t Tag = InputDIE.getTag();
2650 // FIXME: This is slightly wrong. An inline_subroutine without a
2651 // low_pc, but with AT_ranges might be interesting to get into the
2652 // accelerator tables too. For now stick with dsymutil's behavior.
2653 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2654 Tag != dwarf::DW_TAG_compile_unit &&
2655 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2656 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2657 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2658 AttrInfo.MangledNameOffset,
2659 Tag == dwarf::DW_TAG_inlined_subroutine);
2660 if (AttrInfo.Name)
2661 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2662 Tag == dwarf::DW_TAG_inlined_subroutine);
2663 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2664 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2665 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2666 }
2667
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002668 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002669 // If a scope DIE is kept, we must have kept at least one child. If
2670 // it's not the case, we'll just be emitting one wasteful end of
2671 // children marker, but things won't break.
2672 if (InputDIE.hasChildren())
2673 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2674 // Assign a permanent abbrev number
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002675 AssignAbbrev(NewAbbrev);
2676 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002677
2678 // Add the size of the abbreviation number to the output offset.
2679 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2680
2681 if (!Abbrev->hasChildren()) {
2682 // Update our size.
2683 Die->setSize(OutOffset - Die->getOffset());
2684 return Die;
2685 }
2686
2687 // Recursively clone children.
2688 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2689 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00002690 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Duncan P. N. Exon Smith827200c2015-06-25 23:52:10 +00002691 Die->addChild(Clone);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002692 OutOffset = Clone->getOffset() + Clone->getSize();
2693 }
2694 }
2695
2696 // Account for the end of children marker.
2697 OutOffset += sizeof(int8_t);
2698 // Update our size.
2699 Die->setSize(OutOffset - Die->getOffset());
2700 return Die;
2701}
2702
Frederic Riss25440872015-03-13 23:30:31 +00002703/// \brief Patch the input object file relevant debug_ranges entries
2704/// and emit them in the output file. Update the relevant attributes
2705/// to point at the new entries.
2706void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2707 DWARFContext &OrigDwarf) const {
2708 DWARFDebugRangeList RangeList;
2709 const auto &FunctionRanges = Unit.getFunctionRanges();
2710 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2711 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2712 OrigDwarf.isLittleEndian(), AddressSize);
2713 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2714 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002715 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002716 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2717 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2718 // Ranges addresses are based on the unit's low_pc. Compute the
2719 // offset we need to apply to adapt to the the new unit's low_pc.
2720 int64_t UnitPcOffset = 0;
2721 if (OrigLowPc != -1ULL)
2722 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2723
2724 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002725 uint32_t Offset = RangeAttribute.get();
2726 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002727 RangeList.extract(RangeExtractor, &Offset);
2728 const auto &Entries = RangeList.getEntries();
2729 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2730
2731 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2732 First.StartAddress >= CurrRange.stop()) {
2733 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2734 if (CurrRange == InvalidRange ||
2735 CurrRange.start() > First.StartAddress + OrigLowPc) {
2736 reportWarning("no mapping for range.");
2737 continue;
2738 }
2739 }
2740
2741 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2742 AddressSize);
2743 }
2744}
2745
Frederic Riss563b1b02015-03-14 03:46:51 +00002746/// \brief Generate the debug_aranges entries for \p Unit and if the
2747/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2748/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002749/// FIXME: this could actually be done right in patchRangesForUnit,
2750/// but for the sake of initial bit-for-bit compatibility with legacy
2751/// dsymutil, we have to do it in a delayed pass.
2752void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002753 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002754 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002755 Attr->set(Streamer->getRangesSectionSize());
2756 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002757}
2758
Frederic Riss63786b02015-03-15 20:45:43 +00002759/// \brief Insert the new line info sequence \p Seq into the current
2760/// set of already linked line info \p Rows.
2761static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2762 std::vector<DWARFDebugLine::Row> &Rows) {
2763 if (Seq.empty())
2764 return;
2765
2766 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2767 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2768 Seq.clear();
2769 return;
2770 }
2771
2772 auto InsertPoint = std::lower_bound(
2773 Rows.begin(), Rows.end(), Seq.front(),
2774 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2775 return LHS.Address < RHS.Address;
2776 });
2777
2778 // FIXME: this only removes the unneeded end_sequence if the
2779 // sequences have been inserted in order. using a global sort like
2780 // described in patchLineTableForUnit() and delaying the end_sequene
2781 // elimination to emitLineTableForUnit() we can get rid of all of them.
2782 if (InsertPoint != Rows.end() &&
2783 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2784 *InsertPoint = Seq.front();
2785 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2786 } else {
2787 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2788 }
2789
2790 Seq.clear();
2791}
2792
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002793static void patchStmtList(DIE &Die, DIEInteger Offset) {
2794 for (auto &V : Die.values())
2795 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
Duncan P. N. Exon Smith4fb1f9c2015-06-25 23:46:41 +00002796 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002797 return;
2798 }
2799
2800 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2801}
2802
Frederic Riss63786b02015-03-15 20:45:43 +00002803/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2804/// recreate a relocated version of these for the address ranges that
2805/// are present in the binary.
2806void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2807 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002808 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002809 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2810 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2811 if (StmtList == -1ULL)
2812 return;
2813
2814 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002815 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2816 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002817
2818 // Parse the original line info for the unit.
2819 DWARFDebugLine::LineTable LineTable;
2820 uint32_t StmtOffset = StmtList;
2821 StringRef LineData = OrigDwarf.getLineSection().Data;
2822 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2823 Unit.getOrigUnit().getAddressByteSize());
2824 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2825 &StmtOffset);
2826
2827 // This vector is the output line table.
2828 std::vector<DWARFDebugLine::Row> NewRows;
2829 NewRows.reserve(LineTable.Rows.size());
2830
2831 // Current sequence of rows being extracted, before being inserted
2832 // in NewRows.
2833 std::vector<DWARFDebugLine::Row> Seq;
2834 const auto &FunctionRanges = Unit.getFunctionRanges();
2835 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2836
2837 // FIXME: This logic is meant to generate exactly the same output as
2838 // Darwin's classic dsynutil. There is a nicer way to implement this
2839 // by simply putting all the relocated line info in NewRows and simply
2840 // sorting NewRows before passing it to emitLineTableForUnit. This
2841 // should be correct as sequences for a function should stay
2842 // together in the sorted output. There are a few corner cases that
2843 // look suspicious though, and that required to implement the logic
2844 // this way. Revisit that once initial validation is finished.
2845
2846 // Iterate over the object file line info and extract the sequences
2847 // that correspond to linked functions.
2848 for (auto &Row : LineTable.Rows) {
2849 // Check wether we stepped out of the range. The range is
2850 // half-open, but consider accept the end address of the range if
2851 // it is marked as end_sequence in the input (because in that
2852 // case, the relocation offset is accurate and that entry won't
2853 // serve as the start of another function).
2854 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2855 Row.Address > CurrRange.stop() ||
2856 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2857 // We just stepped out of a known range. Insert a end_sequence
2858 // corresponding to the end of the range.
2859 uint64_t StopAddress = CurrRange != InvalidRange
2860 ? CurrRange.stop() + CurrRange.value()
2861 : -1ULL;
2862 CurrRange = FunctionRanges.find(Row.Address);
2863 bool CurrRangeValid =
2864 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2865 if (!CurrRangeValid) {
2866 CurrRange = InvalidRange;
2867 if (StopAddress != -1ULL) {
2868 // Try harder by looking in the DebugMapObject function
2869 // ranges map. There are corner cases where this finds a
2870 // valid entry. It's unclear if this is right or wrong, but
2871 // for now do as dsymutil.
2872 // FIXME: Understand exactly what cases this addresses and
2873 // potentially remove it along with the Ranges map.
2874 auto Range = Ranges.lower_bound(Row.Address);
2875 if (Range != Ranges.begin() && Range != Ranges.end())
2876 --Range;
2877
2878 if (Range != Ranges.end() && Range->first <= Row.Address &&
2879 Range->second.first >= Row.Address) {
2880 StopAddress = Row.Address + Range->second.second;
2881 }
2882 }
2883 }
2884 if (StopAddress != -1ULL && !Seq.empty()) {
2885 // Insert end sequence row with the computed end address, but
2886 // the same line as the previous one.
Yaron Keren3f85a22c2015-08-08 21:03:19 +00002887 Seq.reserve(Seq.size() + 1);
Frederic Riss63786b02015-03-15 20:45:43 +00002888 Seq.emplace_back(Seq.back());
2889 Seq.back().Address = StopAddress;
2890 Seq.back().EndSequence = 1;
2891 Seq.back().PrologueEnd = 0;
2892 Seq.back().BasicBlock = 0;
2893 Seq.back().EpilogueBegin = 0;
2894 insertLineSequence(Seq, NewRows);
2895 }
2896
2897 if (!CurrRangeValid)
2898 continue;
2899 }
2900
2901 // Ignore empty sequences.
2902 if (Row.EndSequence && Seq.empty())
2903 continue;
2904
2905 // Relocate row address and add it to the current sequence.
2906 Row.Address += CurrRange.value();
2907 Seq.emplace_back(Row);
2908
2909 if (Row.EndSequence)
2910 insertLineSequence(Seq, NewRows);
2911 }
2912
2913 // Finished extracting, now emit the line tables.
2914 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2915 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2916 // prologue over and that works because we act as both producer and
2917 // consumer. It would be nicer to have a real configurable line
2918 // table emitter.
2919 if (LineTable.Prologue.Version != 2 ||
2920 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
Frederic Rissa5e14532015-08-07 15:14:13 +00002921 LineTable.Prologue.OpcodeBase > 13)
Frederic Riss63786b02015-03-15 20:45:43 +00002922 reportWarning("line table paramters mismatch. Cannot emit.");
Frederic Rissa5e14532015-08-07 15:14:13 +00002923 else {
2924 MCDwarfLineTableParams Params;
2925 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
2926 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
2927 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
2928 Streamer->emitLineTableForUnit(Params,
2929 LineData.slice(StmtList + 4, PrologueEnd),
Frederic Riss63786b02015-03-15 20:45:43 +00002930 LineTable.Prologue.MinInstLength, NewRows,
2931 Unit.getOrigUnit().getAddressByteSize());
Frederic Rissa5e14532015-08-07 15:14:13 +00002932 }
Frederic Riss63786b02015-03-15 20:45:43 +00002933}
2934
Frederic Rissbce93ff2015-03-16 02:05:10 +00002935void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2936 Streamer->emitPubNamesForUnit(Unit);
2937 Streamer->emitPubTypesForUnit(Unit);
2938}
2939
Frederic Riss5a642072015-06-05 23:06:11 +00002940/// \brief Read the frame info stored in the object, and emit the
2941/// patched frame descriptions for the linked binary.
2942///
2943/// This is actually pretty easy as the data of the CIEs and FDEs can
2944/// be considered as black boxes and moved as is. The only thing to do
2945/// is to patch the addresses in the headers.
2946void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2947 DWARFContext &OrigDwarf,
2948 unsigned AddrSize) {
2949 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2950 if (FrameData.empty())
2951 return;
2952
2953 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2954 uint32_t InputOffset = 0;
2955
2956 // Store the data of the CIEs defined in this object, keyed by their
2957 // offsets.
2958 DenseMap<uint32_t, StringRef> LocalCIES;
2959
2960 while (Data.isValidOffset(InputOffset)) {
2961 uint32_t EntryOffset = InputOffset;
2962 uint32_t InitialLength = Data.getU32(&InputOffset);
2963 if (InitialLength == 0xFFFFFFFF)
2964 return reportWarning("Dwarf64 bits no supported");
2965
2966 uint32_t CIEId = Data.getU32(&InputOffset);
2967 if (CIEId == 0xFFFFFFFF) {
2968 // This is a CIE, store it.
2969 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2970 LocalCIES[EntryOffset] = CIEData;
2971 // The -4 is to account for the CIEId we just read.
2972 InputOffset += InitialLength - 4;
2973 continue;
2974 }
2975
2976 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2977
2978 // Some compilers seem to emit frame info that doesn't start at
2979 // the function entry point, thus we can't just lookup the address
2980 // in the debug map. Use the linker's range map to see if the FDE
2981 // describes something that we can relocate.
2982 auto Range = Ranges.upper_bound(Loc);
2983 if (Range != Ranges.begin())
2984 --Range;
2985 if (Range == Ranges.end() || Range->first > Loc ||
2986 Range->second.first <= Loc) {
2987 // The +4 is to account for the size of the InitialLength field itself.
2988 InputOffset = EntryOffset + InitialLength + 4;
2989 continue;
2990 }
2991
2992 // This is an FDE, and we have a mapping.
2993 // Have we already emitted a corresponding CIE?
2994 StringRef CIEData = LocalCIES[CIEId];
2995 if (CIEData.empty())
2996 return reportWarning("Inconsistent debug_frame content. Dropping.");
2997
2998 // Look if we already emitted a CIE that corresponds to the
2999 // referenced one (the CIE data is the key of that lookup).
3000 auto IteratorInserted = EmittedCIEs.insert(
3001 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3002 // If there is no CIE yet for this ID, emit it.
3003 if (IteratorInserted.second ||
3004 // FIXME: dsymutil-classic only caches the last used CIE for
3005 // reuse. Mimic that behavior for now. Just removing that
3006 // second half of the condition and the LastCIEOffset variable
3007 // makes the code DTRT.
3008 LastCIEOffset != IteratorInserted.first->getValue()) {
3009 LastCIEOffset = Streamer->getFrameSectionSize();
3010 IteratorInserted.first->getValue() = LastCIEOffset;
3011 Streamer->emitCIE(CIEData);
3012 }
3013
3014 // Emit the FDE with updated address and CIE pointer.
3015 // (4 + AddrSize) is the size of the CIEId + initial_location
3016 // fields that will get reconstructed by emitFDE().
3017 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3018 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3019 Loc + Range->second.second,
3020 FrameData.substr(InputOffset, FDERemainingBytes));
3021 InputOffset += FDERemainingBytes;
3022 }
3023}
3024
Frederic Risseb85c8f2015-07-24 06:41:11 +00003025ErrorOr<const object::ObjectFile &>
3026DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3027 const DebugMap &Map) {
3028 auto ErrOrObjs =
3029 BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
3030 if (std::error_code EC = ErrOrObjs.getError())
3031 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3032 auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3033 if (std::error_code EC = ErrOrObj.getError())
3034 reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3035 return ErrOrObj;
3036}
3037
Frederic Rissd3455182015-01-28 18:27:01 +00003038bool DwarfLinker::link(const DebugMap &Map) {
3039
3040 if (Map.begin() == Map.end()) {
3041 errs() << "Empty debug map.\n";
3042 return false;
3043 }
3044
Frederic Rissc99ea202015-02-28 00:29:11 +00003045 if (!createStreamer(Map.getTriple(), OutputFilename))
3046 return false;
3047
Frederic Rissb8b43d52015-03-04 22:07:44 +00003048 // Size of the DIEs (and headers) generated for the linked output.
3049 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00003050 // A unique ID that identifies each compile unit.
3051 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00003052 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00003053 CurrentDebugObject = Obj.get();
3054
Frederic Rissb9818322015-02-28 00:29:07 +00003055 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00003056 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
Frederic Risseb85c8f2015-07-24 06:41:11 +00003057 auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3058 if (!ErrOrObj)
Frederic Rissd3455182015-01-28 18:27:01 +00003059 continue;
Frederic Rissd3455182015-01-28 18:27:01 +00003060
Frederic Riss1036e642015-02-13 23:18:22 +00003061 // Look for relocations that correspond to debug map entries.
3062 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00003063 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00003064 outs() << "No valid relocations found. Skipping.\n";
3065 continue;
3066 }
3067
Frederic Riss563cba62015-01-28 22:15:14 +00003068 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00003069 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00003070 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00003071
Frederic Riss563cba62015-01-28 22:15:14 +00003072 // In a first phase, just read in the debug info and store the DIE
3073 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00003074 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003075 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00003076 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00003077 outs() << "Input compilation unit:";
3078 CUDie->dump(outs(), CU.get(), 0);
3079 }
Frederic Riss1c650942015-07-21 22:41:43 +00003080 Units.emplace_back(*CU, UnitID++, !Options.NoODR);
3081 gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
3082 StringPool, ODRContexts);
Frederic Rissd3455182015-01-28 18:27:01 +00003083 }
Frederic Riss563cba62015-01-28 22:15:14 +00003084
Frederic Riss84c09a52015-02-13 23:18:34 +00003085 // Then mark all the DIEs that need to be present in the linked
3086 // output and collect some information about them. Note that this
3087 // loop can not be merged with the previous one becaue cross-cu
3088 // references require the ParentIdx to be setup for every CU in
3089 // the object file before calling this.
3090 for (auto &CurrentUnit : Units)
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003091 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00003092 CurrentUnit, 0);
3093
Frederic Riss23e20e92015-03-07 01:25:09 +00003094 // The calls to applyValidRelocs inside cloneDIE will walk the
3095 // reloc array again (in the same way findValidRelocsInDebugInfo()
3096 // did). We need to reset the NextValidReloc index to the beginning.
3097 NextValidReloc = 0;
3098
Frederic Rissb8b43d52015-03-04 22:07:44 +00003099 // Construct the output DIE tree by cloning the DIEs we chose to
3100 // keep above. If there are no valid relocs, then there's nothing
3101 // to clone/emit.
3102 if (!ValidRelocs.empty())
3103 for (auto &CurrentUnit : Units) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00003104 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00003105 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00003106 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
3107 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00003108 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00003109 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00003110 if (Options.NoOutput)
3111 continue;
3112 // FIXME: for compatibility with the classic dsymutil, we emit
3113 // an empty line table for the unit, even if the unit doesn't
3114 // actually exist in the DIE tree.
3115 patchLineTableForUnit(CurrentUnit, DwarfContext);
3116 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00003117 continue;
3118 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00003119 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissbce93ff2015-03-16 02:05:10 +00003120 emitAcceleratorEntriesForUnit(CurrentUnit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00003121 }
3122
3123 // Emit all the compile unit's debug information.
3124 if (!ValidRelocs.empty() && !Options.NoOutput)
3125 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00003126 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00003127 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00003128 Streamer->emitCompileUnitHeader(CurrentUnit);
3129 if (!CurrentUnit.getOutputUnitDIE())
3130 continue;
3131 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
3132 }
3133
Frederic Riss5a642072015-06-05 23:06:11 +00003134 if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
3135 patchFrameInfoForObject(*Obj, DwarfContext,
3136 Units[0].getOrigUnit().getAddressByteSize());
3137
Frederic Riss563cba62015-01-28 22:15:14 +00003138 // Clean-up before starting working on the next object.
3139 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00003140 }
3141
Frederic Rissb8b43d52015-03-04 22:07:44 +00003142 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00003143 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00003144 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00003145 Streamer->emitStrings(StringPool);
3146 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00003147
Frederic Rissc99ea202015-02-28 00:29:11 +00003148 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00003149}
3150}
Frederic Rissd3455182015-01-28 18:27:01 +00003151
Frederic Rissb9818322015-02-28 00:29:07 +00003152bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3153 const LinkOptions &Options) {
3154 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00003155 return Linker.link(DM);
3156}
3157}
Frederic Riss231f7142014-12-12 17:31:24 +00003158}